diff --git a/CMakeLists.txt b/CMakeLists.txt index b870463e12..d4503e3ee7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,6 +40,7 @@ option(BuildMPDed "Whether to create projects for the MP dedicated server (etern option(BuildMPGame "Whether to create projects for the MP server-side gamecode (jampgamex86.dll)" ON) option(BuildMPCGame "Whether to create projects for the MP clientside gamecode (cgamex86.dll)" ON) option(BuildMPUI "Whether to create projects for the MP UI code (uix86.dll)" ON) +option(BuildMPRend2 "Whether to create projects for the EXPERIMENTAL MP rend2 renderer (rd-rend2_x86.dll)" ON) option(BuildDiscordRichPresence "Whether to build with Discord Rich Presence integration" ON) @@ -147,6 +148,7 @@ endif() set(MPEngine "eternaljk.${Architecture}") set(MPVanillaRenderer "rd-eternaljk_${Architecture}") set(MPVulkanRenderer "rd-vulkan_${Architecture}") +set(MPRend2 "rd-rend2_${Architecture}") set(MPDed "eternaljkded.${Architecture}") set(MPGame "jampgame${Architecture}") set(MPCGame "cgame${Architecture}") diff --git a/assets/japro/ui/jamp/ingame_setup.menu b/assets/japro/ui/jamp/ingame_setup.menu index 3dcdd51114..2b0fd16e6b 100644 --- a/assets/japro/ui/jamp/ingame_setup.menu +++ b/assets/japro/ui/jamp/ingame_setup.menu @@ -27,6 +27,7 @@ show setup_background show video + hide video2 hide advancedvideo hide lighting hide advancedlighting @@ -75,7 +76,7 @@ style WINDOW_STYLE_SHADER background "gfx/menus/menu_blendbox" text @MENUS_SETUP - rect 20 5 510 28 + rect 20 5 530 28 textalign ITEM_ALIGN_CENTER textalignx 255 textaligny 2 @@ -204,6 +205,7 @@ show setup_background hide video + hide video2 hide advancedvideo show lighting hide advancedlighting @@ -270,6 +272,7 @@ show setup_background hide video + hide video2 hide advancedvideo hide lighting hide advancedlighting @@ -336,6 +339,7 @@ show setup_background hide video + hide video2 hide advancedvideo hide lighting hide advancedlighting @@ -402,6 +406,7 @@ show setup_background hide video + hide video2 hide advancedvideo hide lighting hide advancedlighting @@ -469,6 +474,7 @@ show setup_background hide video + hide video2 hide advancedvideo hide lighting hide advancedlighting @@ -535,6 +541,7 @@ show setup_background hide video + hide video2 hide advancedvideo hide lighting hide advancedlighting @@ -616,6 +623,7 @@ show setup_background hide video + hide video2 hide advancedvideo hide lighting hide advancedlighting @@ -841,9 +849,9 @@ //---------------------------------------------------------------------------------------------- itemDef { - name graphics - group video - text @MENUS_VIDEO_QUALITY + name renderer + group video + text "Renderer:" type ITEM_TYPE_MULTI rect 220 43 300 20 textalign ITEM_ALIGN_RIGHT @@ -853,19 +861,10 @@ textscale 1 style WINDOW_STYLE_FILLED forecolor .615 .615 .956 1 - descText @MENUS_SELECT_PRESET_GRAPHIC - - visible 0 - - cvar "ui_r_glCustom" - cvarFloatList - { - @MENUS_HIGH_QUALITY 0 - @MENUS_NORMAL 1 - @MENUS_FAST 2 - @MENUS_FASTEST 3 - @MENUS_CUSTOM 4 - } + cvarStrList { "Vanilla" , "rd-vanilla" , "Vulkan", "rd-vulkan", "Rend2" , "rd-rend2" } + descText "Change the renderer library to use." + cvar "cl_renderer" + visible 1 mouseenter { @@ -1624,6 +1623,506 @@ mouseexit { hide advancedvideobutton_glow } } + // rend2 addition: button advanced video settings + itemDef + { + name advanced_video + group advancedvideo + type ITEM_TYPE_BUTTON + text "Rend2 Video Settings" + rect 260 303 200 20 + textalign ITEM_ALIGN_CENTER + textalignx 100 + textaligny 0 + font 4 + textscale 1 + forecolor 1 .682 0 1 + visible 0 + descText "Configure rend2 video options" + cvarTest "cl_renderer" + hideCvar { "rd-vanilla" } + + action + { + play "sound/interface/button1.wav" ; + hide advancedvideo + show video2 + hide applybutton_glow + } + mouseenter + { + show highlight14 + } + mouseexit + { + hide highlight14 + } + } + + // rend2 addition: button advanced video settings + itemDef + { + name advanced_video + group video2 + type ITEM_TYPE_BUTTON + text "Back" + rect 220 303 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor 0.65 0.65 1 1 + visible 0 + descText "Rend2 video settings" + cvarTest "cl_renderer" + hideCvar { "rd-vanilla" } + + action + { + play "sound/interface/button1.wav" ; + show video + hide video2 + hide applybutton_glow + } + mouseenter + { + show highlight14 + } + mouseexit + { + hide highlight14 + } + } + + // rend2 addition + itemDef + { + name hdr + group video2 + type ITEM_TYPE_MULTI + text "HDR:" + rect 220 43 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Rendering in HDR Colorspace" + cvar "r_hdr" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight1 + } + mouseexit + { + hide highlight1 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name tonemapping + group video2 + type ITEM_TYPE_MULTI + text "Tonemapping:" + rect 220 63 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Tonemapping" + cvar "r_tonemap" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight2 + } + mouseexit + { + hide highlight2 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name autoexp + group video2 + type ITEM_TYPE_MULTI + text "Autoexposure:" + rect 220 83 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Autoexposure" + cvar "r_autoexposure" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight3 + } + mouseexit + { + hide highlight3 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name hdrlightmap + group video2 + type ITEM_TYPE_MULTI + text "HDR Lighting support:" + rect 220 103 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Load hdr lighting data. (requires rend2 lighting data)" + cvar "r_floatLightmap" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 0 + cvarTest "r_hdr" + hideCvar { 0 } + + mouseenter + { + show highlight4 + } + mouseexit + { + hide highlight4 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name deluxemap + group video2 + type ITEM_TYPE_MULTI + text "Deluxemapping:" + rect 220 123 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Enables normalmapping and specularmapping on static geometry." + cvar "r_deluxemapping" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight5 + } + mouseexit + { + hide highlight5 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name deluxeSpec + group video2 + type ITEM_TYPE_SLIDER + text "Deluxemap Specular:" + cvarfloat "r_deluxeSpecular" 1 0.0 1.0 + rect 220 143 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + visible 0 + descText "Scale the specular response from deluxemaps." + cvarTest "r_deluxemapping" + hideCvar { 0 } + action + { + play "sound/interface/button1.wav" ; + } + mouseenter + { + show highlight6 + } + mouseexit + { + hide highlight6 + } + } + + // rend2 addition + itemDef + { + name cubemap + group video2 + type ITEM_TYPE_MULTI + text "Cubemapping:" + rect 220 163 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Render cubemaps for reflections." + cvar "r_cubemapping" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight7 + } + mouseexit + { + hide highlight7 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name cubemapbounces + group video2 + type ITEM_TYPE_MULTI + text "Cubemapping bounces:" + rect 220 183 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "How many reflection bounces to render in cubemaps." + cvar "r_cubemappingBounces" + cvarFloatList + { + "0" 0 + "1" 1 + "2" 2 + } + cvarTest "r_cubemapping" + hideCvar { 0 } + visible 1 + + mouseenter + { + show highlight8 + } + mouseexit + { + hide highlight8 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name parallax + group video2 + type ITEM_TYPE_MULTI + text "Parallax Occlusion Mapping:" + rect 220 203 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Parallax Occlusion Mapping (requires rend2 materials)" + cvar "r_parallaxmapping" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight9 + } + mouseexit + { + hide highlight9 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name genNormals + group video2 + type ITEM_TYPE_MULTI + text "Generate Normalmaps:" + rect 220 223 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Generate normalmaps from diffuse textures." + cvar "r_genNormalMaps" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight10 + } + mouseexit + { + hide highlight10 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name ssao + group video2 + type ITEM_TYPE_MULTI + text "SSAO:" + rect 220 243 300 20 + textalign ITEM_ALIGN_RIGHT + textalignx 165 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Screenspace ambient occlusion" + cvar "r_ssao" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 0 + + mouseenter + { + show highlight11 + } + mouseexit + { + hide highlight11 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + // APPLY CHANGES BUTTON itemDef { diff --git a/assets/japro/ui/jamp/setup.menu b/assets/japro/ui/jamp/setup.menu index 52ccd4274d..1dabb19d3e 100644 --- a/assets/japro/ui/jamp/setup.menu +++ b/assets/japro/ui/jamp/setup.menu @@ -26,6 +26,7 @@ show video hide applyChanges hide video2 + hide video3 hide vidrestart hide sound hide options @@ -493,6 +494,7 @@ show video ; hide applyChanges ; hide video2 ; + hide video3 ; hide vidrestart ; hide sound ; hide options ; @@ -554,6 +556,7 @@ hide video ; hide applyChanges ; show video2 ; + hide video3 ; hide vidrestart ; hide sound ; hide options ; @@ -614,6 +617,7 @@ hide video ; hide applyChanges ; hide video2 ; + hide video3 ; hide vidrestart ; show sound ; hide options ; @@ -673,6 +677,7 @@ hide video hide applyChanges hide video2 + hide video3 hide vidrestart hide sound show options @@ -735,6 +740,7 @@ hide video ; hide applyChanges ; hide video2 ; + hide video3 ; hide vidrestart ; hide sound ; hide options ; @@ -796,6 +802,7 @@ hide video ; hide applyChanges ; hide video2 ; + hide video3 ; hide vidrestart ; hide sound ; hide options ; @@ -1010,33 +1017,25 @@ // VIDEO 1 MENU BUTTONS // //---------------------------------------------------------------------------------------------- - itemDef + + // rend2 addition: select renderer library + itemDef { - name graphics - group video - text @MENUS_VIDEO_QUALITY - type ITEM_TYPE_MULTI - rect 260 188 340 14 - textalign ITEM_ALIGN_RIGHT - textalignx 174 - textaligny 0 - font 4 - textscale 1 - style WINDOW_STYLE_FILLED + name renderer + group video + type ITEM_TYPE_MULTI + text "Renderer:" + rect 260 188 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 forecolor .615 .615 .956 1 - descText @MENUS_SELECT_PRESET_GRAPHIC - - visible 1 - - cvar "ui_r_glCustom" - cvarFloatList - { - @MENUS_HIGH_QUALITY 0 - @MENUS_NORMAL 1 - @MENUS_FAST 2 - @MENUS_FASTEST 3 - @MENUS_CUSTOM 4 - } + cvarStrList { "Vanilla" , "rd-vanilla" , "Vulkan", "rd-vulkan", "Rend2" , "rd-rend2" } + descText "Change the renderer library to use." + cvar "cl_renderer" + visible 1 mouseenter { @@ -1048,21 +1047,20 @@ } action { - play "sound/interface/button1.wav" ; - uiScript update "ui_r_glCustom" ; + play "sound/interface/button1.wav" ; setcvar ui_r_modified 1 ; show applyChanges } } - + // rend2 addition: added native resolution to the menu itemDef { name video_mode group video type ITEM_TYPE_MULTI text @MENUS_VIDEO_MODE - cvarFloatList { @MENUS_640_X_480 3 @MENUS_800_X_600 4 @MENUS_1024_X_768 6 @MENUS_1152_X_864 7 @MENUS_1280_X_1024 8 @MENUS_1600_X_1200 9 @MENUS_2048_X_1536 10 @MENUS_2400_X_600 12 } + cvarFloatList { @MENUS_640_X_480 3 @MENUS_800_X_600 4 @MENUS_1024_X_768 6 @MENUS_1152_X_864 7 @MENUS_1280_X_1024 8 @MENUS_1600_X_1200 9 @MENUS_2048_X_1536 10 @MENUS_2400_X_600 12 "Native" -2} cvar "ui_r_mode" rect 260 216 340 14 textalign ITEM_ALIGN_RIGHT @@ -1374,6 +1372,546 @@ } } + // rend2 addition: set antialiasing + itemDef + { + name video_aa + group video + type ITEM_TYPE_MULTI + text "Antialiasing:" + cvar "r_ext_multisample" + cvarFloatList + { + @MENUS_OFF 0 + "MSAA 2x" 2 + "MSAA 4x" 4 + "MSAA 8x" 8 + } + rect 260 342 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor 0.65 0.65 1 1 + visible 0 + descText "Antialiasing" + action + { + play "sound/interface/button1.wav" ; + } + mouseenter + { + show highlight12 + } + mouseexit + { + hide highlight12 + } + } + + // rend2 addition: button advanced video settings + itemDef + { + name advanced_video + group video + type ITEM_TYPE_BUTTON + text "Advanced Video Settings" + rect 260 370 340 14 + textalign ITEM_ALIGN_CENTER + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor 0.65 0.65 1 1 + visible 0 + descText "Advanced video settings" + cvarTest "cl_renderer" + hideCvar { "rd-vanilla" } + + action + { + play "sound/interface/button1.wav" ; + hide video + hide video2 + show video3 + hide applybutton_glow + } + mouseenter + { + show highlight14 + } + mouseexit + { + hide highlight14 + } + } + + // rend2 addition: button advanced video settings + itemDef + { + name advanced_video + group video3 + type ITEM_TYPE_BUTTON + text "Back" + rect 260 370 340 14 + textalign ITEM_ALIGN_CENTER + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor 0.65 0.65 1 1 + visible 0 + descText "Advanced video settings" + cvarTest "cl_renderer" + hideCvar { "rd-vanilla" } + + action + { + play "sound/interface/button1.wav" ; + show video + hide video2 + hide video3 + hide applybutton_glow + } + mouseenter + { + show highlight14 + } + mouseexit + { + hide highlight14 + } + } + + // rend2 addition + itemDef + { + name hdr + group video3 + type ITEM_TYPE_MULTI + text "HDR:" + rect 260 188 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Rendering in HDR Colorspace" + cvar "r_hdr" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight1 + } + mouseexit + { + hide highlight1 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name tonemapping + group video3 + type ITEM_TYPE_MULTI + text "Tonemapping:" + rect 260 202 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Tonemapping" + cvar "r_tonemap" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight2 + } + mouseexit + { + hide highlight2 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name autoexp + group video3 + type ITEM_TYPE_MULTI + text "Autoexposure:" + rect 260 216 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Autoexposure" + cvar "r_autoexposure" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight3 + } + mouseexit + { + hide highlight3 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name hdrlightmap + group video3 + type ITEM_TYPE_MULTI + text "HDR Lighting support:" + rect 260 230 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Load hdr lighting data. (requires rend2 lighting data)" + cvar "r_floatLightmap" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 0 + cvarTest "r_hdr" + hideCvar { 0 } + + mouseenter + { + show highlight4 + } + mouseexit + { + hide highlight4 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name deluxemap + group video3 + type ITEM_TYPE_MULTI + text "Deluxemapping:" + rect 260 244 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Enables normalmapping and specularmapping on static geometry." + cvar "r_deluxemapping" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight5 + } + mouseexit + { + hide highlight5 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name deluxeSpec + group video3 + type ITEM_TYPE_SLIDER + text "Deluxemap Specular:" + cvarfloat "r_deluxeSpecular" 1 0.0 1.0 + rect 260 258 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + visible 0 + descText "Scale the specular response from deluxemaps." + cvarTest "r_deluxemapping" + hideCvar { 0 } + action + { + play "sound/interface/button1.wav" ; + } + mouseenter + { + show highlight6 + } + mouseexit + { + hide highlight6 + } + } + + // rend2 addition + itemDef + { + name cubemap + group video3 + type ITEM_TYPE_MULTI + text "Cubemapping:" + rect 260 272 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Render cubemaps for reflections." + cvar "r_cubemapping" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight7 + } + mouseexit + { + hide highlight7 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name cubemapbounces + group video3 + type ITEM_TYPE_MULTI + text "Cubemapping bounces:" + rect 260 286 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "How many reflection bounces to render in cubemaps." + cvar "r_cubemappingBounces" + cvarFloatList + { + "0" 0 + "1" 1 + "2" 2 + } + cvarTest "r_cubemapping" + hideCvar { 0 } + visible 1 + + mouseenter + { + show highlight8 + } + mouseexit + { + hide highlight8 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name parallax + group video3 + type ITEM_TYPE_MULTI + text "Parallax Occlusion Mapping:" + rect 260 300 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Parallax Occlusion Mapping (requires rend2 materials)" + cvar "r_parallaxmapping" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight9 + } + mouseexit + { + hide highlight9 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name genNormals + group video3 + type ITEM_TYPE_MULTI + text "Generate Normalmaps:" + rect 260 314 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Generate normalmaps from diffuse textures." + cvar "r_genNormalMaps" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 1 + + mouseenter + { + show highlight10 + } + mouseexit + { + hide highlight10 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + + // rend2 addition + itemDef + { + name ssao + group video3 + type ITEM_TYPE_MULTI + text "SSAO:" + rect 260 328 340 14 + textalign ITEM_ALIGN_RIGHT + textalignx 174 + textaligny 0 + font 4 + textscale 1 + forecolor .615 .615 .956 1 + descText "Screenspace ambient occlusion" + cvar "r_ssao" + cvarFloatList + { + @MENUS_OFF 0 + @MENUS_ON 1 + } + visible 0 + + mouseenter + { + show highlight11 + } + mouseexit + { + hide highlight11 + } + action + { + play "sound/interface/button1.wav" ; + setcvar ui_r_modified 1 ; + show applyChanges + } + } + // APPLY CHANGES BUTTON itemDef { @@ -1420,6 +1958,7 @@ show vidrestart hide video hide video2 + hide video3 hide applybutton_glow } } @@ -1557,6 +2096,7 @@ hide vidrestart ; show video ; hide video2 ; + hide video3 ; show applyChanges ; hide player ; hide vidrestart_yes_button ; diff --git a/codemp/CMakeLists.txt b/codemp/CMakeLists.txt index 7bec282d29..45f5493881 100644 --- a/codemp/CMakeLists.txt +++ b/codemp/CMakeLists.txt @@ -49,6 +49,11 @@ if(BuildMPRdVulkan) endif(BuildMPRdVulkan) +# Add rend2 JKA Renderer Project +if(BuildMPRend2) + add_subdirectory("${MPDir}/rd-rend2") +endif(BuildMPRend2) + # Common things between Engine and Dedicated Server if(BuildMPEngine OR BuildMPDed) @@ -264,11 +269,11 @@ if(BuildMPEngine OR BuildMPDed) ${SharedCommonFiles} ) - + if(MSVC) #dunno how to do this for other compilers set_source_files_properties(${MPDir}/qcommon/cm_polylib.cpp PROPERTIES COMPILE_FLAGS /arch:IA32) endif(MSVC) - + if(WIN32) set(MPEngineAndDedCommonFiles ${MPEngineAndDedCommonFiles}) endif(WIN32) @@ -370,7 +375,7 @@ if(BuildMPEngine) find_package(OpenGL REQUIRED) set(MPEngineIncludeDirectories ${MPEngineIncludeDirectories} ${OPENGL_INCLUDE_DIR}) set(MPEngineLibraries ${MPEngineLibraries} ${OPENGL_LIBRARIES}) - + if(BuildDiscordRichPresence) if (APPLE) set(MPEngineIncludeDirectories ${MPEngineIncludeDirectories} ${OpenJKLibDir}/discord-rpc/include) @@ -399,7 +404,7 @@ if(BuildMPEngine) set(MPEngineIncludeDirectories ${MPEngineIncludeDirectories} ${OPENAL_INCLUDE_DIR}) set(MPEngineLibraries ${MPEngineLibraries} ${OPENAL_LIBRARY}) endif(UseInternalOpenAL) - + if(BuildDiscordRichPresence) set(MPEngineIncludeDirectories ${MPEngineIncludeDirectories} ${OpenJKLibDir}/discord-rpc/include) set(MPEngineDefines ${MPEngineDefines} "DISCORD") diff --git a/codemp/ghoul2/G2_gore.cpp b/codemp/ghoul2/G2_gore.cpp index f821093e91..ecc90dba8d 100644 --- a/codemp/ghoul2/G2_gore.cpp +++ b/codemp/ghoul2/G2_gore.cpp @@ -23,6 +23,8 @@ along with this program; if not, see . #include "G2_gore.h" #include "../rd-common/tr_common.h" +#ifdef _G2_GORE + GoreTextureCoordinates::GoreTextureCoordinates() { Com_Memset (tex, 0, sizeof (tex)); @@ -39,3 +41,5 @@ GoreTextureCoordinates::~GoreTextureCoordinates() } } } + +#endif \ No newline at end of file diff --git a/codemp/ghoul2/ghoul2_shared.h b/codemp/ghoul2/ghoul2_shared.h index f20fa75c54..347850bee9 100644 --- a/codemp/ghoul2/ghoul2_shared.h +++ b/codemp/ghoul2/ghoul2_shared.h @@ -54,19 +54,17 @@ struct surfaceInfo_t int genPolySurfaceIndex; // used to point back to the original surface and poly if this is a generated surface int genLod; // used to determine original lod of original surface and poly hit location -surfaceInfo_t(): - offFlags(0), - surface(0), - genBarycentricJ(0), - genBarycentricI(0), - genPolySurfaceIndex(0), - genLod(0) - {} - + surfaceInfo_t() + : offFlags(0) + , surface(0) + , genBarycentricJ(0) + , genBarycentricI(0) + , genPolySurfaceIndex(0) + , genLod(0) + { + } }; - - #define MDXABONEDEF // used in the mdxformat.h file to stop redefinitions of the bone struct. // we save the whole structure here. @@ -153,26 +151,24 @@ struct boneInfo_t int airTime; //base is in air, be more quick and sensitive about collisions //rww - RAGDOLL_END -boneInfo_t(): - boneNumber(-1), - flags(0), - startFrame(0), - endFrame(0), - startTime(0), - pauseTime(0), - animSpeed(0), - blendFrame(0), - blendLerpFrame(0), - blendTime(0), - blendStart(0), - boneBlendTime(0), - boneBlendStart(0), - lastTime(0), - RagFlags(0) + boneInfo_t() + : boneNumber(-1) + , flags(0) + , startFrame(0) + , endFrame(0) + , startTime(0) + , pauseTime(0) + , animSpeed(0) + , blendFrame(0) + , blendLerpFrame(0) + , blendTime(0) + , blendStart(0) + , boneBlendTime(0) + , boneBlendStart(0) + , lastTime(0) + , RagFlags(0) { - matrix.matrix[0][0] = matrix.matrix[0][1] = matrix.matrix[0][2] = matrix.matrix[0][3] = - matrix.matrix[1][0] = matrix.matrix[1][1] = matrix.matrix[1][2] = matrix.matrix[1][3] = - matrix.matrix[2][0] = matrix.matrix[2][1] = matrix.matrix[2][2] = matrix.matrix[2][3] = 0.0f; + Com_Memset(&matrix, 0, sizeof(matrix)); } }; diff --git a/codemp/qcommon/qfiles.h b/codemp/qcommon/qfiles.h index 98a6e4d7e8..423c15de18 100644 --- a/codemp/qcommon/qfiles.h +++ b/codemp/qcommon/qfiles.h @@ -169,6 +169,130 @@ typedef struct md3Header_s { int ofsEnd; // end of file } md3Header_t; +/* +============================================================================== + +MDR file format + +============================================================================== +*/ + +/* + * Here are the definitions for Ravensoft's model format of md4. Raven stores their + * playermodels in .mdr files, in some games, which are pretty much like the md4 + * format implemented by ID soft. It seems like ID's original md4 stuff is not used at all. + * MDR is being used in EliteForce, JediKnight2 and Soldiers of Fortune2 (I think). + * So this comes in handy for anyone who wants to make it possible to load player + * models from these games. + * This format has bone tags, which is similar to the thing you have in md3 I suppose. + * Raven has released their version of md3view under GPL enabling me to add support + * to this codebase. Thanks to Steven Howes aka Skinner for helping with example + * source code. + * + * - Thilo Schulz (arny@ats.s.bawue.de) + */ + +#define MDR_IDENT (('5'<<24)+('M'<<16)+('D'<<8)+'R') +#define MDR_VERSION 2 +#define MDR_MAX_BONES 128 + +typedef struct { + int boneIndex; // these are indexes into the boneReferences, + float boneWeight; // not the global per-frame bone list + vec3_t offset; +} mdrWeight_t; + +typedef struct { + vec3_t normal; + vec2_t texCoords; + int numWeights; + mdrWeight_t weights[1]; // variable sized +} mdrVertex_t; + +typedef struct { + int indexes[3]; +} mdrTriangle_t; + +typedef struct { + int ident; + + char name[MAX_QPATH]; // polyset name + char shader[MAX_QPATH]; + int shaderIndex; // for in-game use + + int ofsHeader; // this will be a negative number + + int numVerts; + int ofsVerts; + + int numTriangles; + int ofsTriangles; + + // Bone references are a set of ints representing all the bones + // present in any vertex weights for this surface. This is + // needed because a model may have surfaces that need to be + // drawn at different sort times, and we don't want to have + // to re-interpolate all the bones for each surface. + int numBoneReferences; + int ofsBoneReferences; + + int ofsEnd; // next surface follows +} mdrSurface_t; + +typedef struct { + float matrix[3][4]; +} mdrBone_t; + +typedef struct { + vec3_t bounds[2]; // bounds of all surfaces of all LOD's for this frame + vec3_t localOrigin; // midpoint of bounds, used for sphere cull + float radius; // dist from localOrigin to corner + char name[16]; + mdrBone_t bones[1]; // [numBones] +} mdrFrame_t; + +typedef struct { + unsigned char Comp[24]; // MC_COMP_BYTES is in MatComp.h, but don't want to couple +} mdrCompBone_t; + +typedef struct { + vec3_t bounds[2]; // bounds of all surfaces of all LOD's for this frame + vec3_t localOrigin; // midpoint of bounds, used for sphere cull + float radius; // dist from localOrigin to corner + mdrCompBone_t bones[1]; // [numBones] +} mdrCompFrame_t; + +typedef struct { + int numSurfaces; + int ofsSurfaces; // first surface, others follow + int ofsEnd; // next lod follows +} mdrLOD_t; + +typedef struct { + int boneIndex; + char name[32]; +} mdrTag_t; + +typedef struct { + int ident; + int version; + + char name[MAX_QPATH]; // model name + + // frames and bones are shared by all levels of detail + int numFrames; + int numBones; + int ofsFrames; // mdrFrame_t[numFrames] + + // each level of detail has completely separate sets of surfaces + int numLODs; + int ofsLODs; + + int numTags; + int ofsTags; + + int ofsEnd; // end of file +} mdrHeader_t; /* ============================================================================== diff --git a/codemp/rd-common/tr_types.h b/codemp/rd-common/tr_types.h index 746b27ce8b..4ec970178c 100644 --- a/codemp/rd-common/tr_types.h +++ b/codemp/rd-common/tr_types.h @@ -343,7 +343,8 @@ typedef int stereoFrame_t; typedef enum { // r_ext_preferred_tc_method TC_NONE, TC_S3TC, - TC_S3TC_DXT + TC_S3TC_DXT, + TC_S3TC_ARB } textureCompression_t; typedef struct glconfig_s { diff --git a/codemp/rd-dedicated/G2_API.cpp b/codemp/rd-dedicated/G2_API.cpp index c95a0edc69..2555cf05f3 100644 --- a/codemp/rd-dedicated/G2_API.cpp +++ b/codemp/rd-dedicated/G2_API.cpp @@ -2485,6 +2485,11 @@ qboolean G2API_SkinlessModel(CGhoul2Info_v& ghoul2, int modelIndex) return qtrue; } +int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) +{ + return ghoul2.size(); +} + //#ifdef _SOF2 #ifdef _G2_GORE void ResetGoreTag(); // put here to reduce coupling @@ -2521,11 +2526,6 @@ void G2API_ClearSkinGore ( CGhoul2Info_v &ghoul2 ) } } -int G2API_Ghoul2Size ( CGhoul2Info_v &ghoul2 ) -{ - return ghoul2.size(); -} - extern int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod); void G2API_AddSkinGore(CGhoul2Info_v &ghoul2,SSkinGoreData &gore) { diff --git a/codemp/rd-dedicated/G2_misc.cpp b/codemp/rd-dedicated/G2_misc.cpp index 1bcec8e457..96a58fae32 100644 --- a/codemp/rd-dedicated/G2_misc.cpp +++ b/codemp/rd-dedicated/G2_misc.cpp @@ -26,11 +26,10 @@ along with this program; if not, see . #include "server/server.h" #include "ghoul2/g2_local.h" +#include "tr_local.h" #ifdef _G2_GORE #include "ghoul2/G2_gore.h" -#include "tr_local.h" - #define GORE_TAG_UPPER (256) #define GORE_TAG_MASK (~255) @@ -549,6 +548,7 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, vec3_t correctScale; qboolean firstModelOnly = qfalse; +#ifdef _G2_GORE if ( cg_g2MarksAllModels == NULL ) { cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "" ); @@ -559,7 +559,7 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, { firstModelOnly = qtrue; } - +#endif VectorCopy(scale, correctScale); // check for scales of 0 - that's the default I believe @@ -1497,6 +1497,7 @@ void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, Colli shader_t *cust_shader; qboolean firstModelOnly = qfalse; +#ifdef _G2_GORE if ( cg_g2MarksAllModels == NULL ) { cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "" ); @@ -1507,6 +1508,7 @@ void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, Colli { firstModelOnly = qtrue; } +#endif // walk each possible model for this entity and try tracing against it for (i=0; i + +#ifdef _MSC_VER +#pragma warning (push, 3) //go back down to 3 for the stl include +#endif +#include +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +#ifdef _FULL_G2_LEAK_CHECKING +int g_Ghoul2Allocations = 0; +int g_G2ServerAlloc = 0; +int g_G2ClientAlloc = 0; +int g_G2AllocServer = 0; + +//stupid debug crap to track leaks in case they happen. +//we used to shove everything into a map and delete it all and not care about +//leaks, but that was not the Right Thing. -rww +#define MAX_TRACKED_ALLOC 4096 +static bool g_G2AllocTrackInit = false; //want to keep this thing contained +static CGhoul2Info_v *g_G2AllocTrack[MAX_TRACKED_ALLOC]; + +void G2_DEBUG_InitPtrTracker(void) +{ + memset(g_G2AllocTrack, 0, sizeof(g_G2AllocTrack)); + g_G2AllocTrackInit = true; +} + +void G2_DEBUG_ReportLeaks(void) +{ + int i = 0; + + if (!g_G2AllocTrackInit) + { + Com_Printf("g2 leak tracker was never initialized!\n"); + return; + } + + while (i < MAX_TRACKED_ALLOC) + { + if (g_G2AllocTrack[i]) + { + Com_Printf("Bad guy found in slot %i, attempting to access...", i); + CGhoul2Info_v &g2v = *g_G2AllocTrack[i]; + CGhoul2Info &g2 = g2v[0]; + + if (g2v.IsValid() && g2.mFileName && g2.mFileName[0]) + { + Com_Printf("Bad guy's filename is %s\n", g2.mFileName); + } + else + { + Com_Printf("He's not valid! BURN HIM!\n"); + } + } + i++; + } +} + +void G2_DEBUG_ShovePtrInTracker(CGhoul2Info_v *g2) +{ + int i = 0; + + if (!g_G2AllocTrackInit) + { + G2_DEBUG_InitPtrTracker(); + } + + if (!g_G2AllocTrackInit) + { + G2_DEBUG_InitPtrTracker(); + } + + while (i < MAX_TRACKED_ALLOC) + { + if (!g_G2AllocTrack[i]) + { + g_G2AllocTrack[i] = g2; + return; + } + i++; + } + + CGhoul2Info_v &g2v = *g2; + + if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) + { + Com_Printf("%s could not be fit into g2 debug instance tracker.\n", g2v[0].currentModel->name); + } + else + { + Com_Printf("Crap g2 instance passed to instance tracker (in).\n"); + } +} + +void G2_DEBUG_RemovePtrFromTracker(CGhoul2Info_v *g2) +{ + int i = 0; + + if (!g_G2AllocTrackInit) + { + G2_DEBUG_InitPtrTracker(); + } + + while (i < MAX_TRACKED_ALLOC) + { + if (g_G2AllocTrack[i] == g2) + { + g_G2AllocTrack[i] = NULL; + return; + } + i++; + } + + CGhoul2Info_v &g2v = *g2; + + if (g2v[0].currentModel && g2v[0].currentModel->name && g2v[0].currentModel->name[0]) + { + Com_Printf("%s not in g2 debug instance tracker.\n", g2v[0].currentModel->name); + } + else + { + Com_Printf("Crap g2 instance passed to instance tracker (out).\n"); + } +} +#endif + +qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo); +qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2); +qboolean G2_TestModelPointers(CGhoul2Info *ghlInfo); + +//rww - RAGDOLL_BEGIN +#define NUM_G2T_TIME (2) +static int G2TimeBases[NUM_G2T_TIME]; + +void G2API_SetTime(int currentTime,int clock) +{ + assert(clock>=0&&clockG2TimeBases[0]+200) + { + G2TimeBases[1]=0; // use server time instead + return; + } +#if G2_DEBUG_TIME + Com_Printf(" after c%6d s%6d\n",G2TimeBases[1],G2TimeBases[0]); +#endif +} + +int G2API_GetTime(int argTime) // this may or may not return arg depending on ghoul2_time cvar +{ + int ret=G2TimeBases[1]; + if ( !ret ) + { + ret = G2TimeBases[0]; + } + + return ret; +} +//rww - RAGDOLL_END + +//rww - Stuff to allow association of ghoul2 instances to entity numbers. +//This way, on listen servers when both the client and server are doing +//ghoul2 operations, we can copy relevant data off the client instance +//directly onto the server instance and slash the transforms and whatnot +//right in half. +#ifdef _G2_LISTEN_SERVER_OPT +CGhoul2Info_v *g2ClientAttachments[MAX_GENTITIES]; +#endif + +void G2API_AttachInstanceToEntNum(CGhoul2Info_v &ghoul2, int entityNum, qboolean server) +{ //Assign the pointers in the arrays +#ifdef _G2_LISTEN_SERVER_OPT + if (server) + { + ghoul2[0].entityNum = entityNum; + } + else + { + g2ClientAttachments[entityNum] = &ghoul2; + } +#endif +} + +void G2API_ClearAttachedInstance(int entityNum) +{ +#ifdef _G2_LISTEN_SERVER_OPT + g2ClientAttachments[entityNum] = NULL; +#endif +} + +void G2API_CleanEntAttachments(void) +{ +#ifdef _G2_LISTEN_SERVER_OPT + int i = 0; + + while (i < MAX_GENTITIES) + { + g2ClientAttachments[i] = NULL; + i++; + } +#endif +} + +#ifdef _G2_LISTEN_SERVER_OPT +void CopyBoneCache(CBoneCache *to, CBoneCache *from); +#endif + +qboolean G2API_OverrideServerWithClientData(CGhoul2Info_v& ghoul2, int modelIndex) +{ +#ifndef _G2_LISTEN_SERVER_OPT + return qfalse; +#else + CGhoul2Info *serverInstance = &ghoul2[modelIndex]; + CGhoul2Info *clientInstance; + + if (ri.Cvar_VariableIntegerValue( "dedicated" )) + { //No client to get from! + return qfalse; + } + + if (!g2ClientAttachments[serverInstance->entityNum]) + { //No clientside instance is attached to this entity + return qfalse; + } + + CGhoul2Info_v &g2Ref = *g2ClientAttachments[serverInstance->entityNum]; + clientInstance = &g2Ref[0]; + + int frameNum = G2API_GetTime(0); + + if (clientInstance->mSkelFrameNum != frameNum) + { //it has to be constructed already + return qfalse; + } + + if (!clientInstance->mBoneCache) + { //that just won't do + return qfalse; + } + + //Just copy over the essentials + serverInstance->aHeader = clientInstance->aHeader; + serverInstance->animModel = clientInstance->animModel; + serverInstance->currentAnimModelSize = clientInstance->currentAnimModelSize; + serverInstance->currentModel = clientInstance->currentModel; + serverInstance->currentModelSize = clientInstance->currentModelSize; + serverInstance->mAnimFrameDefault = clientInstance->mAnimFrameDefault; + serverInstance->mModel = clientInstance->mModel; + serverInstance->mModelindex = clientInstance->mModelindex; + serverInstance->mSurfaceRoot = clientInstance->mSurfaceRoot; + serverInstance->mTransformedVertsArray = clientInstance->mTransformedVertsArray; + + if (!serverInstance->mBoneCache) + { //if this is the case.. I guess we can use the client one instead + serverInstance->mBoneCache = clientInstance->mBoneCache; + } + + //Copy the contents of the client cache over the contents of the server cache + if (serverInstance->mBoneCache != clientInstance->mBoneCache) + { + CopyBoneCache(serverInstance->mBoneCache, clientInstance->mBoneCache); + } + + serverInstance->mSkelFrameNum = clientInstance->mSkelFrameNum; + return qtrue; +#endif +} + +// must be a power of two +#define MAX_G2_MODELS (1024) +#define G2_MODEL_BITS (10) + +#define G2_INDEX_MASK (MAX_G2_MODELS-1) + +static size_t GetSizeOfGhoul2Info ( const CGhoul2Info& g2Info ) +{ + size_t size = 0; + + // This is pretty ugly, but we don't want to save everything in the CGhoul2Info object. + size += offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); + + // Surface vector + size + size += sizeof (int); + size += g2Info.mSlist.size() * sizeof (surfaceInfo_t); + + // Bone vector + size + size += sizeof (int); + size += g2Info.mBlist.size() * sizeof (boneInfo_t); + + // Bolt vector + size + size += sizeof (int); + size += g2Info.mBltlist.size() * sizeof (boltInfo_t); + + return size; +} + +static size_t SerializeGhoul2Info ( char *buffer, const CGhoul2Info& g2Info ) +{ + char *base = buffer; + size_t blockSize; + + // Oh the ugliness... + blockSize = offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); + memcpy (buffer, &g2Info.mModelindex, blockSize); + buffer += blockSize; + + // Surfaces vector + size + *(int *)buffer = g2Info.mSlist.size(); + buffer += sizeof (int); + + blockSize = g2Info.mSlist.size() * sizeof (surfaceInfo_t); + memcpy (buffer, g2Info.mSlist.data(), g2Info.mSlist.size() * sizeof (surfaceInfo_t)); + buffer += blockSize; + + // Bones vector + size + *(int *)buffer = g2Info.mBlist.size(); + buffer += sizeof (int); + + blockSize = g2Info.mBlist.size() * sizeof (boneInfo_t); + memcpy (buffer, g2Info.mBlist.data(), g2Info.mBlist.size() * sizeof (boneInfo_t)); + buffer += blockSize; + + // Bolts vector + size + *(int *)buffer = g2Info.mBltlist.size(); + buffer += sizeof (int); + + blockSize = g2Info.mBltlist.size() * sizeof (boltInfo_t); + memcpy (buffer, g2Info.mBltlist.data(), g2Info.mBltlist.size() * sizeof (boltInfo_t)); + buffer += blockSize; + + return static_cast(buffer - base); +} + +static size_t DeserializeGhoul2Info ( const char *buffer, CGhoul2Info& g2Info ) +{ + const char *base = buffer; + size_t size; + + size = offsetof (CGhoul2Info, mTransformedVertsArray) - offsetof (CGhoul2Info, mModelindex); + memcpy (&g2Info.mModelindex, buffer, size); + buffer += size; + + // Surfaces vector + size = *(int *)buffer; + buffer += sizeof (int); + + g2Info.mSlist.assign ((surfaceInfo_t *)buffer, (surfaceInfo_t *)buffer + size); + buffer += sizeof (surfaceInfo_t) * size; + + // Bones vector + size = *(int *)buffer; + buffer += sizeof (int); + + g2Info.mBlist.assign ((boneInfo_t *)buffer, (boneInfo_t *)buffer + size); + buffer += sizeof (boneInfo_t) * size; + + // Bolt vector + size = *(int *)buffer; + buffer += sizeof (int); + + g2Info.mBltlist.assign ((boltInfo_t *)buffer, (boltInfo_t *)buffer + size); + buffer += sizeof (boltInfo_t) * size; + + return static_cast(buffer - base); +} + +class Ghoul2InfoArray : public IGhoul2InfoArray +{ + std::vector mInfos[MAX_G2_MODELS]; + int mIds[MAX_G2_MODELS]; + std::list mFreeIndecies; + void DeleteLow(int idx) + { + for (size_t model=0; model< mInfos[idx].size(); model++) + { + if (mInfos[idx][model].mBoneCache) + { + RemoveBoneCache(mInfos[idx][model].mBoneCache); + mInfos[idx][model].mBoneCache=0; + } + } + + mInfos[idx].clear(); + + if ((mIds[idx]>>G2_MODEL_BITS)>(1<<(31-G2_MODEL_BITS))) + { + mIds[idx]=MAX_G2_MODELS+idx; //rollover reset id to minimum value + mFreeIndecies.push_back(idx); + } + else + { + mIds[idx]+=MAX_G2_MODELS; + mFreeIndecies.push_front(idx); + } + } +public: + Ghoul2InfoArray() + { + int i; + for (i=0;i(buffer - base); + } + + size_t Deserialize ( const char *buffer, size_t size ) + { + const char *base = buffer; + size_t count; + + // Free indices + count = *(int *)buffer; + buffer += sizeof (int); + + mFreeIndecies.assign ((int *)buffer, (int *)buffer + count); + buffer += sizeof (int) * count; + + // IDs + memcpy (mIds, buffer, sizeof (mIds)); + buffer += sizeof (mIds); + + // Ghoul2 infos + for ( size_t i = 0; i < MAX_G2_MODELS; i++ ) + { + mInfos[i].clear(); + + count = *(int *)buffer; + buffer += sizeof (int); + + mInfos[i].resize (count); + + for ( size_t j = 0; j < count; j++ ) + { + buffer += DeserializeGhoul2Info (buffer, mInfos[i][j]); + } + } + + return static_cast(buffer - base); + } + +#if G2API_DEBUG + ~Ghoul2InfoArray() + { + char mess[1000]; + if (mFreeIndecies.size()::iterator j; + for (j=mFreeIndecies.begin();j!=mFreeIndecies.end();j++) + { + if (*j==i) + break; + } + if (j==mFreeIndecies.end()) + { + sprintf(mess,"Leaked Info idx=%d id=%d sz=%d\n", i, mIds[i], mInfos[i].size()); + OutputDebugString(mess); + if (mInfos[i].size()) + { + sprintf(mess,"%s\n", mInfos[i][0].mFileName); + OutputDebugString(mess); + } + } + } + } + else + { + OutputDebugString("No ghoul2 info slots leaked\n"); + } + } +#endif + int New() + { + if (mFreeIndecies.empty()) + { + assert(0); + Com_Error(ERR_FATAL, "Out of ghoul2 info slots"); + + } + // gonna pull from the front, doing a + int idx=*mFreeIndecies.begin(); + mFreeIndecies.erase(mFreeIndecies.begin()); + return mIds[idx]; + } + bool IsValid(int handle) const + { + if ( handle <= 0 ) + { + return false; + } + assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)=0&&(handle&G2_INDEX_MASK) &Get(int handle) + { + assert(handle>0); //null handle + assert((handle&G2_INDEX_MASK)>=0&&(handle&G2_INDEX_MASK)=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle)); + + return mInfos[handle&G2_INDEX_MASK]; + } + const std::vector &Get(int handle) const + { + assert(handle>0); + assert(mIds[handle&G2_INDEX_MASK]==handle); // not a valid handle, could be old or garbage + return mInfos[handle&G2_INDEX_MASK]; + } + +#if G2API_DEBUG + vector &GetDebug(int handle) + { + static vector null; + if (handle<=0||(handle&G2_INDEX_MASK)<0||(handle&G2_INDEX_MASK)>=MAX_G2_MODELS||mIds[handle&G2_INDEX_MASK]!=handle) + { + return *(vector *)0; // null reference, intentional + } + return mInfos[handle&G2_INDEX_MASK]; + } + void TestAllAnims() + { + int j; + for (j=0;j &ghoul2=mInfos[j]; + int i; + for (i=0; iDeserialize ((const char *)data, size); + Z_Free ((void *)data); + + assert (read == size); + } +} + +void SaveGhoul2InfoArray() +{ + size_t size = singleton->GetSerializedSize(); + void *data = Z_Malloc (size, TAG_GHOUL2); + size_t written = singleton->Serialize ((char *)data); + + assert (written == size); + + if ( !ri.PD_Store (PERSISTENT_G2DATA, data, size) ) + { + Com_Printf (S_COLOR_RED "ERROR: Failed to store persistent renderer data.\n"); + } +} + +void Ghoul2InfoArray_Free(void) +{ + if(singleton) { + delete singleton; + singleton = NULL; + } +} + +// this is the ONLY function to read entity states directly +void G2API_CleanGhoul2Models(CGhoul2Info_v **ghoul2Ptr) +{ + if (*ghoul2Ptr) + { + CGhoul2Info_v &ghoul2 = *(*ghoul2Ptr); + +#if 0 //rwwFIXMEFIXME: Disable this before release!!!!!! I am just trying to find a crash bug. + extern int R_GetRNumEntities(void); + extern void R_SetRNumEntities(int num); + //check if this instance is actually on a refentity + int i = 0; + int r = R_GetRNumEntities(); + + while (i < r) + { + if ((CGhoul2Info_v *)backEndData->entities[i].e.ghoul2 == *ghoul2Ptr) + { + char fName[MAX_QPATH]; + char mName[MAX_QPATH]; + + if (ghoul2[0].currentModel) + { + strcpy(mName, ghoul2[0].currentModel->name); + } + else + { + strcpy(mName, "NULL!"); + } + + if (ghoul2[0].mFileName && ghoul2[0].mFileName[0]) + { + strcpy(fName, ghoul2[0].mFileName); + } + else + { + strcpy(fName, "None?!"); + } + + Com_Printf("ERROR, GHOUL2 INSTANCE BEING REMOVED BELONGS TO A REFENTITY!\nThis is in caps because it's important. Tell Rich and save the following text.\n\n"); + Com_Printf("Ref num: %i\nModel: %s\nFilename: %s\n", i, mName, fName); + + R_SetRNumEntities(0); //avoid recursive error + Com_Error(ERR_DROP, "Write down or save this error message, show it to Rich\nRef num: %i\nModel: %s\nFilename: %s\n", i, mName, fName); + } + i++; + } +#endif + +#ifdef _G2_GORE + G2API_ClearSkinGore ( ghoul2 ); +#endif + +#ifdef _FULL_G2_LEAK_CHECKING + if (g_G2AllocServer) + { + g_G2ServerAlloc -= sizeof(*ghoul2Ptr); + } + else + { + g_G2ClientAlloc -= sizeof(*ghoul2Ptr); + } + g_Ghoul2Allocations -= sizeof(*ghoul2Ptr); + G2_DEBUG_RemovePtrFromTracker(*ghoul2Ptr); +#endif + + delete *ghoul2Ptr; + *ghoul2Ptr = NULL; + } +} + +qboolean G2_ShouldRegisterServer(void) +{ + vm_t *currentVM = ri.GetCurrentVM(); + + if ( currentVM && currentVM->slot == VM_GAME ) + { + if ( ri.Cvar_VariableIntegerValue( "cl_running" ) && + ri.Com_TheHunkMarkHasBeenMade() && ShaderHashTableExists()) + { //if the hunk has been marked then we are now loading client assets so don't load on server. + return qfalse; + } + + return qtrue; + } + return qfalse; +} + +qhandle_t G2API_PrecacheGhoul2Model( const char *fileName ) +{ + if ( G2_ShouldRegisterServer() ) + return RE_RegisterServerModel( fileName ); + else + return RE_RegisterModel( fileName ); +} + +void CL_InitRef( void ); + +// initialise all that needs to be on a new Ghoul II model +int G2API_InitGhoul2Model(CGhoul2Info_v **ghoul2Ptr, const char *fileName, int modelIndex, qhandle_t customSkin, + qhandle_t customShader, int modelFlags, int lodBias) +{ + int model; + CGhoul2Info newModel; + + // are we actually asking for a model to be loaded. + if (!fileName || !fileName[0]) + { + assert(0); + return -1; + } + + if (!(*ghoul2Ptr)) + { + *ghoul2Ptr = new CGhoul2Info_v; +#ifdef _FULL_G2_LEAK_CHECKING + if (g_G2AllocServer) + { + g_G2ServerAlloc += sizeof(CGhoul2Info_v); + } + else + { + g_G2ClientAlloc += sizeof(CGhoul2Info_v); + } + g_Ghoul2Allocations += sizeof(CGhoul2Info_v); + G2_DEBUG_ShovePtrInTracker(*ghoul2Ptr); +#endif + } + + CGhoul2Info_v &ghoul2 = *(*ghoul2Ptr); + + // find a free spot in the list + for (model=0; model< ghoul2.size(); model++) + { + if (ghoul2[model].mModelindex == -1) + { + ghoul2[model]=CGhoul2Info(); + break; + } + } + if (model==ghoul2.size()) + { //init should not be used to create additional models, only the first one + assert(ghoul2.size() < 4); //use G2API_CopySpecificG2Model to add models + ghoul2.push_back(CGhoul2Info()); + } + + strcpy(ghoul2[model].mFileName, fileName); + ghoul2[model].mModelindex = model; + if (!G2_TestModelPointers(&ghoul2[model])) + { + ghoul2[model].mFileName[0]=0; + ghoul2[model].mModelindex = -1; + } + else + { + G2_Init_Bone_List(ghoul2[model].mBlist, ghoul2[model].aHeader->numBones); + G2_Init_Bolt_List(ghoul2[model].mBltlist); + ghoul2[model].mCustomShader = customShader; + ghoul2[model].mCustomSkin = customSkin; + ghoul2[model].mLodBias = lodBias; + ghoul2[model].mAnimFrameDefault = 0; + ghoul2[model].mFlags = 0; + + ghoul2[model].mModelBoltLink = -1; + } + return ghoul2[model].mModelindex; +} + +qboolean G2API_SetLodBias(CGhoul2Info *ghlInfo, int lodBias) +{ + if (ghlInfo) + { + ghlInfo->mLodBias = lodBias; + return qtrue; + } + return qfalse; +} + +void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin); +qboolean G2API_SetSkin(CGhoul2Info_v& ghoul2, int modelIndex, qhandle_t customSkin, qhandle_t renderSkin) +{ + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + + if (ghlInfo) + { + ghlInfo->mCustomSkin = customSkin; + if (renderSkin) + {//this is going to set the surfs on/off matching the skin file + G2_SetSurfaceOnOffFromSkin( ghlInfo, renderSkin ); + } + + return qtrue; + } + return qfalse; +} + +qboolean G2API_SetShader(CGhoul2Info *ghlInfo, qhandle_t customShader) +{ + if (ghlInfo) + { + ghlInfo->mCustomShader = customShader; + return qtrue; + } + return qfalse; +} + +qboolean G2API_SetSurfaceOnOff(CGhoul2Info_v &ghoul2, const char *surfaceName, const int flags) +{ + CGhoul2Info *ghlInfo = NULL; + + if (ghoul2.size()>0) + { + ghlInfo = &ghoul2[0]; + } + + if (G2_SetupModelPointers(ghlInfo)) + { + // ensure we flush the cache + ghlInfo->mMeshFrameNum = 0; + return G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, surfaceName, flags); + } + return qfalse; +} + +int G2API_GetSurfaceOnOff(CGhoul2Info *ghlInfo, const char *surfaceName) +{ + if (ghlInfo) + { + return G2_IsSurfaceOff(ghlInfo, ghlInfo->mSlist, surfaceName); + } + return -1; +} + +qboolean G2API_SetRootSurface(CGhoul2Info_v &ghoul2, const int modelIndex, const char *surfaceName) +{ + if (G2_SetupModelPointers(ghoul2)) + { + return G2_SetRootSurface(ghoul2, modelIndex, surfaceName); + } + + return qfalse; +} + +int G2API_AddSurface(CGhoul2Info *ghlInfo, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + // ensure we flush the cache + ghlInfo->mMeshFrameNum = 0; + return G2_AddSurface(ghlInfo, surfaceNumber, polyNumber, BarycentricI, BarycentricJ, lod); + } + return -1; +} + +qboolean G2API_RemoveSurface(CGhoul2Info *ghlInfo, const int index) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + // ensure we flush the cache + ghlInfo->mMeshFrameNum = 0; + return G2_RemoveSurface(ghlInfo->mSlist, index); + } + return qfalse; +} + +int G2API_GetParentSurface(CGhoul2Info *ghlInfo, const int index) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_GetParentSurface(ghlInfo, index); + } + return -1; +} + +int G2API_GetSurfaceRenderStatus(CGhoul2Info_v& ghoul2, int modelIndex, const char *surfaceName) +{ + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_IsSurfaceRendered(ghlInfo, surfaceName, ghlInfo->mSlist); + } + return -1; +} + +qboolean G2API_HasGhoul2ModelOnIndex(CGhoul2Info_v **ghlRemove, const int modelIndex) +{ + CGhoul2Info_v &ghlInfo = **ghlRemove; + + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) + { + return qfalse; + } + + return qtrue; +} + +qboolean G2API_RemoveGhoul2Model(CGhoul2Info_v **ghlRemove, const int modelIndex) +{ + CGhoul2Info_v &ghlInfo = **ghlRemove; + + // sanity check + if (!ghlInfo.size() || (ghlInfo.size() <= modelIndex) || (ghlInfo[modelIndex].mModelindex == -1)) + { + // if we hit this assert then we are trying to delete a ghoul2 model on a ghoul2 instance that + // one way or another is already gone. + assert(0); + return qfalse; + } + + if (ghlInfo.size() > modelIndex) + { +#ifdef _G2_GORE + // Cleanup the gore attached to this model + if ( ghlInfo[modelIndex].mGoreSetTag ) + { + DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + ghlInfo[modelIndex].mGoreSetTag = 0; + } +#endif + + if (ghlInfo[modelIndex].mBoneCache) + { + RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); + ghlInfo[modelIndex].mBoneCache=0; + } + + // clear out the vectors this model used. + ghlInfo[modelIndex].mBlist.clear(); + ghlInfo[modelIndex].mBltlist.clear(); + ghlInfo[modelIndex].mSlist.clear(); + + // set us to be the 'not active' state + ghlInfo[modelIndex].mModelindex = -1; + + int newSize = ghlInfo.size(); + // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list + for (int i=ghlInfo.size()-1; i>-1; i--) + { + if (ghlInfo[i].mModelindex == -1) + { + newSize = i; + } + // once we hit one that isn't a -1, we are done. + else + { + break; + } + } + // do we need to resize? + if (newSize != ghlInfo.size()) + { + // yes, so lets do it + ghlInfo.resize(newSize); + } + + // if we are not using any space, just delete the ghoul2 vector entirely + if (!ghlInfo.size()) + { +#ifdef _FULL_G2_LEAK_CHECKING + if (g_G2AllocServer) + { + g_G2ServerAlloc -= sizeof(*ghlRemove); + } + else + { + g_G2ClientAlloc -= sizeof(*ghlRemove); + } + g_Ghoul2Allocations -= sizeof(*ghlRemove); +#endif + delete *ghlRemove; + *ghlRemove = NULL; + } + } + + + return qtrue; +} + +qboolean G2API_RemoveGhoul2Models(CGhoul2Info_v **ghlRemove) +{//remove 'em ALL! + CGhoul2Info_v &ghlInfo = **ghlRemove; + int modelIndex = 0; + int newSize = 0; + int i; + + // sanity check + if ( !ghlInfo.size() ) + {// if we hit this then we are trying to delete a ghoul2 model on a ghoul2 instance that + // one way or another is already gone. + return qfalse; + } + + for ( modelIndex = 0; modelIndex < ghlInfo.size(); modelIndex++ ) + { + if ( ghlInfo[modelIndex].mModelindex == -1 ) + { + continue; + } +#ifdef _G2_GORE + // Cleanup the gore attached to this model + if ( ghlInfo[modelIndex].mGoreSetTag ) + { + DeleteGoreSet ( ghlInfo[modelIndex].mGoreSetTag ); + ghlInfo[modelIndex].mGoreSetTag = 0; + } +#endif + + if (ghlInfo[modelIndex].mBoneCache) + { + RemoveBoneCache(ghlInfo[modelIndex].mBoneCache); + ghlInfo[modelIndex].mBoneCache=0; + } + + // clear out the vectors this model used. + ghlInfo[modelIndex].mBlist.clear(); + ghlInfo[modelIndex].mBltlist.clear(); + ghlInfo[modelIndex].mSlist.clear(); + + // set us to be the 'not active' state + ghlInfo[modelIndex].mModelindex = -1; + } + + newSize = ghlInfo.size(); + // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list + for (i=ghlInfo.size()-1; i>-1; i--) + { + if (ghlInfo[i].mModelindex == -1) + { + newSize = i; + } + // once we hit one that isn't a -1, we are done. + else + { + break; + } + } + // do we need to resize? + if (newSize != ghlInfo.size()) + { + // yes, so lets do it + ghlInfo.resize(newSize); + } + + // if we are not using any space, just delete the ghoul2 vector entirely + if (!ghlInfo.size()) + { +#ifdef _FULL_G2_LEAK_CHECKING + if (g_G2AllocServer) + { + g_G2ServerAlloc -= sizeof(*ghlRemove); + } + else + { + g_G2ClientAlloc -= sizeof(*ghlRemove); + } + g_Ghoul2Allocations -= sizeof(*ghlRemove); +#endif + delete *ghlRemove; + *ghlRemove = NULL; + } + return qtrue; +} + +//check if a bone exists on skeleton without actually adding to the bone list -rww +qboolean G2API_DoesBoneExist(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName) +{ + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + + if (G2_SetupModelPointers(ghlInfo)) + { //model is valid + mdxaHeader_t *mdxa = ghlInfo->currentModel->data.gla; + if (mdxa) + { //get the skeleton data and iterate through the bones + int i; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + + offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + + for (i = 0; i < mdxa->numBones; i++) + { + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + if (!Q_stricmp(skel->name, boneName)) + { //got it + return qtrue; + } + } + } + } + + //guess it doesn't exist + return qfalse; +} + +//rww - RAGDOLL_BEGIN +#define GHOUL2_RAG_STARTED 0x0010 +#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled +//rww - RAGDOLL_END + +qboolean G2API_SetBoneAnimIndex(CGhoul2Info *ghlInfo, const int index, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) +{ + qboolean setPtrs = qfalse; + qboolean res = qfalse; + + //rww - RAGDOLL_BEGIN + if (ghlInfo) + { + res = G2_SetupModelPointers(ghlInfo); + setPtrs = qtrue; + + if (res) + { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) + { + return qfalse; + } + } + } + //rww - RAGDOLL_END + + int endFrame=AendFrame; + int startFrame=AstartFrame; + float setFrame=AsetFrame; + assert(endFrame>0); + assert(startFrame>=0); + assert(endFrame<100000); + assert(startFrame<100000); + assert(setFrame>=0.0f||setFrame==-1.0f); + assert(setFrame<=100000.0f); + if (endFrame<=0) + { + endFrame=1; + } + if (endFrame>=100000) + { + endFrame=1; + } + if (startFrame<0) + { + startFrame=0; + } + if (startFrame>=100000) + { + startFrame=0; + } + if (setFrame<0.0f&&setFrame!=-1.0f) + { + setFrame=0.0f; + } + if (setFrame>100000.0f) + { + setFrame=0.0f; + } + if (!setPtrs) + { + res = G2_SetupModelPointers(ghlInfo); + } + + if (res) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Set_Bone_Anim_Index(ghlInfo->mBlist, index, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime, ghlInfo->aHeader->numFrames); + } + return qfalse; +} + +#define _PLEASE_SHUT_THE_HELL_UP + +qboolean G2API_SetBoneAnim(CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName, const int AstartFrame, const int AendFrame, const int flags, const float animSpeed, const int currentTime, const float AsetFrame, const int blendTime) +{ + int endFrame=AendFrame; + int startFrame=AstartFrame; + float setFrame=AsetFrame; +#ifndef _PLEASE_SHUT_THE_HELL_UP + assert(endFrame>0); + assert(startFrame>=0); + assert(endFrame<100000); + assert(startFrame<100000); + assert(setFrame>=0.0f||setFrame==-1.0f); + assert(setFrame<=100000.0f); +#endif + if (endFrame<=0) + { + endFrame=1; + } + if (endFrame>=100000) + { + endFrame=1; + } + if (startFrame<0) + { + startFrame=0; + } + if (startFrame>=100000) + { + startFrame=0; + } + if (setFrame<0.0f&&setFrame!=-1.0f) + { + setFrame=0.0f; + } + if (setFrame>100000.0f) + { + setFrame=0.0f; + } + if (ghoul2.size()>modelIndex) + { + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + qboolean setPtrs = qfalse; + qboolean res = qfalse; + + //rww - RAGDOLL_BEGIN + if (ghlInfo) + { + res = G2_SetupModelPointers(ghlInfo); + setPtrs = qtrue; + + if (res) + { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) + { + return qfalse; + } + } + } + //rww - RAGDOLL_END + + if (!setPtrs) + { + res = G2_SetupModelPointers(ghlInfo); + } + + if (res) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Set_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, setFrame, blendTime); + } + } + return qfalse; +} + +qboolean G2API_GetBoneAnim(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName, const int currentTime, float *currentFrame, + int *startFrame, int *endFrame, int *flags, float *animSpeed, int *modelList) +{ + assert(startFrame!=endFrame); //this is bad + assert(startFrame!=flags); //this is bad + assert(endFrame!=flags); //this is bad + assert(currentFrame!=animSpeed); //this is bad + + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + + if (G2_SetupModelPointers(ghlInfo)) + { + int aCurrentTime=G2API_GetTime(currentTime); + qboolean ret=G2_Get_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, aCurrentTime, currentFrame, + startFrame, endFrame, flags, animSpeed, modelList, ghlInfo->mModelindex); +#ifdef _DEBUG + /* + assert(*endFrame>0); + assert(*endFrame<100000); + assert(*startFrame>=0); + assert(*startFrame<100000); + assert(*currentFrame>=0.0f); + assert(*currentFrame<100000.0f); + */ + if (*endFrame<1) + { + *endFrame=1; + } + if (*endFrame>100000) + { + *endFrame=1; + } + if (*startFrame<0) + { + *startFrame=0; + } + if (*startFrame>100000) + { + *startFrame=1; + } + if (*currentFrame<0.0f) + { + *currentFrame=0.0f; + } + if (*currentFrame>100000) + { + *currentFrame=1; + } +#endif + return ret; + } + return qfalse; +} + +qboolean G2API_GetAnimRange(CGhoul2Info *ghlInfo, const char *boneName, int *startFrame, int *endFrame) +{ + assert(startFrame!=endFrame); //this is bad + if (G2_SetupModelPointers(ghlInfo)) + { + qboolean ret=G2_Get_Bone_Anim_Range(ghlInfo, ghlInfo->mBlist, boneName, startFrame, endFrame); +#ifdef _DEBUG + assert(*endFrame>0); + assert(*endFrame<100000); + assert(*startFrame>=0); + assert(*startFrame<100000); + if (*endFrame<1) + { + *endFrame=1; + } + if (*endFrame>100000) + { + *endFrame=1; + } + if (*startFrame<0) + { + *startFrame=0; + } + if (*startFrame>100000) + { + *startFrame=1; + } +#endif + return ret; + } + return qfalse; +} + + +qboolean G2API_PauseBoneAnim(CGhoul2Info *ghlInfo, const char *boneName, const int currentTime) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_Pause_Bone_Anim(ghlInfo, ghlInfo->mBlist, boneName, currentTime); + } + return qfalse; +} + +qboolean G2API_IsPaused(CGhoul2Info *ghlInfo, const char *boneName) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_IsPaused(ghlInfo->mFileName, ghlInfo->mBlist, boneName); + } + return qfalse; +} + +qboolean G2API_StopBoneAnimIndex(CGhoul2Info *ghlInfo, const int index) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_Stop_Bone_Anim_Index(ghlInfo->mBlist, index); + } + return qfalse; +} + +qboolean G2API_StopBoneAnim(CGhoul2Info *ghlInfo, const char *boneName) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_Stop_Bone_Anim(ghlInfo->mFileName, ghlInfo->mBlist, boneName); + } + return qfalse; +} + +qboolean G2API_SetBoneAnglesIndex( + CGhoul2Info *ghlInfo, + const int index, + const vec3_t angles, + const int flags, + const Eorientations yaw, + const Eorientations pitch, + const Eorientations roll, + qhandle_t *modelList, + int blendTime, + int currentTime) +{ + qboolean setPtrs = qfalse; + qboolean res = qfalse; + + if (ghlInfo) + { + res = G2_SetupModelPointers(ghlInfo); + setPtrs = qtrue; + + if (res) + { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) + { + return qfalse; + } + } + } + + if (!setPtrs) + { + res = G2_SetupModelPointers(ghlInfo); + } + + if (res) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Set_Bone_Angles_Index( + ghlInfo->mBlist, + index, + angles, + flags, + yaw, + pitch, + roll, + modelList, + ghlInfo->mModelindex, + blendTime, + currentTime); + } + + return qfalse; +} + +qboolean G2API_SetBoneAngles( + CGhoul2Info_v &ghoul2, + const int modelIndex, + const char *boneName, + const vec3_t angles, + const int flags, + const Eorientations up, + const Eorientations left, + const Eorientations forward, + qhandle_t *modelList, + int blendTime, + int currentTime) +{ + if (ghoul2.size() > modelIndex) + { + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + qboolean setPtrs = qfalse; + qboolean res = qfalse; + + // rww - RAGDOLL_BEGIN + if (ghlInfo) + { + res = G2_SetupModelPointers(ghlInfo); + setPtrs = qtrue; + + if (res) + { + if (ghlInfo->mFlags & GHOUL2_RAG_STARTED) + { + return qfalse; + } + } + } + // rww - RAGDOLL_END + + if (!setPtrs) + { + res = G2_SetupModelPointers(ghoul2); + } + + if (res) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Set_Bone_Angles( + ghlInfo, + ghlInfo->mBlist, + boneName, + angles, + flags, + up, + left, + forward, + modelList, + ghlInfo->mModelindex, + blendTime, + currentTime); + } + } + return qfalse; +} + +qboolean G2API_SetBoneAnglesMatrixIndex( + CGhoul2Info *ghlInfo, + const int index, + const mdxaBone_t &matrix, + const int flags, + qhandle_t *modelList, + int blendTime, + int currentTime) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Set_Bone_Angles_Matrix_Index( + ghlInfo->mBlist, + index, + matrix, + flags, + modelList, + ghlInfo->mModelindex, + blendTime, + currentTime); + } + return qfalse; +} + +qboolean G2API_SetBoneAnglesMatrix( + CGhoul2Info *ghlInfo, + const char *boneName, + const mdxaBone_t &matrix, + const int flags, + qhandle_t *modelList, + int blendTime, + int currentTime) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Set_Bone_Angles_Matrix( + ghlInfo->mFileName, + ghlInfo->mBlist, + boneName, + matrix, + flags, + modelList, + ghlInfo->mModelindex, + blendTime, + currentTime); + } + return qfalse; +} + +qboolean G2API_StopBoneAnglesIndex(CGhoul2Info *ghlInfo, const int index) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Stop_Bone_Angles_Index(ghlInfo->mBlist, index); + } + return qfalse; +} + +qboolean G2API_StopBoneAngles(CGhoul2Info *ghlInfo, const char *boneName) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Stop_Bone_Angles( + ghlInfo->mFileName, ghlInfo->mBlist, boneName); + } + return qfalse; +} + +void G2API_AbsurdSmoothing(CGhoul2Info_v &ghoul2, qboolean status) +{ + assert(ghoul2.size()); + CGhoul2Info *ghlInfo = &ghoul2[0]; + + if (status) + { //turn it on + ghlInfo->mFlags |= GHOUL2_CRAZY_SMOOTH; + } + else + { //off + ghlInfo->mFlags &= ~GHOUL2_CRAZY_SMOOTH; + } +} + +//rww - RAGDOLL_BEGIN +class CRagDollParams; +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms); +void G2API_SetRagDoll(CGhoul2Info_v &ghoul2,CRagDollParams *parms) +{ + G2_SetRagDoll(ghoul2,parms); +} + +void G2_ResetRagDoll(CGhoul2Info_v &ghoul2V); +void G2API_ResetRagDoll(CGhoul2Info_v &ghoul2) +{ + G2_ResetRagDoll(ghoul2); +} +//rww - RAGDOLL_END + +qboolean G2API_RemoveBone(CGhoul2Info_v& ghoul2, int modelIndex, const char *boneName) +{ + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + + if (G2_SetupModelPointers(ghlInfo)) + { + // ensure we flush the cache + ghlInfo->mSkelFrameNum = 0; + return G2_Remove_Bone(ghlInfo, ghlInfo->mBlist, boneName); + } + return qfalse; +} + +//rww - RAGDOLL_BEGIN +#ifdef _DEBUG +extern int ragTraceTime; +extern int ragSSCount; +extern int ragTraceCount; +#endif + +void G2API_AnimateG2ModelsRag( + CGhoul2Info_v &ghoul2, int AcurrentTime, CRagDollUpdateParams *params) +{ + int model; + int currentTime = G2API_GetTime(AcurrentTime); + +#ifdef _DEBUG + ragTraceTime = 0; + ragSSCount = 0; + ragTraceCount = 0; +#endif + + // Walk the list and find all models that are active + for (model = 0; model < ghoul2.size(); model++) + { + if (ghoul2[model].mModel) + { + G2_Animate_Bone_List(ghoul2, currentTime, model, params); + } + } +} +// rww - RAGDOLL_END + +int G2_Find_Bone_Rag( + CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName); +#define RAG_PCJ (0x00001) +#define RAG_EFFECTOR (0x00100) + +static boneInfo_t * +G2_GetRagBoneConveniently(CGhoul2Info_v &ghoul2, const char *boneName) +{ + assert(ghoul2.size()); + CGhoul2Info *ghlInfo = &ghoul2[0]; + + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) + { // can't do this if not in ragdoll + return NULL; + } + + int boneIndex = G2_Find_Bone_Rag(ghlInfo, ghlInfo->mBlist, boneName); + + if (boneIndex < 0) + { // bad bone specification + return NULL; + } + + boneInfo_t *bone = &ghlInfo->mBlist[boneIndex]; + + if (!(bone->flags & BONE_ANGLES_RAGDOLL)) + { // only want to return rag bones + return NULL; + } + + return bone; +} + +qboolean G2API_RagPCJConstraint( + CGhoul2Info_v &ghoul2, const char *boneName, vec3_t min, vec3_t max) +{ + boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); + + if (!bone) + { + return qfalse; + } + + if (!(bone->RagFlags & RAG_PCJ)) + { // this function is only for PCJ bones + return qfalse; + } + + VectorCopy(min, bone->minAngles); + VectorCopy(max, bone->maxAngles); + + return qtrue; +} + +qboolean G2API_RagPCJGradientSpeed( + CGhoul2Info_v &ghoul2, const char *boneName, const float speed) +{ + boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); + + if (!bone) + { + return qfalse; + } + + if (!(bone->RagFlags & RAG_PCJ)) + { // this function is only for PCJ bones + return qfalse; + } + + bone->overGradSpeed = speed; + + return qtrue; +} + +qboolean +G2API_RagEffectorGoal(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t pos) +{ + boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); + + if (!bone) + { + return qfalse; + } + + if (!(bone->RagFlags & RAG_EFFECTOR)) + { // this function is only for effectors + return qfalse; + } + + if (!pos) + { // go back to none in case we have one then + bone->hasOverGoal = false; + } + else + { + VectorCopy(pos, bone->overGoalSpot); + bone->hasOverGoal = true; + } + return qtrue; +} + +qboolean G2API_GetRagBonePos( + CGhoul2Info_v &ghoul2, + const char *boneName, + vec3_t pos, + vec3_t entAngles, + vec3_t entPos, + vec3_t entScale) +{ //do something? + return qfalse; +} + +qboolean G2API_RagEffectorKick(CGhoul2Info_v &ghoul2, const char *boneName, vec3_t velocity) +{ + boneInfo_t *bone = G2_GetRagBoneConveniently(ghoul2, boneName); + + if (!bone) + { + return qfalse; + } + + if (!(bone->RagFlags & RAG_EFFECTOR)) + { //this function is only for effectors + return qfalse; + } + + bone->epVelocity[2] = 0; + VectorAdd(bone->epVelocity, velocity, bone->epVelocity); + bone->physicsSettled = false; + + return qtrue; +} + +qboolean G2API_RagForceSolve(CGhoul2Info_v &ghoul2, qboolean force) +{ + assert(ghoul2.size()); + CGhoul2Info *ghlInfo = &ghoul2[0]; + + if (!(ghlInfo->mFlags & GHOUL2_RAG_STARTED)) + { //can't do this if not in ragdoll + return qfalse; + } + + if (force) + { + ghlInfo->mFlags |= GHOUL2_RAG_FORCESOLVE; + } + else + { + ghlInfo->mFlags &= ~GHOUL2_RAG_FORCESOLVE; + } + + return qtrue; +} + +qboolean G2_SetBoneIKState( + CGhoul2Info_v &ghoul2, + int time, + const char *boneName, + int ikState, + sharedSetBoneIKStateParams_t *params); +qboolean G2API_SetBoneIKState( + CGhoul2Info_v &ghoul2, + int time, + const char *boneName, + int ikState, + sharedSetBoneIKStateParams_t *params) +{ + return G2_SetBoneIKState(ghoul2, time, boneName, ikState, params); +} + +qboolean G2_IKMove( + CGhoul2Info_v &ghoul2, + int time, + sharedIKMoveParams_t *params); +qboolean G2API_IKMove( + CGhoul2Info_v &ghoul2, + int time, + sharedIKMoveParams_t *params) +{ + return G2_IKMove(ghoul2, time, params); +} + +qboolean G2API_RemoveBolt(CGhoul2Info *ghlInfo, const int index) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_Remove_Bolt(ghlInfo->mBltlist, index); + } + return qfalse; +} + +int G2API_AddBolt( + CGhoul2Info_v &ghoul2, const int modelIndex, const char *boneName) +{ + // assert(ghoul2.size()>modelIndex); + + if (ghoul2.size() > modelIndex) + { + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_Add_Bolt( + ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, boneName); + } + } + return -1; +} + +int G2API_AddBoltSurfNum(CGhoul2Info *ghlInfo, const int surfIndex) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_Add_Bolt_Surf_Num( + ghlInfo, ghlInfo->mBltlist, ghlInfo->mSlist, surfIndex); + } + return -1; +} + +qboolean G2API_AttachG2Model( + CGhoul2Info_v &ghoul2From, + int modelFrom, + CGhoul2Info_v &ghoul2To, + int toBoltIndex, + int toModel) +{ + assert(toBoltIndex >= 0); + if (toBoltIndex < 0) + { + return qfalse; + } + + if (G2_SetupModelPointers(ghoul2From) && G2_SetupModelPointers(ghoul2To)) + { + // make sure we have a model to attach, a model to attach to, and a + // bolt on that model + if ((ghoul2From.size() > modelFrom) && (ghoul2To.size() > toModel) && + ((ghoul2To[toModel].mBltlist[toBoltIndex].boneNumber != -1) || + (ghoul2To[toModel].mBltlist[toBoltIndex].surfaceNumber != -1))) + { + // encode the bolt address into the model bolt link + toModel &= MODEL_AND; + toBoltIndex &= BOLT_AND; + ghoul2From[modelFrom].mModelBoltLink = + (toModel << MODEL_SHIFT) | (toBoltIndex << BOLT_SHIFT); + return qtrue; + } + } + return qfalse; +} + +void G2API_SetBoltInfo(CGhoul2Info_v &ghoul2, int modelIndex, int boltInfo) +{ + if (ghoul2.size() > modelIndex) + { + ghoul2[modelIndex].mModelBoltLink = boltInfo; + } +} + +qboolean G2API_DetachG2Model(CGhoul2Info *ghlInfo) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + ghlInfo->mModelBoltLink = -1; + return qtrue; + } + return qfalse; +} + +qboolean G2API_AttachEnt( + int *boltInfo, + CGhoul2Info_v &ghoul2, + int modelIndex, + int toBoltIndex, + int entNum, + int toModelNum) +{ + CGhoul2Info *ghlInfoTo = &ghoul2[modelIndex]; + + if (boltInfo && G2_SetupModelPointers(ghlInfoTo)) + { + // make sure we have a model to attach, a model to attach to, and a + // bolt on that model + if (ghlInfoTo->mBltlist.size() && + ((ghlInfoTo->mBltlist[toBoltIndex].boneNumber != -1) || + (ghlInfoTo->mBltlist[toBoltIndex].surfaceNumber != -1))) + { + // encode the bolt address into the model bolt link + toModelNum &= MODEL_AND; + toBoltIndex &= BOLT_AND; + entNum &= ENTITY_AND; + *boltInfo = (toBoltIndex << BOLT_SHIFT) | + (toModelNum << MODEL_SHIFT) | + (entNum << ENTITY_SHIFT); + return qtrue; + } + } + return qfalse; +} + +qboolean gG2_GBMNoReconstruct; +qboolean gG2_GBMUseSPMethod; + +qboolean G2API_GetBoltMatrix_SPMethod( + CGhoul2Info_v &ghoul2, + const int modelIndex, + const int boltIndex, + mdxaBone_t *matrix, + const vec3_t angles, + const vec3_t position, + const int frameNum, + qhandle_t *modelList, + const vec3_t scale) +{ + assert(ghoul2.size() > modelIndex); + + if (ghoul2.size() > modelIndex) + { + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + + if (ghlInfo && + (boltIndex < (int)ghlInfo->mBltlist.size()) && + boltIndex >= 0) + { + // make sure we have transformed the skeleton + if (!gG2_GBMNoReconstruct) + { + G2_ConstructGhoulSkeleton(ghoul2, frameNum, true, scale); + } + + gG2_GBMNoReconstruct = qfalse; + + mdxaBone_t scaled; + mdxaBone_t *use; + use = &ghlInfo->mBltlist[boltIndex].position; + + if (scale[0] || scale[1] || scale[2]) + { + scaled = *use; + use = &scaled; + + // scale the bolt position by the scale factor for this model + // since at this point its still in model space + if (scale[0]) + { + scaled.matrix[0][3] *= scale[0]; + } + if (scale[1]) + { + scaled.matrix[1][3] *= scale[1]; + } + if (scale[2]) + { + scaled.matrix[2][3] *= scale[2]; + } + } + + // pre generate the world matrix + G2_GenerateWorldMatrix(angles, position); + + VectorNormalize((float *)use->matrix[0]); + VectorNormalize((float *)use->matrix[1]); + VectorNormalize((float *)use->matrix[2]); + + Mat3x4_Multiply(matrix, &worldMatrix, use); + return qtrue; + } + } + return qfalse; +} + +#define G2ERROR(exp, m) ((void)0) // rwwFIXMEFIXME: This is because I'm lazy. +#define G2WARNING(exp, m) ((void)0) +#define G2NOTE(exp, m) ((void)0) +#define G2ANIM(ghlInfo, m) ((void)0) +bool G2_NeedsRecalc(CGhoul2Info *ghlInfo, int frameNum); +void G2_GetBoltMatrixLow( + CGhoul2Info &ghoul2, + int boltNum, + const vec3_t scale, + mdxaBone_t &retMatrix); +void G2_GetBoneMatrixLow( + CGhoul2Info &ghoul2, + int boneNum, + const vec3_t scale, + mdxaBone_t &retMatrix, + mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv); + +qboolean G2API_GetBoltMatrix( + CGhoul2Info_v &ghoul2, + const int modelIndex, + const int boltIndex, + mdxaBone_t *matrix, + const vec3_t angles, + const vec3_t position, + const int frameNum, + qhandle_t *modelList, + vec3_t scale) +{ + G2ERROR(matrix, "NULL matrix"); + G2ERROR( + modelIndex >= 0 && modelIndex < ghoul2.size(), + "Invalid ModelIndex"); + const static mdxaBone_t identityMatrix = { + { + {0.0f, -1.0f, 0.0f, 0.0f}, + {1.0f, 0.0f, 0.0f, 0.0f}, + {0.0f, 0.0f, 1.0f, 0.0f} + } + }; + + G2_GenerateWorldMatrix(angles, position); + if (G2_SetupModelPointers(ghoul2)) + { + if (matrix && modelIndex >= 0 && modelIndex < ghoul2.size()) + { + int tframeNum = G2API_GetTime(frameNum); + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + G2ERROR + (boltIndex >= 0 && (boltIndex < ghlInfo->mBltlist.size()), + va("Invalid Bolt Index (%d:%s)", + boltIndex, + ghlInfo->mFileName)); + + if (boltIndex >= 0 && ghlInfo && + (boltIndex < (int)ghlInfo->mBltlist.size())) + { + mdxaBone_t bolt; + + if (G2_NeedsRecalc(ghlInfo, tframeNum)) + { + G2_ConstructGhoulSkeleton(ghoul2, tframeNum, true, scale); + } + + G2_GetBoltMatrixLow(*ghlInfo, boltIndex, scale, bolt); + + // scale the bolt position by the scale factor for this model + // since at this point its still in model space + if (scale[0]) + { + bolt.matrix[0][3] *= scale[0]; + } + + if (scale[1]) + { + bolt.matrix[1][3] *= scale[1]; + } + + if (scale[2]) + { + bolt.matrix[2][3] *= scale[2]; + } + + VectorNormalize((float *)&bolt.matrix[0]); + VectorNormalize((float *)&bolt.matrix[1]); + VectorNormalize((float *)&bolt.matrix[2]); + + Mat3x4_Multiply(matrix, &worldMatrix, &bolt); +#if G2API_DEBUG + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 4; j++) + { + assert(!_isnan(matrix->matrix[i][j])); + } + } +#endif // _DEBUG + G2ANIM(ghlInfo, "G2API_GetBoltMatrix"); + + if (!gG2_GBMUseSPMethod) + { + // this is horribly stupid and I hate it. But lots of game + // code is written to assume this 90 degree offset thing. + mdxaBone_t rotMat, tempMatrix; + vec3_t newangles = {0, 270, 0}; + Create_Matrix(newangles, &rotMat); + + // make the model space matrix we have for this bolt into a + // world matrix + Mat3x4_Multiply(&tempMatrix, &worldMatrix, &bolt); + vec3_t origin; + origin[0] = tempMatrix.matrix[0][3]; + origin[1] = tempMatrix.matrix[1][3]; + origin[2] = tempMatrix.matrix[2][3]; + tempMatrix.matrix[0][3] = + tempMatrix.matrix[1][3] = + tempMatrix.matrix[2][3] = 0; + Mat3x4_Multiply(matrix, &tempMatrix, &rotMat); + matrix->matrix[0][3] = origin[0]; + matrix->matrix[1][3] = origin[1]; + matrix->matrix[2][3] = origin[2]; + } + else + { // reset it + gG2_GBMUseSPMethod = qfalse; + } + + return qtrue; + } + } + } + else + { + G2WARNING(0, "G2API_GetBoltMatrix Failed on empty or bad model"); + } + Mat3x4_Multiply(matrix, &worldMatrix, (mdxaBone_t *)&identityMatrix); + return qfalse; +} + +void G2API_ListSurfaces(CGhoul2Info *ghlInfo) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + G2_List_Model_Surfaces(ghlInfo->mFileName); + } +} + +void G2API_ListBones(CGhoul2Info *ghlInfo, int frame) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + G2_List_Model_Bones(ghlInfo->mFileName, frame); + } +} + +// decide if we have Ghoul2 models associated with this ghoul list or not +qboolean G2API_HaveWeGhoul2Models(CGhoul2Info_v &ghoul2) +{ + if (ghoul2.size()) + { + for (int i = 0; i < ghoul2.size(); i++) + { + if (ghoul2[i].mModelindex != -1) + { + return qtrue; + } + } + } + return qfalse; +} + +// run through the Ghoul2 models and set each of the mModel values to the +// correct one from the cgs.gameModel offset lsit +void G2API_SetGhoul2ModelIndexes( + CGhoul2Info_v &ghoul2, + qhandle_t *modelList, + qhandle_t *skinList) +{ + return; +#if 0 + int i; + if (&ghoul2) + { + for (i=0; idata.glm->header->animName; +} + +qboolean G2API_GetAnimFileName(CGhoul2Info *ghlInfo, char **filename) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_GetAnimFileName(ghlInfo->mFileName, filename); + } + return qfalse; +} + +/* +======================= +SV_QsortEntityNumbers +======================= +*/ +static int QDECL QsortDistance(const void *a, const void *b) +{ + const float &ea = ((CollisionRecord_t *)a)->mDistance; + const float &eb = ((CollisionRecord_t *)b)->mDistance; + + if (ea < eb) + { + return -1; + } + return 1; +} + +static bool G2_NeedRetransform(CGhoul2Info *g2, int frameNum) +{ + // see if we need to do another transform + bool needTrans = false; + for (auto &bone : g2->mBlist) + { + float time; + if (bone.pauseTime) + { + time = (bone.pauseTime - bone.startTime) / 50.0f; + } + else + { + time = (frameNum - bone.startTime) / 50.0f; + } + + const int newFrame = bone.startFrame + (time * bone.animSpeed); + if (newFrame < bone.endFrame || + (bone.flags & BONE_ANIM_OVERRIDE_LOOP) || + (bone.flags & BONE_NEED_TRANSFORM)) + { + // ok, we're gonna have to do it. bone is apparently animating. + bone.flags &= ~BONE_NEED_TRANSFORM; + needTrans = true; + } + } + + return needTrans; +} + +void G2API_CollisionDetectCache( + CollisionRecord_t *collRecMap, + CGhoul2Info_v &ghoul2, + const vec3_t angles, + const vec3_t position, + int frameNumber, + int entNum, + vec3_t rayStart, + vec3_t rayEnd, + vec3_t scale, + IHeapAllocator *G2VertSpace, + int traceFlags, + int useLod, + float fRadius) +{ + // this will store off the transformed verts for the next trace - this is + // slower, but for models that do not animate frequently it is much much + // faster. -rww + if (G2_SetupModelPointers(ghoul2)) + { + vec3_t transRayStart, transRayEnd; + + int tframeNum = G2API_GetTime(frameNumber); + + // make sure we have transformed the whole skeletons for each model + if (G2_NeedRetransform(&ghoul2[0], tframeNum) || + !ghoul2[0].mTransformedVertsArray) + { + // optimization, only create new transform space if we need to, + // otherwise store it off! + int i = 0; + while (i < ghoul2.size()) + { + CGhoul2Info &g2 = ghoul2[i]; + + if (!g2.mTransformedVertsArray || + !(g2.mFlags & GHOUL2_ZONETRANSALLOC)) + { + // reworked so we only alloc once! if we have a pointer, + // but not a ghoul2_zonetransalloc flag, then that means it + // is a miniheap pointer. Just stomp over it. + int iSize = + g2.currentModel->data.glm->header->numSurfaces * 4; + g2.mTransformedVertsArray = + (size_t *)Z_Malloc(iSize, TAG_GHOUL2, qtrue); + } + + g2.mFlags |= GHOUL2_ZONETRANSALLOC; + + i++; + } + G2_ConstructGhoulSkeleton(ghoul2, frameNumber, true, scale); + G2VertSpace->ResetHeap(); + + // now having done that, time to build the model +#ifdef _G2_GORE + G2_TransformModel( + ghoul2, + frameNumber, + scale, + G2VertSpace, + useLod, + false); +#else + G2_TransformModel(ghoul2, frameNumber, scale, G2VertSpace, useLod); +#endif + } + + // pre generate the world matrix - used to transform the incoming ray + G2_GenerateWorldMatrix(angles, position); + + // model is built. Lets check to see if any triangles are actually hit. + // first up, translate the ray to model space + TransformAndTranslatePoint(rayStart, transRayStart, &worldMatrixInv); + TransformAndTranslatePoint(rayEnd, transRayEnd, &worldMatrixInv); + + // now walk each model and check the ray against each poly - sigh, this + // is SO expensive. I wish there was a better way to do this. + G2_TraceModels( + ghoul2, + transRayStart, + transRayEnd, + collRecMap, + entNum, + traceFlags, + useLod, + fRadius +#ifdef _G2_GORE + , + 0, + 0, + 0, + 0, + 0, + qfalse +#endif + ); + + int i; + for (i = 0; + i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; + i++) + { + } + + // now sort the resulting array of collision records so they are + // distance ordered + qsort(collRecMap, i, sizeof(CollisionRecord_t), QsortDistance); + } +} + +void G2API_CollisionDetect( + CollisionRecord_t *collRecMap, + CGhoul2Info_v &ghoul2, + const vec3_t angles, + const vec3_t position, + int frameNumber, + int entNum, + vec3_t rayStart, + vec3_t rayEnd, + vec3_t scale, + IHeapAllocator *G2VertSpace, + int traceFlags, + int useLod, + float fRadius) +{ + if (G2_SetupModelPointers(ghoul2)) + { + vec3_t transRayStart, transRayEnd; + + // make sure we have transformed the whole skeletons for each model + G2_ConstructGhoulSkeleton(ghoul2, frameNumber, true, scale); + + // pre generate the world matrix - used to transform the incoming ray + G2_GenerateWorldMatrix(angles, position); + + G2VertSpace->ResetHeap(); + +// now having done that, time to build the model +#ifdef _G2_GORE + G2_TransformModel( + ghoul2, frameNumber, scale, G2VertSpace, useLod, false); +#else + G2_TransformModel(ghoul2, frameNumber, scale, G2VertSpace, useLod); +#endif + + // model is built. Lets check to see if any triangles are actually hit. + // first up, translate the ray to model space + TransformAndTranslatePoint(rayStart, transRayStart, &worldMatrixInv); + TransformAndTranslatePoint(rayEnd, transRayEnd, &worldMatrixInv); + + // now walk each model and check the ray against each poly - sigh, this + // is SO expensive. I wish there was a better way to do this. + G2_TraceModels( + ghoul2, + transRayStart, + transRayEnd, + collRecMap, + entNum, + traceFlags, + useLod, + fRadius +#ifdef _G2_GORE + , + 0, + 0, + 0, + 0, + 0, + qfalse +#endif + ); + + int i; + for (i = 0; + i < MAX_G2_COLLISIONS && collRecMap[i].mEntityNum != -1; + i++) + { + } + + // now sort the resulting array of collision records so they are + // distance ordered + qsort(collRecMap, i, sizeof(CollisionRecord_t), QsortDistance); + } +} + +qboolean G2API_SetGhoul2ModelFlags(CGhoul2Info *ghlInfo, const int flags) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + ghlInfo->mFlags &= GHOUL2_NEWORIGIN; + ghlInfo->mFlags |= flags; + return qtrue; + } + return qfalse; +} + +int G2API_GetGhoul2ModelFlags(CGhoul2Info *ghlInfo) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return (ghlInfo->mFlags & ~GHOUL2_NEWORIGIN); + } + return 0; +} + +// given a boltmatrix, return in vec a normalised vector for the axis requested in flags +void G2API_GiveMeVectorFromMatrix(mdxaBone_t *boltMatrix, Eorientations flags, vec3_t vec) +{ + switch (flags) + { + case ORIGIN: + vec[0] = boltMatrix->matrix[0][3]; + vec[1] = boltMatrix->matrix[1][3]; + vec[2] = boltMatrix->matrix[2][3]; + break; + case POSITIVE_Y: + vec[0] = boltMatrix->matrix[0][1]; + vec[1] = boltMatrix->matrix[1][1]; + vec[2] = boltMatrix->matrix[2][1]; + break; + case POSITIVE_X: + vec[0] = boltMatrix->matrix[0][0]; + vec[1] = boltMatrix->matrix[1][0]; + vec[2] = boltMatrix->matrix[2][0]; + break; + case POSITIVE_Z: + vec[0] = boltMatrix->matrix[0][2]; + vec[1] = boltMatrix->matrix[1][2]; + vec[2] = boltMatrix->matrix[2][2]; + break; + case NEGATIVE_Y: + vec[0] = -boltMatrix->matrix[0][1]; + vec[1] = -boltMatrix->matrix[1][1]; + vec[2] = -boltMatrix->matrix[2][1]; + break; + case NEGATIVE_X: + vec[0] = -boltMatrix->matrix[0][0]; + vec[1] = -boltMatrix->matrix[1][0]; + vec[2] = -boltMatrix->matrix[2][0]; + break; + case NEGATIVE_Z: + vec[0] = -boltMatrix->matrix[0][2]; + vec[1] = -boltMatrix->matrix[1][2]; + vec[2] = -boltMatrix->matrix[2][2]; + break; + } +} + + +int G2API_CopyGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v &g2To, int modelIndex) +{ + assert(modelIndex==-1); // copy individual bolted parts is not used in jk2 and I didn't want to deal with it + // if ya want it, we will add it back correctly + + //G2ERROR(ghoul2From.IsValid(),"Invalid ghlInfo"); + if (g2From.IsValid()) + { +#ifdef _DEBUG + if (g2To.IsValid()) + { + assert(!"Copying to a valid g2 instance?!"); + + if (g2To[0].mBoneCache) + { + assert(!"Instance has a bonecache too.. it's gonna get stomped"); + } + } +#endif + g2To.DeepCopy(g2From); + +#ifdef _G2_GORE //check through gore stuff then, as well. + int model = 0; + + while (model < g2To.size()) + { + if ( g2To[model].mGoreSetTag ) + { + CGoreSet* gore = FindGoreSet ( g2To[model].mGoreSetTag ); + assert(gore); + gore->mRefCount++; + } + + model++; + } +#endif + //G2ANIM(ghoul2From,"G2API_CopyGhoul2Instance (source)"); + //G2ANIM(ghoul2To,"G2API_CopyGhoul2Instance (dest)"); + } + + return -1; +} + +void G2API_CopySpecificG2Model(CGhoul2Info_v &ghoul2From, int modelFrom, CGhoul2Info_v &ghoul2To, int modelTo) +{ +#if 0 + qboolean forceReconstruct = qtrue; +#endif //model1 was not getting reconstructed like it should for thrown sabers? + //might have been a bug in the reconstruct checking which has since been + //mangled and probably fixed. -rww + + // assume we actually have a model to copy from + if (ghoul2From.size() > modelFrom) + { + // if we don't have enough models on the to side, resize us so we do + if (ghoul2To.size() <= modelTo) + { + assert (modelTo < 5); + ghoul2To.resize(modelTo + 1); +#if 0 + forceReconstruct = qtrue; +#endif + } + // do the copy + + if (ghoul2To.IsValid() && ghoul2To.size() >= modelTo) + { //remove the bonecache before we stomp over this instance. + if (ghoul2To[modelTo].mBoneCache) + { + RemoveBoneCache(ghoul2To[modelTo].mBoneCache); + ghoul2To[modelTo].mBoneCache = 0; + } + } + ghoul2To[modelTo] = ghoul2From[modelFrom]; + +#if 0 + if (forceReconstruct) + { //rww - we should really do this shouldn't we? If we don't mark a reconstruct after this, + //and we do a GetBoltMatrix in the same frame, it doesn't reconstruct the skeleton and returns + //a completely invalid matrix + ghoul2To[0].mSkelFrameNum = 0; + } +#endif + } +} + +// This version will automatically copy everything about this model, and make a new one if necessary. +void G2API_DuplicateGhoul2Instance(CGhoul2Info_v &g2From, CGhoul2Info_v **g2To) +{ + //int ignore; + + if (*g2To) + { // This is bad. We only want to do this if there is not yet a to declared. + assert(0); + return; + } + + *g2To = new CGhoul2Info_v; +#ifdef _FULL_G2_LEAK_CHECKING + if (g_G2AllocServer) + { + g_G2ServerAlloc += sizeof(CGhoul2Info_v); + } + else + { + g_G2ClientAlloc += sizeof(CGhoul2Info_v); + } + g_Ghoul2Allocations += sizeof(CGhoul2Info_v); + G2_DEBUG_ShovePtrInTracker(*g2To); +#endif + CGhoul2Info_v &ghoul2 = *(*g2To); + + /*ignore = */G2API_CopyGhoul2Instance(g2From, ghoul2, -1); + + return; +} + +char *G2API_GetSurfaceName(CGhoul2Info_v& ghoul2, int modelIndex, int surfNumber) +{ + static char noSurface[1] = ""; + CGhoul2Info *ghlInfo = &ghoul2[modelIndex]; + + if (G2_SetupModelPointers(ghlInfo)) + { + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmSurface_t *surf = 0; + mdxmSurfHierarchy_t *surfInfo = 0; + mdxmHeader_t *mdxm; + +#ifndef FINAL_BUILD + if (!mod || !mod->data.glm || !mod->data.glm->header) + { + Com_Error(ERR_DROP, "G2API_GetSurfaceName: Bad model on instance %s.", ghlInfo->mFileName); + } +#endif + + mdxm = mod->data.glm->header; + + //ok, I guess it's semi-valid for the user to be passing in surface > numSurfs because they don't know how many surfs a model + //may have.. but how did they get that surf index to begin with? Oh well. + if (surfNumber < 0 || surfNumber >= mdxm->numSurfaces) + { + Com_Printf("G2API_GetSurfaceName: You passed in an invalid surface number (%i) for model %s.\n", surfNumber, ghlInfo->mFileName); + return noSurface; + } + + + surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, 0); + if (surf) + { +#ifndef FINAL_BUILD + if (surf->thisSurfaceIndex < 0 || surf->thisSurfaceIndex >= mdxm->numSurfaces) + { + Com_Error(ERR_DROP, "G2API_GetSurfaceName: Bad surf num (%i) on surf for instance %s.", surf->thisSurfaceIndex, ghlInfo->mFileName); + } +#endif + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); + return surfInfo->name; + } + } + return noSurface; +} + + +int G2API_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_GetSurfaceIndex(ghlInfo, surfaceName); + } + return -1; +} + +char *G2API_GetGLAName(CGhoul2Info_v &ghoul2, int modelIndex) +{ + if (G2_SetupModelPointers(ghoul2)) + { + if (ghoul2.size() > modelIndex) + { + //model_t *mod = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); + //return mod->mdxm->animName; + + assert(ghoul2[modelIndex].currentModel && ghoul2[modelIndex].currentModel->data.glm); + return ghoul2[modelIndex].currentModel->data.glm->header->animName; + } + } + return NULL; +} + +qboolean G2API_SetNewOrigin(CGhoul2Info_v &ghoul2, const int boltIndex) +{ + CGhoul2Info *ghlInfo = NULL; + + if (ghoul2.size()>0) + { + ghlInfo = &ghoul2[0]; + } + + if (G2_SetupModelPointers(ghlInfo)) + { + if (boltIndex < 0) + { + char modelName[MAX_QPATH]; + if (ghlInfo->currentModel && + ghlInfo->currentModel->name[0]) + { + strcpy(modelName, ghlInfo->currentModel->name); + } + else + { + strcpy(modelName, "None?!"); + } + + Com_Error(ERR_DROP, "Bad boltindex (%i) trying to SetNewOrigin (naughty naughty!)\nModel %s\n", boltIndex, modelName); + } + + ghlInfo->mNewOrigin = boltIndex; + ghlInfo->mFlags |= GHOUL2_NEWORIGIN; + return qtrue; + } + return qfalse; +} + +int G2API_GetBoneIndex(CGhoul2Info *ghlInfo, const char *boneName) +{ + if (G2_SetupModelPointers(ghlInfo)) + { + return G2_Get_Bone_Index(ghlInfo, boneName); + } + return -1; +} + +qboolean G2API_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) +{ + return G2_SaveGhoul2Models(ghoul2, buffer, size); +} + +void G2API_LoadGhoul2Models(CGhoul2Info_v &ghoul2, char *buffer) +{ + G2_LoadGhoul2Model(ghoul2, buffer); +} + +void G2API_FreeSaveBuffer(char *buffer) +{ + Z_Free(buffer); +} + +// this is kinda sad, but I need to call the destructor in this module (exe), not the game.dll... +// +void G2API_LoadSaveCodeDestructGhoul2Info(CGhoul2Info_v &ghoul2) +{ + +#ifdef _G2_GORE + G2API_ClearSkinGore ( ghoul2 ); +#endif + ghoul2.~CGhoul2Info_v(); // so I can load junk over it then memset to 0 without orphaning +} + +//see if surfs have any shader info... +qboolean G2API_SkinlessModel(CGhoul2Info_v& ghoul2, int modelIndex) +{ + CGhoul2Info *g2 = &ghoul2[modelIndex]; + + if (G2_SetupModelPointers(g2)) + { + model_t *mod = (model_t *)g2->currentModel; + + if (mod && + mod->data.glm && + mod->data.glm->header) + { + mdxmSurfHierarchy_t *surf; + int i; + mdxmHeader_t *mdxm = mod->data.glm->header; + + surf = (mdxmSurfHierarchy_t *) ( (byte *)mdxm + mdxm->ofsSurfHierarchy ); + + for (i = 0; i < mdxm->numSurfaces; i++) + { + if (surf->shader[0]) + { //found a surface with a shader name, ok. + return qfalse; + } + + surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + } + } + } + + //found nothing. + return qtrue; +} + +int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) +{ + return ghoul2.size(); +} + +//#ifdef _SOF2 +#ifdef _G2_GORE +void ResetGoreTag(); // put here to reduce coupling + +//way of seeing how many marks are on a model currently -rww +int G2API_GetNumGoreMarks(CGhoul2Info_v& ghoul2, int modelIndex) +{ + CGhoul2Info *g2 = &ghoul2[modelIndex]; + + if (g2->mGoreSetTag) + { + CGoreSet *goreSet = FindGoreSet(g2->mGoreSetTag); + + if (goreSet) + { + return goreSet->mGoreRecords.size(); + } + } + + return 0; +} + +void G2API_ClearSkinGore ( CGhoul2Info_v &ghoul2 ) +{ + int i; + + for (i=0; inumLods,3); //limit to the number of lods the main model has + for(lod=lodbias;lodResetHeap(); + + G2_TransformModel(ghoul2, gore.currentTime, gore.scale,ri.GetG2VertSpaceServer(),lod,true); + + // now walk each model and compute new texture coordinates + G2_TraceModels(ghoul2, transHitLocation, transRayDirection, 0, gore.entNum, 0,lod,0.0f,gore.SSize,gore.TSize,gore.theta,gore.shader,&gore,qtrue); + } +} +#endif + +qboolean G2_TestModelPointers(CGhoul2Info *ghlInfo) // returns true if the model is properly set up +{ + G2ERROR(ghlInfo,"NULL ghlInfo"); + if (!ghlInfo) + { + return qfalse; + } + ghlInfo->mValid=false; + if (ghlInfo->mModelindex != -1) + { + if (ri.Cvar_VariableIntegerValue( "dedicated" ) || + (G2_ShouldRegisterServer())) //supreme hackery! + { + ghlInfo->mModel = RE_RegisterServerModel(ghlInfo->mFileName); + } + else + { + ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); + } + ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); + if (ghlInfo->currentModel) + { + if (ghlInfo->currentModel->data.glm && + ghlInfo->currentModel->data.glm->header) + { + mdxmHeader_t *mdxm = ghlInfo->currentModel->data.glm->header; + if (ghlInfo->currentModelSize) + { + if (ghlInfo->currentModelSize!=mdxm->ofsEnd) + { + Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); + } + } + ghlInfo->currentModelSize=mdxm->ofsEnd; + ghlInfo->animModel = R_GetModelByHandle(mdxm->animIndex); + if (ghlInfo->animModel) + { + ghlInfo->aHeader = ghlInfo->animModel->data.gla; + if (ghlInfo->aHeader) + { + if (ghlInfo->currentAnimModelSize) + { + if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) + { + Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); + } + } + ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; + ghlInfo->mValid=true; + } + } + } + } + } + if (!ghlInfo->mValid) + { + ghlInfo->currentModel=0; + ghlInfo->currentModelSize=0; + ghlInfo->animModel=0; + ghlInfo->currentAnimModelSize=0; + ghlInfo->aHeader=0; + } + return (qboolean)ghlInfo->mValid; +} + +#ifdef G2_PERFORMANCE_ANALYSIS +#include "qcommon/timing.h" +extern timing_c G2PerformanceTimer_G2_SetupModelPointers; +extern int G2Time_G2_SetupModelPointers; +#endif + +qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo) // returns true if the model is properly set up +{ +#ifdef G2_PERFORMANCE_ANALYSIS + G2PerformanceTimer_G2_SetupModelPointers.Start(); +#endif + G2ERROR(ghlInfo,"NULL ghlInfo"); + if (!ghlInfo) + { + return qfalse; + } + +// if (ghlInfo->mValid && ghlInfo->currentModel) + if (0) + { //rww - Why are we bothering with all this? We can't change models like this anyway. + //This function goes over 200k on the precision timer (in debug, but still), so I'm + //cutting it off here because it gets called constantly. +#ifdef G2_PERFORMANCE_ANALYSIS + G2Time_G2_SetupModelPointers += G2PerformanceTimer_G2_SetupModelPointers.End(); +#endif + return qtrue; + } + + ghlInfo->mValid=false; + +// G2WARNING(ghlInfo->mModelindex != -1,"Setup request on non-used info slot?"); + if (ghlInfo->mModelindex != -1) + { + G2ERROR(ghlInfo->mFileName[0],"empty ghlInfo->mFileName"); + + // RJ - experimental optimization! + if (!ghlInfo->mModel || 1) + { + if (ri.Cvar_VariableIntegerValue( "dedicated" ) || + (G2_ShouldRegisterServer())) //supreme hackery! + { + ghlInfo->mModel = RE_RegisterServerModel(ghlInfo->mFileName); + } + else + { + ghlInfo->mModel = RE_RegisterModel(ghlInfo->mFileName); + } + ghlInfo->currentModel = R_GetModelByHandle(ghlInfo->mModel); + } + + G2ERROR(ghlInfo->currentModel,va("NULL Model (glm) %s",ghlInfo->mFileName)); + if (ghlInfo->currentModel) + { + G2ERROR(ghlInfo->currentModel->modelData,va("Model has no mdxm (glm) %s",ghlInfo->mFileName)); + if (ghlInfo->currentModel->data.glm && + ghlInfo->currentModel->data.glm->header) + { + mdxmHeader_t *mdxm = ghlInfo->currentModel->data.glm->header; + if (ghlInfo->currentModelSize) + { + if (ghlInfo->currentModelSize!=mdxm->ofsEnd) + { + Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); + } + } + ghlInfo->currentModelSize=mdxm->ofsEnd; + G2ERROR(ghlInfo->currentModelSize,va("Zero sized Model? (glm) %s",ghlInfo->mFileName)); + + ghlInfo->animModel = R_GetModelByHandle(mdxm->animIndex); + G2ERROR(ghlInfo->animModel,va("NULL Model (gla) %s",ghlInfo->mFileName)); + if (ghlInfo->animModel) + { + ghlInfo->aHeader = ghlInfo->animModel->data.gla; + G2ERROR(ghlInfo->aHeader,va("Model has no mdxa (gla) %s",ghlInfo->mFileName)); + if (ghlInfo->aHeader) + { + if (ghlInfo->currentAnimModelSize) + { + if (ghlInfo->currentAnimModelSize!=ghlInfo->aHeader->ofsEnd) + { + Com_Error(ERR_DROP, "Ghoul2 model was reloaded and has changed, map must be restarted.\n"); + } + } + ghlInfo->currentAnimModelSize=ghlInfo->aHeader->ofsEnd; + G2ERROR(ghlInfo->currentAnimModelSize,va("Zero sized Model? (gla) %s",ghlInfo->mFileName)); + ghlInfo->mValid=true; + } + } + } + } + } + if (!ghlInfo->mValid) + { + ghlInfo->currentModel=0; + ghlInfo->currentModelSize=0; + ghlInfo->animModel=0; + ghlInfo->currentAnimModelSize=0; + ghlInfo->aHeader=0; + } + +#ifdef G2_PERFORMANCE_ANALYSIS + G2Time_G2_SetupModelPointers += G2PerformanceTimer_G2_SetupModelPointers.End(); +#endif + return (qboolean)ghlInfo->mValid; +} + +qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2) // returns true if any model is properly set up +{ + bool ret=false; + int i; + for (i=0; imValid); + boltInfo_t tempBolt; + + // first up, make sure have a surface first + if (surfNum >= (int)slist.size()) + { + return -1; + } + + // look through entire list - see if it's already there first + for(size_t i=0; imValid); + model_t *mod_m = (model_t *)ghlInfo->currentModel; + model_t *mod_a = (model_t *)ghlInfo->animModel; + int x, surfNum = -1; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boltInfo_t tempBolt; + int flags; + + // first up, we'll search for that which this bolt names in all the surfaces + surfNum = G2_IsSurfaceLegal((void*)mod_m, boneName, &flags); + + // did we find it as a surface? + if (surfNum != -1) + { + // look through entire list - see if it's already there first + for(size_t i=0; idata.gla; + offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x=0; x< mdxa->numBones; x++) + { + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) + { + break; + } + } + + // check to see we did actually make a match with a bone in the model + if (x == mdxa->numBones) + { + // didn't find it? Error + //assert(0&&x == mod_a->mdxa->numBones); +#ifdef _DEBUG +// Com_Printf("WARNING: %s not found on skeleton\n", boneName); +#endif + return -1; + } + + // look through entire list - see if it's already there first + for(size_t i=0; i-1; i--) + { + if ((bltlist[i].surfaceNumber == -1) && (bltlist[i].boneNumber == -1)) + { + newSize = i; + } + // once we hit one that isn't a -1, we are done. + else + { + break; + } + } + // do we need to resize? + if (newSize != bltlist.size()) + { + // yes, so lets do it + bltlist.resize(newSize); + } + + } + return qtrue; + } + + assert(0); + + // no + return qfalse; +} + +// set the bolt list to all unused so the bone transformation routine ignores it. +void G2_Init_Bolt_List(boltInfo_v &bltlist) +{ + bltlist.clear(); +} + +// remove any bolts that reference original surfaces, generated surfaces, or bones that aren't active anymore +void G2_RemoveRedundantBolts(boltInfo_v &bltlist, surfaceInfo_v &slist, int *activeSurfaces, int *activeBones) +{ + // walk the bolt list + for (size_t i=0; i +#else +#include +#endif +#include "ghoul2/G2_gore.h" + +//#define RAG_TRACE_DEBUG_LINES + +#include "client/client.h" //while this is all "shared" code, there are some places where we want to make cgame callbacks (for ragdoll) only if the cgvm exists +//rww - RAGDOLL_END + +//===================================================================================================================== +// Bone List handling routines - so entities can override bone info on a bone by bone level, and also interrogate this info + +// Given a bone name, see if that bone is already in our bone list - note the model_t pointer that gets passed in here MUST point at the +// gla file, not the glm file type. +int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName) +{ + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + mdxaHeader_t *mdxa = mod->data.gla; + offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[0]); + + // look through entire list + for(size_t i=0; ioffsets[blist[i].boneNumber]); + + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) + { + return i; + } + } + + // didn't find it + return -1; +} + +// we need to add a bone to the list - find a free one and see if we can find a corresponding bone in the gla file +int G2_Add_Bone (const model_t *mod, boneInfo_v &blist, const char *boneName) +{ + int x; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + boneInfo_t tempBone; + mdxaHeader_t *mdxa = mod->data.gla; + + //rww - RAGDOLL_BEGIN + memset(&tempBone, 0, sizeof(tempBone)); + //rww - RAGDOLL_END + + offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + + // walk the entire list of bones in the gla file for this model and see if any match the name of the bone we want to find + for (x=0; x< mdxa->numBones; x++) + { + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[x]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) + { + break; + } + } + + // check to see we did actually make a match with a bone in the model + if (x == mdxa->numBones) + { + // didn't find it? Error + //assert(0); +#ifdef _DEBUG + Com_Printf("WARNING: Failed to add bone %s\n", boneName); +#endif + +#ifdef _RAG_PRINT_TEST + Com_Printf("WARNING: Failed to add bone %s\n", boneName); +#endif + return -1; + } + + // look through entire list - see if it's already there first + for(size_t i=0; ioffsets[blist[i].boneNumber]); + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) + { + return i; + } + } + else + { + // if we found an entry that had a -1 for the bonenumber, then we hit a bone slot that was empty + blist[i].boneNumber = x; + blist[i].flags = 0; + return i; + } + } + +#ifdef _RAG_PRINT_TEST + Com_Printf("New bone added for %s\n", boneName); +#endif + // ok, we didn't find an existing bone of that name, or an empty slot. Lets add an entry + tempBone.boneNumber = x; + tempBone.flags = 0; + blist.push_back(tempBone); + return blist.size()-1; +} + + +// Given a model handle, and a bone name, we want to remove this bone from the bone override list +qboolean G2_Remove_Bone_Index ( boneInfo_v &blist, int index) +{ + if (index != -1) + { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) + { + return qtrue; // don't accept any calls on ragdoll bones + } + } + + // did we find it? + if (index != -1) + { + // check the flags first - if it's still being used Do NOT remove it + if (!blist[index].flags) + { + + // set this bone to not used + blist[index].boneNumber = -1; + + unsigned int newSize = blist.size(); + // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list + for (int i=blist.size()-1; i>-1; i--) + { + if (blist[i].boneNumber == -1) + { + newSize = i; + } + // once we hit one that isn't a -1, we are done. + else + { + break; + } + } + // do we need to resize? + if (newSize != blist.size()) + { + // yes, so lets do it + blist.resize(newSize); + } + + return qtrue; + } + } + +// assert(0); + // no + return qfalse; +} + +// given a bone number, see if there is an override bone in the bone list +int G2_Find_Bone_In_List(boneInfo_v &blist, const int boneNum) +{ + // look through entire list + for(size_t i=0; idata.gla; + offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[blist[index].boneNumber]); + + Mat3x4_Multiply(&temp1, boneOverride,&skel->BasePoseMatInv); + Mat3x4_Multiply(boneOverride,&skel->BasePoseMat, &temp1); + + } + else + { + VectorCopy(angles, newAngles); + + // why I should need do this Fuck alone knows. But I do. + if (left == POSITIVE_Y) + { + newAngles[0] +=180; + } + + Create_Matrix(newAngles, &temp1); + + permutation.matrix[0][0] = permutation.matrix[0][1] = permutation.matrix[0][2] = permutation.matrix[0][3] = 0; + permutation.matrix[1][0] = permutation.matrix[1][1] = permutation.matrix[1][2] = permutation.matrix[1][3] = 0; + permutation.matrix[2][0] = permutation.matrix[2][1] = permutation.matrix[2][2] = permutation.matrix[2][3] = 0; + + // determine what axis newAngles Yaw should revolve around + switch (forward) + { + case NEGATIVE_X: + permutation.matrix[0][0] = -1; // works + break; + case POSITIVE_X: + permutation.matrix[0][0] = 1; // works + break; + case NEGATIVE_Y: + permutation.matrix[1][0] = -1; + break; + case POSITIVE_Y: + permutation.matrix[1][0] = 1; + break; + case NEGATIVE_Z: + permutation.matrix[2][0] = -1; + break; + case POSITIVE_Z: + permutation.matrix[2][0] = 1; + break; + default: + break; + } + + // determine what axis newAngles pitch should revolve around + switch (left) + { + case NEGATIVE_X: + permutation.matrix[0][1] = -1; + break; + case POSITIVE_X: + permutation.matrix[0][1] = 1; + break; + case NEGATIVE_Y: + permutation.matrix[1][1] = -1; // works + break; + case POSITIVE_Y: + permutation.matrix[1][1] = 1; // works + break; + case NEGATIVE_Z: + permutation.matrix[2][1] = -1; + break; + case POSITIVE_Z: + permutation.matrix[2][1] = 1; + break; + default: + break; + } + + // determine what axis newAngles Roll should revolve around + switch (up) + { + case NEGATIVE_X: + permutation.matrix[0][2] = -1; + break; + case POSITIVE_X: + permutation.matrix[0][2] = 1; + break; + case NEGATIVE_Y: + permutation.matrix[1][2] = -1; + break; + case POSITIVE_Y: + permutation.matrix[1][2] = 1; + break; + case NEGATIVE_Z: + permutation.matrix[2][2] = -1; // works + break; + case POSITIVE_Z: + permutation.matrix[2][2] = 1; // works + break; + default: + break; + } + + Mat3x4_Multiply(boneOverride, &temp1,&permutation); + + } + + // keep a copy of the matrix in the newmatrix which is actually what we use + memcpy(&blist[index].newMatrix, &blist[index].matrix, sizeof(mdxaBone_t)); + +} + +//========================================================================================= +//// Public Bone Routines + + +// Given a model handle, and a bone name, we want to remove this bone from the bone override list +qboolean G2_Remove_Bone (CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) +{ + int index; + + assert(ghlInfo->animModel); + index = G2_Find_Bone(ghlInfo->animModel, blist, boneName); + + return G2_Remove_Bone_Index(blist, index); +} + +#define DEBUG_PCJ (0) + + +// Given a model handle, and a bone name, we want to set angles specifically +// for overriding +qboolean G2_Set_Bone_Angles_Index( + boneInfo_v &blist, + const int index, + const float *angles, + const int flags, + const Eorientations yaw, + const Eorientations pitch, + const Eorientations roll, + qhandle_t *modelList, + const int modelIndex, + const int blendTime, + const int currentTime) +{ + if ( index >= (int)blist.size() || blist[index].boneNumber == -1 ) + { + // we are attempting to set a bone override that doesn't exist + return qfalse; + } + + if (index != -1) + { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) + { + // don't accept any calls on ragdoll bones + return qtrue; + } + } + + if (flags & (BONE_ANGLES_PREMULT | BONE_ANGLES_POSTMULT)) + { + // you CANNOT call this with an index with these kinds of bone + // overrides - we need the model details for these kinds of bone angle + // overrides + return qfalse; + } + + // yes, so set the angles and flags correctly + blist[index].flags &= ~BONE_ANGLES_TOTAL; + blist[index].flags |= flags; + blist[index].boneBlendStart = currentTime; + blist[index].boneBlendTime = blendTime; + +#if DEBUG_PCJ + Com_OPrintf( + "PCJ %2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n", + index, + currentTime, + angles[0], + angles[1], + angles[2], + yaw, + pitch, + roll, + flags); +#endif + + G2_Generate_Matrix(nullptr, blist, index, angles, flags, yaw, pitch, roll); + + return qtrue; +} + +// Given a model handle, and a bone name, we want to set angles specifically for overriding +qboolean G2_Set_Bone_Angles(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const float *angles, + const int flags, const Eorientations up, const Eorientations left, const Eorientations forward, + qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) +{ + model_t *mod_a; + + mod_a = (model_t *)ghlInfo->animModel; + + int index = G2_Find_Bone(mod_a, blist, boneName); + + // did we find it? + if (index != -1) + { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) + { + return qtrue; // don't accept any calls on ragdoll bones + } + + // yes, so set the angles and flags correctly + blist[index].flags &= ~(BONE_ANGLES_TOTAL); + blist[index].flags |= flags; + blist[index].boneBlendStart = currentTime; + blist[index].boneBlendTime = blendTime; +#if DEBUG_PCJ + Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],up,left,forward,flags); +#endif + + G2_Generate_Matrix(mod_a, blist, index, angles, flags, up, left, forward); + return qtrue; + } + + // no - lets try and add this bone in + index = G2_Add_Bone(mod_a, blist, boneName); + + // did we find a free one? + if (index != -1) + { + // yes, so set the angles and flags correctly + blist[index].flags &= ~(BONE_ANGLES_TOTAL); + blist[index].flags |= flags; + blist[index].boneBlendStart = currentTime; + blist[index].boneBlendTime = blendTime; +#if DEBUG_PCJ + Com_OPrintf("%2d %6d (%6.2f,%6.2f,%6.2f) %d %d %d %d\n",index,currentTime,angles[0],angles[1],angles[2],up,left,forward,flags); +#endif + + G2_Generate_Matrix(mod_a, blist, index, angles, flags, up, left, forward); + return qtrue; + } +// assert(0); + //Jeese, we don't need an assert here too. There's already a warning in G2_Add_Bone if it fails. + + // no + return qfalse; +} + +// Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly +qboolean G2_Set_Bone_Angles_Matrix_Index(boneInfo_v &blist, const int index, + const mdxaBone_t &matrix, const int flags, qhandle_t *modelList, + const int modelIndex, const int blendTime, const int currentTime) +{ + + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) + { + // we are attempting to set a bone override that doesn't exist + assert(0); + return qfalse; + } + if (index != -1) + { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) + { + return qtrue; // don't accept any calls on ragdoll bones + } + } + // yes, so set the angles and flags correctly + blist[index].flags &= ~(BONE_ANGLES_TOTAL); + blist[index].flags |= flags; + blist[index].boneBlendStart = currentTime; + blist[index].boneBlendTime = blendTime; + + memcpy(&blist[index].matrix, &matrix, sizeof(mdxaBone_t)); + memcpy(&blist[index].newMatrix, &matrix, sizeof(mdxaBone_t)); + return qtrue; + +} + +// Given a model handle, and a bone name, we want to set angles specifically for overriding - using a matrix directly +qboolean G2_Set_Bone_Angles_Matrix(const char *fileName, boneInfo_v &blist, const char *boneName, const mdxaBone_t &matrix, + const int flags, qhandle_t *modelList, const int modelIndex, const int blendTime, const int currentTime) +{ + model_t *mod_m; + if (!fileName[0]) + { + mod_m = R_GetModelByHandle(modelList[modelIndex]); + } + else + { + mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + } + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); + + if (index != -1) + { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) + { + return qtrue; // don't accept any calls on ragdoll bones + } + } + + // did we find it? + if (index != -1) + { + // yes, so set the angles and flags correctly + blist[index].flags &= ~(BONE_ANGLES_TOTAL); + blist[index].flags |= flags; + + memcpy(&blist[index].matrix, &matrix, sizeof(mdxaBone_t)); + memcpy(&blist[index].newMatrix, &matrix, sizeof(mdxaBone_t)); + return qtrue; + } + + // no - lets try and add this bone in + index = G2_Add_Bone(mod_a, blist, boneName); + + // did we find a free one? + if (index != -1) + { + // yes, so set the angles and flags correctly + blist[index].flags &= ~(BONE_ANGLES_TOTAL); + blist[index].flags |= flags; + + memcpy(&blist[index].matrix, &matrix, sizeof(mdxaBone_t)); + memcpy(&blist[index].newMatrix, &matrix, sizeof(mdxaBone_t)); + return qtrue; + } + assert(0); + + // no + return qfalse; +} + +#define DEBUG_G2_TIMING (0) + +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims +qboolean G2_Set_Bone_Anim_Index( + boneInfo_v &blist, + const int index, + const int startFrame, + const int endFrame, + const int flags, + const float animSpeed, + const int currentTime, + const float setFrame, + const int blendTime, + const int numFrames) +{ + int modFlags = flags; + + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) + { + // we are attempting to set a bone override that doesn't exist + assert(0); + return qfalse; + } + + if (index != -1) + { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) + { + return qtrue; // don't accept any calls on ragdoll bones + } + + //mark it for needing a transform for the cached trace transform stuff + blist[index].flags |= BONE_NEED_TRANSFORM; + } + + if (setFrame != -1) + { + assert((setFrame >= startFrame) && (setFrame <= endFrame)); + } + if (flags & BONE_ANIM_BLEND) + { + float currentFrame, animSpeed; + int startFrame, endFrame, flags; + // figure out where we are now + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, numFrames)) + { + if (blist[index].blendStart == currentTime) //we're replacing a blend in progress which hasn't started + { + // set the amount of time it's going to take to blend this anim with the last frame of the last one + blist[index].blendTime = blendTime; + } + else + { + if (animSpeed<0.0f) + { + blist[index].blendFrame = floor(currentFrame); + blist[index].blendLerpFrame = floor(currentFrame); + } + else + { + blist[index].blendFrame = currentFrame; + blist[index].blendLerpFrame = currentFrame+1; + + // cope with if the lerp frame is actually off the end of the anim + if (blist[index].blendFrame >= endFrame ) + { + // we only want to lerp with the first frame of the anim if we are looping + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) + { + blist[index].blendFrame = startFrame; + } + // if we intend to end this anim or freeze after this, then just keep on the last frame + else + { + // assert(endFrame>0); + if (endFrame <= 0) + { + blist[index].blendLerpFrame = 0; + } + else + { + blist[index].blendFrame = endFrame -1; + } + } + } + + // cope with if the lerp frame is actually off the end of the anim + if (blist[index].blendLerpFrame >= endFrame ) + { + // we only want to lerp with the first frame of the anim if we are looping + if (blist[index].flags & BONE_ANIM_OVERRIDE_LOOP) + { + blist[index].blendLerpFrame = startFrame; + } + // if we intend to end this anim or freeze after this, then just keep on the last frame + else + { + // assert(endFrame>0); + if (endFrame <= 0) + { + blist[index].blendLerpFrame = 0; + } + else + { + blist[index].blendLerpFrame = endFrame - 1; + } + } + } + } + // set the amount of time it's going to take to blend this anim with the last frame of the last one + blist[index].blendTime = blendTime; + blist[index].blendStart = currentTime; + + } + } + // hmm, we weren't animating on this bone. In which case disable the blend + else + { + blist[index].blendFrame = blist[index].blendLerpFrame = 0; + blist[index].blendTime = 0; + modFlags &= ~(BONE_ANIM_BLEND); + } + } + else + { + blist[index].blendFrame = blist[index].blendLerpFrame = 0; + blist[index].blendTime = blist[index].blendStart = 0; + // we aren't blending, so remove the option to do so + modFlags &= ~BONE_ANIM_BLEND; + } + // yes, so set the anim data and flags correctly + blist[index].endFrame = endFrame; + blist[index].startFrame = startFrame; + blist[index].animSpeed = animSpeed; + blist[index].pauseTime = 0; + // start up the animation:) + if (setFrame != -1) + { + blist[index].lastTime = blist[index].startTime = (currentTime - (((setFrame - (float)startFrame) * 50.0)/ animSpeed)); + } + else + { + blist[index].lastTime = blist[index].startTime = currentTime; + } + blist[index].flags &= ~(BONE_ANIM_TOTAL); + if (blist[index].flags < 0) + { + blist[index].flags = 0; + } + blist[index].flags |= modFlags; + +#if DEBUG_G2_TIMING + if (index==2) + { + const boneInfo_t &bone=blist[index]; + char mess[1000]; + if (bone.flags&BONE_ANIM_BLEND) + { + sprintf(mess,"sab[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", + index, + currentTime, + bone.startTime, + bone.startFrame, + bone.endFrame, + bone.animSpeed, + bone.flags, + bone.blendStart, + bone.blendStart+bone.blendTime, + bone.blendFrame, + bone.blendLerpFrame + ); + } + else + { + sprintf(mess,"saa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", + index, + currentTime, + bone.startTime, + bone.startFrame, + bone.endFrame, + bone.animSpeed, + bone.flags + ); + } + Com_OPrintf("%s",mess); + } +#endif + + return qtrue; + +} + +// given a model, bone name, a bonelist, a start/end frame number, a anim speed and some anim flags, set up or modify an existing bone entry for a new set of anims +qboolean G2_Set_Bone_Anim(CGhoul2Info *ghlInfo, + boneInfo_v &blist, + const char *boneName, + const int startFrame, + const int endFrame, + const int flags, + const float animSpeed, + const int currentTime, + const float setFrame, + const int blendTime) +{ + model_t *mod_a = (model_t *)ghlInfo->animModel; + + int index = G2_Find_Bone(mod_a, blist, boneName); + if (index == -1) + { + index = G2_Add_Bone(mod_a, blist, boneName); + } + + if (index != -1) + { + if (blist[index].flags & BONE_ANGLES_RAGDOLL) + { + return qtrue; // don't accept any calls on ragdoll bones + } + } + + if (index != -1) + { + return G2_Set_Bone_Anim_Index(blist,index,startFrame,endFrame,flags,animSpeed,currentTime,setFrame,blendTime,ghlInfo->aHeader->numFrames); + } + return qfalse; +} + +qboolean G2_Get_Bone_Anim_Range(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, int *startFrame, int *endFrame) +{ + model_t *mod_a = (model_t *)ghlInfo->animModel; + int index = G2_Find_Bone(mod_a, blist, boneName); + + // did we find it? + if (index != -1) + { + // are we an animating bone? + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) + { + *startFrame = blist[index].startFrame; + *endFrame = blist[index].endFrame; + return qtrue; + } + } + return qfalse; +} + +// given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation +// NOTE if we aren't running an animation, then qfalse is returned +void G2_TimingModel(boneInfo_t &bone,int currentTime,int numFramesInFile,int ¤tFrame,int &newFrame,float &lerp); + +qboolean G2_Get_Bone_Anim_Index( boneInfo_v &blist, const int index, const int currentTime, + float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int numFrames) +{ + + // did we find it? + if ((index>=0) && !((index >= (int)blist.size()) || (blist[index].boneNumber == -1))) + { + + // are we an animating bone? + if (blist[index].flags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) + { + int lcurrentFrame,newFrame; + float lerp; + G2_TimingModel(blist[index],currentTime,numFrames,lcurrentFrame,newFrame,lerp); + + *currentFrame =float(lcurrentFrame)+lerp; + *startFrame = blist[index].startFrame; + *endFrame = blist[index].endFrame; + *flags = blist[index].flags; + *retAnimSpeed = blist[index].animSpeed; + return qtrue; + } + } + *startFrame=0; + *endFrame=1; + *currentFrame=0.0f; + *flags=0; + *retAnimSpeed=0.0f; + return qfalse; +} + +// given a model, bonelist and bonename, return the current frame, startframe and endframe of the current animation +// NOTE if we aren't running an animation, then qfalse is returned +qboolean G2_Get_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime, + float *currentFrame, int *startFrame, int *endFrame, int *flags, float *retAnimSpeed, qhandle_t *modelList, int modelIndex) +{ + model_t *mod_a = (model_t *)ghlInfo->animModel; + + int index = G2_Find_Bone(mod_a, blist, boneName); + + if (index==-1) + { + index = G2_Add_Bone(mod_a, blist, boneName); + + if (index == -1) + { + return qfalse; + } + } + + assert(ghlInfo->aHeader); + + if (G2_Get_Bone_Anim_Index(blist, index, currentTime, currentFrame, startFrame, endFrame, flags, retAnimSpeed, modelList, ghlInfo->aHeader->numFrames)) + { + assert(*startFrame>=0&&*startFrameaHeader->numFrames); + assert(*endFrame>0&&*endFrame<=ghlInfo->aHeader->numFrames); + assert(*currentFrame>=0.0f&&((int)(*currentFrame))aHeader->numFrames); + return qtrue; + } + + return qfalse; +} + +// given a model, bonelist and bonename, lets pause an anim if it's playing. +qboolean G2_Pause_Bone_Anim(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName, const int currentTime) +{ + model_t *mod_a = (model_t *)ghlInfo->animModel; + + int index = G2_Find_Bone(mod_a, blist, boneName); + + // did we find it? + if (index != -1) + { + // are we pausing or un pausing? + if (blist[index].pauseTime) + { + int startFrame, endFrame, flags; + float currentFrame, animSpeed; + + // figure out what frame we are on now + G2_Get_Bone_Anim(ghlInfo, blist, boneName, blist[index].pauseTime, ¤tFrame, &startFrame, &endFrame, &flags, &animSpeed, NULL, 0); + // reset start time so we are actually on this frame right now + G2_Set_Bone_Anim(ghlInfo, blist, boneName, startFrame, endFrame, flags, animSpeed, currentTime, currentFrame, 0); + // no pausing anymore + blist[index].pauseTime = 0; + } + // ahh, just pausing, the easy bit + else + { + blist[index].pauseTime = currentTime; + } + + return qtrue; + } + assert(0); + + return qfalse; +} + +qboolean G2_IsPaused(const char *fileName, boneInfo_v &blist, const char *boneName) +{ + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); + + // did we find it? + if (index != -1) + { + // are we paused? + if (blist[index].pauseTime) + { + // yup. paused. + return qtrue; + } + return qfalse; + } + + return qfalse; +} + +// given a model, bonelist and bonename, lets stop an anim if it's playing. +qboolean G2_Stop_Bone_Anim_Index(boneInfo_v &blist, const int index) +{ + + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) + { + // we are attempting to set a bone override that doesn't exist + assert(0); + return qfalse; + } + + blist[index].flags &= ~(BONE_ANIM_TOTAL); + // try and remove this bone if we can + return G2_Remove_Bone_Index(blist, index); +} + +// given a model, bonelist and bonename, lets stop an anim if it's playing. +qboolean G2_Stop_Bone_Anim(const char *fileName, boneInfo_v &blist, const char *boneName) +{ + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); + + // did we find it? + if (index != -1) + { + blist[index].flags &= ~(BONE_ANIM_TOTAL); + // try and remove this bone if we can + return G2_Remove_Bone_Index(blist, index); + } + assert(0); + + return qfalse; +} + +// given a model, bonelist and bonename, lets stop an anim if it's playing. +qboolean G2_Stop_Bone_Angles_Index(boneInfo_v &blist, const int index) +{ + + if ((index >= (int)blist.size()) || (blist[index].boneNumber == -1)) + { + // we are attempting to set a bone override that doesn't exist + assert(0); + return qfalse; + } + + blist[index].flags &= ~(BONE_ANGLES_TOTAL); + // try and remove this bone if we can + return G2_Remove_Bone_Index(blist, index); + +} + +// given a model, bonelist and bonename, lets stop an anim if it's playing. +qboolean G2_Stop_Bone_Angles(const char *fileName, boneInfo_v &blist, const char *boneName) +{ + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + int index = G2_Find_Bone(mod_a, blist, boneName); + + // did we find it? + if (index != -1) + { + blist[index].flags &= ~(BONE_ANGLES_TOTAL); + // try and remove this bone if we can + return G2_Remove_Bone_Index(blist, index); + } + assert(0); + + return qfalse; +} + + +// actually walk the bone list and update each and every bone if we have ended an animation for them. +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index ) +{ + boneInfo_v &blist = ghoul2[index].mBlist; + + // look through entire list + for(size_t i=0; i 0.0f) && (newFrame_g > endFrame-1 )) || + ((animSpeed < 0.0f) && (newFrame_g < endFrame+1 ))) + { + // yep - decide what to do + if (blist[i].flags & BONE_ANIM_OVERRIDE_LOOP) + { + // get our new animation frame back within the bounds of the animation set + if (animSpeed < 0.0f) + { + if (newFrame_g <= endFrame+1) + { + newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + } + } + else + { + if (newFrame_g >= endFrame) + { + newFrame_g=endFrame+fmod(newFrame_g-endFrame,animSize)-animSize; + } + } + // figure out new start time + float frameTime = newFrame_g - blist[i].startFrame ; + blist[i].startTime = currentTime - (int)((frameTime / animSpeed) * 50.0f); + if (blist[i].startTime>currentTime) + { + blist[i].startTime=currentTime; + } + assert(blist[i].startTime <= currentTime); + blist[i].lastTime = blist[i].startTime; + } + else + { + if ((blist[i].flags & BONE_ANIM_OVERRIDE_FREEZE) != BONE_ANIM_OVERRIDE_FREEZE) + { + // nope, just stop it. And remove the bone if possible + G2_Stop_Bone_Index(blist, i, (BONE_ANIM_TOTAL)); + } + } + } + } + } + } + } +} + +//rww - RAGDOLL_BEGIN +/* + + + rag stuff + +*/ +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool LimitAngles,CRagDollUpdateParams *params = NULL); +static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V,int g2Index,int frameNum,const vec3_t angles,const vec3_t position,const vec3_t scale); +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V,const vec3_t currentOrg,CRagDollUpdateParams *params, int curTime); +static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered); + +void G2_GetBoneBasepose(CGhoul2Info &ghoul2,int boneNum,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); +int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep); +void G2_GetBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); +int G2_GetParentBoneMatrixLow(CGhoul2Info &ghoul2,int boneNum,const vec3_t scale,mdxaBone_t &retMatrix,mdxaBone_t *&retBasepose,mdxaBone_t *&retBaseposeInv); +bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum); + +#define MAX_BONES_RAG (256) + +struct SRagEffector +{ + vec3_t currentOrigin; + vec3_t desiredDirection; + vec3_t desiredOrigin; + float radius; + float weight; +}; + +#define RAG_MASK (CONTENTS_SOLID|CONTENTS_TERRAIN)//|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN//(/*MASK_SOLID|*/CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_SHOTCLIP|CONTENTS_TERRAIN|CONTENTS_BODY) + +extern cvar_t *broadsword; +extern cvar_t *broadsword_kickbones; +extern cvar_t *broadsword_kickorigin; +extern cvar_t *broadsword_dontstopanim; +extern cvar_t *broadsword_waitforshot; +extern cvar_t *broadsword_playflop; + +extern cvar_t *broadsword_effcorr; + +extern cvar_t *broadsword_ragtobase; + +extern cvar_t *broadsword_dircap; + +extern cvar_t *broadsword_extra1; +extern cvar_t *broadsword_extra2; + +#define RAG_PCJ (0x00001) +#define RAG_PCJ_POST_MULT (0x00002) // has the pcj flag as well +#define RAG_PCJ_MODEL_ROOT (0x00004) // has the pcj flag as well +#define RAG_PCJ_PELVIS (0x00008) // has the pcj flag and POST_MULT as well +#define RAG_EFFECTOR (0x00100) +#define RAG_WAS_NOT_RENDERED (0x01000) // not particularily reliable, more of a hint +#define RAG_WAS_EVER_RENDERED (0x02000) // not particularily reliable, more of a hint +#define RAG_BONE_LIGHTWEIGHT (0x04000) //used to indicate a bone's velocity treatment +#define RAG_PCJ_IK_CONTROLLED (0x08000) //controlled from IK move input +#define RAG_UNSNAPPABLE (0x10000) //cannot be broken out of constraints ever + +// thiese flags are on the model and correspond to... +//#define GHOUL2_RESERVED_FOR_RAGDOLL 0x0ff0 // these are not defined here for dependecies sake +#define GHOUL2_RAG_STARTED 0x0010 // we are actually a ragdoll +#define GHOUL2_RAG_PENDING 0x0100 // got start death anim but not end death anim +#define GHOUL2_RAG_DONE 0x0200 // got end death anim +#define GHOUL2_RAG_COLLISION_DURING_DEATH 0x0400 // ever have gotten a collision (da) event +#define GHOUL2_RAG_COLLISION_SLIDE 0x0800 // ever have gotten a collision (slide) event +#define GHOUL2_RAG_FORCESOLVE 0x1000 //api-override, determine if ragdoll should be forced to continue solving even if it thinks it is settled + +//#define flrand Q_flrand + +static mdxaBone_t* ragBasepose[MAX_BONES_RAG]; +static mdxaBone_t* ragBaseposeInv[MAX_BONES_RAG]; +static mdxaBone_t ragBones[MAX_BONES_RAG]; +static SRagEffector ragEffectors[MAX_BONES_RAG]; +static boneInfo_t *ragBoneData[MAX_BONES_RAG]; +static int tempDependents[MAX_BONES_RAG]; +static int ragBlistIndex[MAX_BONES_RAG]; +static int numRags; +static vec3_t ragBoneMins; +static vec3_t ragBoneMaxs; +static vec3_t ragBoneCM; +static bool haveDesiredPelvisOffset=false; +static vec3_t desiredPelvisOffset; // this is for the root +static float ragOriginChange=0.0f; +static vec3_t ragOriginChangeDir; +//debug +#if 0 +static vec3_t handPos={0,0,0}; +static vec3_t handPos2={0,0,0}; +#endif + +enum ERagState +{ + ERS_DYNAMIC, + ERS_SETTLING, + ERS_SETTLED +}; +static int ragState; + +static std::vector rag; // once we get the dependents precomputed this can be local + + +static void G2_Generate_MatrixRag( + // caution this must not be called before the whole skeleton is "remembered" + boneInfo_v &blist, + int index) +{ + + + boneInfo_t &bone=blist[index];//.sent; + + memcpy(&bone.matrix,&bone.ragOverrideMatrix, sizeof(mdxaBone_t)); +#ifdef _DEBUG + int i,j; + for (i = 0; i < 3; i++ ) + { + for (j = 0; j < 4; j++ ) + { + assert( !Q_isnan(bone.matrix.matrix[i][j])); + } + } +#endif// _DEBUG + memcpy(&blist[index].newMatrix,&bone.matrix, sizeof(mdxaBone_t)); +} + +int G2_Find_Bone_Rag(CGhoul2Info *ghlInfo, boneInfo_v &blist, const char *boneName) +{ + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); + skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); + + /* + model_t *currentModel; + model_t *animModel; + mdxaHeader_t *aHeader; + + currentModel = R_GetModelByHandle(RE_RegisterModel(ghlInfo->mFileName)); + assert(currentModel); + animModel = R_GetModelByHandle(currentModel->mdxm->animIndex); + assert(animModel); + aHeader = animModel->mdxa; + assert(aHeader); + + offsets = (mdxaSkelOffsets_t *)((byte *)aHeader + sizeof(mdxaHeader_t)); + skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); + */ + + // look through entire list + for(size_t i=0; iaHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); + //skel = (mdxaSkel_t *)((byte *)aHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); + + // if name is the same, we found it + if (!Q_stricmp(skel->name, boneName)) + { + return i; + } + } +#if _DEBUG +// G2_Bone_Not_Found(boneName,ghlInfo->mFileName); +#endif + // didn't find it + return -1; +} + +static int G2_Set_Bone_Rag(const mdxaHeader_t *mod_a, + boneInfo_v &blist, + const char *boneName, + CGhoul2Info &ghoul2, + const vec3_t scale, + const vec3_t origin) +{ + // do not change the state of the skeleton here + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); + + if (index == -1) + { + index = G2_Add_Bone(ghoul2.animModel, blist, boneName); + } + + if (index != -1) + { + boneInfo_t &bone=blist[index]; + VectorCopy(origin,bone.extraVec1); + + G2_GetBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.originalTrueBoneMatrix,bone.basepose,bone.baseposeInv); +// bone.parentRawBoneIndex=G2_GetParentBoneMatrixLow(ghoul2,bone.boneNumber,scale,bone.parentTrueBoneMatrix,bone.baseposeParent,bone.baseposeInvParent); + assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][1])); + assert( !Q_isnan(bone.originalTrueBoneMatrix.matrix[1][3])); + bone.originalOrigin[0]=bone.originalTrueBoneMatrix.matrix[0][3]; + bone.originalOrigin[1]=bone.originalTrueBoneMatrix.matrix[1][3]; + bone.originalOrigin[2]=bone.originalTrueBoneMatrix.matrix[2][3]; + } + return index; +} + +static int G2_Set_Bone_Angles_Rag( + CGhoul2Info &ghoul2, + const mdxaHeader_t *mod_a, + boneInfo_v &blist, + const char *boneName, + const int flags, + const float radius, + const vec3_t angleMin=0, + const vec3_t angleMax=0, + const int blendTime=500) +{ + int index = G2_Find_Bone_Rag(&ghoul2, blist, boneName); + + if (index == -1) + { + index = G2_Add_Bone(ghoul2.animModel, blist, boneName); + } + if (index != -1) + { + boneInfo_t &bone=blist[index]; + bone.flags &= ~(BONE_ANGLES_TOTAL); + bone.flags |= BONE_ANGLES_RAGDOLL; + if (flags&RAG_PCJ) + { + if (flags&RAG_PCJ_POST_MULT) + { + bone.flags |= BONE_ANGLES_POSTMULT; + } + else if (flags&RAG_PCJ_MODEL_ROOT) + { + bone.flags |= BONE_ANGLES_PREMULT; +// bone.flags |= BONE_ANGLES_POSTMULT; + } + else + { + assert(!"Invalid RAG PCJ\n"); + } + } + bone.ragStartTime=G2API_GetTime(0); + bone.boneBlendStart = bone.ragStartTime; + bone.boneBlendTime = blendTime; + bone.radius=radius; + bone.weight=1.0f; + + //init the others to valid values + bone.epGravFactor = 0; + VectorClear(bone.epVelocity); + bone.solidCount = 0; + bone.physicsSettled = false; + bone.snapped = false; + + bone.parentBoneIndex = -1; + + bone.offsetRotation = 0.0f; + + bone.overGradSpeed = 0.0f; + VectorClear(bone.overGoalSpot); + bone.hasOverGoal = false; + bone.hasAnimFrameMatrix = -1; + +// bone.weight=pow(radius,1.7f); //cubed was too harsh +// bone.weight=radius*radius*radius; + if (angleMin&&angleMax) + { + VectorCopy(angleMin,bone.minAngles); + VectorCopy(angleMax,bone.maxAngles); + } + else + { + VectorCopy(bone.currentAngles,bone.minAngles); // I guess this isn't a rag pcj then + VectorCopy(bone.currentAngles,bone.maxAngles); + } + if (!bone.lastTimeUpdated) + { + static mdxaBone_t id = + { + { + { 1.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f, 0.0f } + } + }; + memcpy(&bone.ragOverrideMatrix,&id, sizeof(mdxaBone_t)); + VectorClear(bone.anglesOffset); + VectorClear(bone.positionOffset); + VectorClear(bone.velocityEffector); // this is actually a velocity now + VectorClear(bone.velocityRoot); // this is actually a velocity now + VectorClear(bone.lastPosition); + VectorClear(bone.lastShotDir); + bone.lastContents=0; + // if this is non-zero, we are in a dynamic state + bone.firstCollisionTime=bone.ragStartTime; + // if this is non-zero, we are in a settling state + bone.restTime=0; + // if they are both zero, we are in a settled state + + bone.firstTime=0; + + bone.RagFlags=flags; + bone.DependentRagIndexMask=0; + + G2_Generate_MatrixRag(blist,index); // set everything to th id + +#if 0 + VectorClear(bone.currentAngles); +// VectorAdd(bone.minAngles,bone.maxAngles,bone.currentAngles); +// VectorScale(bone.currentAngles,0.5f,bone.currentAngles); +#else + { + if ( + (flags&RAG_PCJ_MODEL_ROOT) || + (flags&RAG_PCJ_PELVIS) || + !(flags&RAG_PCJ)) + { + VectorClear(bone.currentAngles); + } + else + { + int k; + for (k=0;k<3;k++) + { + float scalar=flrand(-1.0f,1.0f); + scalar*=flrand(-1.0f,1.0f)*flrand(-1.0f,1.0f); + // this is a heavily central distribution + // center it on .5 (and make it small) + scalar*=0.5f; + scalar+=0.5f; + + bone.currentAngles[k]=(bone.minAngles[k]-bone.maxAngles[k])*scalar+bone.maxAngles[k]; + } + } + } +// VectorClear(bone.currentAngles); +#endif + VectorCopy(bone.currentAngles,bone.lastAngles); + } + } + return index; +} + +class CRagDollParams; +const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2); + + +static void G2_RagDollMatchPosition() +{ + haveDesiredPelvisOffset=false; + int i; + for (i=0;inumBones); +#else //The anims on every bone are messed up too, as are the angles. There's not really any way to get back to a normal state, so just clear the list + //and let them re-set their anims/angles gameside. + int i = 0; + while (i < blist.size()) + { + boneInfo_t &bone = blist[i]; + if (bone.boneNumber != -1 && (bone.flags & BONE_ANGLES_RAGDOLL)) + { + bone.flags &= ~BONE_ANGLES_RAGDOLL; + bone.flags &= ~BONE_ANGLES_IK; + bone.RagFlags = 0; + bone.lastTimeUpdated = 0; + VectorClear(bone.currentAngles); + bone.ragStartTime = 0; + } + i++; + } +#endif + ghoul2.mFlags &= ~(GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED); +} + +void G2_SetRagDoll(CGhoul2Info_v &ghoul2V,CRagDollParams *parms) +{ + if (parms) + { + parms->CallRagDollBegin=qfalse; + } + if (!broadsword||!broadsword->integer||!parms) + { + return; + } + int model; + for (model = 0; model < ghoul2V.size(); model++) + { + if (ghoul2V[model].mModelindex != -1) + { + break; + } + } + if (model==ghoul2V.size()) + { + return; + } + CGhoul2Info &ghoul2=ghoul2V[model]; + const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); + if (!mod_a) + { + return; + } + int curTime=G2API_GetTime(0); + boneInfo_v &blist = ghoul2.mBlist; + int index = G2_Find_Bone_Rag(&ghoul2, blist, "model_root"); + switch (parms->RagPhase) + { + case CRagDollParams::RP_START_DEATH_ANIM: + ghoul2.mFlags|=GHOUL2_RAG_PENDING; + return; /// not doing anything with this yet + break; + case CRagDollParams::RP_END_DEATH_ANIM: + ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE; + if (broadsword_waitforshot && + broadsword_waitforshot->integer) + { + if (broadsword_waitforshot->integer==2) + { + if (!(ghoul2.mFlags&(GHOUL2_RAG_COLLISION_DURING_DEATH|GHOUL2_RAG_COLLISION_SLIDE))) + { + //nothing was encountered, lets just wait for the first shot + return; // we ain't starting yet + } + } + else + { + return; // we ain't starting yet + } + } + break; + case CRagDollParams::RP_DEATH_COLLISION: + if (parms->collisionType) + { + ghoul2.mFlags|=GHOUL2_RAG_COLLISION_SLIDE; + } + else + { + ghoul2.mFlags|=GHOUL2_RAG_COLLISION_DURING_DEATH; + } + if (broadsword_dontstopanim && broadsword_waitforshot && + (broadsword_dontstopanim->integer || broadsword_waitforshot->integer) + ) + { + if (!(ghoul2.mFlags&GHOUL2_RAG_DONE)) + { + return; // we ain't starting yet + } + } + break; + case CRagDollParams::RP_CORPSE_SHOT: + if (broadsword_kickorigin && + broadsword_kickorigin->integer) + { + if (index>=0&&index<(int)blist.size()) + { + boneInfo_t &bone=blist[index]; + if (bone.boneNumber>=0) + { + if (bone.flags & BONE_ANGLES_RAGDOLL) + { + //rww - Would need ent pointer here. But.. since this is SW, we aren't even having corpse shooting anyway I'd imagine. + /* + float magicFactor14=8.0f; //64.0f; // kick strength + + if (parms->fShotStrength) + { //if there is a shot strength, use it instead + magicFactor14 = parms->fShotStrength; + } + + parms->me->s.pos.trType = TR_GRAVITY; + parms->me->s.pos.trDelta[0] += bone.lastShotDir[0]*magicFactor14; + parms->me->s.pos.trDelta[1] += bone.lastShotDir[1]*magicFactor14; + //parms->me->s.pos.trDelta[2] = fabsf(bone.lastShotDir[2])*magicFactor14; + //rww - The vertical portion of this doesn't seem to work very well + //I am just leaving it whatever it is for now, because my velocity scaling + //only works on x and y and the gravity stuff for NPCs is a bit unpleasent + //trying to change/work with + assert( !Q_isnan(bone.lastShotDir[1])); + */ + } + } + } + } + break; + case CRagDollParams::RP_GET_PELVIS_OFFSET: + if (parms->RagPhase==CRagDollParams::RP_GET_PELVIS_OFFSET) + { + VectorClear(parms->pelvisAnglesOffset); + VectorClear(parms->pelvisPositionOffset); + } + // intentional lack of a break + case CRagDollParams::RP_SET_PELVIS_OFFSET: + if (index>=0&&index<(int)blist.size()) + { + boneInfo_t &bone=blist[index]; + if (bone.boneNumber>=0) + { + if (bone.flags & BONE_ANGLES_RAGDOLL) + { + if (parms->RagPhase==CRagDollParams::RP_GET_PELVIS_OFFSET) + { + VectorCopy(bone.anglesOffset,parms->pelvisAnglesOffset); + VectorCopy(bone.positionOffset,parms->pelvisPositionOffset); + } + else + { + VectorCopy(parms->pelvisAnglesOffset,bone.anglesOffset); + VectorCopy(parms->pelvisPositionOffset,bone.positionOffset); + } + } + } + } + return; + break; + case CRagDollParams::RP_DISABLE_EFFECTORS: + // not doing anything with this yet + return; + break; + default: + assert(0); + return; + break; + } + if (ghoul2.mFlags&GHOUL2_RAG_STARTED) + { + // only going to begin ragdoll once, everything else depends on what happens to the origin + return; + } + + ghoul2.mFlags|=GHOUL2_RAG_PENDING|GHOUL2_RAG_DONE|GHOUL2_RAG_STARTED; // well anyway we are going live + parms->CallRagDollBegin=qtrue; + + G2_GenerateWorldMatrix(parms->angles, parms->position); + G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); + + G2_Set_Bone_Rag(mod_a,blist,"model_root",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"pelvis",ghoul2,parms->scale,parms->position); + + G2_Set_Bone_Rag(mod_a,blist,"lower_lumbar",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"upper_lumbar",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"thoracic",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"cranium",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"rhumerus",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"lhumerus",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"rradius",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"lradius",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"rfemurYZ",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"lfemurYZ",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"rtibia",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"ltibia",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"rhand",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"lhand",ghoul2,parms->scale,parms->position); + //G2_Set_Bone_Rag(mod_a,blist,"rtarsal",ghoul2,parms->scale,parms->position); + //G2_Set_Bone_Rag(mod_a,blist,"ltarsal",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"rtalus",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"ltalus",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"rradiusX",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"lradiusX",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"rfemurX",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"lfemurX",ghoul2,parms->scale,parms->position); + G2_Set_Bone_Rag(mod_a,blist,"ceyebrow",ghoul2,parms->scale,parms->position); + + //int startFrame = 3665, endFrame = 3665+1; + int startFrame = parms->startFrame, endFrame = parms->endFrame; + + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"upper_lumbar",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lower_lumbar",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"Motion",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),150,0,true); +// G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"model_root",startFrame,endFrame-1, +// BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, +// 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lfemurYZ",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rfemurYZ",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),150,0,true); + + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"rhumerus",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),150,0,true); + G2_Set_Bone_Anim_No_BS(ghoul2, mod_a,blist,"lhumerus",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),150,0,true); + + G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); + + static const float fRadScale = 0.3f;//0.5f; + + vec3_t pcjMin,pcjMax; + VectorSet(pcjMin,-90.0f,-45.0f,-45.0f); + VectorSet(pcjMax,90.0f,45.0f,45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"model_root",RAG_PCJ_MODEL_ROOT|RAG_PCJ|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); + VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); + VectorSet(pcjMax,45.0f,45.0f,45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"pelvis",RAG_PCJ_PELVIS|RAG_PCJ|RAG_PCJ_POST_MULT|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,100); + +#if 1 + // new base anim, unconscious flop + int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT;//|RAG_EFFECTOR; + + VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); + VectorSet(pcjMax,15.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags|RAG_UNSNAPPABLE,10.0f*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin,-25.0f,-25.0f,-25.0f); + VectorSet(pcjMax,25.0f,25.0f,25.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags|RAG_EFFECTOR|RAG_UNSNAPPABLE,12.0f*fRadScale,pcjMin,pcjMax,500); + + VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); + VectorSet(pcjMax,10.0f,10.0f,90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,6.0f*fRadScale,pcjMin,pcjMax,500); + + static const float sFactLeg = 1.0f; + static const float sFactArm = 1.0f; + static const float sRadArm = 1.0f; + static const float sRadLeg = 1.0f; + + VectorSet(pcjMin,-100.0f,-40.0f,-15.0f); + VectorSet(pcjMax,-15.0f,80.0f,15.0f); + VectorScale(pcjMin, sFactArm, pcjMin); + VectorScale(pcjMax, sFactArm, pcjMax); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin,-50.0f,-80.0f,-15.0f); + VectorSet(pcjMax,15.0f,40.0f,15.0f); + VectorScale(pcjMin, sFactArm, pcjMin); + VectorScale(pcjMax, sFactArm, pcjMax); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT|RAG_UNSNAPPABLE,(4.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + + VectorSet(pcjMin,-25.0f,-20.0f,-20.0f); + VectorSet(pcjMax,90.0f,20.0f,-20.0f); + VectorScale(pcjMin, sFactArm, pcjMin); + VectorScale(pcjMax, sFactArm, pcjMax); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); + VectorSet(pcjMax,30.0f,20.0f,-20.0f); + VectorScale(pcjMin, sFactArm, pcjMin); + VectorScale(pcjMax, sFactArm, pcjMax); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,(3.0f*sRadArm)*fRadScale,pcjMin,pcjMax,500); + + + VectorSet(pcjMin,-80.0f,-50.0f,-20.0f); + VectorSet(pcjMax,30.0f,5.0f,20.0f); + VectorScale(pcjMin, sFactLeg, pcjMin); + VectorScale(pcjMax, sFactLeg, pcjMax); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin,-60.0f,-5.0f,-20.0f); + VectorSet(pcjMax,50.0f,50.0f,20.0f); + VectorScale(pcjMin, sFactLeg, pcjMin); + VectorScale(pcjMax, sFactLeg, pcjMax); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + + VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); + VectorSet(pcjMax,100.0f,15.0f,15.0f); + VectorScale(pcjMin, sFactLeg, pcjMin); + VectorScale(pcjMax, sFactLeg, pcjMax); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); + VectorSet(pcjMin,20.0f,-15.0f,-15.0f); + VectorSet(pcjMax,100.0f,15.0f,15.0f); + VectorScale(pcjMin, sFactLeg, pcjMin); + VectorScale(pcjMax, sFactLeg, pcjMax); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadLeg)*fRadScale,pcjMin,pcjMax,500); +#else + // old base anim + int pcjflags=RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; + + VectorSet(pcjMin,-15.0f,-15.0f,-15.0f); + VectorSet(pcjMax,45.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lower_lumbar",pcjflags,10.0f,pcjMin,pcjMax,500); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"upper_lumbar",pcjflags,10.0f,pcjMin,pcjMax,500); + VectorSet(pcjMin,-45.0f,-45.0f,-45.0f); + VectorSet(pcjMax,45.0f,45.0f,45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"thoracic",pcjflags,10.0f,pcjMin,pcjMax,500); + + VectorSet(pcjMin,-10.0f,-10.0f,-90.0f); + VectorSet(pcjMax,10.0f,10.0f,90.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"cranium",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); + + //VectorSet(pcjMin,-45.0f,-90.0f,-100.0f); + VectorSet(pcjMin,-180.0f,-180.0f,-100.0f); + //VectorSet(pcjMax,60.0f,60.0f,45.0f); + VectorSet(pcjMax,180.0f,180.0f,45.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + //VectorSet(pcjMin,-45.0f,-60.0f,-45.0f); + VectorSet(pcjMin,-180.0f,-180.0f,-100.0f); + //VectorSet(pcjMax,60.0f,90.0f,100.0f); + VectorSet(pcjMax,180.0f,180.0f,100.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhumerus",pcjflags|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + + //-120/120 + VectorSet(pcjMin,-120.0f,-20.0f,-20.0f); + VectorSet(pcjMax,50.0f,20.0f,-20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradius",pcjflags|RAG_BONE_LIGHTWEIGHT,3.0f,pcjMin,pcjMax,500); + VectorSet(pcjMin,-120.0f,-20.0f,-20.0f); + VectorSet(pcjMax,5.0f,20.0f,-20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradius",pcjflags|RAG_BONE_LIGHTWEIGHT,3.0f,pcjMin,pcjMax,500); + + VectorSet(pcjMin,-90.0f,-50.0f,-20.0f); + VectorSet(pcjMax,50.0f,20.0f,20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); + VectorSet(pcjMin,-90.0f,-20.0f,-20.0f); + VectorSet(pcjMax,50.0f,50.0f,20.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurYZ",pcjflags|RAG_BONE_LIGHTWEIGHT,6.0f,pcjMin,pcjMax,500); + + //120 + VectorSet(pcjMin,-20.0f,-15.0f,-15.0f); + VectorSet(pcjMax,120.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); + VectorSet(pcjMin,20.0f,-15.0f,-15.0f); + VectorSet(pcjMax,120.0f,15.0f,15.0f); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",pcjflags|RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,4.0f,pcjMin,pcjMax,500); +#endif + + + float sRadEArm = 1.2f; + float sRadELeg = 1.2f; + +// int rhand= + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lhand",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltarsal",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); +// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); +// G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltibia",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rtalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ltalus",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(4.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lradiusX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(6.0f*sRadEArm)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"rfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"lfemurX",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,(10.0f*sRadELeg)*fRadScale); + //G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,10.0f*fRadScale); + G2_Set_Bone_Angles_Rag(ghoul2, mod_a,blist,"ceyebrow",RAG_EFFECTOR|RAG_BONE_LIGHTWEIGHT,5.0f); +//match the currrent animation + if (!G2_RagDollSetup(ghoul2,curTime,true,parms->position,false)) + { + assert(!"failed to add any rag bones"); + return; + } + G2_RagDollCurrentPosition(ghoul2V,model,curTime,parms->angles,parms->position,parms->scale); + int k; + + CRagDollUpdateParams fparms; + VectorCopy(parms->position, fparms.position); + VectorCopy(parms->angles, fparms.angles); + VectorCopy(parms->scale, fparms.scale); + VectorClear(fparms.velocity); + fparms.me = parms->me; + fparms.settleFrame = parms->endFrame; + + //Guess I don't need to do this, do I? + G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); + + vec3_t dPos; + VectorCopy(parms->position, dPos); +#ifdef _OLD_STYLE_SETTLE + dPos[2] -= 6; +#endif + + for (k=0;kangles,dPos,parms->scale); + G2_RagDollMatchPosition(); + G2_RagDollSolve(ghoul2V,model,1.0f*(1.0f-k/40.0f),curTime,dPos,false); + } +} + +void G2_SetRagDollBullet(CGhoul2Info &ghoul2,const vec3_t rayStart,const vec3_t hit) +{ + if (!broadsword||!broadsword->integer) + { + return; + } + vec3_t shotDir; + VectorSubtract(hit,rayStart,shotDir); + float len=VectorLength(shotDir); + if (len<1.0f) + { + return; + } + float lenr=1.0f/len; + shotDir[0]*=lenr; + shotDir[1]*=lenr; + shotDir[2]*=lenr; + + bool firstOne=false; + if (broadsword_kickbones&&broadsword_kickbones->integer) + { + int magicFactor13=150.0f; // squared radius multiplier for shot effects + boneInfo_v &blist = ghoul2.mBlist; + for(int i=(int)(blist.size()-1);i>=0;i--) + { + boneInfo_t &bone=blist[i]; + if ((bone.flags & BONE_ANGLES_TOTAL)) + { + if (bone.flags & BONE_ANGLES_RAGDOLL) + { + if (!firstOne) + { + firstOne=true; +#if 0 + int curTime=G2API_GetTime(0); + const mdxaHeader_t *mod_a=G2_GetModA(ghoul2); + int startFrame = 0, endFrame = 0; +#if 1 + TheGhoul2Wraith()->GetAnimFrames(ghoul2.mID, "unconsciousdeadflop01", startFrame, endFrame); + if (startFrame == -1 && endFrame == -1) + { //A bad thing happened! Just use the hardcoded numbers even though they could be wrong. + startFrame = 3573; + endFrame = 3583; + assert(0); + } + G2_Set_Bone_Anim_No_BS(mod_a,blist,"upper_lumbar",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),75,0,true); + G2_Set_Bone_Anim_No_BS(mod_a,blist,"lfemurYZ",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),75,0,true); + G2_Set_Bone_Anim_No_BS(mod_a,blist,"rfemurYZ",startFrame,endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f,curTime,float(startFrame),75,0,true); +#else + TheGhoul2Wraith()->GetAnimFrames(ghoul2.mID, "backdeadflop01", startFrame, endFrame); + if (startFrame == -1 && endFrame == -1) + { //A bad thing happened! Just use the hardcoded numbers even though they could be wrong. + startFrame = 3581; + endFrame = 3592; + assert(0); + } + G2_Set_Bone_Anim_No_BS(mod_a,blist,"upper_lumbar",endFrame,startFrame+1, + BONE_ANIM_OVERRIDE_FREEZE, + -1.0f,curTime,float(endFrame-1),50,0,true); + G2_Set_Bone_Anim_No_BS(mod_a,blist,"lfemurYZ",endFrame,startFrame+1, + BONE_ANIM_OVERRIDE_FREEZE, + -1.0f,curTime,float(endFrame-1),50,0,true); + G2_Set_Bone_Anim_No_BS(mod_a,blist,"rfemurYZ",endFrame,startFrame+1, + BONE_ANIM_OVERRIDE_FREEZE, + -1.0f,curTime,float(endFrame-1),50,0,true); +#endif +#endif + } + + VectorCopy(shotDir,bone.lastShotDir); + vec3_t dir; + VectorSubtract(bone.lastPosition,hit,dir); + len=VectorLength(dir); + if (len<1.0f) + { + len=1.0f; + } + lenr=1.0f/len; + float effect=lenr; + effect*=magicFactor13*effect; // this is cubed, one of them is absorbed by the next calc + bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f)); + bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f)); + bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f)); +// bone.velocityEffector[0]=shotDir[0]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); +// bone.velocityEffector[1]=shotDir[1]*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); +// bone.velocityEffector[2]=fabs(shotDir[2])*(effect+flrand(0.0f,0.05f))*flrand(-0.1f,3.0f); + assert( !Q_isnan(shotDir[2])); + // bone.currentAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.currentAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[0]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[1]+=flrand(-10.0f*lenr,10.0f*lenr); + // bone.lastAngles[2]+=flrand(-10.0f*lenr,10.0f*lenr); + + // go dynamic + bone.firstCollisionTime=G2API_GetTime(0); +// bone.firstCollisionTime=0; + bone.restTime=0; + } + } + } + } +} + + +static float G2_RagSetState(CGhoul2Info &ghoul2, boneInfo_t &bone,int frameNum,const vec3_t origin,bool &resetOrigin) +{ + ragOriginChange=DistanceSquared(origin,bone.extraVec1); + VectorSubtract(origin,bone.extraVec1,ragOriginChangeDir); + + float decay=1.0f; + + int dynamicTime=1000; + int settleTime=1000; + + if (ghoul2.mFlags & GHOUL2_RAG_FORCESOLVE) + { + ragState=ERS_DYNAMIC; + if (frameNum>bone.firstCollisionTime+dynamicTime) + { + VectorCopy(origin,bone.extraVec1); + if (ragOriginChange>15.0f) + { //if we moved, or if this bone is still in solid + bone.firstCollisionTime=frameNum; + } + else + { + // settle out + bone.firstCollisionTime=0; + bone.restTime=frameNum; + ragState=ERS_SETTLING; + } + } + } + else if (bone.firstCollisionTime>0) + { + ragState=ERS_DYNAMIC; + if (frameNum>bone.firstCollisionTime+dynamicTime) + { + VectorCopy(origin,bone.extraVec1); + if (ragOriginChange>15.0f) + { //if we moved, or if this bone is still in solid + bone.firstCollisionTime=frameNum; + } + else + { + // settle out + bone.firstCollisionTime=0; + bone.restTime=frameNum; + ragState=ERS_SETTLING; + } + } +//decay=0.0f; + } + else if (bone.restTime>0) + { + decay=1.0f-(frameNum-bone.restTime)/float(dynamicTime); + if (decay<0.0f) + { + decay=0.0f; + } + if (decay>1.0f) + { + decay=1.0f; + } + float magicFactor8=1.0f; // Power for decay + decay=pow(decay,magicFactor8); + ragState=ERS_SETTLING; + if (frameNum>bone.restTime+settleTime) + { + VectorCopy(origin,bone.extraVec1); + if (ragOriginChange>15.0f) + { + bone.restTime=frameNum; + } + else + { + // stop + bone.restTime=0; + ragState=ERS_SETTLED; + } + } +//decay=0.0f; + } + else + { + if (bone.RagFlags & RAG_PCJ_IK_CONTROLLED) + { + bone.firstCollisionTime=frameNum; + ragState=ERS_DYNAMIC; + } + else if (ragOriginChange>15.0f) + { + bone.firstCollisionTime=frameNum; + ragState=ERS_DYNAMIC; + } + else + { + ragState=ERS_SETTLED; + } + decay=0.0f; + } +// ragState=ERS_SETTLED; +// decay=0.0f; + return decay; +} + +static bool G2_RagDollSetup(CGhoul2Info &ghoul2,int frameNum,bool resetOrigin,const vec3_t origin,bool anyRendered) +{ + int minSurvivingBone=10000; + //int minSurvivingBoneAt=-1; + int minSurvivingBoneAlt=10000; + //int minSurvivingBoneAtAlt=-1; + + assert(ghoul2.mFileName[0]); + boneInfo_v &blist = ghoul2.mBlist; + rag.clear(); + int numRendered=0; + int numNotRendered=0; + //int pelvisAt=-1; + for(size_t i=0; i=0) + { + assert(bone.boneNumberbone.boneNumber) + { + minSurvivingBone=bone.boneNumber; + //minSurvivingBoneAt=i; + } + } + else if (wasRendered) + { + if (minSurvivingBoneAlt>bone.boneNumber) + { + minSurvivingBoneAlt=bone.boneNumber; + //minSurvivingBoneAtAlt=i; + } + } + if ( + anyRendered && + (bone.RagFlags&RAG_WAS_EVER_RENDERED) && + !(bone.RagFlags&RAG_PCJ_MODEL_ROOT) && + !(bone.RagFlags&RAG_PCJ_PELVIS) && + !wasRendered && + (bone.RagFlags&RAG_EFFECTOR) + ) + { + // this thing was rendered in the past, but wasn't now, although other bones were, lets get rid of it +// bone.flags &= ~BONE_ANGLES_RAGDOLL; +// bone.RagFlags = 0; +//Com_OPrintf("Deleted Effector %d\n",i); +// continue; + } + if ((int)rag.size()=0 && + pelvisAt>=0) + { + { + // remove the pelvis as a rag + boneInfo_t &bone=blist[minSurvivingBoneAt]; + bone.flags&=~BONE_ANGLES_RAGDOLL; + bone.RagFlags=0; + } + { + // the root-est bone is now our "pelvis + boneInfo_t &bone=blist[minSurvivingBoneAt]; + VectorSet(bone.minAngles,-14500.0f,-14500.0f,-14500.0f); + VectorSet(bone.maxAngles,14500.0f,14500.0f,14500.0f); + bone.RagFlags|=RAG_PCJ_PELVIS|RAG_PCJ; // this guy is our new "pelvis" + bone.flags |= BONE_ANGLES_POSTMULT; + bone.ragStartTime=G2API_GetTime(0); + } + } + } +#endif + numRags=0; + //int ragStartTime=0; + for(size_t i=0; i=0); + assert(numRagsinteger) + { + return; + } + + if (!params) + { + assert(0); + return; + } + + vec3_t dPos; + VectorCopy(params->position, dPos); +#ifdef _OLD_STYLE_SETTLE + dPos[2] -= 6; +#endif + +// params->DebugLine(handPos,handPos2,false); + int frameNum=G2API_GetTime(0); + CGhoul2Info &ghoul2=ghoul2V[g2Index]; + assert(ghoul2.mFileName[0]); + boneInfo_v &blist = ghoul2.mBlist; + + // hack for freezing ragdoll (no idea if it works) +#if 0 + if (0) + { + // we gotta hack this to basically freeze the timers + for(i=0; i=0) + { + assert(bone.boneNumber=0) + { + assert(bone.boneNumber= 0 && bone2.solidCount > 8) + { + noneInSolid = false; + break; + } + } + + if (noneInSolid) + { //we're settled then + params->RagDollSettled(); + return; + } + else + { + continue; + } +#else + params->RagDollSettled(); + return; +#endif + } + if (G2_WasBoneRendered(ghoul2,bone.boneNumber)) + { + anyRendered=true; + break; + } + } + } + } + //int iters=(ragState==ERS_DYNAMIC)?2:1; + int iters=(ragState==ERS_DYNAMIC)?4:2; + //bool kicked=false; + if (ragOriginChangeDir[2]<-100.0f) + { + //kicked=true; + //iters*=8; + iters*=2; //rww - changed to this.. it was getting up to around 600 traces at times before (which is insane) + } + if (iters) + { + if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,dPos,anyRendered)) + { + return; + } + // ok, now our data structures are compact and set up in topological order + + for (int i=0;iangles,dPos,params->scale); + + if (G2_RagDollSettlePositionNumeroTrois(ghoul2V,dPos,params,curTime)) + { +#if 0 + //effectors are start solid alot, so this was pretty extreme + if (!kicked&&iters<4) + { + kicked=true; + //iters*=4; + iters*=2; + } +#endif + } + //params->position[2] += 16; + G2_RagDollSolve(ghoul2V,g2Index,decay*2.0f,frameNum,dPos,true,params); + } + } + + if (params->me != ENTITYNUM_NONE) + { +#if 0 + vec3_t worldMins,worldMaxs; + worldMins[0]=params->position[0]-17; + worldMins[1]=params->position[1]-17; + worldMins[2]=params->position[2]; + worldMaxs[0]=params->position[0]+17; + worldMaxs[1]=params->position[1]+17; + worldMaxs[2]=params->position[2]; +//Com_OPrintf(va("%f \n",worldMins[2]); +// params->DebugLine(worldMins,worldMaxs,true); +#endif + G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); +// SV_UnlinkEntity(params->me); +// params->me->SetMins(BB_SHOOTING_SIZE,ragBoneMins); +// params->me->SetMaxs(BB_SHOOTING_SIZE,ragBoneMaxs); +// SV_LinkEntity(params->me); + } +} + +#ifdef _DEBUG +#define _DEBUG_BONE_NAMES +#endif + +static inline char *G2_Get_Bone_Name(CGhoul2Info *ghlInfo, boneInfo_v &blist, int boneNum) +{ + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + offsets = (mdxaSkelOffsets_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t)); + skel = (mdxaSkel_t *)((byte *)ghlInfo->aHeader + sizeof(mdxaHeader_t) + offsets->offsets[0]); + + // look through entire list + for(size_t i=0; iaHeader + sizeof(mdxaHeader_t) + offsets->offsets[blist[i].boneNumber]); + + return skel->name; + } + + // didn't find it + return "BONE_NOT_FOUND"; +} + +char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum); + +static void G2_RagDollCurrentPosition(CGhoul2Info_v &ghoul2V,int g2Index,int frameNum,const vec3_t angles,const vec3_t position,const vec3_t scale) +{ + CGhoul2Info &ghoul2=ghoul2V[g2Index]; + assert(ghoul2.mFileName[0]); + G2_GenerateWorldMatrix(angles,position); + G2_ConstructGhoulSkeleton(ghoul2V, frameNum, false, scale); + + float totalWt=0.0f; + int i; + for (i=0;iragBoneMaxs[k]) + { + ragBoneMaxs[k]=ragEffectors[i].currentOrigin[k]; + } + if (ragEffectors[i].currentOrigin[k]0.0f); + int k; + { + float wtInv=1.0f/totalWt; + for (k=0;k<3;k++) + { + ragBoneMaxs[k]-=position[k]; + ragBoneMins[k]-=position[k]; + ragBoneMaxs[k]+=10.0f; + ragBoneMins[k]-=10.0f; + ragBoneCM[k]*=wtInv; + + ragBoneCM[k]=ragEffectors[0].currentOrigin[k]; // use the pelvis + } + } +} + +#ifdef _DEBUG +int ragTraceTime = 0; +int ragSSCount = 0; +int ragTraceCount = 0; +#endif + +void Rag_Trace( trace_t *results, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, const int passEntityNum, const int contentmask, const EG2_Collision eG2TraceType, const int useLod ) +{ +#ifdef _DEBUG + int ragPreTrace = ri.Milliseconds(); +#endif + if ( ri.CGVMLoaded() ) + { + ragCallbackTraceLine_t *callData = (ragCallbackTraceLine_t *)ri.GetSharedMemory(); + + VectorCopy(start, callData->start); + VectorCopy(end, callData->end); + VectorCopy(mins, callData->mins); + VectorCopy(maxs, callData->maxs); + callData->ignore = passEntityNum; + callData->mask = contentmask; + + ri.CGVM_RagCallback( RAG_CALLBACK_TRACELINE ); + + *results = callData->tr; + } + else + { + results->entityNum = ENTITYNUM_NONE; + //SV_Trace(results, start, mins, maxs, end, passEntityNum, contentmask, eG2TraceType, useLod); + ri.CM_BoxTrace(results, start, end, mins, maxs, 0, contentmask, 0); + results->entityNum = results->fraction != 1.0 ? ENTITYNUM_WORLD : ENTITYNUM_NONE; + } + +#ifdef _DEBUG + int ragPostTrace = ri.Milliseconds(); + + ragTraceTime += (ragPostTrace - ragPreTrace); + if (results->startsolid) + { + ragSSCount++; + } + ragTraceCount++; +#endif +} + +//run advanced physics on each bone indivudually +//an adaption of my "exphys" custom game physics model +#define MAX_GRAVITY_PULL 256//512 + +static inline bool G2_BoneOnGround(const vec3_t org, const vec3_t mins, const vec3_t maxs, const int ignoreNum) +{ + trace_t tr; + vec3_t gSpot; + + VectorCopy(org, gSpot); + gSpot[2] -= 1.0f; //seems reasonable to me + + Rag_Trace(&tr, org, mins, maxs, gSpot, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + + if (tr.fraction != 1.0f && !tr.startsolid && !tr.allsolid) + { //not in solid, and hit something. Guess it's ground. + return true; + } + + return false; +} + +static inline bool G2_ApplyRealBonePhysics(boneInfo_t &bone, SRagEffector &e, CRagDollUpdateParams *params, vec3_t goalSpot, const vec3_t testMins, const vec3_t testMaxs, + const float gravity, const float mass, const float bounce) +{ + trace_t tr; + vec3_t projectedOrigin; + vec3_t vNorm; + vec3_t ground; + float velScaling = 0.1f; + float vTotal = 0.0f; + bool boneOnGround = false; + + assert(mass <= 1.0f && mass >= 0.01f); + + if (bone.physicsSettled) + { //then we have no need to continue + return true; + } + + if (gravity) + { //factor it in before we do anything. + VectorCopy(e.currentOrigin, ground); + ground[2] -= 1.0f; + + Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, ground, params->me, RAG_MASK, G2_NOCOLLIDE, 0); + + if (tr.entityNum == ENTITYNUM_NONE) + { + boneOnGround = false; + } + else + { + boneOnGround = true; + } + + if (!boneOnGround) + { + if (!params->velocity[2]) + { //only increase gravitational pull once the actual entity is still + bone.epGravFactor += gravity; + } + + if (bone.epGravFactor > MAX_GRAVITY_PULL) + { //cap it off if needed + bone.epGravFactor = MAX_GRAVITY_PULL; + } + + bone.epVelocity[2] -= bone.epGravFactor; + } + else + { //if we're sitting on something then reset the gravity factor. + bone.epGravFactor = 0; + } + } + else + { + boneOnGround = G2_BoneOnGround(e.currentOrigin, testMins, testMaxs, params->me); + } + + if (!bone.epVelocity[0] && !bone.epVelocity[1] && !bone.epVelocity[2]) + { //nothing to do if we have no velocity even after gravity. + VectorCopy(e.currentOrigin, goalSpot); + return true; + } + + //get the projected origin based on velocity. + VectorMA(e.currentOrigin, velScaling, bone.epVelocity, projectedOrigin); + + //scale it down based on mass + VectorScale(bone.epVelocity, 1.0f-mass, bone.epVelocity); + + VectorCopy(bone.epVelocity, vNorm); + vTotal = VectorNormalize(vNorm); + + if (vTotal < 1 && boneOnGround) + { //we've pretty much stopped moving anyway, just clear it out then. + VectorClear(bone.epVelocity); + bone.epGravFactor = 0; + VectorCopy(e.currentOrigin, goalSpot); + return true; + } + + Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, projectedOrigin, params->me, RAG_MASK, G2_NOCOLLIDE, 0); + + if (tr.startsolid || tr.allsolid) + { //can't go anywhere from here + return false; + } + + //Go ahead and set it to the trace endpoint regardless of what it hit + VectorCopy(tr.endpos, goalSpot); + + if (tr.fraction == 1.0f) + { //Nothing was in the way. + return true; + } + + if (bounce) + { + vTotal *= bounce; //scale it by bounce + + VectorScale(tr.plane.normal, vTotal, vNorm); //scale the trace plane normal by the bounce factor + + if (vNorm[2] > 0) + { + bone.epGravFactor -= vNorm[2]*(1.0f-mass); //The lighter it is the more gravity will be reduced by bouncing vertically. + if (bone.epGravFactor < 0) + { + bone.epGravFactor = 0; + } + } + + VectorAdd(bone.epVelocity, vNorm, bone.epVelocity); //add it into the existing velocity. + + //I suppose it could be sort of neat to make a game callback here to actual do stuff + //when bones slam into things. But it could be slow too. + /* + if (tr.entityNum != ENTITYNUM_NONE && ent->touch) + { //then call the touch function + ent->touch(ent, &g_entities[tr.entityNum], &tr); + } + */ + } + else + { //if no bounce, kill when it hits something. + bone.epVelocity[0] = 0; + bone.epVelocity[1] = 0; + + if (!gravity) + { + bone.epVelocity[2] = 0; + } + } + return true; +} + +#ifdef _DEBUG_BONE_NAMES +static inline void G2_RagDebugBox(vec3_t mins, vec3_t maxs, int duration) +{ + if ( !ri.CGVMLoaded() ) + return; + + ragCallbackDebugBox_t *callData = (ragCallbackDebugBox_t *)ri.GetSharedMemory(); + + callData->duration = duration; + VectorCopy(mins, callData->mins); + VectorCopy(maxs, callData->maxs); + + ri.CGVM_RagCallback( RAG_CALLBACK_DEBUGBOX ); +} + +static inline void G2_RagDebugLine(vec3_t start, vec3_t end, int time, int color, int radius) +{ + if ( !ri.CGVMLoaded() ) + return; + + ragCallbackDebugLine_t *callData = (ragCallbackDebugLine_t *)ri.GetSharedMemory(); + + VectorCopy(start, callData->start); + VectorCopy(end, callData->end); + callData->time = time; + callData->color = color; + callData->radius = radius; + + ri.CGVM_RagCallback( RAG_CALLBACK_DEBUGLINE ); +} +#endif + +#ifdef _OLD_STYLE_SETTLE +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) +{ + haveDesiredPelvisOffset=false; + vec3_t desiredPos; + int i; + + assert(params); + //assert(params->me); //no longer valid, because me is an index! + int ignoreNum=params->me; + + bool anyStartSolid=false; + + vec3_t groundSpot={0,0,0}; + // lets find the floor at our quake origin + { + vec3_t testStart; + VectorCopy(currentOrg,testStart); //last arg is dest + vec3_t testEnd; + VectorCopy(testStart,testEnd); //last arg is dest + testEnd[2]-=200.0f; + + vec3_t testMins; + vec3_t testMaxs; + VectorSet(testMins,-10,-10,-10); + VectorSet(testMaxs,10,10,10); + + { + trace_t tr; + assert( !Q_isnan(testStart[1])); + assert( !Q_isnan(testEnd[1])); + assert( !Q_isnan(testMins[1])); + assert( !Q_isnan(testMaxs[1])); + Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0/*SV_TRACE_NO_PLAYER*/); + if (tr.entityNum==0) + { + VectorAdvance(testStart,.5f,testEnd,tr.endpos); + } + if (tr.startsolid) + { + //hmmm, punt + VectorCopy(currentOrg,groundSpot); //last arg is dest + groundSpot[2]-=30.0f; + } + else + { + VectorCopy(tr.endpos,groundSpot); //last arg is dest + } + } + } + + for (i=0;i groundSpot[2]) + { + testStart[2]=groundSpot[2]+(e.radius-10.0f); + } + else + { + // lets try higher + testStart[2]=groundSpot[2]+8.0f; + Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); + if (tr.entityNum==0) + { + VectorAdvance(testStart,.5f,testEnd,tr.endpos); + } + } + + } + if (tr.startsolid) + { + iAmStartSolid=true; + anyStartSolid=true; + // above the origin, so lets slide away + if (e.currentOrigin[2] > groundSpot[2]) + { + if (params) + { + //SRagDollEffectorCollision args(e.currentOrigin,tr); + //params->EffectorCollision(args); + if ( ri.CGVMLoaded() ) + { //make a callback and see if the cgame wants to help us out + ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); + + VectorCopy(e.currentOrigin, callData->bonePos); + callData->entNum = params->me; + callData->solidCount = bone.solidCount; + + ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + } + } + } + else + { + //harumph, we are really screwed + } + } + else + { + vertEffectorTraceFraction=tr.fraction; + if (params && + vertEffectorTraceFraction < .95f && + fabsf(tr.plane.normal[2]) < .707f) + { + //SRagDollEffectorCollision args(e.currentOrigin,tr); + //args.useTracePlane=true; + //params->EffectorCollision(args); + if ( ri.CGVMLoaded() ) + { //make a callback and see if the cgame wants to help us out + ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); + + VectorCopy(e.currentOrigin, callData->bonePos); + callData->entNum = params->me; + callData->solidCount = bone.solidCount; + + ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + } + } + } + } + vec3_t effectorGroundSpot; + VectorAdvance(testStart,vertEffectorTraceFraction,testEnd,effectorGroundSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + // trace from the quake origin horzontally to the effector + // gonna choose the maximum of the ground spot or the effector location + // and clamp it to be roughly in the bbox + VectorCopy(groundSpot,testStart); //last arg is dest + if (iAmStartSolid) + { + // we don't have a meaningful ground spot + VectorCopy(e.currentOrigin,testEnd); //last arg is dest + bone.solidCount++; + } + else + { + VectorCopy(effectorGroundSpot,testEnd); //last arg is dest + bone.solidCount = 0; + } + assert( !Q_isnan(testStart[1])); + assert( !Q_isnan(testEnd[1])); + assert( !Q_isnan(testMins[1])); + assert( !Q_isnan(testMaxs[1])); + + float ztest; + + if (testEnd[2]>testStart[2]) + { + ztest=testEnd[2]; + } + else + { + ztest=testStart[2]; + } + if (ztest c := (1-t)a+tb + + float horzontalTraceFraction=0.0f; + vec3_t HorizontalHitSpot={0,0,0}; + { + trace_t tr; + Rag_Trace(&tr,testStart,testMins,testMaxs,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); + if (tr.entityNum==0) + { + VectorAdvance(testStart,.5f,testEnd,tr.endpos); + } + horzontalTraceFraction=tr.fraction; + if (tr.startsolid) + { + horzontalTraceFraction=1.0f; + // punt + VectorCopy(e.currentOrigin,HorizontalHitSpot); + } + else + { + VectorCopy(tr.endpos,HorizontalHitSpot); + int magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall + //float magicFactor46=0.98f; // shorten percetage to make sure we can go down along a wall + //rww - An..int? + VectorAdvance(tr.endpos,magicFactor46,testStart,HorizontalHitSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + + // roughly speaking this is a wall + if (horzontalTraceFraction<0.9f) + { + + // roughly speaking this is a wall + if (fabsf(tr.plane.normal[2])<0.7f) + { + //SRagDollEffectorCollision args(e.currentOrigin,tr); + //args.useTracePlane=true; + //params->EffectorCollision(args); + if ( ri.CGVMLoaded() ) + { //make a callback and see if the cgame wants to help us out + ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); + + VectorCopy(e.currentOrigin, callData->bonePos); + callData->entNum = params->me; + callData->solidCount = bone.solidCount; + + ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + } + } + } + else if (!iAmStartSolid && + effectorGroundSpot[2] < groundSpot[2] - 8.0f) + { + // this is a situation where we have something dangling below the pelvis, we want to find the plane going downhill away from the origin + // for various reasons, without this correction the body will actually move away from places it can fall off. + //gotta run the trace backwards to get a plane + { + trace_t tr; + VectorCopy(effectorGroundSpot,testStart); + VectorCopy(groundSpot,testEnd); + + // this can be a line trace, we just want the plane normal + Rag_Trace(&tr,testEnd,0,0,testStart,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); + if (tr.entityNum==0) + { + VectorAdvance(testStart,.5f,testEnd,tr.endpos); + } + horzontalTraceFraction=tr.fraction; + if (!tr.startsolid && tr.fraction< 0.7f) + { + //SRagDollEffectorCollision args(e.currentOrigin,tr); + //args.useTracePlane=true; + //params->EffectorCollision(args); + if ( ri.CGVMLoaded() ) + { //make a callback and see if the cgame wants to help us out + ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); + + VectorCopy(e.currentOrigin, callData->bonePos); + callData->entNum = params->me; + callData->solidCount = bone.solidCount; + + ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + } + } + } + } + } + } + vec3_t goalSpot={0,0,0}; + // now lets trace down + VectorCopy(HorizontalHitSpot,testStart); + VectorCopy(testStart,testEnd); //last arg is dest + testEnd[2]=e.currentOrigin[2]-30.0f; + { + trace_t tr; + Rag_Trace(&tr,testStart,NULL,NULL,testEnd,ignoreNum,RAG_MASK,G2_NOCOLLIDE,0); + if (tr.entityNum==0) + { + VectorAdvance(testStart,.5f,testEnd,tr.endpos); + } + if (tr.startsolid) + { + // punt, go to the origin I guess + VectorCopy(currentOrg,goalSpot); + } + else + { + VectorCopy(tr.endpos,goalSpot); + int magicFactor47=0.5f; // shorten percentage to make sure we can go down along a wall + VectorAdvance(tr.endpos,magicFactor47,testStart,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb + } + } + + // ok now as the horizontal trace fraction approaches zero, we want to head toward the horizontalHitSpot + //geeze I would like some reasonable trace fractions + assert(horzontalTraceFraction>=0.0f&&horzontalTraceFraction<=1.0f); + VectorAdvance(HorizontalHitSpot,horzontalTraceFraction*horzontalTraceFraction,goalSpot,goalSpot);// VA(a,t,b,c)-> c := (1-t)a+tb +#if 0 + if ((bone.RagFlags & RAG_EFFECTOR) && (bone.RagFlags & RAG_BONE_LIGHTWEIGHT)) + { //new rule - don't even bother unless it's a lightweight effector + //rww - Factor object velocity into the final desired spot.. + //We want the limbs with a "light" weight to drag behind the general mass. + //If we got here, we shouldn't be the pelvis or the root, so we should be + //fine to treat as lightweight. However, we can flag bones as being particularly + //light. They're given less downscale for the reduction factor. + vec3_t givenVelocity; + vec3_t vSpot; + trace_t vtr; + float vSpeed = 0; + float verticalSpeed = 0; + float vReductionFactor = 0.03f; + float verticalSpeedReductionFactor = 0.06f; //want this to be more obvious + float lwVReductionFactor = 0.1f; + float lwVerticalSpeedReductionFactor = 0.3f; //want this to be more obvious + + + VectorCopy(params->velocity, givenVelocity); + vSpeed = VectorNormalize(givenVelocity); + vSpeed = -vSpeed; //go in the opposite direction of velocity + + verticalSpeed = vSpeed; + + if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) + { + vSpeed *= lwVReductionFactor; + verticalSpeed *= lwVerticalSpeedReductionFactor; + } + else + { + vSpeed *= vReductionFactor; + verticalSpeed *= verticalSpeedReductionFactor; + } + + vSpot[0] = givenVelocity[0]*vSpeed; + vSpot[1] = givenVelocity[1]*vSpeed; + vSpot[2] = givenVelocity[2]*verticalSpeed; + VectorAdd(goalSpot, vSpot, vSpot); + + if (vSpot[0] || vSpot[1] || vSpot[2]) + { + Rag_Trace(&vtr, goalSpot, testMins, testMaxs, vSpot, ignoreNum, RAG_MASK, G2_NOCOLLIDE,0); + if (vtr.fraction == 1) + { + VectorCopy(vSpot, goalSpot); + } + } + } +#endif + + int k; + int magicFactor12=0.8f; // dampening of velocity applied + int magicFactor16=10.0f; // effect multiplier of velocity applied + + if (iAmStartSolid) + { + magicFactor16 = 30.0f; + } + + for (k=0;k<3;k++) + { + e.desiredDirection[k]=goalSpot[k]-e.currentOrigin[k]; + e.desiredDirection[k]+=magicFactor16*bone.velocityEffector[k]; + e.desiredDirection[k]+=flrand(-0.75f,0.75f)*flrand(-0.75f,0.75f); + bone.velocityEffector[k]*=magicFactor12; + } + VectorCopy(e.currentOrigin,bone.lastPosition); // last arg is dest + } + return anyStartSolid; +} +#else + +#if 0 +static inline int G2_RagIndexForBoneNum(int boneNum) +{ + for (int i = 0; i < numRags; i++) + { + // these are used for affecting the end result + if (ragBoneData[i].boneNum == boneNum) + { + return i; + } + } + + return -1; +} +#endif + +#ifdef _RAG_PRINT_TEST +void G2_RagPrintMatrix(mdxaBone_t *mat) +{ + char x[1024]; + x[0] = 0; + int n = 0; + while (n < 3) + { + int o = 0; + while (o < 4) + { + strcat(x, va("%f ", mat->matrix[n][o])); + o++; + } + n++; + } + strcat(x, "\n"); + Com_Printf(x); +} +#endif + +void G2_RagGetBoneBasePoseMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &boneMatrix, mdxaBone_t &retMatrix, vec3_t scale); +void G2_RagGetAnimMatrix(CGhoul2Info &ghoul2, const int boneNum, mdxaBone_t &matrix, const int frame); + +static inline void G2_RagGetWorldAnimMatrix(CGhoul2Info &ghoul2, boneInfo_t &bone, CRagDollUpdateParams *params, mdxaBone_t &retMatrix) +{ + static mdxaBone_t trueBaseMatrix, baseBoneMatrix; + + //get matrix for the settleFrame to use as an ideal + G2_RagGetAnimMatrix(ghoul2, bone.boneNumber, trueBaseMatrix, params->settleFrame); + assert(bone.hasAnimFrameMatrix == params->settleFrame); + + G2_RagGetBoneBasePoseMatrixLow(ghoul2, bone.boneNumber, + trueBaseMatrix, baseBoneMatrix, params->scale); + + //Use params to multiply world coordinate/dir matrix into the + //bone matrix and give us a useable world position + Mat3x4_Multiply(&retMatrix, &worldMatrix, &baseBoneMatrix); + + assert(!Q_isnan(retMatrix.matrix[2][3])); +} + +//get the current pelvis Z direction and the base anim matrix Z direction +//so they can be compared and used to offset -rww +void G2_GetRagBoneMatrixLow(CGhoul2Info &ghoul2, int boneNum, mdxaBone_t &retMatrix); +void G2_GetBoltMatrixLow(CGhoul2Info &ghoul2,int boltNum,const vec3_t scale,mdxaBone_t &retMatrix); +static inline void G2_RagGetPelvisLumbarOffsets(CGhoul2Info &ghoul2, CRagDollUpdateParams *params, vec3_t pos, vec3_t dir, vec3_t animPos, vec3_t animDir) +{ + static mdxaBone_t final; + static mdxaBone_t x; + //static mdxaBone_t *unused1, *unused2; + //static vec3_t lumbarPos; + + assert(ghoul2.animModel); + int boneIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, "pelvis"); + assert(boneIndex != -1); + + G2_RagGetWorldAnimMatrix(ghoul2, ghoul2.mBlist[boneIndex], params, final); + G2API_GiveMeVectorFromMatrix(&final, ORIGIN, animPos); + G2API_GiveMeVectorFromMatrix(&final, POSITIVE_X, animDir); + +#if 0 + //We have the anim matrix pelvis pos now, so get the normal one as well + G2_GetBoneMatrixLow(ghoul2, boneIndex, params->scale, final, unused1, unused2); + G2API_GiveMeVectorFromMatrix(&final, ORIGIN, pos); + G2API_GiveMeVectorFromMatrix(&final, POSITIVE_X, dir); +#else + //We have the anim matrix pelvis pos now, so get the normal one as well + //G2_GetRagBoneMatrixLow(ghoul2, boneIndex, x); + int bolt = G2_Add_Bolt(&ghoul2, ghoul2.mBltlist, ghoul2.mSlist, "pelvis"); + G2_GetBoltMatrixLow(ghoul2, bolt, params->scale, x); + Mat3x4_Multiply(&final, &worldMatrix, &x); + G2API_GiveMeVectorFromMatrix(&final, ORIGIN, pos); + G2API_GiveMeVectorFromMatrix(&final, POSITIVE_X, dir); +#endif + + /* + //now get lumbar + boneIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, "lower_lumbar"); + assert(boneIndex != -1); + + G2_RagGetWorldAnimMatrix(ghoul2, ghoul2.mBlist[boneIndex], params, final); + G2API_GiveMeVectorFromMatrix(&final, ORIGIN, lumbarPos); + + VectorSubtract(animPos, lumbarPos, animDir); + VectorNormalize(animDir); + + //We have the anim matrix lumbar dir now, so get the normal one as well + G2_GetBoneMatrixLow(ghoul2, boneIndex, params->scale, final, unused1, unused2); + G2API_GiveMeVectorFromMatrix(&final, ORIGIN, lumbarPos); + + VectorSubtract(pos, lumbarPos, dir); + VectorNormalize(dir); + */ +} + +static bool G2_RagDollSettlePositionNumeroTrois(CGhoul2Info_v &ghoul2V, const vec3_t currentOrg, CRagDollUpdateParams *params, int curTime) +{ //now returns true if any bone was in solid, otherwise false + int ignoreNum = params->me; + static int i; + static vec3_t goalSpot; + static trace_t tr; + //static trace_t solidTr; + static int k; + static const float velocityDampening = 1.0f; + static const float velocityMultiplier = 60.0f; + static vec3_t testMins; + static vec3_t testMaxs; + vec3_t velDir; + static bool startSolid; + bool anySolid = false; + static mdxaBone_t worldBaseMatrix; + static vec3_t parentOrigin; + static vec3_t basePos; + static vec3_t entScale; + static bool hasDaddy; + static bool hasBasePos; + static vec3_t animPelvisDir, pelvisDir, animPelvisPos, pelvisPos; + + //Maybe customize per-bone? + static const float gravity = 3.0f; + static const float mass = 0.09f; + static const float bounce = 0.0f;//1.3f; + //Bouncing and stuff unfortunately does not work too well at the moment. + //Need to keep a seperate "physics origin" or make the filthy solve stuff + //better. + + bool inAir = false; + + if (params->velocity[0] || params->velocity[1] || params->velocity[2]) + { + inAir = true; + } + + if (!params->scale[0] && !params->scale[1] && !params->scale[2]) + { + VectorSet(entScale, 1.0f, 1.0f, 1.0f); + } + else + { + VectorCopy(params->scale, entScale); + } + + if (broadsword_ragtobase && + broadsword_ragtobase->integer > 1) + { + //grab the pelvis directions to offset base positions for bones + G2_RagGetPelvisLumbarOffsets(ghoul2V[0], params, pelvisPos, pelvisDir, animPelvisPos, + animPelvisDir); + + //don't care about the pitch offsets + pelvisDir[2] = 0; + animPelvisDir[2] = 0; + + /* + vec3_t upelvisPos, uanimPelvisPos; + vec3_t blah; + VectorCopy(pelvisPos, upelvisPos); + VectorCopy(animPelvisPos, uanimPelvisPos); + upelvisPos[2] += 64; + uanimPelvisPos[2] += 64; + + VectorMA(upelvisPos, 32.0f, pelvisDir, blah); + G2_RagDebugLine(upelvisPos, blah, 50, 0x00ff00, 1); + VectorMA(uanimPelvisPos, 32.0f, animPelvisDir, blah); + G2_RagDebugLine(uanimPelvisPos, blah, 50, 0xff0000, 1); + */ + + //just convert to angles now, that's all we'll ever use them for + vectoangles(pelvisDir, pelvisDir); + vectoangles(animPelvisDir, animPelvisDir); + } + + for (i = 0; i < numRags; i++) + { + boneInfo_t &bone = *ragBoneData[i]; + SRagEffector &e = ragEffectors[i]; + + if (inAir) + { + bone.airTime = curTime + 30; + } + + if (bone.RagFlags & RAG_PCJ_PELVIS) + { + VectorSet(goalSpot, params->position[0], params->position[1], (params->position[2]+DEFAULT_MINS_2)+((bone.radius*entScale[2])+2)); + + VectorSubtract(goalSpot, e.currentOrigin, desiredPelvisOffset); + haveDesiredPelvisOffset = true; + VectorCopy(e.currentOrigin, bone.lastPosition); + continue; + } + + if (!(bone.RagFlags & RAG_EFFECTOR)) + { + continue; + } + + if (bone.hasOverGoal) + { //api call was made to override the goal spot + VectorCopy(bone.overGoalSpot, goalSpot); + bone.solidCount = 0; + for (k = 0; k < 3; k++) + { + e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); + e.desiredDirection[k] += (velocityMultiplier * bone.velocityEffector[k]); + bone.velocityEffector[k] *= velocityDampening; + } + VectorCopy(e.currentOrigin, bone.lastPosition); + + continue; + } + + VectorSet(testMins, -e.radius*entScale[0], -e.radius*entScale[1], -e.radius*entScale[2]); + VectorSet(testMaxs, e.radius*entScale[0], e.radius*entScale[1], e.radius*entScale[2]); + + assert(ghoul2V[0].mBoneCache); + + //get the parent bone's position + hasDaddy = false; + if (bone.boneNumber) + { + assert(ghoul2V[0].animModel); + assert(ghoul2V[0].aHeader); + + if (bone.parentBoneIndex == -1) + { + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + int bParentIndex, bParentListIndex = -1; + + offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t)); + skel = (mdxaSkel_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t) + offsets->offsets[bone.boneNumber]); + + bParentIndex = skel->parent; + + while (bParentIndex > 0) + { //go upward through hierarchy searching for the first parent that is a rag bone + skel = (mdxaSkel_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t) + offsets->offsets[bParentIndex]); + bParentIndex = skel->parent; + bParentListIndex = G2_Find_Bone(ghoul2V[0].animModel, ghoul2V[0].mBlist, skel->name); + + if (bParentListIndex != -1) + { + boneInfo_t &pbone = ghoul2V[0].mBlist[bParentListIndex]; + if (pbone.flags & BONE_ANGLES_RAGDOLL) + { //valid rag bone + break; + } + } + + //didn't work out, reset to -1 again + bParentListIndex = -1; + } + + bone.parentBoneIndex = bParentListIndex; + } + + if (bone.parentBoneIndex != -1) + { + boneInfo_t &pbone = ghoul2V[0].mBlist[bone.parentBoneIndex]; + + if (pbone.flags & BONE_ANGLES_RAGDOLL) + { //has origin calculated for us already + VectorCopy(ragEffectors[pbone.ragIndex].currentOrigin, parentOrigin); + hasDaddy = true; + } + } + } + + //get the position this bone would be in if we were in the desired frame + hasBasePos = false; + if (broadsword_ragtobase && + broadsword_ragtobase->integer) + { + vec3_t v, a; + float f; + + G2_RagGetWorldAnimMatrix(ghoul2V[0], bone, params, worldBaseMatrix); + G2API_GiveMeVectorFromMatrix(&worldBaseMatrix, ORIGIN, basePos); + + if (broadsword_ragtobase->integer > 1) + { + float fa = AngleNormalize180(animPelvisDir[YAW]-pelvisDir[YAW]); + float d = fa-bone.offsetRotation; + + if (d > 16.0f || + d < -16.0f) + { //don't update unless x degrees away from the ideal to avoid moving goal spots too much if pelvis rotates + bone.offsetRotation = fa; + } + else + { + fa = bone.offsetRotation; + } + //Rotate the point around the pelvis based on the offsets between pelvis positions + VectorSubtract(basePos, animPelvisPos, v); + f = VectorLength(v); + vectoangles(v, a); + a[YAW] -= fa; + AngleVectors(a, v, 0, 0); + VectorNormalize(v); + VectorMA(animPelvisPos, f, v, basePos); + + //re-orient the position of the bone to the current position of the pelvis + VectorSubtract(basePos, animPelvisPos, v); + //push the spots outward? (to stretch the skeleton more) + //v[0] *= 1.5f; + //v[1] *= 1.5f; + VectorAdd(pelvisPos, v, basePos); + } +#if 0 //for debugging frame skeleton + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + + offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t)); + skel = (mdxaSkel_t *)((byte *)ghoul2V[0].aHeader + sizeof(mdxaHeader_t) + offsets->offsets[bone.boneNumber]); + + vec3_t pu; + VectorCopy(basePos, pu); + pu[2] += 32; + if (bone.boneNumber < 11) + { + G2_RagDebugLine(basePos, pu, 50, 0xff00ff, 1); + } + else if (skel->name[0] == 'l') + { + G2_RagDebugLine(basePos, pu, 50, 0xffff00, 1); + } + else if (skel->name[0] == 'r') + { + G2_RagDebugLine(basePos, pu, 50, 0xffffff, 1); + } + else + { + G2_RagDebugLine(basePos, pu, 50, 0x00ffff, 1); + } +#endif + hasBasePos = true; + } + + //Are we in solid? + if (hasDaddy) + { + Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, parentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + //Rag_Trace(&tr, parentOrigin, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + } + else + { + Rag_Trace(&tr, e.currentOrigin, testMins, testMaxs, params->position, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + } + + if (tr.startsolid || tr.allsolid || tr.fraction != 1.0f) + { //currently in solid, see what we can do about it + vec3_t vSub; + + startSolid = true; + anySolid = true; + + if (hasBasePos)// && bone.solidCount < 32) + { //only go to the base pos for slightly in solid bones +#if 0 //over-compensation + float fl; + float floorBase; + + VectorSubtract(basePos, e.currentOrigin, vSub); + fl = VectorNormalize(vSub); + VectorMA(e.currentOrigin, /*fl*8.0f*/64.0f, vSub, goalSpot); + + floorBase = ((params->position[2]-23)-testMins[2])+8; + + if (goalSpot[2] > floorBase) + { + goalSpot[2] = floorBase; + } +#else //just use the spot directly + VectorCopy(basePos, goalSpot); + goalSpot[2] = (params->position[2]-23)-testMins[2]; +#endif + //Com_Printf("%i: %f %f %f\n", bone.boneNumber, basePos[0], basePos[1], basePos[2]); + } + else + { //if deep in solid want to try to rise up out of solid before hinting back to base + VectorSubtract(e.currentOrigin, params->position, vSub); + VectorNormalize(vSub); + VectorMA(params->position, 40.0f, vSub, goalSpot); + + //should be 1 unit above the ground taking bounding box sizes into account + goalSpot[2] = (params->position[2]-23)-testMins[2]; + } + + //Trace from the entity origin in the direction between the origin and current bone position to + //find a good eventual goal position + Rag_Trace(&tr, params->position, testMins, testMaxs, goalSpot, params->me, RAG_MASK, G2_NOCOLLIDE, 0); + VectorCopy(tr.endpos, goalSpot); + } + else + { + startSolid = false; + +#if 1 //do hinting? + //Hint the bone back to the base origin + if (hasDaddy || hasBasePos) + { + if (hasBasePos) + { + VectorSubtract(basePos, e.currentOrigin, velDir); + } + else + { + VectorSubtract(e.currentOrigin, parentOrigin, velDir); + } + } + else + { + VectorSubtract(e.currentOrigin, params->position, velDir); + } + + if (VectorLength(velDir) > 2.0f) + { //don't bother if already close + VectorNormalize(velDir); + VectorScale(velDir, 8.0f, velDir); + velDir[2] = 0; //don't want to nudge on Z, the gravity will take care of things. + VectorAdd(bone.epVelocity, velDir, bone.epVelocity); + } +#endif + + //Factor the object's velocity into the bone's velocity, by pushing the bone + //opposite the velocity to give the apperance the lighter limbs are being "dragged" + //behind those of greater mass. + if (bone.RagFlags & RAG_BONE_LIGHTWEIGHT) + { + vec3_t vel; + float vellen; + + VectorCopy(params->velocity, vel); + + //Scale down since our velocity scale is different from standard game physics + VectorScale(vel, 0.5f, vel); + + vellen = VectorLength(vel); + + if (vellen > 64.0f) + { //cap it off + VectorScale(vel, 64.0f/vellen, vel); + } + + //Invert the velocity so we go opposite the heavier parts and drag behind + VectorInverse(vel); + + if (vel[2]) + { //want to override entirely instead then + VectorCopy(vel, bone.epVelocity); + } + else + { + VectorAdd(bone.epVelocity, vel, bone.epVelocity); + } + } + + //We're not in solid so we can apply physics freely now. + if (!G2_ApplyRealBonePhysics(bone, e, params, goalSpot, testMins, testMaxs, + gravity, mass, bounce)) + { //if this is the case then somehow we failed to apply physics/get a good goal spot, just use the ent origin + VectorCopy(params->position, goalSpot); + } + } + + //Set this now so we know what to do for angle limiting + if (startSolid) + { + bone.solidCount++; +#if 0 + if ( ri.CGVMLoaded() && bone.solidCount > 8 ) + { //make a callback and see if the cgame wants to help us out + Rag_Trace(&solidTr, params->position, testMins, testMaxs, e.currentOrigin, ignoreNum, RAG_MASK, G2_NOCOLLIDE, 0); + + if (solidTr.fraction != 1.0f && + (solidTr.plane.normal[0] || solidTr.plane.normal[1]) && + (solidTr.plane.normal[2] < 0.1f || solidTr.plane.normal[2] > -0.1f))// && //don't do anything against flat around + // e.currentOrigin[2] > pelvisPos[2]) + { + ragCallbackBoneInSolid_t *callData = (ragCallbackBoneInSolid_t *)ri.GetSharedMemory(); + + VectorCopy(e.currentOrigin, callData->bonePos); + callData->entNum = params->me; + callData->solidCount = bone.solidCount; + + ri.CGVM_RagCallback( RAG_CALLBACK_BONEINSOLID ); + } + } +#endif + +#ifdef _DEBUG_BONE_NAMES + if (bone.solidCount > 64) + { + char *debugBoneName = G2_Get_Bone_Name(&ghoul2V[0], ghoul2V[0].mBlist, bone.boneNumber); + vec3_t absmin, absmax; + + assert(debugBoneName); + + Com_Printf("High bone (%s, %i) solid count: %i\n", debugBoneName, bone.boneNumber, bone.solidCount); + + VectorAdd(e.currentOrigin, testMins, absmin); + VectorAdd(e.currentOrigin, testMaxs, absmax); + G2_RagDebugBox(absmin, absmax, 50); + + G2_RagDebugLine(e.currentOrigin, goalSpot, 50, 0x00ff00, 1); + } +#endif + } + else + { + bone.solidCount = 0; + } + +#if 0 //standard goalSpot capping? + //unless we are really in solid, we should keep adjustments minimal + if (/*bone.epGravFactor < 64 &&*/ bone.solidCount < 2 && + !inAir) + { + vec3_t moveDist; + const float extent = 32.0f; + float len; + + VectorSubtract(goalSpot, e.currentOrigin, moveDist); + len = VectorLength(moveDist); + + if (len > extent) + { //if greater than the extent then scale the vector down to the extent and factor it back into the goalspot + VectorScale(moveDist, extent/len, moveDist); + VectorAdd(e.currentOrigin, moveDist, goalSpot); + } + } +#endif + + //Set the desired direction based on the goal position and other factors. + for (k = 0; k < 3; k++) + { + e.desiredDirection[k] = (goalSpot[k] - e.currentOrigin[k]); + + if (broadsword_dircap && + broadsword_dircap->value) + { + float cap = broadsword_dircap->value; + + if (bone.solidCount > 5) + { + float solidFactor = bone.solidCount*0.2f; + + if (solidFactor > 16.0f) + { //don't go too high or something ugly might happen + solidFactor = 16.0f; + } + + e.desiredDirection[k] *= solidFactor; + cap *= 8; + } + + if (e.desiredDirection[k] > cap) + { + e.desiredDirection[k] = cap; + } + else if (e.desiredDirection[k] < -cap) + { + e.desiredDirection[k] = -cap; + } + } + + e.desiredDirection[k] += (velocityMultiplier * bone.velocityEffector[k]); + e.desiredDirection[k] += (flrand(-0.75f, 0.75f) * flrand(-0.75f, 0.75f)); + + bone.velocityEffector[k] *= velocityDampening; + } + VectorCopy(e.currentOrigin, bone.lastPosition); + } + + return anySolid; +} +#endif + +static float AngleNormZero(float theta) +{ + float ret=fmodf(theta,360.0f); + if (ret<-180.0f) + { + ret+=360.0f; + } + else if (ret>180.0f) + { + ret-=360.0f; + } + assert(ret>=-180.0f&&ret<=180.0f); + return ret; +} + +static inline void G2_BoneSnap(CGhoul2Info_v &ghoul2V, boneInfo_t &bone, CRagDollUpdateParams *params) +{ + if ( !ri.CGVMLoaded() || !params ) + { + return; + } + + ragCallbackBoneSnap_t *callData = (ragCallbackBoneSnap_t *)ri.GetSharedMemory(); + + callData->entNum = params->me; + strcpy(callData->boneName, G2_Get_Bone_Name(&ghoul2V[0], ghoul2V[0].mBlist, bone.boneNumber)); + + ri.CGVM_RagCallback( RAG_CALLBACK_BONESNAP ); +} + +static void G2_RagDollSolve(CGhoul2Info_v &ghoul2V,int g2Index,float decay,int frameNum,const vec3_t currentOrg,bool limitAngles,CRagDollUpdateParams *params) +{ + + int i; + + CGhoul2Info &ghoul2=ghoul2V[g2Index]; + + mdxaBone_t N; + mdxaBone_t P; + mdxaBone_t temp1; + mdxaBone_t temp2; + mdxaBone_t curRot; + mdxaBone_t curRotInv; + mdxaBone_t Gs[3]; + mdxaBone_t Enew[3]; + + assert(ghoul2.mFileName[0]); + boneInfo_v &blist = ghoul2.mBlist; + + + // END this is the objective function thing + for (i=0;i50.0f) + { + bone.velocityRoot[k]=50.0f; + } + if (bone.velocityRoot[k]<-50.0f) + { + bone.velocityRoot[k]=-50.0f; + } + */ + //No -rww + bone.ragOverrideMatrix.matrix[k][3]=bone.velocityRoot[k]; + } + } + } + else + { + vec3_t delAngles; + VectorClear(delAngles); + + for (k=0;k<3;k++) + { + tAngles[k]+=0.5f; + Create_Matrix(tAngles,&temp2); //dest 2nd arg + tAngles[k]-=0.5f; + Mat3x4_Multiply(&temp1,&P,&temp2); //dest first arg + Mat3x4_Multiply(&Gs[k],&temp1,&N); //dest first arg + + } + + int allSolidCount = 0;//bone.solidCount; + + // fixme precompute this + int numDep=G2_GetBoneDependents(ghoul2,bone.boneNumber,tempDependents,MAX_BONES_RAG); + int j; + int numRagDep=0; + for (j=0;jragIndex; + assert(depIndex>i); // these are supposed to be topologically sorted + assert(ragBoneData[depIndex]); + boneInfo_t &depBone=*ragBoneData[depIndex]; + if (depBone.RagFlags & RAG_EFFECTOR) // rag doll effector + { + // this is a dependent of me, and also a rag + numRagDep++; + for (k=0;k<3;k++) + { + Mat3x4_Multiply(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + vec3_t tPosition; + tPosition[0]=Enew[k].matrix[0][3]; + tPosition[1]=Enew[k].matrix[1][3]; + tPosition[2]=Enew[k].matrix[2][3]; + + vec3_t change; + VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg + float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); + assert( !Q_isnan(goodness)); + goodness*=depBone.weight; + delAngles[k]+=goodness; // keep bigger stuff more out of wall or something + assert( !Q_isnan(delAngles[k])); + } + allSolidCount += depBone.solidCount; + } + } + + //bone.solidCount = allSolidCount; + allSolidCount += bone.solidCount; + + VectorCopy(bone.currentAngles,bone.lastAngles); + // Update angles + float magicFactor9=0.75f; // dampfactor for angle changes + float magicFactor1=0.40f; //controls the speed of the gradient descent + float magicFactor32 = 1.5f; + float recip=0.0f; + if (numRagDep) + { + recip=sqrt(4.0f/float(numRagDep)); + } + + if (allSolidCount > 32) + { + magicFactor1 = 0.6f; + } + else if (allSolidCount > 10) + { + magicFactor1 = 0.5f; + } + + if (bone.overGradSpeed) + { //api call was made to specify a speed for this bone + magicFactor1 = bone.overGradSpeed; + } + + float fac=decay*recip*magicFactor1; + assert(fac>=0.0f); +#if 0 + if (bone.RagFlags & RAG_PCJ_PELVIS) + { + magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable + } +#endif + if (ragState==ERS_DYNAMIC) + { + magicFactor9=.85f; // we don't want this swinging radically, make the whole thing kindof unstable + } + +#if 1 //constraint breaks? + if (bone.RagFlags & RAG_UNSNAPPABLE) + { + magicFactor32 = 1.0f; + } +#endif + + for (k=0;k<3;k++) + { + bone.currentAngles[k]+=delAngles[k]*fac; + + bone.currentAngles[k]=(bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k]=AngleNormZero(bone.currentAngles[k]); +// bone.currentAngles[k]=flrand(bone.minAngles[k],bone.maxAngles[k]); +#if 1 //constraint breaks? + if (limitAngles && ( allSolidCount < 32 || (bone.RagFlags & RAG_UNSNAPPABLE) )) //32 tries and still in solid? Then we'll let you move freely +#else + if (limitAngles) +#endif + { + if (!bone.snapped || (bone.RagFlags & RAG_UNSNAPPABLE)) + { + //magicFactor32 += (allSolidCount/32); + + if (bone.currentAngles[k]>bone.maxAngles[k]*magicFactor32) + { + bone.currentAngles[k]=bone.maxAngles[k]*magicFactor32; + } + if (bone.currentAngles[k]bone.maxAngles[k]*magicFactor32) + { + isSnapped = true; + break; + } + if (bone.currentAngles[k]ragIndex; + if (!ragBoneData[depIndex]) + { + continue; + } + boneInfo_t &depBone=*ragBoneData[depIndex]; + + if (depBone.RagFlags & RAG_EFFECTOR) + { + // this is a dependent of me, and also a rag + numRagDep++; + for (k=0;k<3;k++) + { + Mat3x4_Multiply(&Enew[k],&Gs[k],&ragBones[depIndex]); //dest first arg + vec3_t tPosition; + tPosition[0]=Enew[k].matrix[0][3]; + tPosition[1]=Enew[k].matrix[1][3]; + tPosition[2]=Enew[k].matrix[2][3]; + + vec3_t change; + VectorSubtract(tPosition,ragEffectors[depIndex].currentOrigin,change); // dest is last arg + float goodness=DotProduct(change,ragEffectors[depIndex].desiredDirection); + assert( !Q_isnan(goodness)); + goodness*=depBone.weight; + delAngles[k]+=goodness; // keep bigger stuff more out of wall or something + assert( !Q_isnan(delAngles[k])); + } + } + } + + VectorCopy(bone.currentAngles, bone.lastAngles); + + // Update angles + float magicFactor9 = 0.75f; // dampfactor for angle changes + float magicFactor1 = bone.ikSpeed; //controls the speed of the gradient descent + float magicFactor32 = 1.0f; + float recip = 0.0f; + bool freeThisBone = false; + + if (!magicFactor1) + { + magicFactor1 = 0.40f; + } + + recip = sqrt(4.0f/1.0f); + + float fac = (decay*recip*magicFactor1); + assert(fac >= 0.0f); + + if (ragState == ERS_DYNAMIC) + { + magicFactor9 = 0.85f; // we don't want this swinging radically, make the whole thing kindof unstable + } + + + if (!bone.maxAngles[0] && !bone.maxAngles[1] && !bone.maxAngles[2] && + !bone.minAngles[0] && !bone.minAngles[1] && !bone.minAngles[2]) + { + freeThisBone = true; + } + + for (k = 0; k < 3; k++) + { + bone.currentAngles[k] += delAngles[k]*fac; + + bone.currentAngles[k] = (bone.lastAngles[k]-bone.currentAngles[k])*magicFactor9 + bone.currentAngles[k]; + bone.currentAngles[k] = AngleNormZero(bone.currentAngles[k]); + if (limitAngles && !freeThisBone) + { + if (bone.currentAngles[k] > bone.maxAngles[k]*magicFactor32) + { + bone.currentAngles[k] = bone.maxAngles[k]*magicFactor32; + } + if (bone.currentAngles[k] < bone.minAngles[k]*magicFactor32) + { + bone.currentAngles[k] = bone.minAngles[k]*magicFactor32; + } + } + } + Create_Matrix(bone.currentAngles, &temp1); + bone.ragOverrideMatrix = *bone.basepose * (temp1 * *bone.baseposeInv); + assert( !Q_isnan(bone.ragOverrideMatrix.matrix[2][3])); + + G2_Generate_MatrixRag(blist, ragBlistIndex[bone.boneNumber]); + } +} + +static void G2_DoIK(CGhoul2Info_v &ghoul2V,int g2Index,CRagDollUpdateParams *params) +{ + int i; + + if (!params) + { + assert(0); + return; + } + + int frameNum=G2API_GetTime(0); + CGhoul2Info &ghoul2=ghoul2V[g2Index]; + assert(ghoul2.mFileName[0]); + + float decay=1.0f; + bool resetOrigin=false; + bool anyRendered=false; + + int iters = 12; //since we don't trace or anything, we can afford this. + + if (iters) + { + if (!G2_RagDollSetup(ghoul2,frameNum,resetOrigin,params->position,anyRendered)) + { + return; + } + + // ok, now our data structures are compact and set up in topological order + for (i=0;iangles,params->position,params->scale); + + G2_IKReposition(params->position, params); + + G2_IKSolve(ghoul2V,g2Index,decay*2.0f,frameNum,params->position,true); + } + } + + if (params->me != ENTITYNUM_NONE) + { + G2_RagDollCurrentPosition(ghoul2V,g2Index,frameNum,params->angles,params->position,params->scale); + } +} + +//rww - cut out the entire non-ragdoll section of this.. +void G2_Animate_Bone_List(CGhoul2Info_v &ghoul2, const int currentTime, const int index,CRagDollUpdateParams *params) +{ + bool anyRagDoll=false; + bool anyIK = false; + for(size_t i=0; iangles, parms->position); + G2_ConstructGhoulSkeleton(ghoul2V, curTime, false, parms->scale); + + // new base anim, unconscious flop + int pcjFlags; + + //Only need the standard effectors for this. + pcjFlags = RAG_PCJ|RAG_PCJ_POST_MULT|RAG_EFFECTOR; + + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rhand",pcjFlags,6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lhand",pcjFlags,6.0f); +// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtarsal",pcjFlags,4.0f); +// G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltarsal",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtibia",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltibia",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rtalus",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ltalus",pcjFlags,4.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rradiusX",pcjFlags,6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lradiusX",pcjFlags,6.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"rfemurX",pcjFlags,10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"lfemurX",pcjFlags,10.0f); + G2_Set_Bone_Angles_IK(ghoul2, mod_a,blist,"ceyebrow",pcjFlags,10.0f); +} + +qboolean G2_SetBoneIKState(CGhoul2Info_v &ghoul2, int time, const char *boneName, int ikState, sharedSetBoneIKStateParams_t *params) +{ + model_t *mod_a; + int g2index = 0; + int curTime = time; + CGhoul2Info &g2 = ghoul2[g2index]; + const mdxaHeader_t *rmod_a = G2_GetModA(g2); + + boneInfo_v &blist = g2.mBlist; + mod_a = (model_t *)g2.animModel; + + if (!boneName) + { //null bonename param means it's time to init the ik stuff on this instance + sharedRagDollUpdateParams_t sRDUP; + + if (ikState == IKS_NONE) + { //this means we want to reset the IK state completely.. run through the bone list, and reset all the appropriate flags + size_t i = 0; + while (i < blist.size()) + { //we can't use this method for ragdoll. However, since we expect them to set their anims/angles again on the PCJ + //limb after they reset it gameside, it's reasonable for IK bones. + boneInfo_t &bone = blist[i]; + if (bone.boneNumber != -1) + { + bone.flags &= ~BONE_ANGLES_RAGDOLL; + bone.flags &= ~BONE_ANGLES_IK; + bone.RagFlags = 0; + bone.lastTimeUpdated = 0; + } + i++; + } + return qtrue; + } + assert(params); + + if (!params) + { + return qfalse; + } + + sRDUP.me = 0; + VectorCopy(params->angles, sRDUP.angles); + VectorCopy(params->origin, sRDUP.position); + VectorCopy(params->scale, sRDUP.scale); + VectorClear(sRDUP.velocity); + G2_InitIK(ghoul2, &sRDUP, curTime, rmod_a, g2index); + return qtrue; + } + + if (!rmod_a || !mod_a) + { + return qfalse; + } + + int index = G2_Find_Bone(mod_a, blist, boneName); + + if (index == -1) + { + index = G2_Add_Bone(mod_a, blist, boneName); + } + + if (index == -1) + { //couldn't find or add the bone.. + return qfalse; + } + + boneInfo_t &bone = blist[index]; + + if (ikState == IKS_NONE) + { //remove the bone from the list then, so it has to reinit. I don't think this should hurt anything since + //we don't store bone index handles gameside anywhere. + if (!(bone.flags & BONE_ANGLES_RAGDOLL)) + { //you can't set the ik state to none if it's not a rag/ik bone. + return qfalse; + } + //bone.flags = 0; + //G2_Remove_Bone_Index(blist, index); + //actually, I want to keep it on the rag list, and remove it as an IK bone instead. + bone.flags &= ~BONE_ANGLES_RAGDOLL; + bone.flags |= BONE_ANGLES_IK; + bone.RagFlags &= ~RAG_PCJ_IK_CONTROLLED; + return qtrue; + } + + //need params if we're not resetting. + if (!params) + { + assert(0); + return qfalse; + } + + if (bone.flags & BONE_ANGLES_RAGDOLL) + { //otherwise if the bone is already flagged as rag, then we can't set it again. (non-active ik bones will be BONE_ANGLES_IK, active are considered rag) + return qfalse; + } + + G2_GenerateWorldMatrix(params->angles, params->origin); + G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); + + int pcjFlags = RAG_PCJ|RAG_PCJ_IK_CONTROLLED|RAG_PCJ_POST_MULT|RAG_EFFECTOR; + + if (params->pcjOverrides) + { + pcjFlags = params->pcjOverrides; + } + + bone.ikSpeed = 0.4f; + VectorClear(bone.ikPosition); + + G2_Set_Bone_Rag(rmod_a, blist, boneName, g2, params->scale, params->origin); + + int startFrame = params->startFrame, endFrame = params->endFrame; + + if (bone.startFrame != startFrame || bone.endFrame != endFrame || params->forceAnimOnBone) + { //if it's already on this anim leave it alone, to allow smooth transitions into IK on the current anim if it is so desired. + G2_Set_Bone_Anim_No_BS(g2, rmod_a, blist, boneName, startFrame, endFrame-1, + BONE_ANIM_OVERRIDE_FREEZE|BONE_ANIM_BLEND, + 1.0f, curTime, float(startFrame), 150, 0, true); + } + + G2_ConstructGhoulSkeleton(ghoul2, curTime, false, params->scale); + + bone.lastTimeUpdated = 0; + G2_Set_Bone_Angles_Rag(g2, rmod_a, blist, boneName, pcjFlags, params->radius, params->pcjMins, params->pcjMaxs, params->blendTime); + + if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) + { + assert(!"failed to add any rag bones"); + return qfalse; + } + + return qtrue; +} + +qboolean G2_IKMove(CGhoul2Info_v &ghoul2, int time, sharedIKMoveParams_t *params) +{ +#if 0 + model_t *mod_a; + int g2index = 0; + int curTime = time; + CGhoul2Info &g2 = ghoul2[g2index]; + + boneInfo_v &blist = g2.mBlist; + mod_a = (model_t *)g2.animModel; + + if (!mod_a) + { + return qfalse; + } + + int index = G2_Find_Bone(mod_a, blist, params->boneName); + + //don't add here if you can't find it.. ik bones should already be there, because they need to have special stuff done to them anyway. + if (index == -1) + { //couldn't find the bone.. + return qfalse; + } + + if (!params) + { + assert(0); + return qfalse; + } + + if (!(blist[index].flags & BONE_ANGLES_RAGDOLL) && !(blist[index].flags & BONE_ANGLES_IK)) + { //no-can-do, buddy + return qfalse; + } + + VectorCopy(params->desiredOrigin, blist[index].ikPosition); + blist[index].ikSpeed = params->movementSpeed; +#else + int g2index = 0; + int curTime = time; + CGhoul2Info &g2 = ghoul2[g2index]; + + //rwwFIXMEFIXME: Doing this on all bones at the moment, fix this later? + if (!G2_RagDollSetup(g2,curTime,true,params->origin,false)) + { //changed models, possibly. + return qfalse; + } + + for (int i=0;idesiredOrigin, bone.ikPosition); + bone.ikSpeed = params->movementSpeed; + } + } +#endif + return qtrue; +} + +// set the bone list to all unused so the bone transformation routine ignores it. +void G2_Init_Bone_List(boneInfo_v &blist, int numBones) +{ + blist.clear(); + blist.reserve(numBones); +} + +void G2_RemoveRedundantBoneOverrides(boneInfo_v &blist, int *activeBones) +{ + // walk the surface list, removing surface overrides or generated surfaces that are pointing at surfaces that aren't active anymore + for (size_t i=0; imFileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); + + return (G2_Find_Bone(mod_a, ghoul2->mBlist, boneName)); +} diff --git a/codemp/rd-rend2/G2_gore_r2.cpp b/codemp/rd-rend2/G2_gore_r2.cpp new file mode 100644 index 0000000000..f28d367bfa --- /dev/null +++ b/codemp/rd-rend2/G2_gore_r2.cpp @@ -0,0 +1,49 @@ +/* +=========================================================================== +Copyright (C) 2000 - 2013, Raven Software, Inc. +Copyright (C) 2001 - 2013, Activision, Inc. +Copyright (C) 2013 - 2015, OpenJK contributors + +This file is part of the OpenJK source code. + +OpenJK is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . +=========================================================================== +*/ + +#include "G2_gore_r2.h" +#include "../rd-common/tr_common.h" + +#ifdef _G2_GORE + +R2GoreTextureCoordinates::R2GoreTextureCoordinates() +{ + Com_Memset (tex, 0, sizeof (tex)); +} + +R2GoreTextureCoordinates::~R2GoreTextureCoordinates() +{ + for ( int i = 0; i < MAX_LODS; i++ ) + { + if ( tex[i] ) + { + ri.Z_Free(tex[i]->verts); + tex[i]->verts = NULL; + ri.Z_Free(tex[i]->indexes); + tex[i]->indexes = NULL; + ri.Z_Free(tex[i]); + tex[i] = NULL; + } + } +} + +#endif diff --git a/codemp/rd-rend2/G2_gore_r2.h b/codemp/rd-rend2/G2_gore_r2.h new file mode 100644 index 0000000000..2ae4abb181 --- /dev/null +++ b/codemp/rd-rend2/G2_gore_r2.h @@ -0,0 +1,48 @@ +/* +=========================================================================== +Copyright (C) 2000 - 2013, Raven Software, Inc. +Copyright (C) 2001 - 2013, Activision, Inc. +Copyright (C) 2013 - 2015, OpenJK contributors + +This file is part of the OpenJK source code. + +OpenJK is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . +=========================================================================== +*/ + +#pragma once + +#include "tr_local.h" + +#ifdef _G2_GORE + +#define MAX_LODS (8) +#define MAX_GORE_VERTS (3000) +#define MAX_GORE_INDECIES (6000) + +//TODO: This needs to be set via a scalability cvar with some reasonable minimum value if pgore is used at all +#define MAX_GORE_RECORDS (500) + +struct R2GoreTextureCoordinates +{ + srfG2GoreSurface_t *tex[MAX_LODS]; + + R2GoreTextureCoordinates(); + ~R2GoreTextureCoordinates(); +}; + +int AllocR2GoreRecord(); +R2GoreTextureCoordinates *FindR2GoreRecord(int tag); +void DeleteR2GoreRecord(int tag); + +#endif diff --git a/codemp/rd-rend2/G2_misc.cpp b/codemp/rd-rend2/G2_misc.cpp new file mode 100644 index 0000000000..ac64001c4e --- /dev/null +++ b/codemp/rd-rend2/G2_misc.cpp @@ -0,0 +1,1889 @@ +#include "qcommon/matcomp.h" +#include "ghoul2/G2.h" +#include "qcommon/MiniHeap.h" +#include "server/server.h" +#include "ghoul2/g2_local.h" +#include "tr_local.h" + +#ifdef _G2_GORE +#include "ghoul2/G2_gore.h" +#include "G2_gore_r2.h" + +#define GORE_TAG_UPPER (256) +#define GORE_TAG_MASK (~255) + +static int CurrentTag=GORE_TAG_UPPER+1; +static int CurrentTagUpper=GORE_TAG_UPPER; + +static std::map GoreRecords; +static std::map,int> GoreTagsTemp; // this is a surface index to gore tag map used only + // temporarily during the generation phase so we reuse gore tags per LOD +int goreModelIndex; + +static cvar_t *cg_g2MarksAllModels=NULL; + +R2GoreTextureCoordinates *FindR2GoreRecord(int tag); +static inline void DestroyGoreTexCoordinates(int tag) +{ + R2GoreTextureCoordinates *gTC = FindR2GoreRecord(tag); + if (!gTC) + { + return; + } + gTC->~R2GoreTextureCoordinates(); + //I don't know what's going on here, it should call the destructor for + //this when it erases the record but sometimes it doesn't. -rww +} + + +int AllocR2GoreRecord() +{ + while (GoreRecords.size()>MAX_GORE_RECORDS) + { + int tagHigh=(*GoreRecords.begin()).first&GORE_TAG_MASK; + std::map::iterator it; + R2GoreTextureCoordinates *gTC; + + it = GoreRecords.begin(); + gTC = &(*it).second; + + if (gTC) + { + gTC->~R2GoreTextureCoordinates(); + } + GoreRecords.erase(GoreRecords.begin()); + while (GoreRecords.size()) + { + if (((*GoreRecords.begin()).first&GORE_TAG_MASK)!=tagHigh) + { + break; + } + it = GoreRecords.begin(); + gTC = &(*it).second; + + if (gTC) + { + gTC->~R2GoreTextureCoordinates(); + } + GoreRecords.erase(GoreRecords.begin()); + } + } + int ret=CurrentTag; + GoreRecords[CurrentTag]= R2GoreTextureCoordinates(); + CurrentTag++; + return ret; +} + +void ResetGoreTag() +{ + GoreTagsTemp.clear(); + CurrentTag=CurrentTagUpper; + CurrentTagUpper+=GORE_TAG_UPPER; +} + +R2GoreTextureCoordinates *FindR2GoreRecord(int tag) +{ + std::map::iterator i=GoreRecords.find(tag); + if (i!=GoreRecords.end()) + { + return &(*i).second; + } + return 0; +} + +void *G2_GetGoreRecord(int tag) +{ + return FindR2GoreRecord(tag); +} + +void DeleteR2GoreRecord(int tag) +{ + DestroyGoreTexCoordinates(tag); + GoreRecords.erase(tag); +} + +static int CurrentGoreSet=1; // this is a UUID for gore sets +static std::map GoreSets; // map from uuid to goreset + +CGoreSet *FindGoreSet(int goreSetTag) +{ + std::map::iterator f=GoreSets.find(goreSetTag); + if (f!=GoreSets.end()) + { + return (*f).second; + } + return 0; +} + +CGoreSet *NewGoreSet() +{ + CGoreSet *ret=new CGoreSet(CurrentGoreSet++); + GoreSets[ret->mMyGoreSetTag]=ret; + ret->mRefCount = 1; + return ret; +} + +void DeleteGoreSet(int goreSetTag) +{ + std::map::iterator f=GoreSets.find(goreSetTag); + if (f!=GoreSets.end()) + { + if ( (*f).second->mRefCount == 0 || (*f).second->mRefCount - 1 == 0 ) + { + delete (*f).second; + GoreSets.erase(f); + } + else + { + (*f).second->mRefCount--; + } + } +} + + +CGoreSet::~CGoreSet() +{ + std::multimap::iterator i; + for (i=mGoreRecords.begin();i!=mGoreRecords.end();i++) + { + DeleteR2GoreRecord((*i).second.mGoreTag); + } +}; +#endif // _SOF2 + +const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache); + +#ifdef _MSC_VER +#pragma warning(disable : 4512) //assignment op could not be genereated +#endif +class CTraceSurface +{ +public: + int surfaceNum; + surfaceInfo_v &rootSList; + model_t *currentModel; + int lod; + vec3_t rayStart; + vec3_t rayEnd; + CollisionRecord_t *collRecMap; + int entNum; + int modelIndex; + skin_t *skin; +#ifdef _WIN32 + struct shader_t *cust_shader; +#else + shader_t *cust_shader; +#endif + size_t *TransformedVertsArray; + int traceFlags; + bool hitOne; + float m_fRadius; + +#ifdef _G2_GORE + //gore application thing + float ssize; + float tsize; + float theta; + int goreShader; + CGhoul2Info *ghoul2info; + + // Procedural-gore application things + SSkinGoreData *gore; +#endif + + CTraceSurface( + int initsurfaceNum, + surfaceInfo_v &initrootSList, + model_t *initcurrentModel, + int initlod, + vec3_t initrayStart, + vec3_t initrayEnd, + CollisionRecord_t *initcollRecMap, + int initentNum, + int initmodelIndex, + skin_t *initskin, + shader_t *initcust_shader, + size_t *initTransformedVertsArray, + int inittraceFlags, +#ifdef _G2_GORE + float fRadius, + float initssize, + float inittsize, + float inittheta, + int initgoreShader, + CGhoul2Info *initghoul2info, + SSkinGoreData *initgore): +#else + float fRadius): +#endif + + surfaceNum(initsurfaceNum), + rootSList(initrootSList), + currentModel(initcurrentModel), + lod(initlod), + collRecMap(initcollRecMap), + entNum(initentNum), + modelIndex(initmodelIndex), + skin(initskin), + cust_shader(initcust_shader), + TransformedVertsArray(initTransformedVertsArray), + traceFlags(inittraceFlags), +#ifdef _G2_GORE + m_fRadius(fRadius), + ssize(initssize), + tsize(inittsize), + theta(inittheta), + goreShader(initgoreShader), + ghoul2info(initghoul2info), + gore(initgore) +#else + m_fRadius(fRadius) +#endif + { + VectorCopy(initrayStart, rayStart); + VectorCopy(initrayEnd, rayEnd); + hitOne = false; + } + +}; + +// assorted Ghoul 2 functions. +// list all surfaces associated with a model +void G2_List_Model_Surfaces(const char *fileName) +{ + int i, x; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + mdxmSurfHierarchy_t *surf; + mdxmHeader_t *mdxm = mod_m->data.glm->header; + + surf = (mdxmSurfHierarchy_t *) ( (byte *)mdxm + mdxm->ofsSurfHierarchy ); + mdxmSurface_t *surface = (mdxmSurface_t *)((byte *)mdxm + mdxm->ofsLODs + sizeof(mdxmLOD_t)); + + for ( x = 0 ; x < mdxm->numSurfaces ; x++) + { + Com_Printf("Surface %i Name %s\n", x, surf->name); + if ( r_verbose->integer ) + { + Com_Printf("Num Descendants %i\n", surf->numChildren); + for (i=0; inumChildren; i++) + { + Com_Printf("Descendant %i\n", surf->childIndexes[i]); + } + } + // find the next surface + surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + surface =(mdxmSurface_t *)( (byte *)surface + surface->ofsEnd ); + } + +} + +// list all bones associated with a model +void G2_List_Model_Bones(const char *fileName, int frame) +{ + int x, i; + mdxaSkel_t *skel; + mdxaSkelOffsets_t *offsets; + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(fileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->data.glm->header->animIndex); +// mdxaFrame_t *aframe=0; +// int frameSize; + mdxaHeader_t *header = mod_a->data.gla; + + // figure out where the offset list is + offsets = (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); + +// frameSize = (size_t)( &((mdxaFrame_t *)0)->boneIndexes[ header->numBones ] ); + +// aframe = (mdxaFrame_t *)((byte *)header + header->ofsFrames + (frame * frameSize)); + // walk each bone and list it's name + for (x=0; x< header->numBones; x++) + { + skel = (mdxaSkel_t *)((byte *)header + sizeof(mdxaHeader_t) + offsets->offsets[x]); + Com_Printf("Bone %i Name %s\n", x, skel->name); + + Com_Printf("X pos %f, Y pos %f, Z pos %f\n", skel->BasePoseMat.matrix[0][3], skel->BasePoseMat.matrix[1][3], skel->BasePoseMat.matrix[2][3]); + + // if we are in verbose mode give us more details + if ( r_verbose->integer ) + { + Com_Printf("Num Descendants %i\n", skel->numChildren); + for (i=0; inumChildren; i++) + { + Com_Printf("Num Descendants %i\n", skel->numChildren); + } + } + } +} + + +/************************************************************************************************ + * G2_GetAnimFileName + * obtain the .gla filename for a model + * + * Input + * filename of model + * + * Output + * true if we successfully obtained a filename, false otherwise + * + ************************************************************************************************/ +qboolean G2_GetAnimFileName(const char *fileName, char **filename) +{ + // find the model we want + model_t *mod = R_GetModelByHandle(RE_RegisterModel(fileName)); + + if (mod) + { + mdxmHeader_t *mdxm = mod->data.glm->header; + if (mdxm && mdxm->animName[0] != 0) + { + *filename = mdxm->animName; + return qtrue; + } + } + return qfalse; +} + + +///////////////////////////////////////////////////////////////////// +// +// Code for collision detection for models gameside +// +///////////////////////////////////////////////////////////////////// + +int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod) +{ + int returnLod = useLod; + + // if we are overriding the LOD at top level, then we can afford to only check this level of model + if (ghoul2.mLodBias > returnLod) + { + returnLod = ghoul2.mLodBias; + } +// assert(G2_MODEL_OK(&ghoul2)); + + mdxmHeader_t *mdxm = ghoul2.currentModel->data.glm->header; + assert(ghoul2.currentModel); + assert(mdxm); + //what about r_lodBias? + + // now ensure that we haven't selected a lod that doesn't exist for this model + if ( returnLod >= mdxm->numLODs ) + { + returnLod = mdxm->numLODs - 1; + } + + return returnLod; +} + +void R_TransformEachSurface( const mdxmSurface_t *surface, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertsArray,CBoneCache *boneCache) +{ + int j, k; + mdxmVertex_t *v; + float *TransformedVerts; + + // + // deform the vertexes by the lerped bones + // + int *piBoneReferences = (int*) ((byte*)surface + surface->ofsBoneReferences); + + // alloc some space for the transformed verts to get put in + TransformedVerts = (float *)G2VertSpace->MiniHeapAlloc(surface->numVerts * 5 * 4); + TransformedVertsArray[surface->thisSurfaceIndex] = (size_t)TransformedVerts; + if (!TransformedVerts) + { + Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust MiniHeapSize in SV_SpawnServer.\n"); + } + + // whip through and actually transform each vertex + const int numVerts = surface->numVerts; + v = (mdxmVertex_t *) ((byte *)surface + surface->ofsVerts); + mdxmVertexTexCoord_t *pTexCoords = (mdxmVertexTexCoord_t *) &v[numVerts]; + + // optimisation issue + if ((scale[0] != 1.0) || (scale[1] != 1.0) || (scale[2] != 1.0)) + { + for ( j = 0; j < numVerts; j++ ) + { + vec3_t tempVert, tempNormal; +// mdxmWeight_t *w; + + VectorClear( tempVert ); + VectorClear( tempNormal ); +// w = v->weights; + + const int iNumWeights = G2_GetVertWeights( v ); + + float fTotalWeight = 0.0f; + for ( k = 0 ; k < iNumWeights ; k++ ) + { + int iBoneIndex = G2_GetVertBoneIndex( v, k ); + float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + + const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + + tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); + tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); + tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + + tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); + tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); + tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + } + int pos = j * 5; + + // copy tranformed verts into temp space + TransformedVerts[pos++] = tempVert[0] * scale[0]; + TransformedVerts[pos++] = tempVert[1] * scale[1]; + TransformedVerts[pos++] = tempVert[2] * scale[2]; + // we will need the S & T coors too for hitlocation and hitmaterial stuff + TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; + TransformedVerts[pos] = pTexCoords[j].texCoords[1]; + + v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + } + } + else + { + int pos = 0; + for ( j = 0; j < numVerts; j++ ) + { + vec3_t tempVert, tempNormal; +// const mdxmWeight_t *w; + + VectorClear( tempVert ); + VectorClear( tempNormal ); +// w = v->weights; + + const int iNumWeights = G2_GetVertWeights( v ); + + float fTotalWeight = 0.0f; + for ( k = 0 ; k < iNumWeights ; k++ ) + { + int iBoneIndex = G2_GetVertBoneIndex( v, k ); + float fBoneWeight = G2_GetVertBoneWeight( v, k, fTotalWeight, iNumWeights ); + + const mdxaBone_t &bone=EvalBoneCache(piBoneReferences[iBoneIndex],boneCache); + + tempVert[0] += fBoneWeight * ( DotProduct( bone.matrix[0], v->vertCoords ) + bone.matrix[0][3] ); + tempVert[1] += fBoneWeight * ( DotProduct( bone.matrix[1], v->vertCoords ) + bone.matrix[1][3] ); + tempVert[2] += fBoneWeight * ( DotProduct( bone.matrix[2], v->vertCoords ) + bone.matrix[2][3] ); + + tempNormal[0] += fBoneWeight * DotProduct( bone.matrix[0], v->normal ); + tempNormal[1] += fBoneWeight * DotProduct( bone.matrix[1], v->normal ); + tempNormal[2] += fBoneWeight * DotProduct( bone.matrix[2], v->normal ); + } + + // copy tranformed verts into temp space + TransformedVerts[pos++] = tempVert[0]; + TransformedVerts[pos++] = tempVert[1]; + TransformedVerts[pos++] = tempVert[2]; + // we will need the S & T coors too for hitlocation and hitmaterial stuff + TransformedVerts[pos++] = pTexCoords[j].texCoords[0]; + TransformedVerts[pos++] = pTexCoords[j].texCoords[1]; + + v++;// = (mdxmVertex_t *)&v->weights[/*v->numWeights*/surface->maxVertBoneWeights]; + } + } +} + +void G2_TransformSurfaces(int surfaceNum, surfaceInfo_v &rootSList, + CBoneCache *boneCache, const model_t *currentModel, int lod, vec3_t scale, IHeapAllocator *G2VertSpace, size_t *TransformedVertArray, bool secondTimeAround) +{ + int i; + assert(currentModel); + assert(currentModel->data.glm && currentModel->data.glm->header); + // back track and get the surfinfo struct for this surface + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void*)currentModel, surfaceNum, lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + + // see if we have an override surface in the surface list + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); + + // really, we should use the default flags for this surface unless it's been overriden + int offFlags = surfInfo->flags; + + if (surfOverride) + { + offFlags = surfOverride->offFlags; + } + // if this surface is not off, add it to the shader render list + if (!offFlags) + { + + R_TransformEachSurface(surface, scale, G2VertSpace, TransformedVertArray, boneCache); + } + + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) + { + return; + } + + // now recursively call for the children + for (i=0; i< surfInfo->numChildren; i++) + { + G2_TransformSurfaces(surfInfo->childIndexes[i], rootSList, boneCache, currentModel, lod, scale, G2VertSpace, TransformedVertArray, secondTimeAround); + } +} + +// main calling point for the model transform for collision detection. At this point all of the skeleton has been transformed. +#ifdef _G2_GORE +void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, IHeapAllocator *G2VertSpace, int useLod, bool ApplyGore) +#else +void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, IHeapAllocator *G2VertSpace, int useLod) +#endif +{ + int i, lod; + vec3_t correctScale; + qboolean firstModelOnly = qfalse; + +#ifdef _G2_GORE + if ( cg_g2MarksAllModels == NULL ) + { + cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "Render marks on all G2 models" ); + } + + if (cg_g2MarksAllModels == NULL + || !cg_g2MarksAllModels->integer ) + { + firstModelOnly = qtrue; + } +#endif + + VectorCopy(scale, correctScale); + // check for scales of 0 - that's the default I believe + if (!scale[0]) + { + correctScale[0] = 1.0; + } + if (!scale[1]) + { + correctScale[1] = 1.0; + } + if (!scale[2]) + { + correctScale[2] = 1.0; + } + + // walk each possible model for this entity and try rendering it out + for (i=0; i=g.currentModel->numLods) + { + g.mTransformedVertsArray = 0; + if ( firstModelOnly ) + { + // we don't really need to do multiple models for gore. + return; + } + //do the rest + continue; + } + } + else + { +#endif + lod = G2_DecideTraceLod(g, useLod); +#ifdef _G2_GORE + } +#endif + + mdxmHeader_t *mdxm = g.currentModel->data.glm->header; + + // give us space for the transformed vertex array to be put in + if (!(g.mFlags & GHOUL2_ZONETRANSALLOC)) + { //do not stomp if we're using zone space + g.mTransformedVertsArray = (size_t*)G2VertSpace->MiniHeapAlloc(mdxm->numSurfaces * sizeof (size_t)); + if (!g.mTransformedVertsArray) + { + Com_Error(ERR_DROP, "Ran out of transform space for Ghoul2 Models. Adjust MiniHeapSize in SV_SpawnServer.\n"); + } + } + + memset(g.mTransformedVertsArray, 0,mdxm->numSurfaces * sizeof (size_t)); + + G2_FindOverrideSurface(-1,g.mSlist); //reset the quick surface override lookup; + // recursively call the model surface transform + + G2_TransformSurfaces(g.mSurfaceRoot, g.mSlist, g.mBoneCache, g.currentModel, lod, correctScale, G2VertSpace, g.mTransformedVertsArray, false); + +#ifdef _G2_GORE + if (ApplyGore && firstModelOnly) + { + // we don't really need to do multiple models for gore. + break; + } +#endif + } +} + + +// work out how much space a triangle takes +static float G2_AreaOfTri(const vec3_t A, const vec3_t B, const vec3_t C) +{ + vec3_t cross, ab, cb; + VectorSubtract(A, B, ab); + VectorSubtract(C, B, cb); + + CrossProduct(ab, cb, cross); + + return VectorLength(cross); +} + +// actually determine the S and T of the coordinate we hit in a given poly +static void G2_BuildHitPointST( const vec3_t A, const float SA, const float TA, + const vec3_t B, const float SB, const float TB, + const vec3_t C, const float SC, const float TC, + const vec3_t P, float *s, float *t,float &bary_i,float &bary_j) +{ + float areaABC = G2_AreaOfTri(A, B, C); + + float i = G2_AreaOfTri(P, B, C) / areaABC; + bary_i=i; + float j = G2_AreaOfTri(A, P, C) / areaABC; + bary_j=j; + float k = G2_AreaOfTri(A, B, P) / areaABC; + + *s = SA * i + SB * j + SC * k; + *t = TA * i + TB * j + TC * k; + + *s=fmod(*s, 1); + if (*s< 0) + { + *s+= 1.0; + } + + *t=fmod(*t, 1); + if (*t< 0) + { + *t+= 1.0; + } + +} + + +// routine that works out given a ray whether or not it hits a poly +qboolean G2_SegmentTriangleTest( const vec3_t start, const vec3_t end, + const vec3_t A, const vec3_t B, const vec3_t C, + qboolean backFaces,qboolean frontFaces,vec3_t returnedPoint,vec3_t returnedNormal, float *denom) +{ + static const float tiny=1E-10f; + vec3_t returnedNormalT; + vec3_t edgeAC; + + VectorSubtract(C, A, edgeAC); + VectorSubtract(B, A, returnedNormalT); + + CrossProduct(returnedNormalT, edgeAC, returnedNormal); + + vec3_t ray; + VectorSubtract(end, start, ray); + + *denom=DotProduct(ray, returnedNormal); + + if (fabs(*denom)0)|| // not accepting back faces + (!frontFaces && *denom<0)) //not accepting front faces + { + return qfalse; + } + + vec3_t toPlane; + VectorSubtract(A, start, toPlane); + + float t=DotProduct(toPlane, returnedNormal)/ *denom; + + if (t<0.0f||t>1.0f) + { + return qfalse; // off segment + } + + VectorScale(ray, t, ray); + + VectorAdd(ray, start, returnedPoint); + + vec3_t edgePA; + VectorSubtract(A, returnedPoint, edgePA); + + vec3_t edgePB; + VectorSubtract(B, returnedPoint, edgePB); + + vec3_t edgePC; + VectorSubtract(C, returnedPoint, edgePC); + + vec3_t temp; + + CrossProduct(edgePA, edgePB, temp); + if (DotProduct(temp, returnedNormal)<0.0f) + { + return qfalse; // off triangle + } + + CrossProduct(edgePC, edgePA, temp); + if (DotProduct(temp,returnedNormal)<0.0f) + { + return qfalse; // off triangle + } + + CrossProduct(edgePB, edgePC, temp); + if (DotProduct(temp, returnedNormal)<0.0f) + { + return qfalse; // off triangle + } + return qtrue; +} + +#ifdef _G2_GORE +struct SVertexTemp +{ + int flags; + int touch; + int newindex; + float tex[2]; + SVertexTemp() + { + touch=0; + } +}; + +static SVertexTemp GoreVerts[MAX_GORE_VERTS]; +static int GoreIndexCopy[MAX_GORE_VERTS]; +static int GoreTouch=1; +static int GoreIndecies[MAX_GORE_INDECIES]; + +#define GORE_MARGIN (0.0f) +int G2API_GetTime(int argTime); + +// now we at poly level, check each model space transformed poly against the model world transfomed ray +void G2_GorePolys( const mdxmSurface_t *surface, CTraceSurface &TS, const mdxmSurfHierarchy_t *surfInfo) +{ + int j; + vec3_t basis1; + vec3_t basis2; + vec3_t taxis; + vec3_t saxis; + + basis2[0]=0.0f; + basis2[1]=0.0f; + basis2[2]=1.0f; + + CrossProduct(TS.rayEnd,basis2,basis1); + + if (DotProduct(basis1,basis1)<.1f) + { + basis2[0]=0.0f; + basis2[1]=1.0f; + basis2[2]=0.0f; + CrossProduct(TS.rayEnd,basis2,basis1); + } + + CrossProduct(TS.rayEnd,basis1,basis2); + // Give me a shot direction not a bunch of zeros :) -Gil + assert(DotProduct(basis1,basis1)>.0001f); + assert(DotProduct(basis2,basis2)>.0001f); + + VectorNormalize(basis1); + VectorNormalize(basis2); + + float c=cos(TS.theta); + float s=sin(TS.theta); + + VectorScale(basis1,.5f*c/TS.tsize,taxis); + VectorMA(taxis,.5f*s/TS.tsize,basis2,taxis); + + VectorScale(basis1,-.5f*s/TS.ssize,saxis); + VectorMA(saxis,.5f*c/TS.ssize,basis2,saxis); + + float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; + int numVerts = surface->numVerts; + int flags=15; + assert(numVertsGORE_MARGIN) + { + vflags|=1; + } + if (s<1.0f-GORE_MARGIN) + { + vflags|=2; + } + if (t>GORE_MARGIN) + { + vflags|=4; + } + if (t<1.0f-GORE_MARGIN) + { + vflags|=8; + } + vflags=(~vflags); + flags&=vflags; + GoreVerts[j].flags=vflags; + GoreVerts[j].tex[0]=s; + GoreVerts[j].tex[1]=t; + } + if (flags) + { + return; // completely off the gore splotch. + } + int numTris,newNumTris,newNumVerts; + numTris = surface->numTriangles; + mdxmTriangle_t *tris; + tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; + newNumTris=0; + newNumVerts=0; + GoreTouch++; + if (!TS.gore) + { + return; + } + for ( j = 0; j < numTris; j++ ) + { + assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]frontFaces || !TS.gore->backFaces) + { + // we need to back/front face cull + vec3_t e1,e2,n; + + VectorSubtract(&verts[tris[j].indexes[1]*5],&verts[tris[j].indexes[0]*5],e1); + VectorSubtract(&verts[tris[j].indexes[2]*5],&verts[tris[j].indexes[0]*5],e2); + CrossProduct(e1,e2,n); + if (DotProduct(TS.rayEnd,n)>0.0f) + { + if (!TS.gore->frontFaces) + { + continue; + } + } + else + { + if (!TS.gore->backFaces) + { + continue; + } + } + + } + + int k; + + assert(newNumTris*3+3,int>::iterator f=GoreTagsTemp.find(std::pair(goreModelIndex,TS.surfaceNum)); + if (f==GoreTagsTemp.end()) // need to generate a record + { + newTag=AllocR2GoreRecord(); + CGoreSet *goreSet=0; + if (TS.ghoul2info->mGoreSetTag) + { + goreSet=FindGoreSet(TS.ghoul2info->mGoreSetTag); + } + if (!goreSet) + { + goreSet=NewGoreSet(); + TS.ghoul2info->mGoreSetTag=goreSet->mMyGoreSetTag; + } + assert(goreSet); + SGoreSurface add; + add.shader=TS.goreShader; + add.mDeleteTime=0; + if (TS.gore->lifeTime) + { + add.mDeleteTime=G2API_GetTime(0) + TS.gore->lifeTime; + } + add.mFadeTime = TS.gore->fadeOutTime; + add.mFadeRGB = !!(TS.gore->fadeRGB); + add.mGoreTag = newTag; + + add.mGoreGrowStartTime=G2API_GetTime(0); + if( TS.gore->growDuration == -1) + { + add.mGoreGrowEndTime = -1; // set this to -1 to disable growing + } + else + { + add.mGoreGrowEndTime = G2API_GetTime(0) + TS.gore->growDuration; + } + + assert(TS.gore->growDuration != 0); + add.mGoreGrowFactor = ( 1.0f - TS.gore->goreScaleStartFraction) / (float)(TS.gore->growDuration); //curscale = (curtime-mGoreGrowStartTime)*mGoreGrowFactor; + add.mGoreGrowOffset = TS.gore->goreScaleStartFraction; + + goreSet->mGoreRecords.insert(std::pair(TS.surfaceNum,add)); + GoreTagsTemp[std::pair(goreModelIndex,TS.surfaceNum)]=newTag; + } + else + { + newTag=(*f).second; + } + R2GoreTextureCoordinates *gore= FindR2GoreRecord(newTag); + if (gore) + { + srfG2GoreSurface_t *goreSurface=(srfG2GoreSurface_t *)Z_Malloc ( sizeof(srfG2GoreSurface_t), TAG_GHOUL2_GORE, qtrue ); + + if ( gore->tex[TS.lod] ) + { + if (gore->tex[TS.lod]->verts) + Z_Free(gore->tex[TS.lod]->verts); + if (gore->tex[TS.lod]->indexes) + Z_Free(gore->tex[TS.lod]->indexes); + Z_Free(gore->tex[TS.lod]); + } + + gore->tex[TS.lod]=(srfG2GoreSurface_t *)goreSurface; + goreSurface->numVerts = newNumVerts; + goreSurface->verts = (g2GoreVert_t *)Z_Malloc(sizeof(g2GoreVert_t)*newNumVerts, TAG_GHOUL2_GORE, qtrue); + + for (j=0;jverts[j].texCoords[0] = GoreVerts[GoreIndexCopy[j]].tex[0]; + goreSurface->verts[j].texCoords[1] = GoreVerts[GoreIndexCopy[j]].tex[1]; + } + + mdxmVertex_t *v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + int *boneRef = (int *)((byte *)surface + surface->ofsBoneReferences); + for (j = 0; j < newNumVerts; j++) + { + mdxmVertex_t currentVert = v[GoreIndexCopy[j]]; + VectorCopy(currentVert.vertCoords, goreSurface->verts[j].position); + goreSurface->verts[j].normal = R_VboPackNormal(currentVert.normal); + + int numWeights = G2_GetVertWeights(¤tVert); + float fTotalWeight = 0.0f; + for (int w = 0; w < numWeights; w++) + { + float weight = G2_GetVertBoneWeight(¤tVert, w, fTotalWeight, numWeights); + goreSurface->verts[j].weights[w] = (byte)(weight * 255.0f); + int packedIndex = G2_GetVertBoneIndex(¤tVert, w); + goreSurface->verts[j].bonerefs[w] = boneRef[packedIndex]; + } + } + + goreSurface->indexes = (glIndex_t *)Z_Malloc(sizeof(glIndex_t)*newNumTris*3, TAG_GHOUL2_GORE, qtrue); + for (j = 0; j < newNumTris * 3; j++) + { + goreSurface->indexes[j] = GoreIndecies[j] + tr.goreVBOCurrentIndex; + } + goreSurface->numIndexes = newNumTris * 3; + + RB_UpdateGoreVBO(goreSurface); + } +} +#else +struct SVertexTemp +{ + int flags; +// int touch; +// int newindex; +// float tex[2]; + SVertexTemp() + { +// touch=0; + } +}; + +#define MAX_GORE_VERTS (3000) +static SVertexTemp GoreVerts[MAX_GORE_VERTS]; +#endif + +// now we're at poly level, check each model space transformed poly against the model world transfomed ray +static bool G2_TracePolys(const mdxmSurface_t *surface, const mdxmSurfHierarchy_t *surfInfo, CTraceSurface &TS) +{ + int j, numTris; + + // whip through and actually transform each vertex + const mdxmTriangle_t *tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + const float *verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; + numTris = surface->numTriangles; + for ( j = 0; j < numTris; j++ ) + { + float face; + vec3_t hitPoint, normal; + // determine actual coords for this triangle + const float *point1 = &verts[(tris[j].indexes[0] * 5)]; + const float *point2 = &verts[(tris[j].indexes[1] * 5)]; + const float *point3 = &verts[(tris[j].indexes[2] * 5)]; + // did we hit it? + int i; + if (G2_SegmentTriangleTest(TS.rayStart, TS.rayEnd, point1, point2, point3, qtrue, qtrue, hitPoint, normal, &face)) + { // find space in the collision records for this record + for (i=0; ithisSurfaceIndex; + newCol.mModelIndex = TS.modelIndex; + if (face>0) + { + newCol.mFlags = G2_FRONTFACE; + } + else + { + newCol.mFlags = G2_BACKFACE; + } + + VectorSubtract(hitPoint, TS.rayStart, distVect); + newCol.mDistance = VectorLength(distVect); + + // put the hit point back into world space + TransformAndTranslatePoint(hitPoint, newCol.mCollisionPosition, &worldMatrix); + + // transform normal (but don't translate) into world angles + TransformPoint(normal, newCol.mCollisionNormal, &worldMatrix); + VectorNormalize(newCol.mCollisionNormal); + + newCol.mMaterial = newCol.mLocation = 0; + + // Determine our location within the texture, and barycentric coordinates + G2_BuildHitPointST(point1, point1[3], point1[4], + point2, point2[3], point2[4], + point3, point3[3], point3[4], + hitPoint, &x_pos, &y_pos,newCol.mBarycentricI,newCol.mBarycentricJ); + +/* + const shader_t *shader = 0; + // now, we know what surface this hit belongs to, we need to go get the shader handle so we can get the correct hit location and hit material info + if ( cust_shader ) + { + shader = cust_shader; + } + else if ( skin ) + { + int j; + + // match the surface name to something in the skin file + shader = tr.defaultShader; + for ( j = 0 ; j < skin->numSurfaces ; j++ ) + { + // the names have both been lowercased + if ( !strcmp( skin->surfaces[j]->name, surfInfo->name ) ) + { + shader = skin->surfaces[j]->shader; + break; + } + } + } + else + { + shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } + + // do we even care to decide what the hit or location area's are? If we don't have them in the shader there is little point + if ((shader->hitLocation) || (shader->hitMaterial)) + { + // ok, we have a floating point position. - determine location in data we need to look at + if (shader->hitLocation) + { + newCol.mLocation = *(hitMatReg[shader->hitLocation].loc + + ((int)(y_pos * hitMatReg[shader->hitLocation].height) * hitMatReg[shader->hitLocation].width) + + ((int)(x_pos * hitMatReg[shader->hitLocation].width))); + Com_Printf("G2_TracePolys hit location: %d\n", newCol.mLocation); + } + + if (shader->hitMaterial) + { + newCol.mMaterial = *(hitMatReg[shader->hitMaterial].loc + + ((int)(y_pos * hitMatReg[shader->hitMaterial].height) * hitMatReg[shader->hitMaterial].width) + + ((int)(x_pos * hitMatReg[shader->hitMaterial].width))); + } + } +*/ + // exit now if we should + if (TS.traceFlags == G2_RETURNONHIT) + { + TS.hitOne = true; + return true; + } + + break; + } + } + if (i==MAX_G2_COLLISIONS) + { + //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - will probalbly never happen + //It happens. And the assert is bugging me. + TS.hitOne = true; //force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record + } + } + } + return false; +} + +// now we're at poly level, check each model space transformed poly against the model world transfomed ray +static bool G2_RadiusTracePolys( + const mdxmSurface_t *surface, + CTraceSurface &TS + ) +{ + int j; + vec3_t basis1; + vec3_t basis2; + vec3_t taxis; + vec3_t saxis; + + basis2[0]=0.0f; + basis2[1]=0.0f; + basis2[2]=1.0f; + + vec3_t v3RayDir; + VectorSubtract(TS.rayEnd, TS.rayStart, v3RayDir); + + CrossProduct(v3RayDir,basis2,basis1); + + if (DotProduct(basis1,basis1)<.1f) + { + basis2[0]=0.0f; + basis2[1]=1.0f; + basis2[2]=0.0f; + CrossProduct(v3RayDir,basis2,basis1); + } + + CrossProduct(v3RayDir,basis1,basis2); + // Give me a shot direction not a bunch of zeros :) -Gil +// assert(DotProduct(basis1,basis1)>.0001f); +// assert(DotProduct(basis2,basis2)>.0001f); + + VectorNormalize(basis1); + VectorNormalize(basis2); + + const float c=cos(0.0f);//theta + const float s=sin(0.0f);//theta + + VectorScale(basis1, 0.5f * c / TS.m_fRadius,taxis); + VectorMA(taxis, 0.5f * s / TS.m_fRadius,basis2,taxis); + + VectorScale(basis1,-0.5f * s /TS.m_fRadius,saxis); + VectorMA( saxis, 0.5f * c /TS.m_fRadius,basis2,saxis); + + const float * const verts = (float *)TS.TransformedVertsArray[surface->thisSurfaceIndex]; + const int numVerts = surface->numVerts; + + int flags=63; + //rayDir/=lengthSquared(raydir); + const float f = VectorLengthSquared(v3RayDir); + v3RayDir[0]/=f; + v3RayDir[1]/=f; + v3RayDir[2]/=f; + + for ( j = 0; j < numVerts; j++ ) + { + const int pos=j*5; + vec3_t delta; + delta[0]=verts[pos+0]-TS.rayStart[0]; + delta[1]=verts[pos+1]-TS.rayStart[1]; + delta[2]=verts[pos+2]-TS.rayStart[2]; + const float s=DotProduct(delta,saxis)+0.5f; + const float t=DotProduct(delta,taxis)+0.5f; + const float u=DotProduct(delta,v3RayDir); + int vflags=0; + + if (s>0) + { + vflags|=1; + } + if (s<1) + { + vflags|=2; + } + if (t>0) + { + vflags|=4; + } + if (t<1) + { + vflags|=8; + } + if (u>0) + { + vflags|=16; + } + if (u<1) + { + vflags|=32; + } + + vflags=(~vflags); + flags&=vflags; + GoreVerts[j].flags=vflags; + } + + if (flags) + { + return false; // completely off the gore splotch (so presumably hit nothing? -Ste) + } + const int numTris = surface->numTriangles; + const mdxmTriangle_t * const tris = (mdxmTriangle_t *) ((byte *)surface + surface->ofsTriangles); + + for ( j = 0; j < numTris; j++ ) + { + assert(tris[j].indexes[0]>=0&&tris[j].indexes[0]=0&&tris[j].indexes[1]=0&&tris[j].indexes[2]thisSurfaceIndex; + newCol.mModelIndex = TS.modelIndex; +// if (face>0) +// { + newCol.mFlags = G2_FRONTFACE; +// } +// else +// { +// newCol.mFlags = G2_BACKFACE; +// } + + //get normal from triangle + const float *A = &verts[(tris[j].indexes[0] * 5)]; + const float *B = &verts[(tris[j].indexes[1] * 5)]; + const float *C = &verts[(tris[j].indexes[2] * 5)]; + vec3_t normal; + vec3_t edgeAC, edgeBA; + + VectorSubtract(C, A, edgeAC); + VectorSubtract(B, A, edgeBA); + CrossProduct(edgeBA, edgeAC, normal); + + // transform normal (but don't translate) into world angles + TransformPoint(normal, newCol.mCollisionNormal, &worldMatrix); + VectorNormalize(newCol.mCollisionNormal); + + newCol.mMaterial = newCol.mLocation = 0; + // exit now if we should + if (TS.traceFlags == G2_RETURNONHIT) + { + TS.hitOne = true; + return true; + } + + + vec3_t distVect; +#if 0 + //i don't know the hitPoint, but let's just assume it's the first vert for now... + float *hitPoint = (float *)A; +#else + //yeah, I want the collision point. Let's work out the impact point on the triangle. -rww + vec3_t hitPoint; + float side, side2; + float dist; + float third = -(A[0]*(B[1]*C[2] - C[1]*B[2]) + B[0]*(C[1]*A[2] - A[1]*C[2]) + C[0]*(A[1]*B[2] - B[1]*A[2]) ); + + VectorSubtract(TS.rayEnd, TS.rayStart, distVect); + side = normal[0]*TS.rayStart[0] + normal[1]*TS.rayStart[1] + normal[2]*TS.rayStart[2] + third; + side2 = normal[0]*distVect[0] + normal[1]*distVect[1] + normal[2]*distVect[2]; + dist = side/side2; + VectorMA(TS.rayStart, -dist, distVect, hitPoint); +#endif + + VectorSubtract(hitPoint, TS.rayStart, distVect); + newCol.mDistance = VectorLength(distVect); + + // put the hit point back into world space + TransformAndTranslatePoint(hitPoint, newCol.mCollisionPosition, &worldMatrix); + newCol.mBarycentricI = newCol.mBarycentricJ = 0.0f; + break; + } + } + if (i==MAX_G2_COLLISIONS) + { + //assert(i!=MAX_G2_COLLISIONS); // run out of collision record space - happens OFTEN + TS.hitOne = true; //force stop recursion + return true; // return true to avoid wasting further time, but no hit will result without a record + } + } + } + + return false; +} + + +// look at a surface and then do the trace on each poly +static void G2_TraceSurfaces(CTraceSurface &TS) +{ + int i; + // back track and get the surfinfo struct for this surface + assert(TS.currentModel); + assert(TS.currentModel->data.glm && TS.currentModel->data.glm->header); + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface(TS.currentModel, TS.surfaceNum, TS.lod); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)TS.currentModel->data.glm->header + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + + // see if we have an override surface in the surface list + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(TS.surfaceNum, TS.rootSList); + + // don't allow recursion if we've already hit a polygon + if (TS.hitOne) + { + return; + } + + // really, we should use the default flags for this surface unless it's been overriden + int offFlags = surfInfo->flags; + + // set the off flags if we have some + if (surfOverride) + { + offFlags = surfOverride->offFlags; + } + + // if this surface is not off, try to hit it + if (!offFlags) + { +#ifdef _G2_GORE + if (TS.collRecMap) + { +#endif + if (!(fabs(TS.m_fRadius) < 0.1)) // if not a point-trace + { + // .. then use radius check + // + if (G2_RadiusTracePolys(surface, // const mdxmSurface_t *surface, + TS + ) + && (TS.traceFlags == G2_RETURNONHIT) + ) + { + TS.hitOne = true; + return; + } + } + else + { + // go away and trace the polys in this surface + if (G2_TracePolys(surface, surfInfo, TS) + && (TS.traceFlags == G2_RETURNONHIT) + ) + { + // ok, we hit one, *and* we want to return instantly because the returnOnHit is set + // so indicate we've hit one, so other surfaces don't get hit and return + TS.hitOne = true; + return; + } + } +#ifdef _G2_GORE + } + else + { + G2_GorePolys(surface, TS, surfInfo); + } +#endif + } + + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) + { + return; + } + + // now recursively call for the children + for (i=0; i< surfInfo->numChildren && !TS.hitOne; i++) + { + TS.surfaceNum = surfInfo->childIndexes[i]; + G2_TraceSurfaces(TS); + } +} + +#ifdef _G2_GORE +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, float fRadius, float ssize,float tsize,float theta,int shader, SSkinGoreData *gore, qboolean skipIfLODNotMatch) +#else +void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, CollisionRecord_t *collRecMap, int entNum, int eG2TraceType, int useLod, float fRadius) +#endif +{ + int i, lod; + skin_t *skin; + shader_t *cust_shader; + qboolean firstModelOnly = qfalse; + +#ifdef _G2_GORE + if ( cg_g2MarksAllModels == NULL ) + { + cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "Render marks on all G2 models" ); + } + + if (cg_g2MarksAllModels == NULL + || !cg_g2MarksAllModels->integer ) + { + firstModelOnly = qtrue; + } +#endif + + // walk each possible model for this entity and try tracing against it + for (i=0; i 0 && ghoul2[i].mSkin < tr.numSkins ) + { + skin = R_GetSkinByHandle( ghoul2[i].mSkin ); + } + else + { + skin = NULL; + } + + lod = G2_DecideTraceLod(ghoul2[i],useLod); +#ifdef _G2_GORE + if ( skipIfLODNotMatch ) + {//we only want to hit this SPECIFIC LOD... + if ( lod != useLod ) + {//doesn't match, skip this model + continue; + } + } +#endif + //reset the quick surface override lookup + G2_FindOverrideSurface(-1, ghoul2[i].mSlist); + +#ifdef _G2_GORE + CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius, ssize, tsize, theta, shader, &ghoul2[i], gore); +#else + CTraceSurface TS(ghoul2[i].mSurfaceRoot, ghoul2[i].mSlist, (model_t *)ghoul2[i].currentModel, lod, rayStart, rayEnd, collRecMap, entNum, i, skin, cust_shader, ghoul2[i].mTransformedVertsArray, eG2TraceType, fRadius); +#endif + // start the surface recursion loop + G2_TraceSurfaces(TS); + + // if we've hit one surface on one model, don't bother doing the rest + if (TS.hitOne) + { + break; + } +#ifdef _G2_GORE + if (!collRecMap&&firstModelOnly) + { + // we don't really need to do multiple models for gore. + break; + } +#endif + } +} + +void TransformPoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { + for (int i=0;i<3;i++) + { + out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2]; + } +} + +void TransformAndTranslatePoint (const vec3_t in, vec3_t out, mdxaBone_t *mat) { + + for (int i=0;i<3;i++) + { + out[i]= in[0]*mat->matrix[i][0] + in[1]*mat->matrix[i][1] + in[2]*mat->matrix[i][2] + mat->matrix[i][3]; + } +} + + +// create a matrix using a set of angles +void Create_Matrix(const float *angle, mdxaBone_t *matrix) +{ + vec3_t axis[3]; + + // convert angles to axis + AnglesToAxis( angle, axis ); + matrix->matrix[0][0] = axis[0][0]; + matrix->matrix[1][0] = axis[0][1]; + matrix->matrix[2][0] = axis[0][2]; + + matrix->matrix[0][1] = axis[1][0]; + matrix->matrix[1][1] = axis[1][1]; + matrix->matrix[2][1] = axis[1][2]; + + matrix->matrix[0][2] = axis[2][0]; + matrix->matrix[1][2] = axis[2][1]; + matrix->matrix[2][2] = axis[2][2]; + + matrix->matrix[0][3] = 0; + matrix->matrix[1][3] = 0; + matrix->matrix[2][3] = 0; + + +} + +// given a matrix, generate the inverse of that matrix +void Inverse_Matrix(mdxaBone_t *src, mdxaBone_t *dest) +{ + int i, j; + + for (i = 0; i < 3; i++) + { + for (j = 0; j < 3; j++) + { + dest->matrix[i][j]=src->matrix[j][i]; + } + } + for (i = 0; i < 3; i++) + { + dest->matrix[i][3]=0; + for (j = 0; j < 3; j++) + { + dest->matrix[i][3]-=dest->matrix[i][j]*src->matrix[j][3]; + } + } +} + +// generate the world matrix for a given set of angles and origin - called from lots of places +void G2_GenerateWorldMatrix(const vec3_t angles, const vec3_t origin) +{ + Create_Matrix(angles, &worldMatrix); + worldMatrix.matrix[0][3] = origin[0]; + worldMatrix.matrix[1][3] = origin[1]; + worldMatrix.matrix[2][3] = origin[2]; + + Inverse_Matrix(&worldMatrix, &worldMatrixInv); +} + +// go away and determine what the pointer for a specific surface definition within the model definition is +void *G2_FindSurface(void *mod_t, int index, int lod) +{ + // damn include file dependancies + model_t *mod = (model_t *)mod_t; + mdxmHeader_t *mdxm = mod->data.glm->header; + + // point at first lod list + byte *current = (byte*)((size_t)mdxm + (size_t)mdxm->ofsLODs); + int i; + + //walk the lods + for (i=0; iofsEnd; + } + + // avoid the lod pointer data structure + current += sizeof(mdxmLOD_t); + + mdxmLODSurfOffset_t *indexes = (mdxmLODSurfOffset_t *)current; + // we are now looking at the offset array + current += indexes->offsets[index]; + + return (void *)current; +} + +#define SURFACE_SAVE_BLOCK_SIZE sizeof(surfaceInfo_t) +#define BOLT_SAVE_BLOCK_SIZE (sizeof(boltInfo_t) - sizeof(mdxaBone_t)) +#define BONE_SAVE_BLOCK_SIZE sizeof(boneInfo_t) + +qboolean G2_SaveGhoul2Models(CGhoul2Info_v &ghoul2, char **buffer, int *size) +{ + + // is there anything to save? + if (!ghoul2.size()) + { + *buffer = (char *)Z_Malloc(4, TAG_GHOUL2, qtrue); + int *tempBuffer = (int *)*buffer; + *tempBuffer = 0; + *size = 4; + return qtrue; + } + + // yeah, lets get busy + *size = 0; + + // this one isn't a define since I couldn't work out how to figure it out at compile time + int ghoul2BlockSize = (size_t)&ghoul2[0].mTransformedVertsArray - (size_t)&ghoul2[0].mModelindex; + + // add in count for number of ghoul2 models + *size += 4; + // start out working out the total size of the buffer we need to allocate + int i; // Linux GCC is forcing new scoping rules + for (i=0; i i) && + (nextGhoul2[i].mModelindex != -1) && + (nextGhoul2[i].mBlist.size() > x) && + (nextGhoul2[i].mBlist[x].boneNumber != -1)) + { + boneInfo_t &nextBone = nextGhoul2[i].mBlist[x]; + // does this bone override actually have anything in it, and if it does, is it a bone angles override? + if ((bone.boneNumber != -1) && ((bone.flags) & (BONE_ANGLES_TOTAL))) + { + float *nowMatrix = (float*) &bone.matrix; + float *nextMatrix = (float*) &nextBone.matrix; + float *newMatrix = (float*) &bone.newMatrix; + // now interpolate the matrix + for (int z=0; z < 12; z++) + { + newMatrix[z] = nowMatrix[z] + interpolation * ( nextMatrix[z] - nowMatrix[z] ); + } + } + } + else + { + memcpy(&ghoul2[i].mBlist[x].newMatrix, &ghoul2[i].mBlist[x].matrix, sizeof(mdxaBone_t)); + } + } + } + } +} diff --git a/codemp/rd-rend2/G2_surfaces.cpp b/codemp/rd-rend2/G2_surfaces.cpp new file mode 100644 index 0000000000..9fe81bf606 --- /dev/null +++ b/codemp/rd-rend2/G2_surfaces.cpp @@ -0,0 +1,668 @@ +#include "rd-common/tr_types.h" +#include "ghoul2/G2.h" +#include "ghoul2/g2_local.h" +#include "tr_local.h" +#ifdef _MSC_VER +#pragma warning(disable : 4512) //assignment op could not be genereated +#endif + +class CConstructBoneList +{ +public: + int surfaceNum; + int *boneUsedList; + surfaceInfo_v &rootSList; + model_t *currentModel; + boneInfo_v &boneList; + + CConstructBoneList( + int initsurfaceNum, + int *initboneUsedList, + surfaceInfo_v &initrootSList, + model_t *initcurrentModel, + boneInfo_v &initboneList): + + surfaceNum(initsurfaceNum), + boneUsedList(initboneUsedList), + rootSList(initrootSList), + currentModel(initcurrentModel), + boneList(initboneList) { } +}; + +extern void G2_ConstructUsedBoneList(CConstructBoneList &CBL); + + +//===================================================================================================================== +// Surface List handling routines - so entities can determine what surfaces attached to a model are operational or not. + +// find a particular surface in the surface override list +surfaceInfo_t *G2_FindOverrideSurface(int surfaceNum, surfaceInfo_v &surfaceList) +{ + // look through entire list + for(size_t i=0; idata.glm->header; + surf = (mdxmSurfHierarchy_t *) ( (byte *)mdxm + mdxm->ofsSurfHierarchy ); + + for ( int i = 0 ; i < mdxm->numSurfaces ; i++) + { + if (!Q_stricmp(surfaceName, surf->name)) + { + *flags = surf->flags; + return i; + } + // find the next surface + surf = (mdxmSurfHierarchy_t *)( (byte *)surf + (size_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surf->numChildren ] )); + } + return -1; +} + + +/************************************************************************************************ + * G2_FindSurface + * find a surface in a ghoul2 surface override list based on it's name + * + * Input + * filename of model, surface list of model instance, name of surface, int to be filled in + * with the index of this surface (defaults to NULL) + * + * Output + * pointer to surface if successful, false otherwise + * + ************************************************************************************************/ +mdxmSurface_t *G2_FindSurface(CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, + int *surfIndex/*NULL*/) +{ + int i = 0; + // find the model we want + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo; + + // did we find a ghoul 2 model or not? + if (!mod->data.glm || !mod->data.glm->header) + { + assert(0); + if (surfIndex) + { + *surfIndex = -1; + } + return 0; + } + + // first find if we already have this surface in the list + for (i = slist.size() - 1; i >= 0; i--) + { + if ((slist[i].surface != 10000) && (slist[i].surface != -1)) + { + mdxmSurface_t *surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, slist[i].surface, 0); + // back track and get the surfinfo struct for this surface + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); + + // are these the droids we're looking for? + if (!Q_stricmp (surfInfo->name, surfaceName)) + { + // yup + if (surfIndex) + { + *surfIndex = i; + } + return surf; + } + } + } + // didn't find it + if (surfIndex) + { + *surfIndex = -1; + } + return 0; +} + +// set a named surface offFlags - if it doesn't find a surface with this name in the list then it will add one. +qboolean G2_SetSurfaceOnOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName, const int offFlags) +{ + int surfIndex = -1; + surfaceInfo_t temp_slist_entry; + mdxmSurface_t *surf; + // find the model we want + model_t *mod = (model_t *)ghlInfo->currentModel; + + // did we find a ghoul 2 model or not? + if (!mod->data.glm || !mod->data.glm->header) + { + assert(0); + return qfalse; + } + + // first find if we already have this surface in the list + surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); + if (surf) + { + // set descendants value + + // slist[surfIndex].offFlags = offFlags; + // seems to me that we shouldn't overwrite the other flags. + // the only bit we really care about in the incoming flags is the off bit + slist[surfIndex].offFlags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); + slist[surfIndex].offFlags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); + return qtrue; + } + else + { + // ok, not in the list already - in that case, lets verify this surface exists in the model mesh + int flags; + int surfaceNum = G2_IsSurfaceLegal((void*)mod, surfaceName, &flags); + if (surfaceNum != -1) + { + int newflags = flags; + // the only bit we really care about in the incoming flags is the off bit + newflags &= ~(G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); + newflags |= offFlags & (G2SURFACEFLAG_OFF | G2SURFACEFLAG_NODESCENDANTS); + + if (newflags != flags) + { // insert here then because it changed, no need to add an override otherwise + temp_slist_entry.offFlags = newflags; + temp_slist_entry.surface = surfaceNum; + + slist.push_back(temp_slist_entry); + } + return qtrue; + } + } + return qfalse; +} + +void G2_SetSurfaceOnOffFromSkin (CGhoul2Info *ghlInfo, qhandle_t renderSkin) +{ + int j; + const skin_t *skin = R_GetSkinByHandle( renderSkin ); + + ghlInfo->mSlist.clear(); //remove any overrides we had before. + ghlInfo->mMeshFrameNum = 0; + + for ( j = 0 ; j < skin->numSurfaces ; j++ ) + { + // the names have both been lowercased + //Raz: why is this using the shader name and not the surface name? + if ( !strcmp( ((shader_t *)skin->surfaces[j]->shader)->name, "*off") ) { + G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, skin->surfaces[j]->name, G2SURFACEFLAG_OFF); + } + else + { + int flags; + int surfaceNum = G2_IsSurfaceLegal((void *)ghlInfo->currentModel, skin->surfaces[j]->name, &flags); + if ( (surfaceNum != -1) && (!(flags&G2SURFACEFLAG_OFF)) ) //only turn on if it's not an "_off" surface + { + G2_SetSurfaceOnOff(ghlInfo, ghlInfo->mSlist, skin->surfaces[j]->name, 0); + } + } + } +} + +// return a named surfaces off flags - should tell you if this surface is on or off. +int G2_IsSurfaceOff (CGhoul2Info *ghlInfo, surfaceInfo_v &slist, const char *surfaceName) +{ + model_t *mod = (model_t *)ghlInfo->currentModel; + int surfIndex = -1; + mdxmSurface_t *surf = 0; + mdxmHeader_t *mdxm = mod->data.glm->header; + + // did we find a ghoul 2 model or not? + if (!mdxm) + { + return 0; + } + + // first find if we already have this surface in the list + surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); + if (surf) + { + // set descendants value + return slist[surfIndex].offFlags; + } + // ok, we didn't find it in the surface list. Lets look at the original surface then. + + mdxmSurfHierarchy_t *surface = (mdxmSurfHierarchy_t *) ( (byte *)mdxm + mdxm->ofsSurfHierarchy ); + + for ( int i = 0 ; i < mdxm->numSurfaces ; i++) + { + if (!Q_stricmp(surfaceName, surface->name)) + { + return surface->flags; + } + // find the next surface + surface = (mdxmSurfHierarchy_t *)( (byte *)surface + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surface->numChildren ] )); + } + + assert(0); + return 0; +} + +void G2_FindRecursiveSurface(model_t *currentModel, int surfaceNum, surfaceInfo_v &rootList, int *activeSurfaces) +{ + int i; + mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)currentModel, surfaceNum, 0); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + + // see if we have an override surface in the surface list + surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootList); + + // really, we should use the default flags for this surface unless it's been overriden + int offFlags = surfInfo->flags; + + // set the off flags if we have some + if (surfOverride) + { + offFlags = surfOverride->offFlags; + } + + // if this surface is not off, indicate as such in the active surface list + if (!(offFlags & G2SURFACEFLAG_OFF)) + { + activeSurfaces[surfaceNum] = 1; + } + else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) + { + return; + } + + // now recursively call for the children + for (i=0; i< surfInfo->numChildren; i++) + { + surfaceNum = surfInfo->childIndexes[i]; + G2_FindRecursiveSurface(currentModel, surfaceNum, rootList, activeSurfaces); + } + +} + +void G2_RemoveRedundantGeneratedSurfaces(surfaceInfo_v &slist, int *activeSurfaces) +{ + // walk the surface list, removing surface overrides or generated surfaces that are pointing at surfaces that aren't active anymore + for (size_t i=0; idata.glm->header; + mdxaHeader_t *mdxa = mod_a->data.gla; + + // did we find a ghoul 2 model or not? + if (!mdxm) + { + return qfalse; + } + + // first find if we already have this surface in the list + surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); + if (surf != -1) + { + // first see if this ghoul2 model already has this as a root surface + if (ghoul2[modelIndex].mSurfaceRoot == surf) + { + return qtrue; + } + + // set the root surface + ghoul2[modelIndex].mSurfaceRoot = surf; + + // ok, now the tricky bits. + // firstly, generate a list of active / on surfaces below the root point + + // gimme some space to put this list into + activeSurfaces = (int *)Z_Malloc(mdxm->numSurfaces * 4, TAG_GHOUL2, qtrue); + memset(activeSurfaces, 0, (mdxm->numSurfaces * 4)); + activeBones = (int *)Z_Malloc(mdxa->numBones * 4, TAG_GHOUL2, qtrue); + memset(activeBones, 0, (mdxa->numBones * 4)); + + G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); + + // now generate the used bone list + CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, + activeBones, + ghoul2[modelIndex].mSlist, + mod_m, + ghoul2[modelIndex].mBlist); + + G2_ConstructUsedBoneList(CBL); + + // now remove all procedural or override surfaces that refer to surfaces that arent on this list + G2_RemoveRedundantGeneratedSurfaces(ghoul2[modelIndex].mSlist, activeSurfaces); + + // now remove all bones that are pointing at bones that aren't active + G2_RemoveRedundantBoneOverrides(ghoul2[modelIndex].mBlist, activeBones); + + // then remove all bolts that point at surfaces or bones that *arent* active. + G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); + + // then remove all models on this ghoul2 instance that use those bolts that are being removed. + for (int i=0; i> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model + if (((int)ghoul2[boltMod].mBltlist.size() <= boltNum) || + ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && + (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) + { + CGhoul2Info_v *g2i = &ghoul2; + G2API_RemoveGhoul2Model((CGhoul2Info_v **)&g2i, i); + } + } + } + //No support for this, for now. + + // remember to free what we used + Z_Free(activeSurfaces); + Z_Free(activeBones); + + return (qtrue); + } +/* +//g2r if (entstate->ghoul2) + { + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)entstate->ghoul2); + model_t *mod_m = R_GetModelByHandle(RE_RegisterModel(ghoul2[modelIndex].mFileName)); + model_t *mod_a = R_GetModelByHandle(mod_m->mdxm->animIndex); + int surf; + int flags; + int *activeSurfaces, *activeBones; + + // did we find a ghoul 2 model or not? + if (!mod_m->mdxm) + { + return qfalse; + } + + // first find if we already have this surface in the list + surf = G2_IsSurfaceLegal(mod_m, surfaceName, &flags); + if (surf != -1) + { + // first see if this ghoul2 model already has this as a root surface + if (ghoul2[modelIndex].mSurfaceRoot == surf) + { + return qtrue; + } + + // set the root surface + ghoul2[modelIndex].mSurfaceRoot = surf; + + // ok, now the tricky bits. + // firstly, generate a list of active / on surfaces below the root point + + // gimme some space to put this list into + activeSurfaces = (int *)Z_Malloc(mod_m->mdxm->numSurfaces * 4, TAG_GHOUL2, qtrue); + memset(activeSurfaces, 0, (mod_m->mdxm->numSurfaces * 4)); + activeBones = (int *)Z_Malloc(mod_a->mdxa->numBones * 4, TAG_GHOUL2, qtrue); + memset(activeBones, 0, (mod_a->mdxa->numBones * 4)); + + G2_FindRecursiveSurface(mod_m, surf, ghoul2[modelIndex].mSlist, activeSurfaces); + + // now generate the used bone list + CConstructBoneList CBL(ghoul2[modelIndex].mSurfaceRoot, + activeBones, + ghoul2[modelIndex].mSlist, + mod_m, + ghoul2[modelIndex].mBlist); + + G2_ConstructUsedBoneList(CBL); + + // now remove all procedural or override surfaces that refer to surfaces that arent on this list + G2_RemoveRedundantGeneratedSurfaces(ghoul2[modelIndex].mSlist, activeSurfaces); + + // now remove all bones that are pointing at bones that aren't active + G2_RemoveRedundantBoneOverrides(ghoul2[modelIndex].mBlist, activeBones); + + // then remove all bolts that point at surfaces or bones that *arent* active. + G2_RemoveRedundantBolts(ghoul2[modelIndex].mBltlist, ghoul2[modelIndex].mSlist, activeSurfaces, activeBones); + + // then remove all models on this ghoul2 instance that use those bolts that are being removed. + for (int i=0; i> MODEL_SHIFT) & MODEL_AND; + int boltNum = (ghoul2[i].mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + // if either the bolt list is too small, or the bolt we are pointing at references nothing, remove this model + if ((ghoul2[boltMod].mBltlist.size() <= boltNum) || + ((ghoul2[boltMod].mBltlist[boltNum].boneNumber == -1) && + (ghoul2[boltMod].mBltlist[boltNum].surfaceNumber == -1))) + { + G2API_RemoveGhoul2Model(entstate, i); + } + } + } + + // remember to free what we used + Z_Free(activeSurfaces); + Z_Free(activeBones); + + return (qtrue); + } + } + assert(0);*/ + return qfalse; +} + + +extern int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod); +int G2_AddSurface(CGhoul2Info *ghoul2, int surfaceNumber, int polyNumber, float BarycentricI, float BarycentricJ, int lod ) +{ + + surfaceInfo_t temp_slist_entry; + + // decide if LOD is legal + lod = G2_DecideTraceLod(*(CGhoul2Info *)(ghoul2), lod); + + // first up, see if we have a free one already set up - look only from the end of the constant surfaces onwards + for (size_t i=0; imSlist.size(); i++) + { + // is the surface count -1? That would indicate it's free + if (ghoul2->mSlist[i].surface == -1) + { + ghoul2->mSlist[i].offFlags = G2SURFACEFLAG_GENERATED; + ghoul2->mSlist[i].surface = 10000; // no model will ever have 10000 surfaces + ghoul2->mSlist[i].genBarycentricI = BarycentricI; + ghoul2->mSlist[i].genBarycentricJ = BarycentricJ; + ghoul2->mSlist[i].genPolySurfaceIndex = ((polyNumber & 0xffff) << 16) | (surfaceNumber & 0xffff); + ghoul2->mSlist[i].genLod = lod; + return i; + } + } + + // ok, didn't find one. Better create one + + temp_slist_entry.offFlags = G2SURFACEFLAG_GENERATED; + temp_slist_entry.surface = 10000; + temp_slist_entry.genBarycentricI = BarycentricI; + temp_slist_entry.genBarycentricJ = BarycentricJ; + temp_slist_entry.genPolySurfaceIndex = ((polyNumber & 0xffff) << 16) | (surfaceNumber & 0xffff); + temp_slist_entry.genLod = lod; + + ghoul2->mSlist.push_back(temp_slist_entry); + + return (ghoul2->mSlist.size() -1 ); +} + +qboolean G2_RemoveSurface(surfaceInfo_v &slist, const int index) +{ + // did we find it? + if (index != -1) + { + // set us to be the 'not active' state + slist[index].surface = -1; + + unsigned int newSize = slist.size(); + // now look through the list from the back and see if there is a block of -1's we can resize off the end of the list + for (int i=slist.size()-1; i>-1; i--) + { + if (slist[i].surface == -1) + { + newSize = i; + } + // once we hit one that isn't a -1, we are done. + else + { + break; + } + } + // do we need to resize? + if (newSize != slist.size()) + { + // yes, so lets do it + slist.resize(newSize); + } + + return qtrue; + } + + assert(0); + + // no + return qfalse; +} + + +int G2_GetParentSurface(CGhoul2Info *ghlInfo, const int index) +{ + model_t *mod = (model_t *)ghlInfo->currentModel; + mdxmSurface_t *surf = 0; + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mod->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = 0; + + // walk each surface and see if this index is listed in it's children + surf = (mdxmSurface_t *)G2_FindSurface((void *)mod, index, 0); + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surf->thisSurfaceIndex]); + + return surfInfo->parentIndex; + +} + +int G2_GetSurfaceIndex(CGhoul2Info *ghlInfo, const char *surfaceName) +{ + model_t *mod = (model_t *)ghlInfo->currentModel; + int flags; + + return G2_IsSurfaceLegal(mod, surfaceName, &flags); +} + +int G2_IsSurfaceRendered(CGhoul2Info *ghlInfo, const char *surfaceName, surfaceInfo_v &slist) +{ + int flags = 0;//, surfFlags = 0; + int surfIndex = 0; + assert(ghlInfo->currentModel); + assert(ghlInfo->currentModel->data.glm && ghlInfo->currentModel->data.glm->header); + if (!ghlInfo->currentModel->data.glm || !ghlInfo->currentModel->data.glm->header) + { + return -1; + } + + // now travel up the skeleton to see if any of it's ancestors have a 'no descendants' turned on + + // find the original surface in the surface list + int surfNum = G2_IsSurfaceLegal((model_t *)ghlInfo->currentModel, surfaceName, &flags); + if ( surfNum != -1 ) + {//must be legal + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)ghlInfo->currentModel->data.glm->header + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); + surfNum = surfInfo->parentIndex; + // walk the surface hierarchy up until we hit the root + while (surfNum != -1) + { + const mdxmSurface_t *parentSurf; + int parentFlags; + const mdxmSurfHierarchy_t *parentSurfInfo; + + parentSurfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surfNum]); + + // find the original surface in the surface list + //G2 was bug, above comment was accurate, but we don't want the original flags, we want the parent flags + G2_IsSurfaceLegal((model_t *)ghlInfo->currentModel, parentSurfInfo->name, &parentFlags); + + // now see if we already have overriden this surface in the slist + parentSurf = G2_FindSurface(ghlInfo, slist, parentSurfInfo->name, &surfIndex); + if (parentSurf) + { + // set descendants value + parentFlags = slist[surfIndex].offFlags; + } + // now we have the parent flags, lets see if any have the 'no descendants' flag set + if (parentFlags & G2SURFACEFLAG_NODESCENDANTS) + { + flags |= G2SURFACEFLAG_OFF; + break; + } + // set up scan of next parent + surfNum = parentSurfInfo->parentIndex; + } + } + else + { + return -1; + } + if ( flags == 0 ) + {//it's not being overridden by a parent + // now see if we already have overriden this surface in the slist + const mdxmSurface_t *surf = G2_FindSurface(ghlInfo, slist, surfaceName, &surfIndex); + if (surf) + { + // set descendants value + flags = slist[surfIndex].offFlags; + } + // ok, at this point in flags we have what this surface is set to, and the index of the surface itself + } + return flags; +} diff --git a/codemp/rd-rend2/MikkTSpace/README.md b/codemp/rd-rend2/MikkTSpace/README.md new file mode 100644 index 0000000000..9fda1559e4 --- /dev/null +++ b/codemp/rd-rend2/MikkTSpace/README.md @@ -0,0 +1,4 @@ +# MikkTSpace +A common standard for tangent space used in baking tools to produce normal maps. + +More information can be found at http://www.mikktspace.com/. diff --git a/codemp/rd-rend2/MikkTSpace/mikktspace.c b/codemp/rd-rend2/MikkTSpace/mikktspace.c new file mode 100644 index 0000000000..0342ae0146 --- /dev/null +++ b/codemp/rd-rend2/MikkTSpace/mikktspace.c @@ -0,0 +1,1899 @@ +/** \file mikktspace/mikktspace.c + * \ingroup mikktspace + */ +/** + * Copyright (C) 2011 by Morten S. Mikkelsen + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + */ + +#include +#include +#include +#include +#include +#include + +#include "mikktspace.h" + +#define TFALSE 0 +#define TTRUE 1 + +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795 +#endif + +#define INTERNAL_RND_SORT_SEED 39871946 + +// internal structure +typedef struct { + float x, y, z; +} SVec3; + +static tbool veq( const SVec3 v1, const SVec3 v2 ) +{ + return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z); +} + +static SVec3 vadd( const SVec3 v1, const SVec3 v2 ) +{ + SVec3 vRes; + + vRes.x = v1.x + v2.x; + vRes.y = v1.y + v2.y; + vRes.z = v1.z + v2.z; + + return vRes; +} + + +static SVec3 vsub( const SVec3 v1, const SVec3 v2 ) +{ + SVec3 vRes; + + vRes.x = v1.x - v2.x; + vRes.y = v1.y - v2.y; + vRes.z = v1.z - v2.z; + + return vRes; +} + +static SVec3 vscale(const float fS, const SVec3 v) +{ + SVec3 vRes; + + vRes.x = fS * v.x; + vRes.y = fS * v.y; + vRes.z = fS * v.z; + + return vRes; +} + +static float LengthSquared( const SVec3 v ) +{ + return v.x*v.x + v.y*v.y + v.z*v.z; +} + +static float Length( const SVec3 v ) +{ + return sqrtf(LengthSquared(v)); +} + +static SVec3 Normalize( const SVec3 v ) +{ + return vscale(1 / Length(v), v); +} + +static float vdot( const SVec3 v1, const SVec3 v2) +{ + return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z; +} + + +static tbool NotZero(const float fX) +{ + // could possibly use FLT_EPSILON instead + return fabsf(fX) > FLT_MIN; +} + +static tbool VNotZero(const SVec3 v) +{ + // might change this to an epsilon based test + return NotZero(v.x) || NotZero(v.y) || NotZero(v.z); +} + + + +typedef struct { + int iNrFaces; + int * pTriMembers; +} SSubGroup; + +typedef struct { + int iNrFaces; + int * pFaceIndices; + int iVertexRepresentitive; + tbool bOrientPreservering; +} SGroup; + +// +#define MARK_DEGENERATE 1 +#define QUAD_ONE_DEGEN_TRI 2 +#define GROUP_WITH_ANY 4 +#define ORIENT_PRESERVING 8 + + + +typedef struct { + int FaceNeighbors[3]; + SGroup * AssignedGroup[3]; + + // normalized first order face derivatives + SVec3 vOs, vOt; + float fMagS, fMagT; // original magnitudes + + // determines if the current and the next triangle are a quad. + int iOrgFaceNumber; + int iFlag, iTSpacesOffs; + unsigned char vert_num[4]; +} STriInfo; + +typedef struct { + SVec3 vOs; + float fMagS; + SVec3 vOt; + float fMagT; + int iCounter; // this is to average back into quads. + tbool bOrient; +} STSpace; + +static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); +static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); +static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); +static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn); +static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], + const int iNrActiveGroups, const int piTriListIn[], const float fThresCos, + const SMikkTSpaceContext * pContext); + +static int MakeIndex(const int iFace, const int iVert) +{ + assert(iVert>=0 && iVert<4 && iFace>=0); + return (iFace<<2) | (iVert&0x3); +} + +static void IndexToData(int * piFace, int * piVert, const int iIndexIn) +{ + piVert[0] = iIndexIn&0x3; + piFace[0] = iIndexIn>>2; +} + +static STSpace AvgTSpace(const STSpace * pTS0, const STSpace * pTS1) +{ + STSpace ts_res; + + // this if is important. Due to floating point precision + // averaging when ts0==ts1 will cause a slight difference + // which results in tangent space splits later on + if (pTS0->fMagS==pTS1->fMagS && pTS0->fMagT==pTS1->fMagT && + veq(pTS0->vOs,pTS1->vOs) && veq(pTS0->vOt, pTS1->vOt)) + { + ts_res.fMagS = pTS0->fMagS; + ts_res.fMagT = pTS0->fMagT; + ts_res.vOs = pTS0->vOs; + ts_res.vOt = pTS0->vOt; + } + else + { + ts_res.fMagS = 0.5f*(pTS0->fMagS+pTS1->fMagS); + ts_res.fMagT = 0.5f*(pTS0->fMagT+pTS1->fMagT); + ts_res.vOs = vadd(pTS0->vOs,pTS1->vOs); + ts_res.vOt = vadd(pTS0->vOt,pTS1->vOt); + if ( VNotZero(ts_res.vOs) ) ts_res.vOs = Normalize(ts_res.vOs); + if ( VNotZero(ts_res.vOt) ) ts_res.vOt = Normalize(ts_res.vOt); + } + + return ts_res; +} + + + +static SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index); +static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index); +static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index); + + +// degen triangles +static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris); +static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris); + + +tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext) +{ + return genTangSpace(pContext, 180.0f); +} + +tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold) +{ + // count nr_triangles + int * piTriListIn = NULL, * piGroupTrianglesBuffer = NULL; + STriInfo * pTriInfos = NULL; + SGroup * pGroups = NULL; + STSpace * psTspace = NULL; + int iNrTrianglesIn = 0, f=0, t=0, i=0; + int iNrTSPaces = 0, iTotTris = 0, iDegenTriangles = 0, iNrMaxGroups = 0; + int iNrActiveGroups = 0, index = 0; + const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext); + tbool bRes = TFALSE; + const float fThresCos = (float) cos((fAngularThreshold*(float)M_PI)/180.0f); + + // verify all call-backs have been set + if ( pContext->m_pInterface->m_getNumFaces==NULL || + pContext->m_pInterface->m_getNumVerticesOfFace==NULL || + pContext->m_pInterface->m_getPosition==NULL || + pContext->m_pInterface->m_getNormal==NULL || + pContext->m_pInterface->m_getTexCoord==NULL ) + return TFALSE; + + // count triangles on supported faces + for (f=0; fm_pInterface->m_getNumVerticesOfFace(pContext, f); + if (verts==3) ++iNrTrianglesIn; + else if (verts==4) iNrTrianglesIn += 2; + } + if (iNrTrianglesIn<=0) return TFALSE; + + // allocate memory for an index list + piTriListIn = (int *) malloc(sizeof(int)*3*iNrTrianglesIn); + pTriInfos = (STriInfo *) malloc(sizeof(STriInfo)*iNrTrianglesIn); + if (piTriListIn==NULL || pTriInfos==NULL) + { + if (piTriListIn!=NULL) free(piTriListIn); + if (pTriInfos!=NULL) free(pTriInfos); + return TFALSE; + } + + // make an initial triangle --> face index list + iNrTSPaces = GenerateInitialVerticesIndexList(pTriInfos, piTriListIn, pContext, iNrTrianglesIn); + + // make a welded index list of identical positions and attributes (pos, norm, texc) + //printf("gen welded index list begin\n"); + GenerateSharedVerticesIndexList(piTriListIn, pContext, iNrTrianglesIn); + //printf("gen welded index list end\n"); + + // Mark all degenerate triangles + iTotTris = iNrTrianglesIn; + iDegenTriangles = 0; + for (t=0; tm_pInterface->m_getNumVerticesOfFace(pContext, f); + if (verts!=3 && verts!=4) continue; + + + // I've decided to let degenerate triangles and group-with-anythings + // vary between left/right hand coordinate systems at the vertices. + // All healthy triangles on the other hand are built to always be either or. + + /*// force the coordinate system orientation to be uniform for every face. + // (this is already the case for good triangles but not for + // degenerate ones and those with bGroupWithAnything==true) + bool bOrient = psTspace[index].bOrient; + if (psTspace[index].iCounter == 0) // tspace was not derived from a group + { + // look for a space created in GenerateTSpaces() by iCounter>0 + bool bNotFound = true; + int i=1; + while (i 0) bNotFound=false; + else ++i; + } + if (!bNotFound) bOrient = psTspace[index+i].bOrient; + }*/ + + // set data + for (i=0; ivOs.x, pTSpace->vOs.y, pTSpace->vOs.z}; + float bitang[] = {pTSpace->vOt.x, pTSpace->vOt.y, pTSpace->vOt.z}; + if (pContext->m_pInterface->m_setTSpace!=NULL) + pContext->m_pInterface->m_setTSpace(pContext, tang, bitang, pTSpace->fMagS, pTSpace->fMagT, pTSpace->bOrient, f, i); + if (pContext->m_pInterface->m_setTSpaceBasic!=NULL) + pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient==TTRUE ? 1.0f : (-1.0f), f, i); + + ++index; + } + } + + free(psTspace); + + + return TTRUE; +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef struct { + float vert[3]; + int index; +} STmpVert; + +static const int g_iCells = 2048; + +#ifdef _MSC_VER +# define NOINLINE __declspec(noinline) +#else +# define NOINLINE __attribute__ ((noinline)) +#endif + +// it is IMPORTANT that this function is called to evaluate the hash since +// inlining could potentially reorder instructions and generate different +// results for the same effective input value fVal. +static NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal) +{ + const float fIndex = g_iCells * ((fVal-fMin)/(fMax-fMin)); + const int iIndex = (int)fIndex; + return iIndex < g_iCells ? (iIndex >= 0 ? iIndex : 0) : (g_iCells - 1); +} + +static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in); +static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries); +static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn); + +static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn) +{ + + // Generate bounding box + int * piHashTable=NULL, * piHashCount=NULL, * piHashOffsets=NULL, * piHashCount2=NULL; + STmpVert * pTmpVert = NULL; + int i=0, iChannel=0, k=0, e=0; + int iMaxCount=0; + SVec3 vMin = GetPosition(pContext, 0), vMax = vMin, vDim; + float fMin, fMax; + for (i=1; i<(iNrTrianglesIn*3); i++) + { + const int index = piTriList_in_and_out[i]; + + const SVec3 vP = GetPosition(pContext, index); + if (vMin.x > vP.x) vMin.x = vP.x; + else if (vMax.x < vP.x) vMax.x = vP.x; + if (vMin.y > vP.y) vMin.y = vP.y; + else if (vMax.y < vP.y) vMax.y = vP.y; + if (vMin.z > vP.z) vMin.z = vP.z; + else if (vMax.z < vP.z) vMax.z = vP.z; + } + + vDim = vsub(vMax,vMin); + iChannel = 0; + fMin = vMin.x; fMax=vMax.x; + if (vDim.y>vDim.x && vDim.y>vDim.z) + { + iChannel=1; + fMin = vMin.y; + fMax = vMax.y; + } + else if (vDim.z>vDim.x) + { + iChannel=2; + fMin = vMin.z; + fMax = vMax.z; + } + + // make allocations + piHashTable = (int *) malloc(sizeof(int)*iNrTrianglesIn*3); + piHashCount = (int *) malloc(sizeof(int)*g_iCells); + piHashOffsets = (int *) malloc(sizeof(int)*g_iCells); + piHashCount2 = (int *) malloc(sizeof(int)*g_iCells); + + if (piHashTable==NULL || piHashCount==NULL || piHashOffsets==NULL || piHashCount2==NULL) + { + if (piHashTable!=NULL) free(piHashTable); + if (piHashCount!=NULL) free(piHashCount); + if (piHashOffsets!=NULL) free(piHashOffsets); + if (piHashCount2!=NULL) free(piHashCount2); + GenerateSharedVerticesIndexListSlow(piTriList_in_and_out, pContext, iNrTrianglesIn); + return; + } + memset(piHashCount, 0, sizeof(int)*g_iCells); + memset(piHashCount2, 0, sizeof(int)*g_iCells); + + // count amount of elements in each cell unit + for (i=0; i<(iNrTrianglesIn*3); i++) + { + const int index = piTriList_in_and_out[i]; + const SVec3 vP = GetPosition(pContext, index); + const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z); + const int iCell = FindGridCell(fMin, fMax, fVal); + ++piHashCount[iCell]; + } + + // evaluate start index of each cell. + piHashOffsets[0]=0; + for (k=1; kpTmpVert[l].vert[c]) fvMin[c]=pTmpVert[l].vert[c]; + if (fvMax[c]dx && dy>dz) channel=1; + else if (dz>dx) channel=2; + + fSep = 0.5f*(fvMax[channel]+fvMin[channel]); + + // stop if all vertices are NaNs + if (!isfinite(fSep)) + return; + + // terminate recursion when the separation/average value + // is no longer strictly between fMin and fMax values. + if (fSep>=fvMax[channel] || fSep<=fvMin[channel]) + { + // complete the weld + for (l=iL_in; l<=iR_in; l++) + { + int i = pTmpVert[l].index; + const int index = piTriList_in_and_out[i]; + const SVec3 vP = GetPosition(pContext, index); + const SVec3 vN = GetNormal(pContext, index); + const SVec3 vT = GetTexCoord(pContext, index); + + tbool bNotFound = TTRUE; + int l2=iL_in, i2rec=-1; + while (l20); // at least 2 entries + + // separate (by fSep) all points between iL_in and iR_in in pTmpVert[] + while (iL < iR) + { + tbool bReadyLeftSwap = TFALSE, bReadyRightSwap = TFALSE; + while ((!bReadyLeftSwap) && iL=iL_in && iL<=iR_in); + bReadyLeftSwap = !(pTmpVert[iL].vert[channel]=iL_in && iR<=iR_in); + bReadyRightSwap = pTmpVert[iR].vert[channel]m_pInterface->m_getNumFaces(pContext); f++) + { + const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f); + if (verts!=3 && verts!=4) continue; + + pTriInfos[iDstTriIndex].iOrgFaceNumber = f; + pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs; + + if (verts==3) + { + unsigned char * pVerts = pTriInfos[iDstTriIndex].vert_num; + pVerts[0]=0; pVerts[1]=1; pVerts[2]=2; + piTriList_out[iDstTriIndex*3+0] = MakeIndex(f, 0); + piTriList_out[iDstTriIndex*3+1] = MakeIndex(f, 1); + piTriList_out[iDstTriIndex*3+2] = MakeIndex(f, 2); + ++iDstTriIndex; // next + } + else + { + { + pTriInfos[iDstTriIndex+1].iOrgFaceNumber = f; + pTriInfos[iDstTriIndex+1].iTSpacesOffs = iTSpacesOffs; + } + + { + // need an order independent way to evaluate + // tspace on quads. This is done by splitting + // along the shortest diagonal. + const int i0 = MakeIndex(f, 0); + const int i1 = MakeIndex(f, 1); + const int i2 = MakeIndex(f, 2); + const int i3 = MakeIndex(f, 3); + const SVec3 T0 = GetTexCoord(pContext, i0); + const SVec3 T1 = GetTexCoord(pContext, i1); + const SVec3 T2 = GetTexCoord(pContext, i2); + const SVec3 T3 = GetTexCoord(pContext, i3); + const float distSQ_02 = LengthSquared(vsub(T2,T0)); + const float distSQ_13 = LengthSquared(vsub(T3,T1)); + tbool bQuadDiagIs_02; + if (distSQ_02m_pInterface->m_getPosition(pContext, pos, iF, iI); + res.x=pos[0]; res.y=pos[1]; res.z=pos[2]; + return res; +} + +static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index) +{ + int iF, iI; + SVec3 res; float norm[3]; + IndexToData(&iF, &iI, index); + pContext->m_pInterface->m_getNormal(pContext, norm, iF, iI); + res.x=norm[0]; res.y=norm[1]; res.z=norm[2]; + return res; +} + +static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index) +{ + int iF, iI; + SVec3 res; float texc[2]; + IndexToData(&iF, &iI, index); + pContext->m_pInterface->m_getTexCoord(pContext, texc, iF, iI); + res.x=texc[0]; res.y=texc[1]; res.z=1.0f; + return res; +} + +///////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////// + +typedef union { + struct + { + int i0, i1, f; + }; + int array[3]; +} SEdge; + +static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn); +static void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn); + +// returns the texture area times 2 +static float CalcTexArea(const SMikkTSpaceContext * pContext, const int indices[]) +{ + const SVec3 t1 = GetTexCoord(pContext, indices[0]); + const SVec3 t2 = GetTexCoord(pContext, indices[1]); + const SVec3 t3 = GetTexCoord(pContext, indices[2]); + + const float t21x = t2.x-t1.x; + const float t21y = t2.y-t1.y; + const float t31x = t3.x-t1.x; + const float t31y = t3.y-t1.y; + + const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x; + + return fSignedAreaSTx2<0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2; +} + +static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn) +{ + int f=0, i=0, t=0; + // pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function. + + // generate neighbor info list + for (f=0; f0 ? ORIENT_PRESERVING : 0); + + if ( NotZero(fSignedAreaSTx2) ) + { + const float fAbsArea = fabsf(fSignedAreaSTx2); + const float fLenOs = Length(vOs); + const float fLenOt = Length(vOt); + const float fS = (pTriInfos[f].iFlag&ORIENT_PRESERVING)==0 ? (-1.0f) : 1.0f; + if ( NotZero(fLenOs) ) pTriInfos[f].vOs = vscale(fS/fLenOs, vOs); + if ( NotZero(fLenOt) ) pTriInfos[f].vOt = vscale(fS/fLenOt, vOt); + + // evaluate magnitudes prior to normalization of vOs and vOt + pTriInfos[f].fMagS = fLenOs / fAbsArea; + pTriInfos[f].fMagT = fLenOt / fAbsArea; + + // if this is a good triangle + if ( NotZero(pTriInfos[f].fMagS) && NotZero(pTriInfos[f].fMagT)) + pTriInfos[f].iFlag &= (~GROUP_WITH_ANY); + } + } + + // force otherwise healthy quads to a fixed orientation + while (t<(iNrTrianglesIn-1)) + { + const int iFO_a = pTriInfos[t].iOrgFaceNumber; + const int iFO_b = pTriInfos[t+1].iOrgFaceNumber; + if (iFO_a==iFO_b) // this is a quad + { + const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; + const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; + + // bad triangles should already have been removed by + // DegenPrologue(), but just in case check bIsDeg_a and bIsDeg_a are false + if ((bIsDeg_a||bIsDeg_b)==TFALSE) + { + const tbool bOrientA = (pTriInfos[t].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + const tbool bOrientB = (pTriInfos[t+1].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + // if this happens the quad has extremely bad mapping!! + if (bOrientA!=bOrientB) + { + //printf("found quad with bad mapping\n"); + tbool bChooseOrientFirstTri = TFALSE; + if ((pTriInfos[t+1].iFlag&GROUP_WITH_ANY)!=0) bChooseOrientFirstTri = TTRUE; + else if ( CalcTexArea(pContext, &piTriListIn[t*3+0]) >= CalcTexArea(pContext, &piTriListIn[(t+1)*3+0]) ) + bChooseOrientFirstTri = TTRUE; + + // force match + { + const int t0 = bChooseOrientFirstTri ? t : (t+1); + const int t1 = bChooseOrientFirstTri ? (t+1) : t; + pTriInfos[t1].iFlag &= (~ORIENT_PRESERVING); // clear first + pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag&ORIENT_PRESERVING); // copy bit + } + } + } + t += 2; + } + else + ++t; + } + + // match up edge pairs + { + SEdge * pEdges = (SEdge *) malloc(sizeof(SEdge)*iNrTrianglesIn*3); + if (pEdges==NULL) + BuildNeighborsSlow(pTriInfos, piTriListIn, iNrTrianglesIn); + else + { + BuildNeighborsFast(pTriInfos, pEdges, piTriListIn, iNrTrianglesIn); + + free(pEdges); + } + } +} + +///////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////// + +static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup * pGroup); +static void AddTriToGroup(SGroup * pGroup, const int iTriIndex); + +static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn) +{ + const int iNrMaxGroups = iNrTrianglesIn*3; + int iNrActiveGroups = 0; + int iOffset = 0, f=0, i=0; + (void)iNrMaxGroups; /* quiet warnings in non debug mode */ + for (f=0; fiVertexRepresentitive = vert_index; + pTriInfos[f].AssignedGroup[i]->bOrientPreservering = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0; + pTriInfos[f].AssignedGroup[i]->iNrFaces = 0; + pTriInfos[f].AssignedGroup[i]->pFaceIndices = &piGroupTrianglesBuffer[iOffset]; + ++iNrActiveGroups; + + AddTriToGroup(pTriInfos[f].AssignedGroup[i], f); + bOrPre = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + neigh_indexL = pTriInfos[f].FaceNeighbors[i]; + neigh_indexR = pTriInfos[f].FaceNeighbors[i>0?(i-1):2]; + if (neigh_indexL>=0) // neighbor + { + const tbool bAnswer = + AssignRecur(piTriListIn, pTriInfos, neigh_indexL, + pTriInfos[f].AssignedGroup[i] ); + + const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE; + assert(bAnswer || bDiff); + (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ + } + if (neigh_indexR>=0) // neighbor + { + const tbool bAnswer = + AssignRecur(piTriListIn, pTriInfos, neigh_indexR, + pTriInfos[f].AssignedGroup[i] ); + + const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE; + assert(bAnswer || bDiff); + (void)bAnswer, (void)bDiff; /* quiet warnings in non debug mode */ + } + + // update offset + iOffset += pTriInfos[f].AssignedGroup[i]->iNrFaces; + // since the groups are disjoint a triangle can never + // belong to more than 3 groups. Subsequently something + // is completely screwed if this assertion ever hits. + assert(iOffset <= iNrMaxGroups); + } + } + } + + return iNrActiveGroups; +} + +static void AddTriToGroup(SGroup * pGroup, const int iTriIndex) +{ + pGroup->pFaceIndices[pGroup->iNrFaces] = iTriIndex; + ++pGroup->iNrFaces; +} + +static tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], + const int iMyTriIndex, SGroup * pGroup) +{ + STriInfo * pMyTriInfo = &psTriInfos[iMyTriIndex]; + + // track down vertex + const int iVertRep = pGroup->iVertexRepresentitive; + const int * pVerts = &piTriListIn[3*iMyTriIndex+0]; + int i=-1; + if (pVerts[0]==iVertRep) i=0; + else if (pVerts[1]==iVertRep) i=1; + else if (pVerts[2]==iVertRep) i=2; + assert(i>=0 && i<3); + + // early out + if (pMyTriInfo->AssignedGroup[i] == pGroup) return TTRUE; + else if (pMyTriInfo->AssignedGroup[i]!=NULL) return TFALSE; + if ((pMyTriInfo->iFlag&GROUP_WITH_ANY)!=0) + { + // first to group with a group-with-anything triangle + // determines it's orientation. + // This is the only existing order dependency in the code!! + if ( pMyTriInfo->AssignedGroup[0] == NULL && + pMyTriInfo->AssignedGroup[1] == NULL && + pMyTriInfo->AssignedGroup[2] == NULL ) + { + pMyTriInfo->iFlag &= (~ORIENT_PRESERVING); + pMyTriInfo->iFlag |= (pGroup->bOrientPreservering ? ORIENT_PRESERVING : 0); + } + } + { + const tbool bOrient = (pMyTriInfo->iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE; + if (bOrient != pGroup->bOrientPreservering) return TFALSE; + } + + AddTriToGroup(pGroup, iMyTriIndex); + pMyTriInfo->AssignedGroup[i] = pGroup; + + { + const int neigh_indexL = pMyTriInfo->FaceNeighbors[i]; + const int neigh_indexR = pMyTriInfo->FaceNeighbors[i>0?(i-1):2]; + if (neigh_indexL>=0) + AssignRecur(piTriListIn, psTriInfos, neigh_indexL, pGroup); + if (neigh_indexR>=0) + AssignRecur(piTriListIn, psTriInfos, neigh_indexR, pGroup); + } + + + + return TTRUE; +} + +///////////////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////////////// + +static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2); +static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed); +static STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[], const SMikkTSpaceContext * pContext, const int iVertexRepresentitive); + +static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[], + const int iNrActiveGroups, const int piTriListIn[], const float fThresCos, + const SMikkTSpaceContext * pContext) +{ + STSpace * pSubGroupTspace = NULL; + SSubGroup * pUniSubGroups = NULL; + int * pTmpMembers = NULL; + int iMaxNrFaces=0, iUniqueTspaces=0, g=0, i=0; + for (g=0; giNrFaces; i++) // triangles + { + const int f = pGroup->pFaceIndices[i]; // triangle number + int index=-1, iVertIndex=-1, iOF_1=-1, iMembers=0, j=0, l=0; + SSubGroup tmp_group; + tbool bFound; + SVec3 n, vOs, vOt; + if (pTriInfos[f].AssignedGroup[0]==pGroup) index=0; + else if (pTriInfos[f].AssignedGroup[1]==pGroup) index=1; + else if (pTriInfos[f].AssignedGroup[2]==pGroup) index=2; + assert(index>=0 && index<3); + + iVertIndex = piTriListIn[f*3+index]; + assert(iVertIndex==pGroup->iVertexRepresentitive); + + // is normalized already + n = GetNormal(pContext, iVertIndex); + + // project + vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n)); + vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n)); + if ( VNotZero(vOs) ) vOs = Normalize(vOs); + if ( VNotZero(vOt) ) vOt = Normalize(vOt); + + // original face number + iOF_1 = pTriInfos[f].iOrgFaceNumber; + + iMembers = 0; + for (j=0; jiNrFaces; j++) + { + const int t = pGroup->pFaceIndices[j]; // triangle number + const int iOF_2 = pTriInfos[t].iOrgFaceNumber; + + // project + SVec3 vOs2 = vsub(pTriInfos[t].vOs, vscale(vdot(n,pTriInfos[t].vOs), n)); + SVec3 vOt2 = vsub(pTriInfos[t].vOt, vscale(vdot(n,pTriInfos[t].vOt), n)); + if ( VNotZero(vOs2) ) vOs2 = Normalize(vOs2); + if ( VNotZero(vOt2) ) vOt2 = Normalize(vOt2); + + { + const tbool bAny = ( (pTriInfos[f].iFlag | pTriInfos[t].iFlag) & GROUP_WITH_ANY )!=0 ? TTRUE : TFALSE; + // make sure triangles which belong to the same quad are joined. + const tbool bSameOrgFace = iOF_1==iOF_2 ? TTRUE : TFALSE; + + const float fCosS = vdot(vOs,vOs2); + const float fCosT = vdot(vOt,vOt2); + + assert(f!=t || bSameOrgFace); // sanity check + if (bAny || bSameOrgFace || (fCosS>fThresCos && fCosT>fThresCos)) + pTmpMembers[iMembers++] = t; + } + } + + // sort pTmpMembers + tmp_group.iNrFaces = iMembers; + tmp_group.pTriMembers = pTmpMembers; + if (iMembers>1) + { + unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? + QuickSort(pTmpMembers, 0, iMembers-1, uSeed); + } + + // look for an existing match + bFound = TFALSE; + l=0; + while (liVertexRepresentitive); + ++iUniqueSubGroups; + } + + // output tspace + { + const int iOffs = pTriInfos[f].iTSpacesOffs; + const int iVert = pTriInfos[f].vert_num[index]; + STSpace * pTS_out = &psTspace[iOffs+iVert]; + assert(pTS_out->iCounter<2); + assert(((pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0) == pGroup->bOrientPreservering); + if (pTS_out->iCounter==1) + { + *pTS_out = AvgTSpace(pTS_out, &pSubGroupTspace[l]); + pTS_out->iCounter = 2; // update counter + pTS_out->bOrient = pGroup->bOrientPreservering; + } + else + { + assert(pTS_out->iCounter==0); + *pTS_out = pSubGroupTspace[l]; + pTS_out->iCounter = 1; // update counter + pTS_out->bOrient = pGroup->bOrientPreservering; + } + } + } + + // clean up and offset iUniqueTspaces + for (s=0; s=0 && i<3); + + // project + index = piTriListIn[3*f+i]; + n = GetNormal(pContext, index); + vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n)); + vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n)); + if ( VNotZero(vOs) ) vOs = Normalize(vOs); + if ( VNotZero(vOt) ) vOt = Normalize(vOt); + + i2 = piTriListIn[3*f + (i<2?(i+1):0)]; + i1 = piTriListIn[3*f + i]; + i0 = piTriListIn[3*f + (i>0?(i-1):2)]; + + p0 = GetPosition(pContext, i0); + p1 = GetPosition(pContext, i1); + p2 = GetPosition(pContext, i2); + v1 = vsub(p0,p1); + v2 = vsub(p2,p1); + + // project + v1 = vsub(v1, vscale(vdot(n,v1),n)); if ( VNotZero(v1) ) v1 = Normalize(v1); + v2 = vsub(v2, vscale(vdot(n,v2),n)); if ( VNotZero(v2) ) v2 = Normalize(v2); + + // weight contribution by the angle + // between the two edge vectors + fCos = vdot(v1,v2); fCos=fCos>1?1:(fCos<(-1) ? (-1) : fCos); + fAngle = (float) acos(fCos); + fMagS = pTriInfos[f].fMagS; + fMagT = pTriInfos[f].fMagT; + + res.vOs=vadd(res.vOs, vscale(fAngle,vOs)); + res.vOt=vadd(res.vOt,vscale(fAngle,vOt)); + res.fMagS+=(fAngle*fMagS); + res.fMagT+=(fAngle*fMagT); + fAngleSum += fAngle; + } + } + + // normalize + if ( VNotZero(res.vOs) ) res.vOs = Normalize(res.vOs); + if ( VNotZero(res.vOt) ) res.vOt = Normalize(res.vOt); + if (fAngleSum>0) + { + res.fMagS /= fAngleSum; + res.fMagT /= fAngleSum; + } + + return res; +} + +static tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2) +{ + tbool bStillSame=TTRUE; + int i=0; + if (pg1->iNrFaces!=pg2->iNrFaces) return TFALSE; + while (iiNrFaces && bStillSame) + { + bStillSame = pg1->pTriMembers[i]==pg2->pTriMembers[i] ? TTRUE : TFALSE; + if (bStillSame) ++i; + } + return bStillSame; +} + +static void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed) +{ + int iL, iR, n, index, iMid, iTmp; + + // Random + unsigned int t=uSeed&31; + t=(uSeed<>(32-t)); + uSeed=uSeed+t+3; + // Random end + + iL=iLeft; iR=iRight; + n = (iR-iL)+1; + assert(n>=0); + index = (int) (uSeed%n); + + iMid=pSortBuffer[index + iL]; + + + do + { + while (pSortBuffer[iL] < iMid) + ++iL; + while (pSortBuffer[iR] > iMid) + --iR; + + if (iL <= iR) + { + iTmp = pSortBuffer[iL]; + pSortBuffer[iL] = pSortBuffer[iR]; + pSortBuffer[iR] = iTmp; + ++iL; --iR; + } + } + while (iL <= iR); + + if (iLeft < iR) + QuickSort(pSortBuffer, iLeft, iR, uSeed); + if (iL < iRight) + QuickSort(pSortBuffer, iL, iRight, uSeed); +} + +///////////////////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////////////////////////////////////////////////////////////// + +static void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed); +static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in); + +static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn) +{ + // build array of edges + unsigned int uSeed = INTERNAL_RND_SORT_SEED; // could replace with a random seed? + int iEntries=0, iCurStartIndex=-1, f=0, i=0; + for (f=0; f pSortBuffer[iRight].array[channel]) + { + sTmp = pSortBuffer[iLeft]; + pSortBuffer[iLeft] = pSortBuffer[iRight]; + pSortBuffer[iRight] = sTmp; + } + return; + } + + // Random + t=uSeed&31; + t=(uSeed<>(32-t)); + uSeed=uSeed+t+3; + // Random end + + iL = iLeft; + iR = iRight; + n = (iR-iL)+1; + assert(n>=0); + index = (int) (uSeed%n); + + iMid=pSortBuffer[index + iL].array[channel]; + + do + { + while (pSortBuffer[iL].array[channel] < iMid) + ++iL; + while (pSortBuffer[iR].array[channel] > iMid) + --iR; + + if (iL <= iR) + { + sTmp = pSortBuffer[iL]; + pSortBuffer[iL] = pSortBuffer[iR]; + pSortBuffer[iR] = sTmp; + ++iL; --iR; + } + } + while (iL <= iR); + + if (iLeft < iR) + QuickSortEdges(pSortBuffer, iLeft, iR, channel, uSeed); + if (iL < iRight) + QuickSortEdges(pSortBuffer, iL, iRight, channel, uSeed); +} + +// resolve ordering and edge number +static void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in) +{ + *edgenum_out = -1; + + // test if first index is on the edge + if (indices[0]==i0_in || indices[0]==i1_in) + { + // test if second index is on the edge + if (indices[1]==i0_in || indices[1]==i1_in) + { + edgenum_out[0]=0; // first edge + i0_out[0]=indices[0]; + i1_out[0]=indices[1]; + } + else + { + edgenum_out[0]=2; // third edge + i0_out[0]=indices[2]; + i1_out[0]=indices[0]; + } + } + else + { + // only second and third index is on the edge + edgenum_out[0]=1; // second edge + i0_out[0]=indices[1]; + i1_out[0]=indices[2]; + } +} + + +///////////////////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////// Degenerate triangles //////////////////////////////////// + +static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris) +{ + int iNextGoodTriangleSearchIndex=-1; + tbool bStillFindingGoodOnes; + + // locate quads with only one good triangle + int t=0; + while (t<(iTotTris-1)) + { + const int iFO_a = pTriInfos[t].iOrgFaceNumber; + const int iFO_b = pTriInfos[t+1].iOrgFaceNumber; + if (iFO_a==iFO_b) // this is a quad + { + const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; + const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE; + if ((bIsDeg_a^bIsDeg_b)!=0) + { + pTriInfos[t].iFlag |= QUAD_ONE_DEGEN_TRI; + pTriInfos[t+1].iFlag |= QUAD_ONE_DEGEN_TRI; + } + t += 2; + } + else + ++t; + } + + // reorder list so all degen triangles are moved to the back + // without reordering the good triangles + iNextGoodTriangleSearchIndex = 1; + t=0; + bStillFindingGoodOnes = TTRUE; + while (t (t+1)); + + // swap triangle t0 and t1 + if (!bJustADegenerate) + { + int i=0; + for (i=0; i<3; i++) + { + const int index = piTriList_out[t0*3+i]; + piTriList_out[t0*3+i] = piTriList_out[t1*3+i]; + piTriList_out[t1*3+i] = index; + } + { + const STriInfo tri_info = pTriInfos[t0]; + pTriInfos[t0] = pTriInfos[t1]; + pTriInfos[t1] = tri_info; + } + } + else + bStillFindingGoodOnes = TFALSE; // this is not supposed to happen + } + + if (bStillFindingGoodOnes) ++t; + } + + assert(bStillFindingGoodOnes); // code will still work. + assert(iNrTrianglesIn == t); +} + +static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris) +{ + int t=0, i=0; + // deal with degenerate triangles + // punishment for degenerate triangles is O(N^2) + for (t=iNrTrianglesIn; t http://image.diku.dk/projects/media/morten.mikkelsen.08.pdf + * Note that though the tangent spaces at the vertices are generated in an order-independent way, + * by this implementation, the interpolated tangent space is still affected by which diagonal is + * chosen to split each quad. A sensible solution is to have your tools pipeline always + * split quads by the shortest diagonal. This choice is order-independent and works with mirroring. + * If these have the same length then compare the diagonals defined by the texture coordinates. + * XNormal which is a tool for baking normal maps allows you to write your own tangent space plugin + * and also quad triangulator plugin. + */ + + +typedef int tbool; +typedef struct SMikkTSpaceContext SMikkTSpaceContext; + +typedef struct { + // Returns the number of faces (triangles/quads) on the mesh to be processed. + int (*m_getNumFaces)(const SMikkTSpaceContext * pContext); + + // Returns the number of vertices on face number iFace + // iFace is a number in the range {0, 1, ..., getNumFaces()-1} + int (*m_getNumVerticesOfFace)(const SMikkTSpaceContext * pContext, const int iFace); + + // returns the position/normal/texcoord of the referenced face of vertex number iVert. + // iVert is in the range {0,1,2} for triangles and {0,1,2,3} for quads. + void (*m_getPosition)(const SMikkTSpaceContext * pContext, float fvPosOut[], const int iFace, const int iVert); + void (*m_getNormal)(const SMikkTSpaceContext * pContext, float fvNormOut[], const int iFace, const int iVert); + void (*m_getTexCoord)(const SMikkTSpaceContext * pContext, float fvTexcOut[], const int iFace, const int iVert); + + // either (or both) of the two setTSpace callbacks can be set. + // The call-back m_setTSpaceBasic() is sufficient for basic normal mapping. + + // This function is used to return the tangent and fSign to the application. + // fvTangent is a unit length vector. + // For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level. + // bitangent = fSign * cross(vN, tangent); + // Note that the results are returned unindexed. It is possible to generate a new index list + // But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results. + // DO NOT! use an already existing index list. + void (*m_setTSpaceBasic)(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int iFace, const int iVert); + + // This function is used to return tangent space results to the application. + // fvTangent and fvBiTangent are unit length vectors and fMagS and fMagT are their + // true magnitudes which can be used for relief mapping effects. + // fvBiTangent is the "real" bitangent and thus may not be perpendicular to fvTangent. + // However, both are perpendicular to the vertex normal. + // For normal maps it is sufficient to use the following simplified version of the bitangent which is generated at pixel/vertex level. + // fSign = bIsOrientationPreserving ? 1.0f : (-1.0f); + // bitangent = fSign * cross(vN, tangent); + // Note that the results are returned unindexed. It is possible to generate a new index list + // But averaging/overwriting tangent spaces by using an already existing index list WILL produce INCRORRECT results. + // DO NOT! use an already existing index list. + void (*m_setTSpace)(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fvBiTangent[], const float fMagS, const float fMagT, + const tbool bIsOrientationPreserving, const int iFace, const int iVert); +} SMikkTSpaceInterface; + +struct SMikkTSpaceContext +{ + SMikkTSpaceInterface * m_pInterface; // initialized with callback functions + void * m_pUserData; // pointer to client side mesh data etc. (passed as the first parameter with every interface call) +}; + +// these are both thread safe! +tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext); // Default (recommended) fAngularThreshold is 180 degrees (which means threshold disabled) +tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold); + + +// To avoid visual errors (distortions/unwanted hard edges in lighting), when using sampled normal maps, the +// normal map sampler must use the exact inverse of the pixel shader transformation. +// The most efficient transformation we can possibly do in the pixel shader is +// achieved by using, directly, the "unnormalized" interpolated tangent, bitangent and vertex normal: vT, vB and vN. +// pixel shader (fast transform out) +// vNout = normalize( vNt.x * vT + vNt.y * vB + vNt.z * vN ); +// where vNt is the tangent space normal. The normal map sampler must likewise use the +// interpolated and "unnormalized" tangent, bitangent and vertex normal to be compliant with the pixel shader. +// sampler does (exact inverse of pixel shader): +// float3 row0 = cross(vB, vN); +// float3 row1 = cross(vN, vT); +// float3 row2 = cross(vT, vB); +// float fSign = dot(vT, row0)<0 ? -1 : 1; +// vNt = normalize( fSign * float3(dot(vNout,row0), dot(vNout,row1), dot(vNout,row2)) ); +// where vNout is the sampled normal in some chosen 3D space. +// +// Should you choose to reconstruct the bitangent in the pixel shader instead +// of the vertex shader, as explained earlier, then be sure to do this in the normal map sampler also. +// Finally, beware of quad triangulations. If the normal map sampler doesn't use the same triangulation of +// quads as your renderer then problems will occur since the interpolated tangent spaces will differ +// eventhough the vertex level tangent spaces match. This can be solved either by triangulating before +// sampling/exporting or by using the order-independent choice of diagonal for splitting quads suggested earlier. +// However, this must be used both by the sampler and your tools/rendering pipeline. + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/codemp/rd-rend2/glext.h b/codemp/rd-rend2/glext.h new file mode 100644 index 0000000000..63ea7f2465 --- /dev/null +++ b/codemp/rd-rend2/glext.h @@ -0,0 +1,11770 @@ +#ifndef __glext_h_ +#define __glext_h_ 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** Copyright (c) 2013-2014 The Khronos Group Inc. +** +** Permission is hereby granted, free of charge, to any person obtaining a +** copy of this software and/or associated documentation files (the +** "Materials"), to deal in the Materials without restriction, including +** without limitation the rights to use, copy, modify, merge, publish, +** distribute, sublicense, and/or sell copies of the Materials, and to +** permit persons to whom the Materials are furnished to do so, subject to +** the following conditions: +** +** The above copyright notice and this permission notice shall be included +** in all copies or substantial portions of the Materials. +** +** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. +*/ +/* +** This header is generated from the Khronos OpenGL / OpenGL ES XML +** API Registry. The current version of the Registry, generator scripts +** used to make the header, and the header can be found at +** http://www.opengl.org/registry/ +** +** Khronos $Revision: 28986 $ on $Date: 2014-11-18 18:43:15 -0800 (Tue, 18 Nov 2014) $ +*/ + +#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN 1 +#endif +#include +#endif + +#ifndef APIENTRY +#define APIENTRY +#endif +#ifndef APIENTRYP +#define APIENTRYP APIENTRY * +#endif +#ifndef GLAPI +#define GLAPI extern +#endif + +#define GL_GLEXT_VERSION 20141118 + +/* Generated C header for: + * API: gl + * Profile: compatibility + * Versions considered: .* + * Versions emitted: 1\.[2-9]|[234]\.[0-9] + * Default extensions included: gl + * Additional extensions included: _nomatch_^ + * Extensions removed: _nomatch_^ + */ + +#ifndef GL_VERSION_1_2 +#define GL_VERSION_1_2 1 +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E +#define GL_RESCALE_NORMAL 0x803A +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +GLAPI void APIENTRY glTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif +#endif /* GL_VERSION_1_2 */ + +#ifndef GL_VERSION_1_3 +#define GL_VERSION_1_3 1 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_MULTISAMPLE_BIT 0x20000000 +#define GL_NORMAL_MAP 0x8511 +#define GL_REFLECTION_MAP 0x8512 +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_RGB 0x8582 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_SUBTRACT 0x84E7 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLfloat value, GLboolean invert); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, void *img); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTexture (GLenum texture); +GLAPI void APIENTRY glSampleCoverage (GLfloat value, GLboolean invert); +GLAPI void APIENTRY glCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage1D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glGetCompressedTexImage (GLenum target, GLint level, void *img); +GLAPI void APIENTRY glClientActiveTexture (GLenum texture); +GLAPI void APIENTRY glMultiTexCoord1d (GLenum target, GLdouble s); +GLAPI void APIENTRY glMultiTexCoord1dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord1f (GLenum target, GLfloat s); +GLAPI void APIENTRY glMultiTexCoord1fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord1i (GLenum target, GLint s); +GLAPI void APIENTRY glMultiTexCoord1iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord1s (GLenum target, GLshort s); +GLAPI void APIENTRY glMultiTexCoord1sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord2d (GLenum target, GLdouble s, GLdouble t); +GLAPI void APIENTRY glMultiTexCoord2dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord2f (GLenum target, GLfloat s, GLfloat t); +GLAPI void APIENTRY glMultiTexCoord2fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord2i (GLenum target, GLint s, GLint t); +GLAPI void APIENTRY glMultiTexCoord2iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord2s (GLenum target, GLshort s, GLshort t); +GLAPI void APIENTRY glMultiTexCoord2sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord3d (GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI void APIENTRY glMultiTexCoord3dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord3f (GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI void APIENTRY glMultiTexCoord3fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord3i (GLenum target, GLint s, GLint t, GLint r); +GLAPI void APIENTRY glMultiTexCoord3iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord3s (GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI void APIENTRY glMultiTexCoord3sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord4d (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI void APIENTRY glMultiTexCoord4dv (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI void APIENTRY glMultiTexCoord4fv (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord4i (GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI void APIENTRY glMultiTexCoord4iv (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord4s (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI void APIENTRY glMultiTexCoord4sv (GLenum target, const GLshort *v); +GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *m); +GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *m); +GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *m); +GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *m); +#endif +#endif /* GL_VERSION_1_3 */ + +#ifndef GL_VERSION_1_4 +#define GL_VERSION_1_4 1 +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FOG_COORDINATE 0x8451 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_COLOR_SUM 0x8458 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_COMPARE_R_TO_TEXTURE 0x884E +#define GL_FUNC_ADD 0x8006 +#define GL_FUNC_SUBTRACT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT 0x800B +#define GL_MIN 0x8007 +#define GL_MAX 0x8008 +#define GL_CONSTANT_COLOR 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002 +#define GL_CONSTANT_ALPHA 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord); +typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord); +typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord); +typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +GLAPI void APIENTRY glMultiDrawArrays (GLenum mode, const GLint *first, const GLsizei *count, GLsizei drawcount); +GLAPI void APIENTRY glMultiDrawElements (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount); +GLAPI void APIENTRY glPointParameterf (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfv (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glPointParameteri (GLenum pname, GLint param); +GLAPI void APIENTRY glPointParameteriv (GLenum pname, const GLint *params); +GLAPI void APIENTRY glFogCoordf (GLfloat coord); +GLAPI void APIENTRY glFogCoordfv (const GLfloat *coord); +GLAPI void APIENTRY glFogCoordd (GLdouble coord); +GLAPI void APIENTRY glFogCoorddv (const GLdouble *coord); +GLAPI void APIENTRY glFogCoordPointer (GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glSecondaryColor3b (GLbyte red, GLbyte green, GLbyte blue); +GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *v); +GLAPI void APIENTRY glSecondaryColor3d (GLdouble red, GLdouble green, GLdouble blue); +GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *v); +GLAPI void APIENTRY glSecondaryColor3f (GLfloat red, GLfloat green, GLfloat blue); +GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *v); +GLAPI void APIENTRY glSecondaryColor3i (GLint red, GLint green, GLint blue); +GLAPI void APIENTRY glSecondaryColor3iv (const GLint *v); +GLAPI void APIENTRY glSecondaryColor3s (GLshort red, GLshort green, GLshort blue); +GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *v); +GLAPI void APIENTRY glSecondaryColor3ub (GLubyte red, GLubyte green, GLubyte blue); +GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *v); +GLAPI void APIENTRY glSecondaryColor3ui (GLuint red, GLuint green, GLuint blue); +GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *v); +GLAPI void APIENTRY glSecondaryColor3us (GLushort red, GLushort green, GLushort blue); +GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *v); +GLAPI void APIENTRY glSecondaryColorPointer (GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glWindowPos2d (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dv (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2f (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fv (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2i (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2iv (const GLint *v); +GLAPI void APIENTRY glWindowPos2s (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2sv (const GLshort *v); +GLAPI void APIENTRY glWindowPos3d (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dv (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3f (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fv (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3i (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3iv (const GLint *v); +GLAPI void APIENTRY glWindowPos3s (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3sv (const GLshort *v); +GLAPI void APIENTRY glBlendColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +GLAPI void APIENTRY glBlendEquation (GLenum mode); +#endif +#endif /* GL_VERSION_1_4 */ + +#ifndef GL_VERSION_1_5 +#define GL_VERSION_1_5 1 +#include +typedef ptrdiff_t GLsizeiptr; +typedef ptrdiff_t GLintptr; +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_READ_ONLY 0x88B8 +#define GL_WRITE_ONLY 0x88B9 +#define GL_READ_WRITE 0x88BA +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_SAMPLES_PASSED 0x8914 +#define GL_SRC1_ALPHA 0x8589 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_FOG_COORD_SRC 0x8450 +#define GL_FOG_COORD 0x8451 +#define GL_CURRENT_FOG_COORD 0x8453 +#define GL_FOG_COORD_ARRAY_TYPE 0x8454 +#define GL_FOG_COORD_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORD_ARRAY_POINTER 0x8456 +#define GL_FOG_COORD_ARRAY 0x8457 +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING 0x889D +#define GL_SRC0_RGB 0x8580 +#define GL_SRC1_RGB 0x8581 +#define GL_SRC2_RGB 0x8582 +#define GL_SRC0_ALPHA 0x8588 +#define GL_SRC2_ALPHA 0x858A +typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, void *data); +typedef void *(APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueries (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteQueries (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsQuery (GLuint id); +GLAPI void APIENTRY glBeginQuery (GLenum target, GLuint id); +GLAPI void APIENTRY glEndQuery (GLenum target); +GLAPI void APIENTRY glGetQueryiv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectiv (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params); +GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer); +GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers); +GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers); +GLAPI GLboolean APIENTRY glIsBuffer (GLuint buffer); +GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void APIENTRY glGetBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, void *data); +GLAPI void *APIENTRY glMapBuffer (GLenum target, GLenum access); +GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum target); +GLAPI void APIENTRY glGetBufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetBufferPointerv (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_VERSION_1_5 */ + +#ifndef GL_VERSION_2_0 +#define GL_VERSION_2_0 1 +typedef char GLchar; +#define GL_BLEND_EQUATION_RGB 0x8009 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE 0x8642 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 +#define GL_STENCIL_BACK_FUNC 0x8800 +#define GL_STENCIL_BACK_FAIL 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803 +#define GL_MAX_DRAW_BUFFERS 0x8824 +#define GL_DRAW_BUFFER0 0x8825 +#define GL_DRAW_BUFFER1 0x8826 +#define GL_DRAW_BUFFER2 0x8827 +#define GL_DRAW_BUFFER3 0x8828 +#define GL_DRAW_BUFFER4 0x8829 +#define GL_DRAW_BUFFER5 0x882A +#define GL_DRAW_BUFFER6 0x882B +#define GL_DRAW_BUFFER7 0x882C +#define GL_DRAW_BUFFER8 0x882D +#define GL_DRAW_BUFFER9 0x882E +#define GL_DRAW_BUFFER10 0x882F +#define GL_DRAW_BUFFER11 0x8830 +#define GL_DRAW_BUFFER12 0x8831 +#define GL_DRAW_BUFFER13 0x8832 +#define GL_DRAW_BUFFER14 0x8833 +#define GL_DRAW_BUFFER15 0x8834 +#define GL_BLEND_EQUATION_ALPHA 0x883D +#define GL_MAX_VERTEX_ATTRIBS 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A +#define GL_MAX_TEXTURE_IMAGE_UNITS 0x8872 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS 0x8B49 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS 0x8B4A +#define GL_MAX_VARYING_FLOATS 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS 0x8B4D +#define GL_SHADER_TYPE 0x8B4F +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_SAMPLER_1D_SHADOW 0x8B61 +#define GL_SAMPLER_2D_SHADOW 0x8B62 +#define GL_DELETE_STATUS 0x8B80 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_VALIDATE_STATUS 0x8B83 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ATTACHED_SHADERS 0x8B85 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT 0x8B8B +#define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#define GL_CURRENT_PROGRAM 0x8B8D +#define GL_POINT_SPRITE_COORD_ORIGIN 0x8CA0 +#define GL_LOWER_LEFT 0x8CA1 +#define GL_UPPER_LEFT 0x8CA2 +#define GL_STENCIL_BACK_REF 0x8CA3 +#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4 +#define GL_STENCIL_BACK_WRITEMASK 0x8CA5 +#define GL_VERTEX_PROGRAM_TWO_SIDE 0x8643 +#define GL_POINT_SPRITE 0x8861 +#define GL_COORD_REPLACE 0x8862 +#define GL_MAX_TEXTURE_COORDS 0x8871 +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); +typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); +typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader); +typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type); +typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); +typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); +typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader); +typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glDrawBuffers (GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glStencilOpSeparate (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI void APIENTRY glStencilFuncSeparate (GLenum face, GLenum func, GLint ref, GLuint mask); +GLAPI void APIENTRY glStencilMaskSeparate (GLenum face, GLuint mask); +GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glBindAttribLocation (GLuint program, GLuint index, const GLchar *name); +GLAPI void APIENTRY glCompileShader (GLuint shader); +GLAPI GLuint APIENTRY glCreateProgram (void); +GLAPI GLuint APIENTRY glCreateShader (GLenum type); +GLAPI void APIENTRY glDeleteProgram (GLuint program); +GLAPI void APIENTRY glDeleteShader (GLuint shader); +GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader); +GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index); +GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index); +GLAPI void APIENTRY glGetActiveAttrib (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetActiveUniform (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetAttachedShaders (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); +GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glGetShaderSource (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); +GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetUniformfv (GLuint program, GLint location, GLfloat *params); +GLAPI void APIENTRY glGetUniformiv (GLuint program, GLint location, GLint *params); +GLAPI void APIENTRY glGetVertexAttribdv (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfv (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer); +GLAPI GLboolean APIENTRY glIsProgram (GLuint program); +GLAPI GLboolean APIENTRY glIsShader (GLuint shader); +GLAPI void APIENTRY glLinkProgram (GLuint program); +GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length); +GLAPI void APIENTRY glUseProgram (GLuint program); +GLAPI void APIENTRY glUniform1f (GLint location, GLfloat v0); +GLAPI void APIENTRY glUniform2f (GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glUniform3f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glUniform4f (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glUniform1i (GLint location, GLint v0); +GLAPI void APIENTRY glUniform2i (GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glUniform3i (GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glUniform4i (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glUniform1fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform2fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform3fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform4fv (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform1iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform2iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform3iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform4iv (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniformMatrix2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glValidateProgram (GLuint program); +GLAPI void APIENTRY glVertexAttrib1d (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1f (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1s (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2d (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2f (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2s (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3d (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3f (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3s (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4Nbv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4Niv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4Nsv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4Nub (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4Nubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4Nuiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4Nusv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttrib4bv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4f (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4s (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4usv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +#endif +#endif /* GL_VERSION_2_0 */ + +#ifndef GL_VERSION_2_1 +#define GL_VERSION_2_1 1 +#define GL_PIXEL_PACK_BUFFER 0x88EB +#define GL_PIXEL_UNPACK_BUFFER 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING 0x88EF +#define GL_FLOAT_MAT2x3 0x8B65 +#define GL_FLOAT_MAT2x4 0x8B66 +#define GL_FLOAT_MAT3x2 0x8B67 +#define GL_FLOAT_MAT3x4 0x8B68 +#define GL_FLOAT_MAT4x2 0x8B69 +#define GL_FLOAT_MAT4x3 0x8B6A +#define GL_SRGB 0x8C40 +#define GL_SRGB8 0x8C41 +#define GL_SRGB_ALPHA 0x8C42 +#define GL_SRGB8_ALPHA8 0x8C43 +#define GL_COMPRESSED_SRGB 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA 0x8C49 +#define GL_CURRENT_RASTER_SECONDARY_COLOR 0x845F +#define GL_SLUMINANCE_ALPHA 0x8C44 +#define GL_SLUMINANCE8_ALPHA8 0x8C45 +#define GL_SLUMINANCE 0x8C46 +#define GL_SLUMINANCE8 0x8C47 +#define GL_COMPRESSED_SLUMINANCE 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA 0x8C4B +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniformMatrix2x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix2x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4x2fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3x4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4x3fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +#endif +#endif /* GL_VERSION_2_1 */ + +#ifndef GL_VERSION_3_0 +#define GL_VERSION_3_0 1 +typedef unsigned short GLhalf; +#define GL_COMPARE_REF_TO_TEXTURE 0x884E +#define GL_CLIP_DISTANCE0 0x3000 +#define GL_CLIP_DISTANCE1 0x3001 +#define GL_CLIP_DISTANCE2 0x3002 +#define GL_CLIP_DISTANCE3 0x3003 +#define GL_CLIP_DISTANCE4 0x3004 +#define GL_CLIP_DISTANCE5 0x3005 +#define GL_CLIP_DISTANCE6 0x3006 +#define GL_CLIP_DISTANCE7 0x3007 +#define GL_MAX_CLIP_DISTANCES 0x0D32 +#define GL_MAJOR_VERSION 0x821B +#define GL_MINOR_VERSION 0x821C +#define GL_NUM_EXTENSIONS 0x821D +#define GL_CONTEXT_FLAGS 0x821E +#define GL_COMPRESSED_RED 0x8225 +#define GL_COMPRESSED_RG 0x8226 +#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 +#define GL_RGBA32F 0x8814 +#define GL_RGB32F 0x8815 +#define GL_RGBA16F 0x881A +#define GL_RGB16F 0x881B +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER 0x88FD +#define GL_MAX_ARRAY_TEXTURE_LAYERS 0x88FF +#define GL_MIN_PROGRAM_TEXEL_OFFSET 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET 0x8905 +#define GL_CLAMP_READ_COLOR 0x891C +#define GL_FIXED_ONLY 0x891D +#define GL_MAX_VARYING_COMPONENTS 0x8B4B +#define GL_TEXTURE_1D_ARRAY 0x8C18 +#define GL_PROXY_TEXTURE_1D_ARRAY 0x8C19 +#define GL_TEXTURE_2D_ARRAY 0x8C1A +#define GL_PROXY_TEXTURE_2D_ARRAY 0x8C1B +#define GL_TEXTURE_BINDING_1D_ARRAY 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY 0x8C1D +#define GL_R11F_G11F_B10F 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV 0x8C3B +#define GL_RGB9_E5 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV 0x8C3E +#define GL_TEXTURE_SHARED_SIZE 0x8C3F +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH 0x8C76 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE 0x8C85 +#define GL_PRIMITIVES_GENERATED 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN 0x8C88 +#define GL_RASTERIZER_DISCARD 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS 0x8C8B +#define GL_INTERLEAVED_ATTRIBS 0x8C8C +#define GL_SEPARATE_ATTRIBS 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING 0x8C8F +#define GL_RGBA32UI 0x8D70 +#define GL_RGB32UI 0x8D71 +#define GL_RGBA16UI 0x8D76 +#define GL_RGB16UI 0x8D77 +#define GL_RGBA8UI 0x8D7C +#define GL_RGB8UI 0x8D7D +#define GL_RGBA32I 0x8D82 +#define GL_RGB32I 0x8D83 +#define GL_RGBA16I 0x8D88 +#define GL_RGB16I 0x8D89 +#define GL_RGBA8I 0x8D8E +#define GL_RGB8I 0x8D8F +#define GL_RED_INTEGER 0x8D94 +#define GL_GREEN_INTEGER 0x8D95 +#define GL_BLUE_INTEGER 0x8D96 +#define GL_RGB_INTEGER 0x8D98 +#define GL_RGBA_INTEGER 0x8D99 +#define GL_BGR_INTEGER 0x8D9A +#define GL_BGRA_INTEGER 0x8D9B +#define GL_SAMPLER_1D_ARRAY 0x8DC0 +#define GL_SAMPLER_2D_ARRAY 0x8DC1 +#define GL_SAMPLER_1D_ARRAY_SHADOW 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW 0x8DC5 +#define GL_UNSIGNED_INT_VEC2 0x8DC6 +#define GL_UNSIGNED_INT_VEC3 0x8DC7 +#define GL_UNSIGNED_INT_VEC4 0x8DC8 +#define GL_INT_SAMPLER_1D 0x8DC9 +#define GL_INT_SAMPLER_2D 0x8DCA +#define GL_INT_SAMPLER_3D 0x8DCB +#define GL_INT_SAMPLER_CUBE 0x8DCC +#define GL_INT_SAMPLER_1D_ARRAY 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY 0x8DCF +#define GL_UNSIGNED_INT_SAMPLER_1D 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY 0x8DD7 +#define GL_QUERY_WAIT 0x8E13 +#define GL_QUERY_NO_WAIT 0x8E14 +#define GL_QUERY_BY_REGION_WAIT 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT 0x8E16 +#define GL_BUFFER_ACCESS_FLAGS 0x911F +#define GL_BUFFER_MAP_LENGTH 0x9120 +#define GL_BUFFER_MAP_OFFSET 0x9121 +#define GL_DEPTH_COMPONENT32F 0x8CAC +#define GL_DEPTH32F_STENCIL8 0x8CAD +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV 0x8DAD +#define GL_INVALID_FRAMEBUFFER_OPERATION 0x0506 +#define GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING 0x8210 +#define GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE 0x8211 +#define GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE 0x8212 +#define GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE 0x8213 +#define GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE 0x8214 +#define GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE 0x8215 +#define GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE 0x8216 +#define GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE 0x8217 +#define GL_FRAMEBUFFER_DEFAULT 0x8218 +#define GL_FRAMEBUFFER_UNDEFINED 0x8219 +#define GL_DEPTH_STENCIL_ATTACHMENT 0x821A +#define GL_MAX_RENDERBUFFER_SIZE 0x84E8 +#define GL_DEPTH_STENCIL 0x84F9 +#define GL_UNSIGNED_INT_24_8 0x84FA +#define GL_DEPTH24_STENCIL8 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE 0x88F1 +#define GL_TEXTURE_RED_TYPE 0x8C10 +#define GL_TEXTURE_GREEN_TYPE 0x8C11 +#define GL_TEXTURE_BLUE_TYPE 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE 0x8C13 +#define GL_TEXTURE_DEPTH_TYPE 0x8C16 +#define GL_UNSIGNED_NORMALIZED 0x8C17 +#define GL_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_DRAW_FRAMEBUFFER_BINDING 0x8CA6 +#define GL_RENDERBUFFER_BINDING 0x8CA7 +#define GL_READ_FRAMEBUFFER 0x8CA8 +#define GL_DRAW_FRAMEBUFFER 0x8CA9 +#define GL_READ_FRAMEBUFFER_BINDING 0x8CAA +#define GL_RENDERBUFFER_SAMPLES 0x8CAB +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS 0x8CDF +#define GL_COLOR_ATTACHMENT0 0x8CE0 +#define GL_COLOR_ATTACHMENT1 0x8CE1 +#define GL_COLOR_ATTACHMENT2 0x8CE2 +#define GL_COLOR_ATTACHMENT3 0x8CE3 +#define GL_COLOR_ATTACHMENT4 0x8CE4 +#define GL_COLOR_ATTACHMENT5 0x8CE5 +#define GL_COLOR_ATTACHMENT6 0x8CE6 +#define GL_COLOR_ATTACHMENT7 0x8CE7 +#define GL_COLOR_ATTACHMENT8 0x8CE8 +#define GL_COLOR_ATTACHMENT9 0x8CE9 +#define GL_COLOR_ATTACHMENT10 0x8CEA +#define GL_COLOR_ATTACHMENT11 0x8CEB +#define GL_COLOR_ATTACHMENT12 0x8CEC +#define GL_COLOR_ATTACHMENT13 0x8CED +#define GL_COLOR_ATTACHMENT14 0x8CEE +#define GL_COLOR_ATTACHMENT15 0x8CEF +#define GL_DEPTH_ATTACHMENT 0x8D00 +#define GL_STENCIL_ATTACHMENT 0x8D20 +#define GL_FRAMEBUFFER 0x8D40 +#define GL_RENDERBUFFER 0x8D41 +#define GL_RENDERBUFFER_WIDTH 0x8D42 +#define GL_RENDERBUFFER_HEIGHT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT 0x8D44 +#define GL_STENCIL_INDEX1 0x8D46 +#define GL_STENCIL_INDEX4 0x8D47 +#define GL_STENCIL_INDEX8 0x8D48 +#define GL_STENCIL_INDEX16 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE 0x8D55 +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE 0x8D56 +#define GL_MAX_SAMPLES 0x8D57 +#define GL_INDEX 0x8222 +#define GL_TEXTURE_LUMINANCE_TYPE 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE 0x8C15 +#define GL_FRAMEBUFFER_SRGB 0x8DB9 +#define GL_HALF_FLOAT 0x140B +#define GL_MAP_READ_BIT 0x0001 +#define GL_MAP_WRITE_BIT 0x0002 +#define GL_MAP_INVALIDATE_RANGE_BIT 0x0004 +#define GL_MAP_INVALIDATE_BUFFER_BIT 0x0008 +#define GL_MAP_FLUSH_EXPLICIT_BIT 0x0010 +#define GL_MAP_UNSYNCHRONIZED_BIT 0x0020 +#define GL_COMPRESSED_RED_RGTC1 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC +#define GL_COMPRESSED_RG_RGTC2 0x8DBD +#define GL_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE +#define GL_RG 0x8227 +#define GL_RG_INTEGER 0x8228 +#define GL_R8 0x8229 +#define GL_R16 0x822A +#define GL_RG8 0x822B +#define GL_RG16 0x822C +#define GL_R16F 0x822D +#define GL_R32F 0x822E +#define GL_RG16F 0x822F +#define GL_RG32F 0x8230 +#define GL_R8I 0x8231 +#define GL_R8UI 0x8232 +#define GL_R16I 0x8233 +#define GL_R16UI 0x8234 +#define GL_R32I 0x8235 +#define GL_R32UI 0x8236 +#define GL_RG8I 0x8237 +#define GL_RG8UI 0x8238 +#define GL_RG16I 0x8239 +#define GL_RG16UI 0x823A +#define GL_RG32I 0x823B +#define GL_RG32UI 0x823C +#define GL_VERTEX_ARRAY_BINDING 0x85B5 +#define GL_CLAMP_VERTEX_COLOR 0x891A +#define GL_CLAMP_FRAGMENT_COLOR 0x891B +#define GL_ALPHA_INTEGER 0x8D97 +typedef void (APIENTRYP PFNGLCOLORMASKIPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data); +typedef void (APIENTRYP PFNGLENABLEIPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEIPROC) (GLenum target, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISENABLEDIPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGEPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFERBASEPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLCLAMPCOLORPROC) (GLenum target, GLenum clamp); +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERPROC) (GLuint id, GLenum mode); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERPROC) (void); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVPROC) (GLuint index, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IPROC) (GLuint index, GLint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IPROC) (GLuint index, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IPROC) (GLuint index, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIPROC) (GLuint index, GLuint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIPROC) (GLuint index, GLuint x, GLuint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLGETUNIFORMUIVPROC) (GLuint program, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONPROC) (GLuint program, GLuint color, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORM1UIPROC) (GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLUNIFORM2UIPROC) (GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLUNIFORM3UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLUNIFORM4UIPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLUNIFORM1UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM2UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM3UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM4UIVPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVPROC) (GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLCLEARBUFFERIVPROC) (GLenum buffer, GLint drawbuffer, const GLint *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERUIVPROC) (GLenum buffer, GLint drawbuffer, const GLuint *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERFVPROC) (GLenum buffer, GLint drawbuffer, const GLfloat *value); +typedef void (APIENTRYP PFNGLCLEARBUFFERFIPROC) (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFERPROC) (GLuint renderbuffer); +typedef void (APIENTRYP PFNGLBINDRENDERBUFFERPROC) (GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSPROC) (GLsizei n, const GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFERPROC) (GLuint framebuffer); +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFERPROC) (GLenum target, GLuint framebuffer); +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSPROC) (GLsizei n, const GLuint *framebuffers); +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSPROC) (GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFERPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATEMIPMAPPROC) (GLenum target); +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFERPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void *(APIENTRYP PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array); +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYPROC) (GLuint array); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorMaski (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +GLAPI void APIENTRY glGetBooleani_v (GLenum target, GLuint index, GLboolean *data); +GLAPI void APIENTRY glGetIntegeri_v (GLenum target, GLuint index, GLint *data); +GLAPI void APIENTRY glEnablei (GLenum target, GLuint index); +GLAPI void APIENTRY glDisablei (GLenum target, GLuint index); +GLAPI GLboolean APIENTRY glIsEnabledi (GLenum target, GLuint index); +GLAPI void APIENTRY glBeginTransformFeedback (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedback (void); +GLAPI void APIENTRY glBindBufferRange (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferBase (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryings (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +GLAPI void APIENTRY glGetTransformFeedbackVarying (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glClampColor (GLenum target, GLenum clamp); +GLAPI void APIENTRY glBeginConditionalRender (GLuint id, GLenum mode); +GLAPI void APIENTRY glEndConditionalRender (void); +GLAPI void APIENTRY glVertexAttribIPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribIiv (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribIuiv (GLuint index, GLenum pname, GLuint *params); +GLAPI void APIENTRY glVertexAttribI1i (GLuint index, GLint x); +GLAPI void APIENTRY glVertexAttribI2i (GLuint index, GLint x, GLint y); +GLAPI void APIENTRY glVertexAttribI3i (GLuint index, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexAttribI4i (GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexAttribI1ui (GLuint index, GLuint x); +GLAPI void APIENTRY glVertexAttribI2ui (GLuint index, GLuint x, GLuint y); +GLAPI void APIENTRY glVertexAttribI3ui (GLuint index, GLuint x, GLuint y, GLuint z); +GLAPI void APIENTRY glVertexAttribI4ui (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glVertexAttribI1iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI2iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI3iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI4iv (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI1uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI2uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI3uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4uiv (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4bv (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttribI4sv (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttribI4ubv (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribI4usv (GLuint index, const GLushort *v); +GLAPI void APIENTRY glGetUniformuiv (GLuint program, GLint location, GLuint *params); +GLAPI void APIENTRY glBindFragDataLocation (GLuint program, GLuint color, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataLocation (GLuint program, const GLchar *name); +GLAPI void APIENTRY glUniform1ui (GLint location, GLuint v0); +GLAPI void APIENTRY glUniform2ui (GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glUniform3ui (GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glUniform4ui (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glUniform1uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform2uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform3uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform4uiv (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glTexParameterIiv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTexParameterIuiv (GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTexParameterIiv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTexParameterIuiv (GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glClearBufferiv (GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI void APIENTRY glClearBufferuiv (GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI void APIENTRY glClearBufferfv (GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI void APIENTRY glClearBufferfi (GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil); +GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index); +GLAPI GLboolean APIENTRY glIsRenderbuffer (GLuint renderbuffer); +GLAPI void APIENTRY glBindRenderbuffer (GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glDeleteRenderbuffers (GLsizei n, const GLuint *renderbuffers); +GLAPI void APIENTRY glGenRenderbuffers (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glRenderbufferStorage (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetRenderbufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI GLboolean APIENTRY glIsFramebuffer (GLuint framebuffer); +GLAPI void APIENTRY glBindFramebuffer (GLenum target, GLuint framebuffer); +GLAPI void APIENTRY glDeleteFramebuffers (GLsizei n, const GLuint *framebuffers); +GLAPI void APIENTRY glGenFramebuffers (GLsizei n, GLuint *framebuffers); +GLAPI GLenum APIENTRY glCheckFramebufferStatus (GLenum target); +GLAPI void APIENTRY glFramebufferTexture1D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture2D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture3D (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glFramebufferRenderbuffer (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetFramebufferAttachmentParameteriv (GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateMipmap (GLenum target); +GLAPI void APIENTRY glBlitFramebuffer (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI void APIENTRY glRenderbufferStorageMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glFramebufferTextureLayer (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void *APIENTRY glMapBufferRange (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI void APIENTRY glFlushMappedBufferRange (GLenum target, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glBindVertexArray (GLuint array); +GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays); +GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays); +GLAPI GLboolean APIENTRY glIsVertexArray (GLuint array); +#endif +#endif /* GL_VERSION_3_0 */ + +#ifndef GL_VERSION_3_1 +#define GL_VERSION_3_1 1 +#define GL_SAMPLER_2D_RECT 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW 0x8B64 +#define GL_SAMPLER_BUFFER 0x8DC2 +#define GL_INT_SAMPLER_2D_RECT 0x8DCD +#define GL_INT_SAMPLER_BUFFER 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER 0x8DD8 +#define GL_TEXTURE_BUFFER 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING 0x8C2D +#define GL_TEXTURE_RECTANGLE 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE 0x84F8 +#define GL_R8_SNORM 0x8F94 +#define GL_RG8_SNORM 0x8F95 +#define GL_RGB8_SNORM 0x8F96 +#define GL_RGBA8_SNORM 0x8F97 +#define GL_R16_SNORM 0x8F98 +#define GL_RG16_SNORM 0x8F99 +#define GL_RGB16_SNORM 0x8F9A +#define GL_RGBA16_SNORM 0x8F9B +#define GL_SIGNED_NORMALIZED 0x8F9C +#define GL_PRIMITIVE_RESTART 0x8F9D +#define GL_PRIMITIVE_RESTART_INDEX 0x8F9E +#define GL_COPY_READ_BUFFER 0x8F36 +#define GL_COPY_WRITE_BUFFER 0x8F37 +#define GL_UNIFORM_BUFFER 0x8A11 +#define GL_UNIFORM_BUFFER_BINDING 0x8A28 +#define GL_UNIFORM_BUFFER_START 0x8A29 +#define GL_UNIFORM_BUFFER_SIZE 0x8A2A +#define GL_MAX_VERTEX_UNIFORM_BLOCKS 0x8A2B +#define GL_MAX_GEOMETRY_UNIFORM_BLOCKS 0x8A2C +#define GL_MAX_FRAGMENT_UNIFORM_BLOCKS 0x8A2D +#define GL_MAX_COMBINED_UNIFORM_BLOCKS 0x8A2E +#define GL_MAX_UNIFORM_BUFFER_BINDINGS 0x8A2F +#define GL_MAX_UNIFORM_BLOCK_SIZE 0x8A30 +#define GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS 0x8A31 +#define GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS 0x8A32 +#define GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS 0x8A33 +#define GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT 0x8A34 +#define GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH 0x8A35 +#define GL_ACTIVE_UNIFORM_BLOCKS 0x8A36 +#define GL_UNIFORM_TYPE 0x8A37 +#define GL_UNIFORM_SIZE 0x8A38 +#define GL_UNIFORM_NAME_LENGTH 0x8A39 +#define GL_UNIFORM_BLOCK_INDEX 0x8A3A +#define GL_UNIFORM_OFFSET 0x8A3B +#define GL_UNIFORM_ARRAY_STRIDE 0x8A3C +#define GL_UNIFORM_MATRIX_STRIDE 0x8A3D +#define GL_UNIFORM_IS_ROW_MAJOR 0x8A3E +#define GL_UNIFORM_BLOCK_BINDING 0x8A3F +#define GL_UNIFORM_BLOCK_DATA_SIZE 0x8A40 +#define GL_UNIFORM_BLOCK_NAME_LENGTH 0x8A41 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS 0x8A42 +#define GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES 0x8A43 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER 0x8A44 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER 0x8A45 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER 0x8A46 +#define GL_INVALID_INDEX 0xFFFFFFFFu +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); +typedef void (APIENTRYP PFNGLTEXBUFFERPROC) (GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXPROC) (GLuint index); +typedef void (APIENTRYP PFNGLCOPYBUFFERSUBDATAPROC) (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLGETUNIFORMINDICESPROC) (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMSIVPROC) (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMNAMEPROC) (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); +typedef GLuint (APIENTRYP PFNGLGETUNIFORMBLOCKINDEXPROC) (GLuint program, const GLchar *uniformBlockName); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKIVPROC) (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC) (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); +typedef void (APIENTRYP PFNGLUNIFORMBLOCKBINDINGPROC) (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstanced (GLenum mode, GLint first, GLsizei count, GLsizei instancecount); +GLAPI void APIENTRY glDrawElementsInstanced (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount); +GLAPI void APIENTRY glTexBuffer (GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glPrimitiveRestartIndex (GLuint index); +GLAPI void APIENTRY glCopyBufferSubData (GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glGetUniformIndices (GLuint program, GLsizei uniformCount, const GLchar *const*uniformNames, GLuint *uniformIndices); +GLAPI void APIENTRY glGetActiveUniformsiv (GLuint program, GLsizei uniformCount, const GLuint *uniformIndices, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetActiveUniformName (GLuint program, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); +GLAPI GLuint APIENTRY glGetUniformBlockIndex (GLuint program, const GLchar *uniformBlockName); +GLAPI void APIENTRY glGetActiveUniformBlockiv (GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetActiveUniformBlockName (GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformBlockName); +GLAPI void APIENTRY glUniformBlockBinding (GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding); +#endif +#endif /* GL_VERSION_3_1 */ + +#ifndef GL_VERSION_3_2 +#define GL_VERSION_3_2 1 +typedef struct __GLsync *GLsync; +#ifndef GLEXT_64_TYPES_DEFINED +/* This code block is duplicated in glxext.h, so must be protected */ +#define GLEXT_64_TYPES_DEFINED +/* Define int32_t, int64_t, and uint64_t types for UST/MSC */ +/* (as used in the GL_EXT_timer_query extension). */ +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L +#include +#elif defined(__sun__) || defined(__digital__) +#include +#if defined(__STDC__) +#if defined(__arch64__) || defined(_LP64) +typedef long int int64_t; +typedef unsigned long int uint64_t; +#else +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +#endif /* __arch64__ */ +#endif /* __STDC__ */ +#elif defined( __VMS ) || defined(__sgi) +#include +#elif defined(__SCO__) || defined(__USLC__) +#include +#elif defined(__UNIXOS2__) || defined(__SOL64__) +typedef long int int32_t; +typedef long long int int64_t; +typedef unsigned long long int uint64_t; +#elif defined(_WIN32) && defined(__GNUC__) +#include +#elif defined(_WIN32) +typedef __int32 int32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +/* Fallback if nothing above works */ +#include +#endif +#endif +typedef uint64_t GLuint64; +typedef int64_t GLint64; +#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 +#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 +#define GL_LINES_ADJACENCY 0x000A +#define GL_LINE_STRIP_ADJACENCY 0x000B +#define GL_TRIANGLES_ADJACENCY 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY 0x000D +#define GL_PROGRAM_POINT_SIZE 0x8642 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS 0x8C29 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS 0x8DA8 +#define GL_GEOMETRY_SHADER 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT 0x8916 +#define GL_GEOMETRY_INPUT_TYPE 0x8917 +#define GL_GEOMETRY_OUTPUT_TYPE 0x8918 +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS 0x8DE1 +#define GL_MAX_VERTEX_OUTPUT_COMPONENTS 0x9122 +#define GL_MAX_GEOMETRY_INPUT_COMPONENTS 0x9123 +#define GL_MAX_GEOMETRY_OUTPUT_COMPONENTS 0x9124 +#define GL_MAX_FRAGMENT_INPUT_COMPONENTS 0x9125 +#define GL_CONTEXT_PROFILE_MASK 0x9126 +#define GL_DEPTH_CLAMP 0x864F +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION 0x8E4D +#define GL_LAST_VERTEX_CONVENTION 0x8E4E +#define GL_PROVOKING_VERTEX 0x8E4F +#define GL_TEXTURE_CUBE_MAP_SEAMLESS 0x884F +#define GL_MAX_SERVER_WAIT_TIMEOUT 0x9111 +#define GL_OBJECT_TYPE 0x9112 +#define GL_SYNC_CONDITION 0x9113 +#define GL_SYNC_STATUS 0x9114 +#define GL_SYNC_FLAGS 0x9115 +#define GL_SYNC_FENCE 0x9116 +#define GL_SYNC_GPU_COMMANDS_COMPLETE 0x9117 +#define GL_UNSIGNALED 0x9118 +#define GL_SIGNALED 0x9119 +#define GL_ALREADY_SIGNALED 0x911A +#define GL_TIMEOUT_EXPIRED 0x911B +#define GL_CONDITION_SATISFIED 0x911C +#define GL_WAIT_FAILED 0x911D +#define GL_TIMEOUT_IGNORED 0xFFFFFFFFFFFFFFFFull +#define GL_SYNC_FLUSH_COMMANDS_BIT 0x00000001 +#define GL_SAMPLE_POSITION 0x8E50 +#define GL_SAMPLE_MASK 0x8E51 +#define GL_SAMPLE_MASK_VALUE 0x8E52 +#define GL_MAX_SAMPLE_MASK_WORDS 0x8E59 +#define GL_TEXTURE_2D_MULTISAMPLE 0x9100 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE 0x9101 +#define GL_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9102 +#define GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY 0x9103 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE 0x9104 +#define GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY 0x9105 +#define GL_TEXTURE_SAMPLES 0x9106 +#define GL_TEXTURE_FIXED_SAMPLE_LOCATIONS 0x9107 +#define GL_SAMPLER_2D_MULTISAMPLE 0x9108 +#define GL_INT_SAMPLER_2D_MULTISAMPLE 0x9109 +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE 0x910A +#define GL_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910B +#define GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910C +#define GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY 0x910D +#define GL_MAX_COLOR_TEXTURE_SAMPLES 0x910E +#define GL_MAX_DEPTH_TEXTURE_SAMPLES 0x910F +#define GL_MAX_INTEGER_SAMPLES 0x9110 +typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXPROC) (GLenum mode); +typedef GLsync (APIENTRYP PFNGLFENCESYNCPROC) (GLenum condition, GLbitfield flags); +typedef GLboolean (APIENTRYP PFNGLISSYNCPROC) (GLsync sync); +typedef void (APIENTRYP PFNGLDELETESYNCPROC) (GLsync sync); +typedef GLenum (APIENTRYP PFNGLCLIENTWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (APIENTRYP PFNGLWAITSYNCPROC) (GLsync sync, GLbitfield flags, GLuint64 timeout); +typedef void (APIENTRYP PFNGLGETINTEGER64VPROC) (GLenum pname, GLint64 *data); +typedef void (APIENTRYP PFNGLGETSYNCIVPROC) (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERI64VPROC) (GLenum target, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVPROC) (GLenum pname, GLuint index, GLfloat *val); +typedef void (APIENTRYP PFNGLSAMPLEMASKIPROC) (GLuint maskNumber, GLbitfield mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI void APIENTRY glDrawRangeElementsBaseVertex (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLint basevertex); +GLAPI void APIENTRY glDrawElementsInstancedBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex); +GLAPI void APIENTRY glMultiDrawElementsBaseVertex (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei drawcount, const GLint *basevertex); +GLAPI void APIENTRY glProvokingVertex (GLenum mode); +GLAPI GLsync APIENTRY glFenceSync (GLenum condition, GLbitfield flags); +GLAPI GLboolean APIENTRY glIsSync (GLsync sync); +GLAPI void APIENTRY glDeleteSync (GLsync sync); +GLAPI GLenum APIENTRY glClientWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI void APIENTRY glWaitSync (GLsync sync, GLbitfield flags, GLuint64 timeout); +GLAPI void APIENTRY glGetInteger64v (GLenum pname, GLint64 *data); +GLAPI void APIENTRY glGetSynciv (GLsync sync, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +GLAPI void APIENTRY glGetInteger64i_v (GLenum target, GLuint index, GLint64 *data); +GLAPI void APIENTRY glGetBufferParameteri64v (GLenum target, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glFramebufferTexture (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glTexImage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTexImage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glGetMultisamplefv (GLenum pname, GLuint index, GLfloat *val); +GLAPI void APIENTRY glSampleMaski (GLuint maskNumber, GLbitfield mask); +#endif +#endif /* GL_VERSION_3_2 */ + +#ifndef GL_VERSION_3_3 +#define GL_VERSION_3_3 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR 0x88FE +#define GL_SRC1_COLOR 0x88F9 +#define GL_ONE_MINUS_SRC1_COLOR 0x88FA +#define GL_ONE_MINUS_SRC1_ALPHA 0x88FB +#define GL_MAX_DUAL_SOURCE_DRAW_BUFFERS 0x88FC +#define GL_ANY_SAMPLES_PASSED 0x8C2F +#define GL_SAMPLER_BINDING 0x8919 +#define GL_RGB10_A2UI 0x906F +#define GL_TEXTURE_SWIZZLE_R 0x8E42 +#define GL_TEXTURE_SWIZZLE_G 0x8E43 +#define GL_TEXTURE_SWIZZLE_B 0x8E44 +#define GL_TEXTURE_SWIZZLE_A 0x8E45 +#define GL_TEXTURE_SWIZZLE_RGBA 0x8E46 +#define GL_TIME_ELAPSED 0x88BF +#define GL_TIMESTAMP 0x8E28 +#define GL_INT_2_10_10_10_REV 0x8D9F +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONINDEXEDPROC) (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATAINDEXPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGENSAMPLERSPROC) (GLsizei count, GLuint *samplers); +typedef void (APIENTRYP PFNGLDELETESAMPLERSPROC) (GLsizei count, const GLuint *samplers); +typedef GLboolean (APIENTRYP PFNGLISSAMPLERPROC) (GLuint sampler); +typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIPROC) (GLuint sampler, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFPROC) (GLuint sampler, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, const GLuint *param); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIVPROC) (GLuint sampler, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIIVPROC) (GLuint sampler, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERFVPROC) (GLuint sampler, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETSAMPLERPARAMETERIUIVPROC) (GLuint sampler, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLQUERYCOUNTERPROC) (GLuint id, GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VPROC) (GLuint id, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VPROC) (GLuint id, GLenum pname, GLuint64 *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORPROC) (GLuint index, GLuint divisor); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP1UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP2UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP3UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIPROC) (GLuint index, GLenum type, GLboolean normalized, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXATTRIBP4UIVPROC) (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP2UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP2UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP3UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP3UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLVERTEXP4UIPROC) (GLenum type, GLuint value); +typedef void (APIENTRYP PFNGLVERTEXP4UIVPROC) (GLenum type, const GLuint *value); +typedef void (APIENTRYP PFNGLTEXCOORDP1UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP1UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP2UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP2UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP3UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP3UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLTEXCOORDP4UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLTEXCOORDP4UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP1UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP2UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP3UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIPROC) (GLenum texture, GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORDP4UIVPROC) (GLenum texture, GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLNORMALP3UIPROC) (GLenum type, GLuint coords); +typedef void (APIENTRYP PFNGLNORMALP3UIVPROC) (GLenum type, const GLuint *coords); +typedef void (APIENTRYP PFNGLCOLORP3UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLCOLORP3UIVPROC) (GLenum type, const GLuint *color); +typedef void (APIENTRYP PFNGLCOLORP4UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLCOLORP4UIVPROC) (GLenum type, const GLuint *color); +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIPROC) (GLenum type, GLuint color); +typedef void (APIENTRYP PFNGLSECONDARYCOLORP3UIVPROC) (GLenum type, const GLuint *color); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindFragDataLocationIndexed (GLuint program, GLuint colorNumber, GLuint index, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataIndex (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGenSamplers (GLsizei count, GLuint *samplers); +GLAPI void APIENTRY glDeleteSamplers (GLsizei count, const GLuint *samplers); +GLAPI GLboolean APIENTRY glIsSampler (GLuint sampler); +GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler); +GLAPI void APIENTRY glSamplerParameteri (GLuint sampler, GLenum pname, GLint param); +GLAPI void APIENTRY glSamplerParameteriv (GLuint sampler, GLenum pname, const GLint *param); +GLAPI void APIENTRY glSamplerParameterf (GLuint sampler, GLenum pname, GLfloat param); +GLAPI void APIENTRY glSamplerParameterfv (GLuint sampler, GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glSamplerParameterIiv (GLuint sampler, GLenum pname, const GLint *param); +GLAPI void APIENTRY glSamplerParameterIuiv (GLuint sampler, GLenum pname, const GLuint *param); +GLAPI void APIENTRY glGetSamplerParameteriv (GLuint sampler, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSamplerParameterIiv (GLuint sampler, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSamplerParameterfv (GLuint sampler, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetSamplerParameterIuiv (GLuint sampler, GLenum pname, GLuint *params); +GLAPI void APIENTRY glQueryCounter (GLuint id, GLenum target); +GLAPI void APIENTRY glGetQueryObjecti64v (GLuint id, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetQueryObjectui64v (GLuint id, GLenum pname, GLuint64 *params); +GLAPI void APIENTRY glVertexAttribDivisor (GLuint index, GLuint divisor); +GLAPI void APIENTRY glVertexAttribP1ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP1uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP2ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP2uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP3ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP3uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexAttribP4ui (GLuint index, GLenum type, GLboolean normalized, GLuint value); +GLAPI void APIENTRY glVertexAttribP4uiv (GLuint index, GLenum type, GLboolean normalized, const GLuint *value); +GLAPI void APIENTRY glVertexP2ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP2uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glVertexP3ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP3uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glVertexP4ui (GLenum type, GLuint value); +GLAPI void APIENTRY glVertexP4uiv (GLenum type, const GLuint *value); +GLAPI void APIENTRY glTexCoordP1ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP1uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP2ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP2uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP3ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP3uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glTexCoordP4ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glTexCoordP4uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP1ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP1uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP2ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP2uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP3ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP3uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glMultiTexCoordP4ui (GLenum texture, GLenum type, GLuint coords); +GLAPI void APIENTRY glMultiTexCoordP4uiv (GLenum texture, GLenum type, const GLuint *coords); +GLAPI void APIENTRY glNormalP3ui (GLenum type, GLuint coords); +GLAPI void APIENTRY glNormalP3uiv (GLenum type, const GLuint *coords); +GLAPI void APIENTRY glColorP3ui (GLenum type, GLuint color); +GLAPI void APIENTRY glColorP3uiv (GLenum type, const GLuint *color); +GLAPI void APIENTRY glColorP4ui (GLenum type, GLuint color); +GLAPI void APIENTRY glColorP4uiv (GLenum type, const GLuint *color); +GLAPI void APIENTRY glSecondaryColorP3ui (GLenum type, GLuint color); +GLAPI void APIENTRY glSecondaryColorP3uiv (GLenum type, const GLuint *color); +#endif +#endif /* GL_VERSION_3_3 */ + +#ifndef GL_VERSION_4_0 +#define GL_VERSION_4_0 1 +#define GL_SAMPLE_SHADING 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE 0x8C37 +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET 0x8E5F +#define GL_TEXTURE_CUBE_MAP_ARRAY 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY 0x900A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY 0x900B +#define GL_SAMPLER_CUBE_MAP_ARRAY 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY 0x900F +#define GL_DRAW_INDIRECT_BUFFER 0x8F3F +#define GL_DRAW_INDIRECT_BUFFER_BINDING 0x8F43 +#define GL_GEOMETRY_SHADER_INVOCATIONS 0x887F +#define GL_MAX_GEOMETRY_SHADER_INVOCATIONS 0x8E5A +#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET 0x8E5B +#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET 0x8E5C +#define GL_FRAGMENT_INTERPOLATION_OFFSET_BITS 0x8E5D +#define GL_MAX_VERTEX_STREAMS 0x8E71 +#define GL_DOUBLE_VEC2 0x8FFC +#define GL_DOUBLE_VEC3 0x8FFD +#define GL_DOUBLE_VEC4 0x8FFE +#define GL_DOUBLE_MAT2 0x8F46 +#define GL_DOUBLE_MAT3 0x8F47 +#define GL_DOUBLE_MAT4 0x8F48 +#define GL_DOUBLE_MAT2x3 0x8F49 +#define GL_DOUBLE_MAT2x4 0x8F4A +#define GL_DOUBLE_MAT3x2 0x8F4B +#define GL_DOUBLE_MAT3x4 0x8F4C +#define GL_DOUBLE_MAT4x2 0x8F4D +#define GL_DOUBLE_MAT4x3 0x8F4E +#define GL_ACTIVE_SUBROUTINES 0x8DE5 +#define GL_ACTIVE_SUBROUTINE_UNIFORMS 0x8DE6 +#define GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS 0x8E47 +#define GL_ACTIVE_SUBROUTINE_MAX_LENGTH 0x8E48 +#define GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH 0x8E49 +#define GL_MAX_SUBROUTINES 0x8DE7 +#define GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS 0x8DE8 +#define GL_NUM_COMPATIBLE_SUBROUTINES 0x8E4A +#define GL_COMPATIBLE_SUBROUTINES 0x8E4B +#define GL_PATCHES 0x000E +#define GL_PATCH_VERTICES 0x8E72 +#define GL_PATCH_DEFAULT_INNER_LEVEL 0x8E73 +#define GL_PATCH_DEFAULT_OUTER_LEVEL 0x8E74 +#define GL_TESS_CONTROL_OUTPUT_VERTICES 0x8E75 +#define GL_TESS_GEN_MODE 0x8E76 +#define GL_TESS_GEN_SPACING 0x8E77 +#define GL_TESS_GEN_VERTEX_ORDER 0x8E78 +#define GL_TESS_GEN_POINT_MODE 0x8E79 +#define GL_ISOLINES 0x8E7A +#define GL_FRACTIONAL_ODD 0x8E7B +#define GL_FRACTIONAL_EVEN 0x8E7C +#define GL_MAX_PATCH_VERTICES 0x8E7D +#define GL_MAX_TESS_GEN_LEVEL 0x8E7E +#define GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E7F +#define GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E80 +#define GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS 0x8E81 +#define GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS 0x8E82 +#define GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS 0x8E83 +#define GL_MAX_TESS_PATCH_COMPONENTS 0x8E84 +#define GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS 0x8E85 +#define GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS 0x8E86 +#define GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS 0x8E89 +#define GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS 0x8E8A +#define GL_MAX_TESS_CONTROL_INPUT_COMPONENTS 0x886C +#define GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS 0x886D +#define GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS 0x8E1E +#define GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS 0x8E1F +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER 0x84F0 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER 0x84F1 +#define GL_TESS_EVALUATION_SHADER 0x8E87 +#define GL_TESS_CONTROL_SHADER 0x8E88 +#define GL_TRANSFORM_FEEDBACK 0x8E22 +#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED 0x8E23 +#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING 0x8E25 +#define GL_MAX_TRANSFORM_FEEDBACK_BUFFERS 0x8E70 +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGPROC) (GLfloat value); +typedef void (APIENTRYP PFNGLBLENDEQUATIONIPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLBLENDFUNCIPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +typedef void (APIENTRYP PFNGLDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect); +typedef void (APIENTRYP PFNGLUNIFORM1DPROC) (GLint location, GLdouble x); +typedef void (APIENTRYP PFNGLUNIFORM2DPROC) (GLint location, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLUNIFORM3DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLUNIFORM4DPROC) (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLUNIFORM1DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM2DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM3DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORM4DVPROC) (GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3X4DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X2DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4X3DVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLGETUNIFORMDVPROC) (GLuint program, GLint location, GLdouble *params); +typedef GLint (APIENTRYP PFNGLGETSUBROUTINEUNIFORMLOCATIONPROC) (GLuint program, GLenum shadertype, const GLchar *name); +typedef GLuint (APIENTRYP PFNGLGETSUBROUTINEINDEXPROC) (GLuint program, GLenum shadertype, const GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMIVPROC) (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINEUNIFORMNAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVESUBROUTINENAMEPROC) (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORMSUBROUTINESUIVPROC) (GLenum shadertype, GLsizei count, const GLuint *indices); +typedef void (APIENTRYP PFNGLGETUNIFORMSUBROUTINEUIVPROC) (GLenum shadertype, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTAGEIVPROC) (GLuint program, GLenum shadertype, GLenum pname, GLint *values); +typedef void (APIENTRYP PFNGLPATCHPARAMETERIPROC) (GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLPATCHPARAMETERFVPROC) (GLenum pname, const GLfloat *values); +typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSPROC) (GLsizei n, const GLuint *ids); +typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKPROC) (GLuint id); +typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKPROC) (void); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKPROC) (GLenum mode, GLuint id); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMPROC) (GLenum mode, GLuint id, GLuint stream); +typedef void (APIENTRYP PFNGLBEGINQUERYINDEXEDPROC) (GLenum target, GLuint index, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYINDEXEDPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLGETQUERYINDEXEDIVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMinSampleShading (GLfloat value); +GLAPI void APIENTRY glBlendEquationi (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparatei (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glBlendFunci (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparatei (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GLAPI void APIENTRY glDrawArraysIndirect (GLenum mode, const void *indirect); +GLAPI void APIENTRY glDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect); +GLAPI void APIENTRY glUniform1d (GLint location, GLdouble x); +GLAPI void APIENTRY glUniform2d (GLint location, GLdouble x, GLdouble y); +GLAPI void APIENTRY glUniform3d (GLint location, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glUniform4d (GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glUniform1dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform2dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform3dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniform4dv (GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix2x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix3x4dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4x2dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glUniformMatrix4x3dv (GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glGetUniformdv (GLuint program, GLint location, GLdouble *params); +GLAPI GLint APIENTRY glGetSubroutineUniformLocation (GLuint program, GLenum shadertype, const GLchar *name); +GLAPI GLuint APIENTRY glGetSubroutineIndex (GLuint program, GLenum shadertype, const GLchar *name); +GLAPI void APIENTRY glGetActiveSubroutineUniformiv (GLuint program, GLenum shadertype, GLuint index, GLenum pname, GLint *values); +GLAPI void APIENTRY glGetActiveSubroutineUniformName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glGetActiveSubroutineName (GLuint program, GLenum shadertype, GLuint index, GLsizei bufsize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glUniformSubroutinesuiv (GLenum shadertype, GLsizei count, const GLuint *indices); +GLAPI void APIENTRY glGetUniformSubroutineuiv (GLenum shadertype, GLint location, GLuint *params); +GLAPI void APIENTRY glGetProgramStageiv (GLuint program, GLenum shadertype, GLenum pname, GLint *values); +GLAPI void APIENTRY glPatchParameteri (GLenum pname, GLint value); +GLAPI void APIENTRY glPatchParameterfv (GLenum pname, const GLfloat *values); +GLAPI void APIENTRY glBindTransformFeedback (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteTransformFeedbacks (GLsizei n, const GLuint *ids); +GLAPI void APIENTRY glGenTransformFeedbacks (GLsizei n, GLuint *ids); +GLAPI GLboolean APIENTRY glIsTransformFeedback (GLuint id); +GLAPI void APIENTRY glPauseTransformFeedback (void); +GLAPI void APIENTRY glResumeTransformFeedback (void); +GLAPI void APIENTRY glDrawTransformFeedback (GLenum mode, GLuint id); +GLAPI void APIENTRY glDrawTransformFeedbackStream (GLenum mode, GLuint id, GLuint stream); +GLAPI void APIENTRY glBeginQueryIndexed (GLenum target, GLuint index, GLuint id); +GLAPI void APIENTRY glEndQueryIndexed (GLenum target, GLuint index); +GLAPI void APIENTRY glGetQueryIndexediv (GLenum target, GLuint index, GLenum pname, GLint *params); +#endif +#endif /* GL_VERSION_4_0 */ + +#ifndef GL_VERSION_4_1 +#define GL_VERSION_4_1 1 +#define GL_FIXED 0x140C +#define GL_IMPLEMENTATION_COLOR_READ_TYPE 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT 0x8B9B +#define GL_LOW_FLOAT 0x8DF0 +#define GL_MEDIUM_FLOAT 0x8DF1 +#define GL_HIGH_FLOAT 0x8DF2 +#define GL_LOW_INT 0x8DF3 +#define GL_MEDIUM_INT 0x8DF4 +#define GL_HIGH_INT 0x8DF5 +#define GL_SHADER_COMPILER 0x8DFA +#define GL_SHADER_BINARY_FORMATS 0x8DF8 +#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 +#define GL_MAX_VERTEX_UNIFORM_VECTORS 0x8DFB +#define GL_MAX_VARYING_VECTORS 0x8DFC +#define GL_MAX_FRAGMENT_UNIFORM_VECTORS 0x8DFD +#define GL_RGB565 0x8D62 +#define GL_PROGRAM_BINARY_RETRIEVABLE_HINT 0x8257 +#define GL_PROGRAM_BINARY_LENGTH 0x8741 +#define GL_NUM_PROGRAM_BINARY_FORMATS 0x87FE +#define GL_PROGRAM_BINARY_FORMATS 0x87FF +#define GL_VERTEX_SHADER_BIT 0x00000001 +#define GL_FRAGMENT_SHADER_BIT 0x00000002 +#define GL_GEOMETRY_SHADER_BIT 0x00000004 +#define GL_TESS_CONTROL_SHADER_BIT 0x00000008 +#define GL_TESS_EVALUATION_SHADER_BIT 0x00000010 +#define GL_ALL_SHADER_BITS 0xFFFFFFFF +#define GL_PROGRAM_SEPARABLE 0x8258 +#define GL_ACTIVE_PROGRAM 0x8259 +#define GL_PROGRAM_PIPELINE_BINDING 0x825A +#define GL_MAX_VIEWPORTS 0x825B +#define GL_VIEWPORT_SUBPIXEL_BITS 0x825C +#define GL_VIEWPORT_BOUNDS_RANGE 0x825D +#define GL_LAYER_PROVOKING_VERTEX 0x825E +#define GL_VIEWPORT_INDEX_PROVOKING_VERTEX 0x825F +#define GL_UNDEFINED_VERTEX 0x8260 +typedef void (APIENTRYP PFNGLRELEASESHADERCOMPILERPROC) (void); +typedef void (APIENTRYP PFNGLSHADERBINARYPROC) (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); +typedef void (APIENTRYP PFNGLGETSHADERPRECISIONFORMATPROC) (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +typedef void (APIENTRYP PFNGLDEPTHRANGEFPROC) (GLfloat n, GLfloat f); +typedef void (APIENTRYP PFNGLCLEARDEPTHFPROC) (GLfloat d); +typedef void (APIENTRYP PFNGLGETPROGRAMBINARYPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +typedef void (APIENTRYP PFNGLPROGRAMBINARYPROC) (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIPROC) (GLuint program, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLUSEPROGRAMSTAGESPROC) (GLuint pipeline, GLbitfield stages, GLuint program); +typedef void (APIENTRYP PFNGLACTIVESHADERPROGRAMPROC) (GLuint pipeline, GLuint program); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMVPROC) (GLenum type, GLsizei count, const GLchar *const*strings); +typedef void (APIENTRYP PFNGLBINDPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLDELETEPROGRAMPIPELINESPROC) (GLsizei n, const GLuint *pipelines); +typedef void (APIENTRYP PFNGLGENPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEIVPROC) (GLuint pipeline, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IPROC) (GLuint program, GLint location, GLint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FPROC) (GLuint program, GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DPROC) (GLuint program, GLint location, GLdouble v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIPROC) (GLuint program, GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IPROC) (GLuint program, GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DPROC) (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPIPELINEPROC) (GLuint pipeline); +typedef void (APIENTRYP PFNGLGETPROGRAMPIPELINEINFOLOGPROC) (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTERPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLVIEWPORTARRAYVPROC) (GLuint first, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +typedef void (APIENTRYP PFNGLVIEWPORTINDEXEDFVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLSCISSORARRAYVPROC) (GLuint first, GLsizei count, const GLint *v); +typedef void (APIENTRYP PFNGLSCISSORINDEXEDPROC) (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLSCISSORINDEXEDVPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLDEPTHRANGEARRAYVPROC) (GLuint first, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLDEPTHRANGEINDEXEDPROC) (GLuint index, GLdouble n, GLdouble f); +typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReleaseShaderCompiler (void); +GLAPI void APIENTRY glShaderBinary (GLsizei count, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); +GLAPI void APIENTRY glGetShaderPrecisionFormat (GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); +GLAPI void APIENTRY glDepthRangef (GLfloat n, GLfloat f); +GLAPI void APIENTRY glClearDepthf (GLfloat d); +GLAPI void APIENTRY glGetProgramBinary (GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); +GLAPI void APIENTRY glProgramBinary (GLuint program, GLenum binaryFormat, const void *binary, GLsizei length); +GLAPI void APIENTRY glProgramParameteri (GLuint program, GLenum pname, GLint value); +GLAPI void APIENTRY glUseProgramStages (GLuint pipeline, GLbitfield stages, GLuint program); +GLAPI void APIENTRY glActiveShaderProgram (GLuint pipeline, GLuint program); +GLAPI GLuint APIENTRY glCreateShaderProgramv (GLenum type, GLsizei count, const GLchar *const*strings); +GLAPI void APIENTRY glBindProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glDeleteProgramPipelines (GLsizei n, const GLuint *pipelines); +GLAPI void APIENTRY glGenProgramPipelines (GLsizei n, GLuint *pipelines); +GLAPI GLboolean APIENTRY glIsProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glGetProgramPipelineiv (GLuint pipeline, GLenum pname, GLint *params); +GLAPI void APIENTRY glProgramUniform1i (GLuint program, GLint location, GLint v0); +GLAPI void APIENTRY glProgramUniform1iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform1f (GLuint program, GLint location, GLfloat v0); +GLAPI void APIENTRY glProgramUniform1fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform1d (GLuint program, GLint location, GLdouble v0); +GLAPI void APIENTRY glProgramUniform1dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform1ui (GLuint program, GLint location, GLuint v0); +GLAPI void APIENTRY glProgramUniform1uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform2i (GLuint program, GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glProgramUniform2iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform2f (GLuint program, GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glProgramUniform2fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform2d (GLuint program, GLint location, GLdouble v0, GLdouble v1); +GLAPI void APIENTRY glProgramUniform2dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform2ui (GLuint program, GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glProgramUniform2uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform3i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glProgramUniform3iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform3f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glProgramUniform3fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform3d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2); +GLAPI void APIENTRY glProgramUniform3dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform3ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glProgramUniform3uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform4i (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glProgramUniform4iv (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform4f (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glProgramUniform4fv (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform4d (GLuint program, GLint location, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); +GLAPI void APIENTRY glProgramUniform4dv (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform4ui (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glProgramUniform4uiv (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniformMatrix2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3fv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3dv (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glValidateProgramPipeline (GLuint pipeline); +GLAPI void APIENTRY glGetProgramPipelineInfoLog (GLuint pipeline, GLsizei bufSize, GLsizei *length, GLchar *infoLog); +GLAPI void APIENTRY glVertexAttribL1d (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttribL2d (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttribL3d (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttribL4d (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttribL1dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL2dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL3dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL4dv (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribLPointer (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribLdv (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glViewportArrayv (GLuint first, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glViewportIndexedf (GLuint index, GLfloat x, GLfloat y, GLfloat w, GLfloat h); +GLAPI void APIENTRY glViewportIndexedfv (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glScissorArrayv (GLuint first, GLsizei count, const GLint *v); +GLAPI void APIENTRY glScissorIndexed (GLuint index, GLint left, GLint bottom, GLsizei width, GLsizei height); +GLAPI void APIENTRY glScissorIndexedv (GLuint index, const GLint *v); +GLAPI void APIENTRY glDepthRangeArrayv (GLuint first, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glDepthRangeIndexed (GLuint index, GLdouble n, GLdouble f); +GLAPI void APIENTRY glGetFloati_v (GLenum target, GLuint index, GLfloat *data); +GLAPI void APIENTRY glGetDoublei_v (GLenum target, GLuint index, GLdouble *data); +#endif +#endif /* GL_VERSION_4_1 */ + +#ifndef GL_VERSION_4_2 +#define GL_VERSION_4_2 1 +#define GL_COPY_READ_BUFFER_BINDING 0x8F36 +#define GL_COPY_WRITE_BUFFER_BINDING 0x8F37 +#define GL_TRANSFORM_FEEDBACK_ACTIVE 0x8E24 +#define GL_TRANSFORM_FEEDBACK_PAUSED 0x8E23 +#define GL_UNPACK_COMPRESSED_BLOCK_WIDTH 0x9127 +#define GL_UNPACK_COMPRESSED_BLOCK_HEIGHT 0x9128 +#define GL_UNPACK_COMPRESSED_BLOCK_DEPTH 0x9129 +#define GL_UNPACK_COMPRESSED_BLOCK_SIZE 0x912A +#define GL_PACK_COMPRESSED_BLOCK_WIDTH 0x912B +#define GL_PACK_COMPRESSED_BLOCK_HEIGHT 0x912C +#define GL_PACK_COMPRESSED_BLOCK_DEPTH 0x912D +#define GL_PACK_COMPRESSED_BLOCK_SIZE 0x912E +#define GL_NUM_SAMPLE_COUNTS 0x9380 +#define GL_MIN_MAP_BUFFER_ALIGNMENT 0x90BC +#define GL_ATOMIC_COUNTER_BUFFER 0x92C0 +#define GL_ATOMIC_COUNTER_BUFFER_BINDING 0x92C1 +#define GL_ATOMIC_COUNTER_BUFFER_START 0x92C2 +#define GL_ATOMIC_COUNTER_BUFFER_SIZE 0x92C3 +#define GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE 0x92C4 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS 0x92C5 +#define GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES 0x92C6 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER 0x92C7 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER 0x92C8 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER 0x92C9 +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER 0x92CA +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER 0x92CB +#define GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS 0x92CC +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS 0x92CD +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS 0x92CE +#define GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS 0x92CF +#define GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS 0x92D0 +#define GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS 0x92D1 +#define GL_MAX_VERTEX_ATOMIC_COUNTERS 0x92D2 +#define GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS 0x92D3 +#define GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS 0x92D4 +#define GL_MAX_GEOMETRY_ATOMIC_COUNTERS 0x92D5 +#define GL_MAX_FRAGMENT_ATOMIC_COUNTERS 0x92D6 +#define GL_MAX_COMBINED_ATOMIC_COUNTERS 0x92D7 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE 0x92D8 +#define GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS 0x92DC +#define GL_ACTIVE_ATOMIC_COUNTER_BUFFERS 0x92D9 +#define GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX 0x92DA +#define GL_UNSIGNED_INT_ATOMIC_COUNTER 0x92DB +#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT 0x00000001 +#define GL_ELEMENT_ARRAY_BARRIER_BIT 0x00000002 +#define GL_UNIFORM_BARRIER_BIT 0x00000004 +#define GL_TEXTURE_FETCH_BARRIER_BIT 0x00000008 +#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT 0x00000020 +#define GL_COMMAND_BARRIER_BIT 0x00000040 +#define GL_PIXEL_BUFFER_BARRIER_BIT 0x00000080 +#define GL_TEXTURE_UPDATE_BARRIER_BIT 0x00000100 +#define GL_BUFFER_UPDATE_BARRIER_BIT 0x00000200 +#define GL_FRAMEBUFFER_BARRIER_BIT 0x00000400 +#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT 0x00000800 +#define GL_ATOMIC_COUNTER_BARRIER_BIT 0x00001000 +#define GL_ALL_BARRIER_BITS 0xFFFFFFFF +#define GL_MAX_IMAGE_UNITS 0x8F38 +#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS 0x8F39 +#define GL_IMAGE_BINDING_NAME 0x8F3A +#define GL_IMAGE_BINDING_LEVEL 0x8F3B +#define GL_IMAGE_BINDING_LAYERED 0x8F3C +#define GL_IMAGE_BINDING_LAYER 0x8F3D +#define GL_IMAGE_BINDING_ACCESS 0x8F3E +#define GL_IMAGE_1D 0x904C +#define GL_IMAGE_2D 0x904D +#define GL_IMAGE_3D 0x904E +#define GL_IMAGE_2D_RECT 0x904F +#define GL_IMAGE_CUBE 0x9050 +#define GL_IMAGE_BUFFER 0x9051 +#define GL_IMAGE_1D_ARRAY 0x9052 +#define GL_IMAGE_2D_ARRAY 0x9053 +#define GL_IMAGE_CUBE_MAP_ARRAY 0x9054 +#define GL_IMAGE_2D_MULTISAMPLE 0x9055 +#define GL_IMAGE_2D_MULTISAMPLE_ARRAY 0x9056 +#define GL_INT_IMAGE_1D 0x9057 +#define GL_INT_IMAGE_2D 0x9058 +#define GL_INT_IMAGE_3D 0x9059 +#define GL_INT_IMAGE_2D_RECT 0x905A +#define GL_INT_IMAGE_CUBE 0x905B +#define GL_INT_IMAGE_BUFFER 0x905C +#define GL_INT_IMAGE_1D_ARRAY 0x905D +#define GL_INT_IMAGE_2D_ARRAY 0x905E +#define GL_INT_IMAGE_CUBE_MAP_ARRAY 0x905F +#define GL_INT_IMAGE_2D_MULTISAMPLE 0x9060 +#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x9061 +#define GL_UNSIGNED_INT_IMAGE_1D 0x9062 +#define GL_UNSIGNED_INT_IMAGE_2D 0x9063 +#define GL_UNSIGNED_INT_IMAGE_3D 0x9064 +#define GL_UNSIGNED_INT_IMAGE_2D_RECT 0x9065 +#define GL_UNSIGNED_INT_IMAGE_CUBE 0x9066 +#define GL_UNSIGNED_INT_IMAGE_BUFFER 0x9067 +#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY 0x9068 +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY 0x9069 +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY 0x906A +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE 0x906B +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY 0x906C +#define GL_MAX_IMAGE_SAMPLES 0x906D +#define GL_IMAGE_BINDING_FORMAT 0x906E +#define GL_IMAGE_FORMAT_COMPATIBILITY_TYPE 0x90C7 +#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE 0x90C8 +#define GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS 0x90C9 +#define GL_MAX_VERTEX_IMAGE_UNIFORMS 0x90CA +#define GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS 0x90CB +#define GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS 0x90CC +#define GL_MAX_GEOMETRY_IMAGE_UNIFORMS 0x90CD +#define GL_MAX_FRAGMENT_IMAGE_UNIFORMS 0x90CE +#define GL_MAX_COMBINED_IMAGE_UNIFORMS 0x90CF +#define GL_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXBASEINSTANCEPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +typedef void (APIENTRYP PFNGLGETINTERNALFORMATIVPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); +typedef void (APIENTRYP PFNGLGETACTIVEATOMICCOUNTERBUFFERIVPROC) (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREPROC) (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +typedef void (APIENTRYP PFNGLMEMORYBARRIERPROC) (GLbitfield barriers); +typedef void (APIENTRYP PFNGLTEXSTORAGE1DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXSTORAGE2DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXSTORAGE3DPROC) (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKINSTANCEDPROC) (GLenum mode, GLuint id, GLsizei instancecount); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKSTREAMINSTANCEDPROC) (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedBaseInstance (GLenum mode, GLint first, GLsizei count, GLsizei instancecount, GLuint baseinstance); +GLAPI void APIENTRY glDrawElementsInstancedBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLuint baseinstance); +GLAPI void APIENTRY glDrawElementsInstancedBaseVertexBaseInstance (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei instancecount, GLint basevertex, GLuint baseinstance); +GLAPI void APIENTRY glGetInternalformativ (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint *params); +GLAPI void APIENTRY glGetActiveAtomicCounterBufferiv (GLuint program, GLuint bufferIndex, GLenum pname, GLint *params); +GLAPI void APIENTRY glBindImageTexture (GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format); +GLAPI void APIENTRY glMemoryBarrier (GLbitfield barriers); +GLAPI void APIENTRY glTexStorage1D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTexStorage2D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTexStorage3D (GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glDrawTransformFeedbackInstanced (GLenum mode, GLuint id, GLsizei instancecount); +GLAPI void APIENTRY glDrawTransformFeedbackStreamInstanced (GLenum mode, GLuint id, GLuint stream, GLsizei instancecount); +#endif +#endif /* GL_VERSION_4_2 */ + +#ifndef GL_VERSION_4_3 +#define GL_VERSION_4_3 1 +typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#define GL_NUM_SHADING_LANGUAGE_VERSIONS 0x82E9 +#define GL_VERTEX_ATTRIB_ARRAY_LONG 0x874E +#define GL_COMPRESSED_RGB8_ETC2 0x9274 +#define GL_COMPRESSED_SRGB8_ETC2 0x9275 +#define GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 +#define GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 +#define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#define GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 +#define GL_COMPRESSED_R11_EAC 0x9270 +#define GL_COMPRESSED_SIGNED_R11_EAC 0x9271 +#define GL_COMPRESSED_RG11_EAC 0x9272 +#define GL_COMPRESSED_SIGNED_RG11_EAC 0x9273 +#define GL_PRIMITIVE_RESTART_FIXED_INDEX 0x8D69 +#define GL_ANY_SAMPLES_PASSED_CONSERVATIVE 0x8D6A +#define GL_MAX_ELEMENT_INDEX 0x8D6B +#define GL_COMPUTE_SHADER 0x91B9 +#define GL_MAX_COMPUTE_UNIFORM_BLOCKS 0x91BB +#define GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS 0x91BC +#define GL_MAX_COMPUTE_IMAGE_UNIFORMS 0x91BD +#define GL_MAX_COMPUTE_SHARED_MEMORY_SIZE 0x8262 +#define GL_MAX_COMPUTE_UNIFORM_COMPONENTS 0x8263 +#define GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS 0x8264 +#define GL_MAX_COMPUTE_ATOMIC_COUNTERS 0x8265 +#define GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS 0x8266 +#define GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS 0x90EB +#define GL_MAX_COMPUTE_WORK_GROUP_COUNT 0x91BE +#define GL_MAX_COMPUTE_WORK_GROUP_SIZE 0x91BF +#define GL_COMPUTE_WORK_GROUP_SIZE 0x8267 +#define GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER 0x90EC +#define GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER 0x90ED +#define GL_DISPATCH_INDIRECT_BUFFER 0x90EE +#define GL_DISPATCH_INDIRECT_BUFFER_BINDING 0x90EF +#define GL_COMPUTE_SHADER_BIT 0x00000020 +#define GL_DEBUG_OUTPUT_SYNCHRONOUS 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM 0x8245 +#define GL_DEBUG_SOURCE_API 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION 0x824A +#define GL_DEBUG_SOURCE_OTHER 0x824B +#define GL_DEBUG_TYPE_ERROR 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR 0x824E +#define GL_DEBUG_TYPE_PORTABILITY 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE 0x8250 +#define GL_DEBUG_TYPE_OTHER 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES 0x9145 +#define GL_DEBUG_SEVERITY_HIGH 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM 0x9147 +#define GL_DEBUG_SEVERITY_LOW 0x9148 +#define GL_DEBUG_TYPE_MARKER 0x8268 +#define GL_DEBUG_TYPE_PUSH_GROUP 0x8269 +#define GL_DEBUG_TYPE_POP_GROUP 0x826A +#define GL_DEBUG_SEVERITY_NOTIFICATION 0x826B +#define GL_MAX_DEBUG_GROUP_STACK_DEPTH 0x826C +#define GL_DEBUG_GROUP_STACK_DEPTH 0x826D +#define GL_BUFFER 0x82E0 +#define GL_SHADER 0x82E1 +#define GL_PROGRAM 0x82E2 +#define GL_QUERY 0x82E3 +#define GL_PROGRAM_PIPELINE 0x82E4 +#define GL_SAMPLER 0x82E6 +#define GL_MAX_LABEL_LENGTH 0x82E8 +#define GL_DEBUG_OUTPUT 0x92E0 +#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 +#define GL_MAX_UNIFORM_LOCATIONS 0x826E +#define GL_FRAMEBUFFER_DEFAULT_WIDTH 0x9310 +#define GL_FRAMEBUFFER_DEFAULT_HEIGHT 0x9311 +#define GL_FRAMEBUFFER_DEFAULT_LAYERS 0x9312 +#define GL_FRAMEBUFFER_DEFAULT_SAMPLES 0x9313 +#define GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS 0x9314 +#define GL_MAX_FRAMEBUFFER_WIDTH 0x9315 +#define GL_MAX_FRAMEBUFFER_HEIGHT 0x9316 +#define GL_MAX_FRAMEBUFFER_LAYERS 0x9317 +#define GL_MAX_FRAMEBUFFER_SAMPLES 0x9318 +#define GL_INTERNALFORMAT_SUPPORTED 0x826F +#define GL_INTERNALFORMAT_PREFERRED 0x8270 +#define GL_INTERNALFORMAT_RED_SIZE 0x8271 +#define GL_INTERNALFORMAT_GREEN_SIZE 0x8272 +#define GL_INTERNALFORMAT_BLUE_SIZE 0x8273 +#define GL_INTERNALFORMAT_ALPHA_SIZE 0x8274 +#define GL_INTERNALFORMAT_DEPTH_SIZE 0x8275 +#define GL_INTERNALFORMAT_STENCIL_SIZE 0x8276 +#define GL_INTERNALFORMAT_SHARED_SIZE 0x8277 +#define GL_INTERNALFORMAT_RED_TYPE 0x8278 +#define GL_INTERNALFORMAT_GREEN_TYPE 0x8279 +#define GL_INTERNALFORMAT_BLUE_TYPE 0x827A +#define GL_INTERNALFORMAT_ALPHA_TYPE 0x827B +#define GL_INTERNALFORMAT_DEPTH_TYPE 0x827C +#define GL_INTERNALFORMAT_STENCIL_TYPE 0x827D +#define GL_MAX_WIDTH 0x827E +#define GL_MAX_HEIGHT 0x827F +#define GL_MAX_DEPTH 0x8280 +#define GL_MAX_LAYERS 0x8281 +#define GL_MAX_COMBINED_DIMENSIONS 0x8282 +#define GL_COLOR_COMPONENTS 0x8283 +#define GL_DEPTH_COMPONENTS 0x8284 +#define GL_STENCIL_COMPONENTS 0x8285 +#define GL_COLOR_RENDERABLE 0x8286 +#define GL_DEPTH_RENDERABLE 0x8287 +#define GL_STENCIL_RENDERABLE 0x8288 +#define GL_FRAMEBUFFER_RENDERABLE 0x8289 +#define GL_FRAMEBUFFER_RENDERABLE_LAYERED 0x828A +#define GL_FRAMEBUFFER_BLEND 0x828B +#define GL_READ_PIXELS 0x828C +#define GL_READ_PIXELS_FORMAT 0x828D +#define GL_READ_PIXELS_TYPE 0x828E +#define GL_TEXTURE_IMAGE_FORMAT 0x828F +#define GL_TEXTURE_IMAGE_TYPE 0x8290 +#define GL_GET_TEXTURE_IMAGE_FORMAT 0x8291 +#define GL_GET_TEXTURE_IMAGE_TYPE 0x8292 +#define GL_MIPMAP 0x8293 +#define GL_MANUAL_GENERATE_MIPMAP 0x8294 +#define GL_AUTO_GENERATE_MIPMAP 0x8295 +#define GL_COLOR_ENCODING 0x8296 +#define GL_SRGB_READ 0x8297 +#define GL_SRGB_WRITE 0x8298 +#define GL_FILTER 0x829A +#define GL_VERTEX_TEXTURE 0x829B +#define GL_TESS_CONTROL_TEXTURE 0x829C +#define GL_TESS_EVALUATION_TEXTURE 0x829D +#define GL_GEOMETRY_TEXTURE 0x829E +#define GL_FRAGMENT_TEXTURE 0x829F +#define GL_COMPUTE_TEXTURE 0x82A0 +#define GL_TEXTURE_SHADOW 0x82A1 +#define GL_TEXTURE_GATHER 0x82A2 +#define GL_TEXTURE_GATHER_SHADOW 0x82A3 +#define GL_SHADER_IMAGE_LOAD 0x82A4 +#define GL_SHADER_IMAGE_STORE 0x82A5 +#define GL_SHADER_IMAGE_ATOMIC 0x82A6 +#define GL_IMAGE_TEXEL_SIZE 0x82A7 +#define GL_IMAGE_COMPATIBILITY_CLASS 0x82A8 +#define GL_IMAGE_PIXEL_FORMAT 0x82A9 +#define GL_IMAGE_PIXEL_TYPE 0x82AA +#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST 0x82AC +#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST 0x82AD +#define GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE 0x82AE +#define GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE 0x82AF +#define GL_TEXTURE_COMPRESSED_BLOCK_WIDTH 0x82B1 +#define GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT 0x82B2 +#define GL_TEXTURE_COMPRESSED_BLOCK_SIZE 0x82B3 +#define GL_CLEAR_BUFFER 0x82B4 +#define GL_TEXTURE_VIEW 0x82B5 +#define GL_VIEW_COMPATIBILITY_CLASS 0x82B6 +#define GL_FULL_SUPPORT 0x82B7 +#define GL_CAVEAT_SUPPORT 0x82B8 +#define GL_IMAGE_CLASS_4_X_32 0x82B9 +#define GL_IMAGE_CLASS_2_X_32 0x82BA +#define GL_IMAGE_CLASS_1_X_32 0x82BB +#define GL_IMAGE_CLASS_4_X_16 0x82BC +#define GL_IMAGE_CLASS_2_X_16 0x82BD +#define GL_IMAGE_CLASS_1_X_16 0x82BE +#define GL_IMAGE_CLASS_4_X_8 0x82BF +#define GL_IMAGE_CLASS_2_X_8 0x82C0 +#define GL_IMAGE_CLASS_1_X_8 0x82C1 +#define GL_IMAGE_CLASS_11_11_10 0x82C2 +#define GL_IMAGE_CLASS_10_10_10_2 0x82C3 +#define GL_VIEW_CLASS_128_BITS 0x82C4 +#define GL_VIEW_CLASS_96_BITS 0x82C5 +#define GL_VIEW_CLASS_64_BITS 0x82C6 +#define GL_VIEW_CLASS_48_BITS 0x82C7 +#define GL_VIEW_CLASS_32_BITS 0x82C8 +#define GL_VIEW_CLASS_24_BITS 0x82C9 +#define GL_VIEW_CLASS_16_BITS 0x82CA +#define GL_VIEW_CLASS_8_BITS 0x82CB +#define GL_VIEW_CLASS_S3TC_DXT1_RGB 0x82CC +#define GL_VIEW_CLASS_S3TC_DXT1_RGBA 0x82CD +#define GL_VIEW_CLASS_S3TC_DXT3_RGBA 0x82CE +#define GL_VIEW_CLASS_S3TC_DXT5_RGBA 0x82CF +#define GL_VIEW_CLASS_RGTC1_RED 0x82D0 +#define GL_VIEW_CLASS_RGTC2_RG 0x82D1 +#define GL_VIEW_CLASS_BPTC_UNORM 0x82D2 +#define GL_VIEW_CLASS_BPTC_FLOAT 0x82D3 +#define GL_UNIFORM 0x92E1 +#define GL_UNIFORM_BLOCK 0x92E2 +#define GL_PROGRAM_INPUT 0x92E3 +#define GL_PROGRAM_OUTPUT 0x92E4 +#define GL_BUFFER_VARIABLE 0x92E5 +#define GL_SHADER_STORAGE_BLOCK 0x92E6 +#define GL_VERTEX_SUBROUTINE 0x92E8 +#define GL_TESS_CONTROL_SUBROUTINE 0x92E9 +#define GL_TESS_EVALUATION_SUBROUTINE 0x92EA +#define GL_GEOMETRY_SUBROUTINE 0x92EB +#define GL_FRAGMENT_SUBROUTINE 0x92EC +#define GL_COMPUTE_SUBROUTINE 0x92ED +#define GL_VERTEX_SUBROUTINE_UNIFORM 0x92EE +#define GL_TESS_CONTROL_SUBROUTINE_UNIFORM 0x92EF +#define GL_TESS_EVALUATION_SUBROUTINE_UNIFORM 0x92F0 +#define GL_GEOMETRY_SUBROUTINE_UNIFORM 0x92F1 +#define GL_FRAGMENT_SUBROUTINE_UNIFORM 0x92F2 +#define GL_COMPUTE_SUBROUTINE_UNIFORM 0x92F3 +#define GL_TRANSFORM_FEEDBACK_VARYING 0x92F4 +#define GL_ACTIVE_RESOURCES 0x92F5 +#define GL_MAX_NAME_LENGTH 0x92F6 +#define GL_MAX_NUM_ACTIVE_VARIABLES 0x92F7 +#define GL_MAX_NUM_COMPATIBLE_SUBROUTINES 0x92F8 +#define GL_NAME_LENGTH 0x92F9 +#define GL_TYPE 0x92FA +#define GL_ARRAY_SIZE 0x92FB +#define GL_OFFSET 0x92FC +#define GL_BLOCK_INDEX 0x92FD +#define GL_ARRAY_STRIDE 0x92FE +#define GL_MATRIX_STRIDE 0x92FF +#define GL_IS_ROW_MAJOR 0x9300 +#define GL_ATOMIC_COUNTER_BUFFER_INDEX 0x9301 +#define GL_BUFFER_BINDING 0x9302 +#define GL_BUFFER_DATA_SIZE 0x9303 +#define GL_NUM_ACTIVE_VARIABLES 0x9304 +#define GL_ACTIVE_VARIABLES 0x9305 +#define GL_REFERENCED_BY_VERTEX_SHADER 0x9306 +#define GL_REFERENCED_BY_TESS_CONTROL_SHADER 0x9307 +#define GL_REFERENCED_BY_TESS_EVALUATION_SHADER 0x9308 +#define GL_REFERENCED_BY_GEOMETRY_SHADER 0x9309 +#define GL_REFERENCED_BY_FRAGMENT_SHADER 0x930A +#define GL_REFERENCED_BY_COMPUTE_SHADER 0x930B +#define GL_TOP_LEVEL_ARRAY_SIZE 0x930C +#define GL_TOP_LEVEL_ARRAY_STRIDE 0x930D +#define GL_LOCATION 0x930E +#define GL_LOCATION_INDEX 0x930F +#define GL_IS_PER_PATCH 0x92E7 +#define GL_SHADER_STORAGE_BUFFER 0x90D2 +#define GL_SHADER_STORAGE_BUFFER_BINDING 0x90D3 +#define GL_SHADER_STORAGE_BUFFER_START 0x90D4 +#define GL_SHADER_STORAGE_BUFFER_SIZE 0x90D5 +#define GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS 0x90D6 +#define GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS 0x90D7 +#define GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS 0x90D8 +#define GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS 0x90D9 +#define GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS 0x90DA +#define GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS 0x90DB +#define GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS 0x90DC +#define GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS 0x90DD +#define GL_MAX_SHADER_STORAGE_BLOCK_SIZE 0x90DE +#define GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT 0x90DF +#define GL_SHADER_STORAGE_BARRIER_BIT 0x00002000 +#define GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES 0x8F39 +#define GL_DEPTH_STENCIL_TEXTURE_MODE 0x90EA +#define GL_TEXTURE_BUFFER_OFFSET 0x919D +#define GL_TEXTURE_BUFFER_SIZE 0x919E +#define GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT 0x919F +#define GL_TEXTURE_VIEW_MIN_LEVEL 0x82DB +#define GL_TEXTURE_VIEW_NUM_LEVELS 0x82DC +#define GL_TEXTURE_VIEW_MIN_LAYER 0x82DD +#define GL_TEXTURE_VIEW_NUM_LAYERS 0x82DE +#define GL_TEXTURE_IMMUTABLE_LEVELS 0x82DF +#define GL_VERTEX_ATTRIB_BINDING 0x82D4 +#define GL_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D5 +#define GL_VERTEX_BINDING_DIVISOR 0x82D6 +#define GL_VERTEX_BINDING_OFFSET 0x82D7 +#define GL_VERTEX_BINDING_STRIDE 0x82D8 +#define GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET 0x82D9 +#define GL_MAX_VERTEX_ATTRIB_BINDINGS 0x82DA +#define GL_VERTEX_BINDING_BUFFER 0x8F4F +#define GL_DISPLAY_LIST 0x82E7 +typedef void (APIENTRYP PFNGLCLEARBUFFERDATAPROC) (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARBUFFERSUBDATAPROC) (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEINDIRECTPROC) (GLintptr indirect); +typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATAPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +typedef void (APIENTRYP PFNGLFRAMEBUFFERPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETINTERNALFORMATI64VPROC) (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params); +typedef void (APIENTRYP PFNGLINVALIDATETEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLINVALIDATETEXIMAGEPROC) (GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLINVALIDATEBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLINVALIDATEBUFFERDATAPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLINVALIDATEFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments); +typedef void (APIENTRYP PFNGLINVALIDATESUBFRAMEBUFFERPROC) (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTPROC) (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLGETPROGRAMINTERFACEIVPROC) (GLuint program, GLenum programInterface, GLenum pname, GLint *params); +typedef GLuint (APIENTRYP PFNGLGETPROGRAMRESOURCEINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCENAMEPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEIVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params); +typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETPROGRAMRESOURCELOCATIONINDEXPROC) (GLuint program, GLenum programInterface, const GLchar *name); +typedef void (APIENTRYP PFNGLSHADERSTORAGEBLOCKBINDINGPROC) (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); +typedef void (APIENTRYP PFNGLTEXBUFFERRANGEPROC) (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLTEXSTORAGE2DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXSTORAGE3DMULTISAMPLEPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTUREVIEWPROC) (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERPROC) (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATPROC) (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXATTRIBBINDINGPROC) (GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXBINDINGDIVISORPROC) (GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC) (GLDEBUGPROC callback, const void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +typedef void (APIENTRYP PFNGLPUSHDEBUGGROUPPROC) (GLenum source, GLuint id, GLsizei length, const GLchar *message); +typedef void (APIENTRYP PFNGLPOPDEBUGGROUPPROC) (void); +typedef void (APIENTRYP PFNGLOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTLABELPROC) (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +typedef void (APIENTRYP PFNGLOBJECTPTRLABELPROC) (const void *ptr, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTPTRLABELPROC) (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClearBufferData (GLenum target, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearBufferSubData (GLenum target, GLenum internalformat, GLintptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glDispatchCompute (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z); +GLAPI void APIENTRY glDispatchComputeIndirect (GLintptr indirect); +GLAPI void APIENTRY glCopyImageSubData (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei srcWidth, GLsizei srcHeight, GLsizei srcDepth); +GLAPI void APIENTRY glFramebufferParameteri (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glGetFramebufferParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetInternalformati64v (GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint64 *params); +GLAPI void APIENTRY glInvalidateTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glInvalidateTexImage (GLuint texture, GLint level); +GLAPI void APIENTRY glInvalidateBufferSubData (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glInvalidateBufferData (GLuint buffer); +GLAPI void APIENTRY glInvalidateFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments); +GLAPI void APIENTRY glInvalidateSubFramebuffer (GLenum target, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glMultiDrawArraysIndirect (GLenum mode, const void *indirect, GLsizei drawcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirect (GLenum mode, GLenum type, const void *indirect, GLsizei drawcount, GLsizei stride); +GLAPI void APIENTRY glGetProgramInterfaceiv (GLuint program, GLenum programInterface, GLenum pname, GLint *params); +GLAPI GLuint APIENTRY glGetProgramResourceIndex (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI void APIENTRY glGetProgramResourceName (GLuint program, GLenum programInterface, GLuint index, GLsizei bufSize, GLsizei *length, GLchar *name); +GLAPI void APIENTRY glGetProgramResourceiv (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLint *params); +GLAPI GLint APIENTRY glGetProgramResourceLocation (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI GLint APIENTRY glGetProgramResourceLocationIndex (GLuint program, GLenum programInterface, const GLchar *name); +GLAPI void APIENTRY glShaderStorageBlockBinding (GLuint program, GLuint storageBlockIndex, GLuint storageBlockBinding); +GLAPI void APIENTRY glTexBufferRange (GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glTexStorage2DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTexStorage3DMultisample (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureView (GLuint texture, GLenum target, GLuint origtexture, GLenum internalformat, GLuint minlevel, GLuint numlevels, GLuint minlayer, GLuint numlayers); +GLAPI void APIENTRY glBindVertexBuffer (GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexAttribFormat (GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribIFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribLFormat (GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexAttribBinding (GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexBindingDivisor (GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glDebugMessageControl (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsert (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallback (GLDEBUGPROC callback, const void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLog (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +GLAPI void APIENTRY glPushDebugGroup (GLenum source, GLuint id, GLsizei length, const GLchar *message); +GLAPI void APIENTRY glPopDebugGroup (void); +GLAPI void APIENTRY glObjectLabel (GLenum identifier, GLuint name, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectLabel (GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); +GLAPI void APIENTRY glObjectPtrLabel (const void *ptr, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectPtrLabel (const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); +#endif +#endif /* GL_VERSION_4_3 */ + +#ifndef GL_VERSION_4_4 +#define GL_VERSION_4_4 1 +#define GL_MAX_VERTEX_ATTRIB_STRIDE 0x82E5 +#define GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED 0x8221 +#define GL_TEXTURE_BUFFER_BINDING 0x8C2A +#define GL_MAP_PERSISTENT_BIT 0x0040 +#define GL_MAP_COHERENT_BIT 0x0080 +#define GL_DYNAMIC_STORAGE_BIT 0x0100 +#define GL_CLIENT_STORAGE_BIT 0x0200 +#define GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT 0x00004000 +#define GL_BUFFER_IMMUTABLE_STORAGE 0x821F +#define GL_BUFFER_STORAGE_FLAGS 0x8220 +#define GL_CLEAR_TEXTURE 0x9365 +#define GL_LOCATION_COMPONENT 0x934A +#define GL_TRANSFORM_FEEDBACK_BUFFER_INDEX 0x934B +#define GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE 0x934C +#define GL_QUERY_BUFFER 0x9192 +#define GL_QUERY_BUFFER_BARRIER_BIT 0x00008000 +#define GL_QUERY_BUFFER_BINDING 0x9193 +#define GL_QUERY_RESULT_NO_WAIT 0x9194 +#define GL_MIRROR_CLAMP_TO_EDGE 0x8743 +typedef void (APIENTRYP PFNGLBUFFERSTORAGEPROC) (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLCLEARTEXIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARTEXSUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLBINDBUFFERSBASEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers); +typedef void (APIENTRYP PFNGLBINDBUFFERSRANGEPROC) (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); +typedef void (APIENTRYP PFNGLBINDTEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures); +typedef void (APIENTRYP PFNGLBINDSAMPLERSPROC) (GLuint first, GLsizei count, const GLuint *samplers); +typedef void (APIENTRYP PFNGLBINDIMAGETEXTURESPROC) (GLuint first, GLsizei count, const GLuint *textures); +typedef void (APIENTRYP PFNGLBINDVERTEXBUFFERSPROC) (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferStorage (GLenum target, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glClearTexImage (GLuint texture, GLint level, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearTexSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glBindBuffersBase (GLenum target, GLuint first, GLsizei count, const GLuint *buffers); +GLAPI void APIENTRY glBindBuffersRange (GLenum target, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizeiptr *sizes); +GLAPI void APIENTRY glBindTextures (GLuint first, GLsizei count, const GLuint *textures); +GLAPI void APIENTRY glBindSamplers (GLuint first, GLsizei count, const GLuint *samplers); +GLAPI void APIENTRY glBindImageTextures (GLuint first, GLsizei count, const GLuint *textures); +GLAPI void APIENTRY glBindVertexBuffers (GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +#endif +#endif /* GL_VERSION_4_4 */ + +#ifndef GL_VERSION_4_5 +#define GL_VERSION_4_5 1 +#define GL_CONTEXT_LOST 0x0507 +#define GL_NEGATIVE_ONE_TO_ONE 0x935E +#define GL_ZERO_TO_ONE 0x935F +#define GL_CLIP_ORIGIN 0x935C +#define GL_CLIP_DEPTH_MODE 0x935D +#define GL_QUERY_WAIT_INVERTED 0x8E17 +#define GL_QUERY_NO_WAIT_INVERTED 0x8E18 +#define GL_QUERY_BY_REGION_WAIT_INVERTED 0x8E19 +#define GL_QUERY_BY_REGION_NO_WAIT_INVERTED 0x8E1A +#define GL_MAX_CULL_DISTANCES 0x82F9 +#define GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES 0x82FA +#define GL_TEXTURE_TARGET 0x1006 +#define GL_QUERY_TARGET 0x82EA +#define GL_TEXTURE_BINDING 0x82EB +#define GL_GUILTY_CONTEXT_RESET 0x8253 +#define GL_INNOCENT_CONTEXT_RESET 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET 0x8255 +#define GL_RESET_NOTIFICATION_STRATEGY 0x8256 +#define GL_LOSE_CONTEXT_ON_RESET 0x8252 +#define GL_NO_RESET_NOTIFICATION 0x8261 +#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT 0x00000004 +#define GL_CONTEXT_RELEASE_BEHAVIOR 0x82FB +#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82FC +typedef void (APIENTRYP PFNGLCLIPCONTROLPROC) (GLenum origin, GLenum depth); +typedef void (APIENTRYP PFNGLCREATETRANSFORMFEEDBACKSPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERBASEPROC) (GLuint xfb, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKBUFFERRANGEPROC) (GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizei size); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKIVPROC) (GLuint xfb, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); +typedef void (APIENTRYP PFNGLCREATEBUFFERSPROC) (GLsizei n, GLuint *buffers); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEPROC) (GLuint buffer, GLsizei size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAPROC) (GLuint buffer, GLsizei size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizei size, const void *data); +typedef void (APIENTRYP PFNGLCOPYNAMEDBUFFERSUBDATAPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizei size); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLenum internalformat, GLintptr offset, GLsizei size, GLenum format, GLenum type, const void *data); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERPROC) (GLuint buffer, GLenum access); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEPROC) (GLuint buffer, GLintptr offset, GLsizei length, GLbitfield access); +typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFERPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEPROC) (GLuint buffer, GLintptr offset, GLsizei length); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERI64VPROC) (GLuint buffer, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVPROC) (GLuint buffer, GLenum pname, void **params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAPROC) (GLuint buffer, GLintptr offset, GLsizei size, void *data); +typedef void (APIENTRYP PFNGLCREATEFRAMEBUFFERSPROC) (GLsizei n, GLuint *framebuffers); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFERPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIPROC) (GLuint framebuffer, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYERPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERPROC) (GLuint framebuffer, GLenum buf); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERDRAWBUFFERSPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERREADBUFFERPROC) (GLuint framebuffer, GLenum src); +typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERDATAPROC) (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); +typedef void (APIENTRYP PFNGLINVALIDATENAMEDFRAMEBUFFERSUBDATAPROC) (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERIVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERUIVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFVPROC) (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); +typedef void (APIENTRYP PFNGLCLEARNAMEDFRAMEBUFFERFIPROC) (GLuint framebuffer, GLenum buffer, const GLfloat depth, GLint stencil); +typedef void (APIENTRYP PFNGLBLITNAMEDFRAMEBUFFERPROC) (GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSPROC) (GLuint framebuffer, GLenum target); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVPROC) (GLuint framebuffer, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATERENDERBUFFERSPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVPROC) (GLuint renderbuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATETEXTURESPROC) (GLenum target, GLsizei n, GLuint *textures); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERPROC) (GLuint texture, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEPROC) (GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizei size); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DPROC) (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEPROC) (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEPROC) (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DPROC) (GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFPROC) (GLuint texture, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVPROC) (GLuint texture, GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIPROC) (GLuint texture, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVPROC) (GLuint texture, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVPROC) (GLuint texture, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVPROC) (GLuint texture, GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLBINDTEXTUREUNITPROC) (GLuint unit, GLuint texture); +typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEPROC) (GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEPROC) (GLuint texture, GLint level, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVPROC) (GLuint texture, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVPROC) (GLuint texture, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVPROC) (GLuint texture, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVPROC) (GLuint texture, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVPROC) (GLuint texture, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVPROC) (GLuint texture, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCREATEVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLVERTEXARRAYELEMENTBUFFERPROC) (GLuint vaobj, GLuint buffer); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBUFFERSPROC) (GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBBINDINGPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBIFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYATTRIBLFORMATPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYBINDINGDIVISORPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYIVPROC) (GLuint vaobj, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXEDIVPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINDEXED64IVPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); +typedef void (APIENTRYP PFNGLCREATESAMPLERSPROC) (GLsizei n, GLuint *samplers); +typedef void (APIENTRYP PFNGLCREATEPROGRAMPIPELINESPROC) (GLsizei n, GLuint *pipelines); +typedef void (APIENTRYP PFNGLCREATEQUERIESPROC) (GLenum target, GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTI64VPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTIVPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUI64VPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLGETQUERYBUFFEROBJECTUIVPROC) (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +typedef void (APIENTRYP PFNGLMEMORYBARRIERBYREGIONPROC) (GLbitfield barriers); +typedef void (APIENTRYP PFNGLGETTEXTURESUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTURESUBIMAGEPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); +typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSPROC) (void); +typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint lod, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETNTEXIMAGEPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +typedef void (APIENTRYP PFNGLGETNUNIFORMDVPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMFVPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMIVPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMUIVPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +typedef void (APIENTRYP PFNGLREADNPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +typedef void (APIENTRYP PFNGLGETNMAPDVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +typedef void (APIENTRYP PFNGLGETNMAPFVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +typedef void (APIENTRYP PFNGLGETNMAPIVPROC) (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +typedef void (APIENTRYP PFNGLGETNPIXELMAPFVPROC) (GLenum map, GLsizei bufSize, GLfloat *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVPROC) (GLenum map, GLsizei bufSize, GLuint *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVPROC) (GLenum map, GLsizei bufSize, GLushort *values); +typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEPROC) (GLsizei bufSize, GLubyte *pattern); +typedef void (APIENTRYP PFNGLGETNCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +typedef void (APIENTRYP PFNGLGETNHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLGETNMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLTEXTUREBARRIERPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClipControl (GLenum origin, GLenum depth); +GLAPI void APIENTRY glCreateTransformFeedbacks (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glTransformFeedbackBufferBase (GLuint xfb, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackBufferRange (GLuint xfb, GLuint index, GLuint buffer, GLintptr offset, GLsizei size); +GLAPI void APIENTRY glGetTransformFeedbackiv (GLuint xfb, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetTransformFeedbacki_v (GLuint xfb, GLenum pname, GLuint index, GLint *param); +GLAPI void APIENTRY glGetTransformFeedbacki64_v (GLuint xfb, GLenum pname, GLuint index, GLint64 *param); +GLAPI void APIENTRY glCreateBuffers (GLsizei n, GLuint *buffers); +GLAPI void APIENTRY glNamedBufferStorage (GLuint buffer, GLsizei size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glNamedBufferData (GLuint buffer, GLsizei size, const void *data, GLenum usage); +GLAPI void APIENTRY glNamedBufferSubData (GLuint buffer, GLintptr offset, GLsizei size, const void *data); +GLAPI void APIENTRY glCopyNamedBufferSubData (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizei size); +GLAPI void APIENTRY glClearNamedBufferData (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearNamedBufferSubData (GLuint buffer, GLenum internalformat, GLintptr offset, GLsizei size, GLenum format, GLenum type, const void *data); +GLAPI void *APIENTRY glMapNamedBuffer (GLuint buffer, GLenum access); +GLAPI void *APIENTRY glMapNamedBufferRange (GLuint buffer, GLintptr offset, GLsizei length, GLbitfield access); +GLAPI GLboolean APIENTRY glUnmapNamedBuffer (GLuint buffer); +GLAPI void APIENTRY glFlushMappedNamedBufferRange (GLuint buffer, GLintptr offset, GLsizei length); +GLAPI void APIENTRY glGetNamedBufferParameteriv (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedBufferParameteri64v (GLuint buffer, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetNamedBufferPointerv (GLuint buffer, GLenum pname, void **params); +GLAPI void APIENTRY glGetNamedBufferSubData (GLuint buffer, GLintptr offset, GLsizei size, void *data); +GLAPI void APIENTRY glCreateFramebuffers (GLsizei n, GLuint *framebuffers); +GLAPI void APIENTRY glNamedFramebufferRenderbuffer (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glNamedFramebufferParameteri (GLuint framebuffer, GLenum pname, GLint param); +GLAPI void APIENTRY glNamedFramebufferTexture (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTextureLayer (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glNamedFramebufferDrawBuffer (GLuint framebuffer, GLenum buf); +GLAPI void APIENTRY glNamedFramebufferDrawBuffers (GLuint framebuffer, GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glNamedFramebufferReadBuffer (GLuint framebuffer, GLenum src); +GLAPI void APIENTRY glInvalidateNamedFramebufferData (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments); +GLAPI void APIENTRY glInvalidateNamedFramebufferSubData (GLuint framebuffer, GLsizei numAttachments, const GLenum *attachments, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glClearNamedFramebufferiv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLint *value); +GLAPI void APIENTRY glClearNamedFramebufferuiv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLuint *value); +GLAPI void APIENTRY glClearNamedFramebufferfv (GLuint framebuffer, GLenum buffer, GLint drawbuffer, const GLfloat *value); +GLAPI void APIENTRY glClearNamedFramebufferfi (GLuint framebuffer, GLenum buffer, const GLfloat depth, GLint stencil); +GLAPI void APIENTRY glBlitNamedFramebuffer (GLuint readFramebuffer, GLuint drawFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +GLAPI GLenum APIENTRY glCheckNamedFramebufferStatus (GLuint framebuffer, GLenum target); +GLAPI void APIENTRY glGetNamedFramebufferParameteriv (GLuint framebuffer, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameteriv (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateRenderbuffers (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glNamedRenderbufferStorage (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisample (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetNamedRenderbufferParameteriv (GLuint renderbuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateTextures (GLenum target, GLsizei n, GLuint *textures); +GLAPI void APIENTRY glTextureBuffer (GLuint texture, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glTextureBufferRange (GLuint texture, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizei size); +GLAPI void APIENTRY glTextureStorage1D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTextureStorage2D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureStorage3D (GLuint texture, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glTextureStorage2DMultisample (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureStorage3DMultisample (GLuint texture, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCompressedTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCopyTextureSubImage1D (GLuint texture, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTextureSubImage2D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glCopyTextureSubImage3D (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureParameterf (GLuint texture, GLenum pname, GLfloat param); +GLAPI void APIENTRY glTextureParameterfv (GLuint texture, GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glTextureParameteri (GLuint texture, GLenum pname, GLint param); +GLAPI void APIENTRY glTextureParameterIiv (GLuint texture, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureParameterIuiv (GLuint texture, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glTextureParameteriv (GLuint texture, GLenum pname, const GLint *param); +GLAPI void APIENTRY glGenerateTextureMipmap (GLuint texture); +GLAPI void APIENTRY glBindTextureUnit (GLuint unit, GLuint texture); +GLAPI void APIENTRY glGetTextureImage (GLuint texture, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetCompressedTextureImage (GLuint texture, GLint level, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetTextureLevelParameterfv (GLuint texture, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureLevelParameteriv (GLuint texture, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterfv (GLuint texture, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureParameterIiv (GLuint texture, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterIuiv (GLuint texture, GLenum pname, GLuint *params); +GLAPI void APIENTRY glGetTextureParameteriv (GLuint texture, GLenum pname, GLint *params); +GLAPI void APIENTRY glCreateVertexArrays (GLsizei n, GLuint *arrays); +GLAPI void APIENTRY glDisableVertexArrayAttrib (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glEnableVertexArrayAttrib (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glVertexArrayElementBuffer (GLuint vaobj, GLuint buffer); +GLAPI void APIENTRY glVertexArrayVertexBuffer (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexArrayVertexBuffers (GLuint vaobj, GLuint first, GLsizei count, const GLuint *buffers, const GLintptr *offsets, const GLsizei *strides); +GLAPI void APIENTRY glVertexArrayAttribBinding (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexArrayAttribFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayAttribIFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayAttribLFormat (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayBindingDivisor (GLuint vaobj, GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glGetVertexArrayiv (GLuint vaobj, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayIndexediv (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayIndexed64iv (GLuint vaobj, GLuint index, GLenum pname, GLint64 *param); +GLAPI void APIENTRY glCreateSamplers (GLsizei n, GLuint *samplers); +GLAPI void APIENTRY glCreateProgramPipelines (GLsizei n, GLuint *pipelines); +GLAPI void APIENTRY glCreateQueries (GLenum target, GLsizei n, GLuint *ids); +GLAPI void APIENTRY glGetQueryBufferObjecti64v (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectiv (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectui64v (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glGetQueryBufferObjectuiv (GLuint id, GLuint buffer, GLenum pname, GLintptr offset); +GLAPI void APIENTRY glMemoryBarrierByRegion (GLbitfield barriers); +GLAPI void APIENTRY glGetTextureSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetCompressedTextureSubImage (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei bufSize, void *pixels); +GLAPI GLenum APIENTRY glGetGraphicsResetStatus (void); +GLAPI void APIENTRY glGetnCompressedTexImage (GLenum target, GLint lod, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetnTexImage (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *pixels); +GLAPI void APIENTRY glGetnUniformdv (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +GLAPI void APIENTRY glGetnUniformfv (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GLAPI void APIENTRY glGetnUniformiv (GLuint program, GLint location, GLsizei bufSize, GLint *params); +GLAPI void APIENTRY glGetnUniformuiv (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +GLAPI void APIENTRY glReadnPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GLAPI void APIENTRY glGetnMapdv (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +GLAPI void APIENTRY glGetnMapfv (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +GLAPI void APIENTRY glGetnMapiv (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +GLAPI void APIENTRY glGetnPixelMapfv (GLenum map, GLsizei bufSize, GLfloat *values); +GLAPI void APIENTRY glGetnPixelMapuiv (GLenum map, GLsizei bufSize, GLuint *values); +GLAPI void APIENTRY glGetnPixelMapusv (GLenum map, GLsizei bufSize, GLushort *values); +GLAPI void APIENTRY glGetnPolygonStipple (GLsizei bufSize, GLubyte *pattern); +GLAPI void APIENTRY glGetnColorTable (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +GLAPI void APIENTRY glGetnConvolutionFilter (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +GLAPI void APIENTRY glGetnSeparableFilter (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +GLAPI void APIENTRY glGetnHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glGetnMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glTextureBarrier (void); +#endif +#endif /* GL_VERSION_4_5 */ + +#ifndef GL_ARB_ES2_compatibility +#define GL_ARB_ES2_compatibility 1 +#endif /* GL_ARB_ES2_compatibility */ + +#ifndef GL_ARB_ES3_1_compatibility +#define GL_ARB_ES3_1_compatibility 1 +#endif /* GL_ARB_ES3_1_compatibility */ + +#ifndef GL_ARB_ES3_compatibility +#define GL_ARB_ES3_compatibility 1 +#endif /* GL_ARB_ES3_compatibility */ + +#ifndef GL_ARB_arrays_of_arrays +#define GL_ARB_arrays_of_arrays 1 +#endif /* GL_ARB_arrays_of_arrays */ + +#ifndef GL_ARB_base_instance +#define GL_ARB_base_instance 1 +#endif /* GL_ARB_base_instance */ + +#ifndef GL_ARB_bindless_texture +#define GL_ARB_bindless_texture 1 +typedef uint64_t GLuint64EXT; +#define GL_UNSIGNED_INT64_ARB 0x140F +typedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLEARBPROC) (GLuint texture); +typedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLEARBPROC) (GLuint texture, GLuint sampler); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTARBPROC) (GLuint64 handle); +typedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLEARBPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle, GLenum access); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64ARBPROC) (GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VARBPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64ARBPROC) (GLuint program, GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VARBPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTARBPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64ARBPROC) (GLuint index, GLuint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VARBPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VARBPROC) (GLuint index, GLenum pname, GLuint64EXT *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint64 APIENTRY glGetTextureHandleARB (GLuint texture); +GLAPI GLuint64 APIENTRY glGetTextureSamplerHandleARB (GLuint texture, GLuint sampler); +GLAPI void APIENTRY glMakeTextureHandleResidentARB (GLuint64 handle); +GLAPI void APIENTRY glMakeTextureHandleNonResidentARB (GLuint64 handle); +GLAPI GLuint64 APIENTRY glGetImageHandleARB (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +GLAPI void APIENTRY glMakeImageHandleResidentARB (GLuint64 handle, GLenum access); +GLAPI void APIENTRY glMakeImageHandleNonResidentARB (GLuint64 handle); +GLAPI void APIENTRY glUniformHandleui64ARB (GLint location, GLuint64 value); +GLAPI void APIENTRY glUniformHandleui64vARB (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniformHandleui64ARB (GLuint program, GLint location, GLuint64 value); +GLAPI void APIENTRY glProgramUniformHandleui64vARB (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +GLAPI GLboolean APIENTRY glIsTextureHandleResidentARB (GLuint64 handle); +GLAPI GLboolean APIENTRY glIsImageHandleResidentARB (GLuint64 handle); +GLAPI void APIENTRY glVertexAttribL1ui64ARB (GLuint index, GLuint64EXT x); +GLAPI void APIENTRY glVertexAttribL1ui64vARB (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glGetVertexAttribLui64vARB (GLuint index, GLenum pname, GLuint64EXT *params); +#endif +#endif /* GL_ARB_bindless_texture */ + +#ifndef GL_ARB_blend_func_extended +#define GL_ARB_blend_func_extended 1 +#endif /* GL_ARB_blend_func_extended */ + +#ifndef GL_ARB_buffer_storage +#define GL_ARB_buffer_storage 1 +#endif /* GL_ARB_buffer_storage */ + +#ifndef GL_ARB_cl_event +#define GL_ARB_cl_event 1 +struct _cl_context; +struct _cl_event; +#define GL_SYNC_CL_EVENT_ARB 0x8240 +#define GL_SYNC_CL_EVENT_COMPLETE_ARB 0x8241 +typedef GLsync (APIENTRYP PFNGLCREATESYNCFROMCLEVENTARBPROC) (struct _cl_context *context, struct _cl_event *event, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLsync APIENTRY glCreateSyncFromCLeventARB (struct _cl_context *context, struct _cl_event *event, GLbitfield flags); +#endif +#endif /* GL_ARB_cl_event */ + +#ifndef GL_ARB_clear_buffer_object +#define GL_ARB_clear_buffer_object 1 +#endif /* GL_ARB_clear_buffer_object */ + +#ifndef GL_ARB_clear_texture +#define GL_ARB_clear_texture 1 +#endif /* GL_ARB_clear_texture */ + +#ifndef GL_ARB_clip_control +#define GL_ARB_clip_control 1 +#endif /* GL_ARB_clip_control */ + +#ifndef GL_ARB_color_buffer_float +#define GL_ARB_color_buffer_float 1 +#define GL_RGBA_FLOAT_MODE_ARB 0x8820 +#define GL_CLAMP_VERTEX_COLOR_ARB 0x891A +#define GL_CLAMP_FRAGMENT_COLOR_ARB 0x891B +#define GL_CLAMP_READ_COLOR_ARB 0x891C +#define GL_FIXED_ONLY_ARB 0x891D +typedef void (APIENTRYP PFNGLCLAMPCOLORARBPROC) (GLenum target, GLenum clamp); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClampColorARB (GLenum target, GLenum clamp); +#endif +#endif /* GL_ARB_color_buffer_float */ + +#ifndef GL_ARB_compatibility +#define GL_ARB_compatibility 1 +#endif /* GL_ARB_compatibility */ + +#ifndef GL_ARB_compressed_texture_pixel_storage +#define GL_ARB_compressed_texture_pixel_storage 1 +#endif /* GL_ARB_compressed_texture_pixel_storage */ + +#ifndef GL_ARB_compute_shader +#define GL_ARB_compute_shader 1 +#endif /* GL_ARB_compute_shader */ + +#ifndef GL_ARB_compute_variable_group_size +#define GL_ARB_compute_variable_group_size 1 +#define GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB 0x9344 +#define GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB 0x90EB +#define GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB 0x9345 +#define GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB 0x91BF +typedef void (APIENTRYP PFNGLDISPATCHCOMPUTEGROUPSIZEARBPROC) (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDispatchComputeGroupSizeARB (GLuint num_groups_x, GLuint num_groups_y, GLuint num_groups_z, GLuint group_size_x, GLuint group_size_y, GLuint group_size_z); +#endif +#endif /* GL_ARB_compute_variable_group_size */ + +#ifndef GL_ARB_conditional_render_inverted +#define GL_ARB_conditional_render_inverted 1 +#endif /* GL_ARB_conditional_render_inverted */ + +#ifndef GL_ARB_conservative_depth +#define GL_ARB_conservative_depth 1 +#endif /* GL_ARB_conservative_depth */ + +#ifndef GL_ARB_copy_buffer +#define GL_ARB_copy_buffer 1 +#endif /* GL_ARB_copy_buffer */ + +#ifndef GL_ARB_copy_image +#define GL_ARB_copy_image 1 +#endif /* GL_ARB_copy_image */ + +#ifndef GL_ARB_cull_distance +#define GL_ARB_cull_distance 1 +#endif /* GL_ARB_cull_distance */ + +#ifndef GL_ARB_debug_output +#define GL_ARB_debug_output 1 +typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam); +#define GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242 +#define GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243 +#define GL_DEBUG_CALLBACK_FUNCTION_ARB 0x8244 +#define GL_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245 +#define GL_DEBUG_SOURCE_API_ARB 0x8246 +#define GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247 +#define GL_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248 +#define GL_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249 +#define GL_DEBUG_SOURCE_APPLICATION_ARB 0x824A +#define GL_DEBUG_SOURCE_OTHER_ARB 0x824B +#define GL_DEBUG_TYPE_ERROR_ARB 0x824C +#define GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D +#define GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E +#define GL_DEBUG_TYPE_PORTABILITY_ARB 0x824F +#define GL_DEBUG_TYPE_PERFORMANCE_ARB 0x8250 +#define GL_DEBUG_TYPE_OTHER_ARB 0x8251 +#define GL_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES_ARB 0x9145 +#define GL_DEBUG_SEVERITY_HIGH_ARB 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM_ARB 0x9147 +#define GL_DEBUG_SEVERITY_LOW_ARB 0x9148 +typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLARBPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTARBPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKARBPROC) (GLDEBUGPROCARB callback, const void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGARBPROC) (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDebugMessageControlARB (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsertARB (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallbackARB (GLDEBUGPROCARB callback, const void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLogARB (GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); +#endif +#endif /* GL_ARB_debug_output */ + +#ifndef GL_ARB_depth_buffer_float +#define GL_ARB_depth_buffer_float 1 +#endif /* GL_ARB_depth_buffer_float */ + +#ifndef GL_ARB_depth_clamp +#define GL_ARB_depth_clamp 1 +#endif /* GL_ARB_depth_clamp */ + +#ifndef GL_ARB_depth_texture +#define GL_ARB_depth_texture 1 +#define GL_DEPTH_COMPONENT16_ARB 0x81A5 +#define GL_DEPTH_COMPONENT24_ARB 0x81A6 +#define GL_DEPTH_COMPONENT32_ARB 0x81A7 +#define GL_TEXTURE_DEPTH_SIZE_ARB 0x884A +#define GL_DEPTH_TEXTURE_MODE_ARB 0x884B +#endif /* GL_ARB_depth_texture */ + +#ifndef GL_ARB_derivative_control +#define GL_ARB_derivative_control 1 +#endif /* GL_ARB_derivative_control */ + +#ifndef GL_ARB_direct_state_access +#define GL_ARB_direct_state_access 1 +#endif /* GL_ARB_direct_state_access */ + +#ifndef GL_ARB_draw_buffers +#define GL_ARB_draw_buffers 1 +#define GL_MAX_DRAW_BUFFERS_ARB 0x8824 +#define GL_DRAW_BUFFER0_ARB 0x8825 +#define GL_DRAW_BUFFER1_ARB 0x8826 +#define GL_DRAW_BUFFER2_ARB 0x8827 +#define GL_DRAW_BUFFER3_ARB 0x8828 +#define GL_DRAW_BUFFER4_ARB 0x8829 +#define GL_DRAW_BUFFER5_ARB 0x882A +#define GL_DRAW_BUFFER6_ARB 0x882B +#define GL_DRAW_BUFFER7_ARB 0x882C +#define GL_DRAW_BUFFER8_ARB 0x882D +#define GL_DRAW_BUFFER9_ARB 0x882E +#define GL_DRAW_BUFFER10_ARB 0x882F +#define GL_DRAW_BUFFER11_ARB 0x8830 +#define GL_DRAW_BUFFER12_ARB 0x8831 +#define GL_DRAW_BUFFER13_ARB 0x8832 +#define GL_DRAW_BUFFER14_ARB 0x8833 +#define GL_DRAW_BUFFER15_ARB 0x8834 +typedef void (APIENTRYP PFNGLDRAWBUFFERSARBPROC) (GLsizei n, const GLenum *bufs); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawBuffersARB (GLsizei n, const GLenum *bufs); +#endif +#endif /* GL_ARB_draw_buffers */ + +#ifndef GL_ARB_draw_buffers_blend +#define GL_ARB_draw_buffers_blend 1 +typedef void (APIENTRYP PFNGLBLENDEQUATIONIARBPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEIARBPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +typedef void (APIENTRYP PFNGLBLENDFUNCIARBPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEIARBPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationiARB (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparateiARB (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +GLAPI void APIENTRY glBlendFunciARB (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparateiARB (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +#endif +#endif /* GL_ARB_draw_buffers_blend */ + +#ifndef GL_ARB_draw_elements_base_vertex +#define GL_ARB_draw_elements_base_vertex 1 +#endif /* GL_ARB_draw_elements_base_vertex */ + +#ifndef GL_ARB_draw_indirect +#define GL_ARB_draw_indirect 1 +#endif /* GL_ARB_draw_indirect */ + +#ifndef GL_ARB_draw_instanced +#define GL_ARB_draw_instanced 1 +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDARBPROC) (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDARBPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedARB (GLenum mode, GLint first, GLsizei count, GLsizei primcount); +GLAPI void APIENTRY glDrawElementsInstancedARB (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#endif +#endif /* GL_ARB_draw_instanced */ + +#ifndef GL_ARB_enhanced_layouts +#define GL_ARB_enhanced_layouts 1 +#endif /* GL_ARB_enhanced_layouts */ + +#ifndef GL_ARB_explicit_attrib_location +#define GL_ARB_explicit_attrib_location 1 +#endif /* GL_ARB_explicit_attrib_location */ + +#ifndef GL_ARB_explicit_uniform_location +#define GL_ARB_explicit_uniform_location 1 +#endif /* GL_ARB_explicit_uniform_location */ + +#ifndef GL_ARB_fragment_coord_conventions +#define GL_ARB_fragment_coord_conventions 1 +#endif /* GL_ARB_fragment_coord_conventions */ + +#ifndef GL_ARB_fragment_layer_viewport +#define GL_ARB_fragment_layer_viewport 1 +#endif /* GL_ARB_fragment_layer_viewport */ + +#ifndef GL_ARB_fragment_program +#define GL_ARB_fragment_program 1 +#define GL_FRAGMENT_PROGRAM_ARB 0x8804 +#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 +#define GL_PROGRAM_LENGTH_ARB 0x8627 +#define GL_PROGRAM_FORMAT_ARB 0x8876 +#define GL_PROGRAM_BINDING_ARB 0x8677 +#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 +#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 +#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 +#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 +#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 +#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 +#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 +#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 +#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 +#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 +#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA +#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB +#define GL_PROGRAM_ATTRIBS_ARB 0x88AC +#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD +#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE +#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF +#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 +#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 +#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 +#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 +#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 +#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 +#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 +#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 +#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A +#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B +#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C +#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D +#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E +#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F +#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 +#define GL_PROGRAM_STRING_ARB 0x8628 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_CURRENT_MATRIX_ARB 0x8641 +#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 +#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 +#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F +#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E +#define GL_MAX_TEXTURE_COORDS_ARB 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_MATRIX0_ARB 0x88C0 +#define GL_MATRIX1_ARB 0x88C1 +#define GL_MATRIX2_ARB 0x88C2 +#define GL_MATRIX3_ARB 0x88C3 +#define GL_MATRIX4_ARB 0x88C4 +#define GL_MATRIX5_ARB 0x88C5 +#define GL_MATRIX6_ARB 0x88C6 +#define GL_MATRIX7_ARB 0x88C7 +#define GL_MATRIX8_ARB 0x88C8 +#define GL_MATRIX9_ARB 0x88C9 +#define GL_MATRIX10_ARB 0x88CA +#define GL_MATRIX11_ARB 0x88CB +#define GL_MATRIX12_ARB 0x88CC +#define GL_MATRIX13_ARB 0x88CD +#define GL_MATRIX14_ARB 0x88CE +#define GL_MATRIX15_ARB 0x88CF +#define GL_MATRIX16_ARB 0x88D0 +#define GL_MATRIX17_ARB 0x88D1 +#define GL_MATRIX18_ARB 0x88D2 +#define GL_MATRIX19_ARB 0x88D3 +#define GL_MATRIX20_ARB 0x88D4 +#define GL_MATRIX21_ARB 0x88D5 +#define GL_MATRIX22_ARB 0x88D6 +#define GL_MATRIX23_ARB 0x88D7 +#define GL_MATRIX24_ARB 0x88D8 +#define GL_MATRIX25_ARB 0x88D9 +#define GL_MATRIX26_ARB 0x88DA +#define GL_MATRIX27_ARB 0x88DB +#define GL_MATRIX28_ARB 0x88DC +#define GL_MATRIX29_ARB 0x88DD +#define GL_MATRIX30_ARB 0x88DE +#define GL_MATRIX31_ARB 0x88DF +typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const void *string); +typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program); +typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, void *string); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramStringARB (GLenum target, GLenum format, GLsizei len, const void *string); +GLAPI void APIENTRY glBindProgramARB (GLenum target, GLuint program); +GLAPI void APIENTRY glDeleteProgramsARB (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glGenProgramsARB (GLsizei n, GLuint *programs); +GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetProgramivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramStringARB (GLenum target, GLenum pname, void *string); +GLAPI GLboolean APIENTRY glIsProgramARB (GLuint program); +#endif +#endif /* GL_ARB_fragment_program */ + +#ifndef GL_ARB_fragment_program_shadow +#define GL_ARB_fragment_program_shadow 1 +#endif /* GL_ARB_fragment_program_shadow */ + +#ifndef GL_ARB_fragment_shader +#define GL_ARB_fragment_shader 1 +#define GL_FRAGMENT_SHADER_ARB 0x8B30 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B +#endif /* GL_ARB_fragment_shader */ + +#ifndef GL_ARB_framebuffer_no_attachments +#define GL_ARB_framebuffer_no_attachments 1 +#endif /* GL_ARB_framebuffer_no_attachments */ + +#ifndef GL_ARB_framebuffer_object +#define GL_ARB_framebuffer_object 1 +#endif /* GL_ARB_framebuffer_object */ + +#ifndef GL_ARB_framebuffer_sRGB +#define GL_ARB_framebuffer_sRGB 1 +#endif /* GL_ARB_framebuffer_sRGB */ + +#ifndef GL_ARB_geometry_shader4 +#define GL_ARB_geometry_shader4 1 +#define GL_LINES_ADJACENCY_ARB 0x000A +#define GL_LINE_STRIP_ADJACENCY_ARB 0x000B +#define GL_TRIANGLES_ADJACENCY_ARB 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_ARB 0x000D +#define GL_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB 0x8C29 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB 0x8DA7 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB 0x8DA9 +#define GL_GEOMETRY_SHADER_ARB 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT_ARB 0x8DDA +#define GL_GEOMETRY_INPUT_TYPE_ARB 0x8DDB +#define GL_GEOMETRY_OUTPUT_TYPE_ARB 0x8DDC +#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB 0x8DDD +#define GL_MAX_VERTEX_VARYING_COMPONENTS_ARB 0x8DDE +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB 0x8DE1 +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIARBPROC) (GLuint program, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYERARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEARBPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramParameteriARB (GLuint program, GLenum pname, GLint value); +GLAPI void APIENTRY glFramebufferTextureARB (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTextureLayerARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glFramebufferTextureFaceARB (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#endif +#endif /* GL_ARB_geometry_shader4 */ + +#ifndef GL_ARB_get_program_binary +#define GL_ARB_get_program_binary 1 +#endif /* GL_ARB_get_program_binary */ + +#ifndef GL_ARB_get_texture_sub_image +#define GL_ARB_get_texture_sub_image 1 +#endif /* GL_ARB_get_texture_sub_image */ + +#ifndef GL_ARB_gpu_shader5 +#define GL_ARB_gpu_shader5 1 +#endif /* GL_ARB_gpu_shader5 */ + +#ifndef GL_ARB_gpu_shader_fp64 +#define GL_ARB_gpu_shader_fp64 1 +#endif /* GL_ARB_gpu_shader_fp64 */ + +#ifndef GL_ARB_half_float_pixel +#define GL_ARB_half_float_pixel 1 +typedef unsigned short GLhalfARB; +#define GL_HALF_FLOAT_ARB 0x140B +#endif /* GL_ARB_half_float_pixel */ + +#ifndef GL_ARB_half_float_vertex +#define GL_ARB_half_float_vertex 1 +#endif /* GL_ARB_half_float_vertex */ + +#ifndef GL_ARB_imaging +#define GL_ARB_imaging 1 +#define GL_BLEND_COLOR 0x8005 +#define GL_BLEND_EQUATION 0x8009 +#define GL_CONVOLUTION_1D 0x8010 +#define GL_CONVOLUTION_2D 0x8011 +#define GL_SEPARABLE_2D 0x8012 +#define GL_CONVOLUTION_BORDER_MODE 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS 0x8015 +#define GL_REDUCE 0x8016 +#define GL_CONVOLUTION_FORMAT 0x8017 +#define GL_CONVOLUTION_WIDTH 0x8018 +#define GL_CONVOLUTION_HEIGHT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS 0x8023 +#define GL_HISTOGRAM 0x8024 +#define GL_PROXY_HISTOGRAM 0x8025 +#define GL_HISTOGRAM_WIDTH 0x8026 +#define GL_HISTOGRAM_FORMAT 0x8027 +#define GL_HISTOGRAM_RED_SIZE 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE 0x802C +#define GL_HISTOGRAM_SINK 0x802D +#define GL_MINMAX 0x802E +#define GL_MINMAX_FORMAT 0x802F +#define GL_MINMAX_SINK 0x8030 +#define GL_TABLE_TOO_LARGE 0x8031 +#define GL_COLOR_MATRIX 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS 0x80BB +#define GL_COLOR_TABLE 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE 0x80D2 +#define GL_PROXY_COLOR_TABLE 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5 +#define GL_COLOR_TABLE_SCALE 0x80D6 +#define GL_COLOR_TABLE_BIAS 0x80D7 +#define GL_COLOR_TABLE_FORMAT 0x80D8 +#define GL_COLOR_TABLE_WIDTH 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE 0x80DF +#define GL_CONSTANT_BORDER 0x8151 +#define GL_REPLICATE_BORDER 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR 0x8154 +typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, void *image); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target); +typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTable (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glColorTableParameterfv (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glColorTableParameteriv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyColorTable (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glGetColorTable (GLenum target, GLenum format, GLenum type, void *table); +GLAPI void APIENTRY glGetColorTableParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetColorTableParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glColorSubTable (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glCopyColorSubTable (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glConvolutionFilter1D (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionParameterf (GLenum target, GLenum pname, GLfloat params); +GLAPI void APIENTRY glConvolutionParameterfv (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glConvolutionParameteri (GLenum target, GLenum pname, GLint params); +GLAPI void APIENTRY glConvolutionParameteriv (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetConvolutionFilter (GLenum target, GLenum format, GLenum type, void *image); +GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSeparableFilter (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +GLAPI void APIENTRY glSeparableFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +GLAPI void APIENTRY glGetHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetHistogramParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetHistogramParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glHistogram (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glMinmax (GLenum target, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glResetHistogram (GLenum target); +GLAPI void APIENTRY glResetMinmax (GLenum target); +#endif +#endif /* GL_ARB_imaging */ + +#ifndef GL_ARB_indirect_parameters +#define GL_ARB_indirect_parameters 1 +#define GL_PARAMETER_BUFFER_ARB 0x80EE +#define GL_PARAMETER_BUFFER_BINDING_ARB 0x80EF +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTCOUNTARBPROC) (GLenum mode, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTCOUNTARBPROC) (GLenum mode, GLenum type, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectCountARB (GLenum mode, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirectCountARB (GLenum mode, GLenum type, GLintptr indirect, GLintptr drawcount, GLsizei maxdrawcount, GLsizei stride); +#endif +#endif /* GL_ARB_indirect_parameters */ + +#ifndef GL_ARB_instanced_arrays +#define GL_ARB_instanced_arrays 1 +#define GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB 0x88FE +typedef void (APIENTRYP PFNGLVERTEXATTRIBDIVISORARBPROC) (GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribDivisorARB (GLuint index, GLuint divisor); +#endif +#endif /* GL_ARB_instanced_arrays */ + +#ifndef GL_ARB_internalformat_query +#define GL_ARB_internalformat_query 1 +#endif /* GL_ARB_internalformat_query */ + +#ifndef GL_ARB_internalformat_query2 +#define GL_ARB_internalformat_query2 1 +#define GL_SRGB_DECODE_ARB 0x8299 +#endif /* GL_ARB_internalformat_query2 */ + +#ifndef GL_ARB_invalidate_subdata +#define GL_ARB_invalidate_subdata 1 +#endif /* GL_ARB_invalidate_subdata */ + +#ifndef GL_ARB_map_buffer_alignment +#define GL_ARB_map_buffer_alignment 1 +#endif /* GL_ARB_map_buffer_alignment */ + +#ifndef GL_ARB_map_buffer_range +#define GL_ARB_map_buffer_range 1 +#endif /* GL_ARB_map_buffer_range */ + +#ifndef GL_ARB_matrix_palette +#define GL_ARB_matrix_palette 1 +#define GL_MATRIX_PALETTE_ARB 0x8840 +#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841 +#define GL_MAX_PALETTE_MATRICES_ARB 0x8842 +#define GL_CURRENT_PALETTE_MATRIX_ARB 0x8843 +#define GL_MATRIX_INDEX_ARRAY_ARB 0x8844 +#define GL_CURRENT_MATRIX_INDEX_ARB 0x8845 +#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB 0x8846 +#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB 0x8847 +#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB 0x8848 +#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849 +typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index); +typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices); +typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint index); +GLAPI void APIENTRY glMatrixIndexubvARB (GLint size, const GLubyte *indices); +GLAPI void APIENTRY glMatrixIndexusvARB (GLint size, const GLushort *indices); +GLAPI void APIENTRY glMatrixIndexuivARB (GLint size, const GLuint *indices); +GLAPI void APIENTRY glMatrixIndexPointerARB (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_ARB_matrix_palette */ + +#ifndef GL_ARB_multi_bind +#define GL_ARB_multi_bind 1 +#endif /* GL_ARB_multi_bind */ + +#ifndef GL_ARB_multi_draw_indirect +#define GL_ARB_multi_draw_indirect 1 +#endif /* GL_ARB_multi_draw_indirect */ + +#ifndef GL_ARB_multisample +#define GL_ARB_multisample 1 +#define GL_MULTISAMPLE_ARB 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_ARB 0x809F +#define GL_SAMPLE_COVERAGE_ARB 0x80A0 +#define GL_SAMPLE_BUFFERS_ARB 0x80A8 +#define GL_SAMPLES_ARB 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE_ARB 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT_ARB 0x80AB +#define GL_MULTISAMPLE_BIT_ARB 0x20000000 +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLfloat value, GLboolean invert); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleCoverageARB (GLfloat value, GLboolean invert); +#endif +#endif /* GL_ARB_multisample */ + +#ifndef GL_ARB_multitexture +#define GL_ARB_multitexture 1 +#define GL_TEXTURE0_ARB 0x84C0 +#define GL_TEXTURE1_ARB 0x84C1 +#define GL_TEXTURE2_ARB 0x84C2 +#define GL_TEXTURE3_ARB 0x84C3 +#define GL_TEXTURE4_ARB 0x84C4 +#define GL_TEXTURE5_ARB 0x84C5 +#define GL_TEXTURE6_ARB 0x84C6 +#define GL_TEXTURE7_ARB 0x84C7 +#define GL_TEXTURE8_ARB 0x84C8 +#define GL_TEXTURE9_ARB 0x84C9 +#define GL_TEXTURE10_ARB 0x84CA +#define GL_TEXTURE11_ARB 0x84CB +#define GL_TEXTURE12_ARB 0x84CC +#define GL_TEXTURE13_ARB 0x84CD +#define GL_TEXTURE14_ARB 0x84CE +#define GL_TEXTURE15_ARB 0x84CF +#define GL_TEXTURE16_ARB 0x84D0 +#define GL_TEXTURE17_ARB 0x84D1 +#define GL_TEXTURE18_ARB 0x84D2 +#define GL_TEXTURE19_ARB 0x84D3 +#define GL_TEXTURE20_ARB 0x84D4 +#define GL_TEXTURE21_ARB 0x84D5 +#define GL_TEXTURE22_ARB 0x84D6 +#define GL_TEXTURE23_ARB 0x84D7 +#define GL_TEXTURE24_ARB 0x84D8 +#define GL_TEXTURE25_ARB 0x84D9 +#define GL_TEXTURE26_ARB 0x84DA +#define GL_TEXTURE27_ARB 0x84DB +#define GL_TEXTURE28_ARB 0x84DC +#define GL_TEXTURE29_ARB 0x84DD +#define GL_TEXTURE30_ARB 0x84DE +#define GL_TEXTURE31_ARB 0x84DF +#define GL_ACTIVE_TEXTURE_ARB 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 +#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 +typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveTextureARB (GLenum texture); +GLAPI void APIENTRY glClientActiveTextureARB (GLenum texture); +GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum target, GLdouble s); +GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum target, GLfloat s); +GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum target, GLint s); +GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum target, GLshort s); +GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum target, GLdouble s, GLdouble t); +GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum target, GLfloat s, GLfloat t); +GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum target, GLint s, GLint t); +GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum target, GLshort s, GLshort t); +GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r); +GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r); +GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum target, GLint s, GLint t, GLint r); +GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum target, GLshort s, GLshort t, GLshort r); +GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum target, const GLshort *v); +GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); +GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum target, const GLdouble *v); +GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); +GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum target, const GLfloat *v); +GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum target, GLint s, GLint t, GLint r, GLint q); +GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum target, const GLint *v); +GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); +GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum target, const GLshort *v); +#endif +#endif /* GL_ARB_multitexture */ + +#ifndef GL_ARB_occlusion_query +#define GL_ARB_occlusion_query 1 +#define GL_QUERY_COUNTER_BITS_ARB 0x8864 +#define GL_CURRENT_QUERY_ARB 0x8865 +#define GL_QUERY_RESULT_ARB 0x8866 +#define GL_QUERY_RESULT_AVAILABLE_ARB 0x8867 +#define GL_SAMPLES_PASSED_ARB 0x8914 +typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenQueriesARB (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteQueriesARB (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsQueryARB (GLuint id); +GLAPI void APIENTRY glBeginQueryARB (GLenum target, GLuint id); +GLAPI void APIENTRY glEndQueryARB (GLenum target); +GLAPI void APIENTRY glGetQueryivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectivARB (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint id, GLenum pname, GLuint *params); +#endif +#endif /* GL_ARB_occlusion_query */ + +#ifndef GL_ARB_occlusion_query2 +#define GL_ARB_occlusion_query2 1 +#endif /* GL_ARB_occlusion_query2 */ + +#ifndef GL_ARB_pipeline_statistics_query +#define GL_ARB_pipeline_statistics_query 1 +#define GL_VERTICES_SUBMITTED_ARB 0x82EE +#define GL_PRIMITIVES_SUBMITTED_ARB 0x82EF +#define GL_VERTEX_SHADER_INVOCATIONS_ARB 0x82F0 +#define GL_TESS_CONTROL_SHADER_PATCHES_ARB 0x82F1 +#define GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB 0x82F2 +#define GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB 0x82F3 +#define GL_FRAGMENT_SHADER_INVOCATIONS_ARB 0x82F4 +#define GL_COMPUTE_SHADER_INVOCATIONS_ARB 0x82F5 +#define GL_CLIPPING_INPUT_PRIMITIVES_ARB 0x82F6 +#define GL_CLIPPING_OUTPUT_PRIMITIVES_ARB 0x82F7 +#endif /* GL_ARB_pipeline_statistics_query */ + +#ifndef GL_ARB_pixel_buffer_object +#define GL_ARB_pixel_buffer_object 1 +#define GL_PIXEL_PACK_BUFFER_ARB 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_ARB 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_ARB 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_ARB 0x88EF +#endif /* GL_ARB_pixel_buffer_object */ + +#ifndef GL_ARB_point_parameters +#define GL_ARB_point_parameters 1 +#define GL_POINT_SIZE_MIN_ARB 0x8126 +#define GL_POINT_SIZE_MAX_ARB 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_ARB 0x8128 +#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfARB (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvARB (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_ARB_point_parameters */ + +#ifndef GL_ARB_point_sprite +#define GL_ARB_point_sprite 1 +#define GL_POINT_SPRITE_ARB 0x8861 +#define GL_COORD_REPLACE_ARB 0x8862 +#endif /* GL_ARB_point_sprite */ + +#ifndef GL_ARB_program_interface_query +#define GL_ARB_program_interface_query 1 +#endif /* GL_ARB_program_interface_query */ + +#ifndef GL_ARB_provoking_vertex +#define GL_ARB_provoking_vertex 1 +#endif /* GL_ARB_provoking_vertex */ + +#ifndef GL_ARB_query_buffer_object +#define GL_ARB_query_buffer_object 1 +#endif /* GL_ARB_query_buffer_object */ + +#ifndef GL_ARB_robust_buffer_access_behavior +#define GL_ARB_robust_buffer_access_behavior 1 +#endif /* GL_ARB_robust_buffer_access_behavior */ + +#ifndef GL_ARB_robustness +#define GL_ARB_robustness 1 +#define GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB 0x00000004 +#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 +#define GL_GUILTY_CONTEXT_RESET_ARB 0x8253 +#define GL_INNOCENT_CONTEXT_RESET_ARB 0x8254 +#define GL_UNKNOWN_CONTEXT_RESET_ARB 0x8255 +#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 +#define GL_NO_RESET_NOTIFICATION_ARB 0x8261 +typedef GLenum (APIENTRYP PFNGLGETGRAPHICSRESETSTATUSARBPROC) (void); +typedef void (APIENTRYP PFNGLGETNTEXIMAGEARBPROC) (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); +typedef void (APIENTRYP PFNGLREADNPIXELSARBPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +typedef void (APIENTRYP PFNGLGETNCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint lod, GLsizei bufSize, void *img); +typedef void (APIENTRYP PFNGLGETNUNIFORMFVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMUIVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +typedef void (APIENTRYP PFNGLGETNUNIFORMDVARBPROC) (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNMAPDVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +typedef void (APIENTRYP PFNGLGETNMAPFVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +typedef void (APIENTRYP PFNGLGETNMAPIVARBPROC) (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +typedef void (APIENTRYP PFNGLGETNPIXELMAPFVARBPROC) (GLenum map, GLsizei bufSize, GLfloat *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUIVARBPROC) (GLenum map, GLsizei bufSize, GLuint *values); +typedef void (APIENTRYP PFNGLGETNPIXELMAPUSVARBPROC) (GLenum map, GLsizei bufSize, GLushort *values); +typedef void (APIENTRYP PFNGLGETNPOLYGONSTIPPLEARBPROC) (GLsizei bufSize, GLubyte *pattern); +typedef void (APIENTRYP PFNGLGETNCOLORTABLEARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +typedef void (APIENTRYP PFNGLGETNCONVOLUTIONFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +typedef void (APIENTRYP PFNGLGETNSEPARABLEFILTERARBPROC) (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +typedef void (APIENTRYP PFNGLGETNHISTOGRAMARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +typedef void (APIENTRYP PFNGLGETNMINMAXARBPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLenum APIENTRY glGetGraphicsResetStatusARB (void); +GLAPI void APIENTRY glGetnTexImageARB (GLenum target, GLint level, GLenum format, GLenum type, GLsizei bufSize, void *img); +GLAPI void APIENTRY glReadnPixelsARB (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void *data); +GLAPI void APIENTRY glGetnCompressedTexImageARB (GLenum target, GLint lod, GLsizei bufSize, void *img); +GLAPI void APIENTRY glGetnUniformfvARB (GLuint program, GLint location, GLsizei bufSize, GLfloat *params); +GLAPI void APIENTRY glGetnUniformivARB (GLuint program, GLint location, GLsizei bufSize, GLint *params); +GLAPI void APIENTRY glGetnUniformuivARB (GLuint program, GLint location, GLsizei bufSize, GLuint *params); +GLAPI void APIENTRY glGetnUniformdvARB (GLuint program, GLint location, GLsizei bufSize, GLdouble *params); +GLAPI void APIENTRY glGetnMapdvARB (GLenum target, GLenum query, GLsizei bufSize, GLdouble *v); +GLAPI void APIENTRY glGetnMapfvARB (GLenum target, GLenum query, GLsizei bufSize, GLfloat *v); +GLAPI void APIENTRY glGetnMapivARB (GLenum target, GLenum query, GLsizei bufSize, GLint *v); +GLAPI void APIENTRY glGetnPixelMapfvARB (GLenum map, GLsizei bufSize, GLfloat *values); +GLAPI void APIENTRY glGetnPixelMapuivARB (GLenum map, GLsizei bufSize, GLuint *values); +GLAPI void APIENTRY glGetnPixelMapusvARB (GLenum map, GLsizei bufSize, GLushort *values); +GLAPI void APIENTRY glGetnPolygonStippleARB (GLsizei bufSize, GLubyte *pattern); +GLAPI void APIENTRY glGetnColorTableARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *table); +GLAPI void APIENTRY glGetnConvolutionFilterARB (GLenum target, GLenum format, GLenum type, GLsizei bufSize, void *image); +GLAPI void APIENTRY glGetnSeparableFilterARB (GLenum target, GLenum format, GLenum type, GLsizei rowBufSize, void *row, GLsizei columnBufSize, void *column, void *span); +GLAPI void APIENTRY glGetnHistogramARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +GLAPI void APIENTRY glGetnMinmaxARB (GLenum target, GLboolean reset, GLenum format, GLenum type, GLsizei bufSize, void *values); +#endif +#endif /* GL_ARB_robustness */ + +#ifndef GL_ARB_robustness_isolation +#define GL_ARB_robustness_isolation 1 +#endif /* GL_ARB_robustness_isolation */ + +#ifndef GL_ARB_sample_shading +#define GL_ARB_sample_shading 1 +#define GL_SAMPLE_SHADING_ARB 0x8C36 +#define GL_MIN_SAMPLE_SHADING_VALUE_ARB 0x8C37 +typedef void (APIENTRYP PFNGLMINSAMPLESHADINGARBPROC) (GLfloat value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMinSampleShadingARB (GLfloat value); +#endif +#endif /* GL_ARB_sample_shading */ + +#ifndef GL_ARB_sampler_objects +#define GL_ARB_sampler_objects 1 +#endif /* GL_ARB_sampler_objects */ + +#ifndef GL_ARB_seamless_cube_map +#define GL_ARB_seamless_cube_map 1 +#endif /* GL_ARB_seamless_cube_map */ + +#ifndef GL_ARB_seamless_cubemap_per_texture +#define GL_ARB_seamless_cubemap_per_texture 1 +#endif /* GL_ARB_seamless_cubemap_per_texture */ + +#ifndef GL_ARB_separate_shader_objects +#define GL_ARB_separate_shader_objects 1 +#endif /* GL_ARB_separate_shader_objects */ + +#ifndef GL_ARB_shader_atomic_counters +#define GL_ARB_shader_atomic_counters 1 +#endif /* GL_ARB_shader_atomic_counters */ + +#ifndef GL_ARB_shader_bit_encoding +#define GL_ARB_shader_bit_encoding 1 +#endif /* GL_ARB_shader_bit_encoding */ + +#ifndef GL_ARB_shader_draw_parameters +#define GL_ARB_shader_draw_parameters 1 +#endif /* GL_ARB_shader_draw_parameters */ + +#ifndef GL_ARB_shader_group_vote +#define GL_ARB_shader_group_vote 1 +#endif /* GL_ARB_shader_group_vote */ + +#ifndef GL_ARB_shader_image_load_store +#define GL_ARB_shader_image_load_store 1 +#endif /* GL_ARB_shader_image_load_store */ + +#ifndef GL_ARB_shader_image_size +#define GL_ARB_shader_image_size 1 +#endif /* GL_ARB_shader_image_size */ + +#ifndef GL_ARB_shader_objects +#define GL_ARB_shader_objects 1 +#ifdef __APPLE__ +typedef void *GLhandleARB; +#else +typedef unsigned int GLhandleARB; +#endif +typedef char GLcharARB; +#define GL_PROGRAM_OBJECT_ARB 0x8B40 +#define GL_SHADER_OBJECT_ARB 0x8B48 +#define GL_OBJECT_TYPE_ARB 0x8B4E +#define GL_OBJECT_SUBTYPE_ARB 0x8B4F +#define GL_FLOAT_VEC2_ARB 0x8B50 +#define GL_FLOAT_VEC3_ARB 0x8B51 +#define GL_FLOAT_VEC4_ARB 0x8B52 +#define GL_INT_VEC2_ARB 0x8B53 +#define GL_INT_VEC3_ARB 0x8B54 +#define GL_INT_VEC4_ARB 0x8B55 +#define GL_BOOL_ARB 0x8B56 +#define GL_BOOL_VEC2_ARB 0x8B57 +#define GL_BOOL_VEC3_ARB 0x8B58 +#define GL_BOOL_VEC4_ARB 0x8B59 +#define GL_FLOAT_MAT2_ARB 0x8B5A +#define GL_FLOAT_MAT3_ARB 0x8B5B +#define GL_FLOAT_MAT4_ARB 0x8B5C +#define GL_SAMPLER_1D_ARB 0x8B5D +#define GL_SAMPLER_2D_ARB 0x8B5E +#define GL_SAMPLER_3D_ARB 0x8B5F +#define GL_SAMPLER_CUBE_ARB 0x8B60 +#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61 +#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62 +#define GL_SAMPLER_2D_RECT_ARB 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64 +#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80 +#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 +#define GL_OBJECT_LINK_STATUS_ARB 0x8B82 +#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83 +#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 +#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85 +#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86 +#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87 +#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88 +typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj); +typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname); +typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj); +typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType); +typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); +typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj); +typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void); +typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj); +typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj); +typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0); +typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); +typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); +typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); +typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params); +typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params); +typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB obj); +GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum pname); +GLAPI void APIENTRY glDetachObjectARB (GLhandleARB containerObj, GLhandleARB attachedObj); +GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum shaderType); +GLAPI void APIENTRY glShaderSourceARB (GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); +GLAPI void APIENTRY glCompileShaderARB (GLhandleARB shaderObj); +GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void); +GLAPI void APIENTRY glAttachObjectARB (GLhandleARB containerObj, GLhandleARB obj); +GLAPI void APIENTRY glLinkProgramARB (GLhandleARB programObj); +GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB programObj); +GLAPI void APIENTRY glValidateProgramARB (GLhandleARB programObj); +GLAPI void APIENTRY glUniform1fARB (GLint location, GLfloat v0); +GLAPI void APIENTRY glUniform2fARB (GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glUniform3fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glUniform4fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glUniform1iARB (GLint location, GLint v0); +GLAPI void APIENTRY glUniform2iARB (GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glUniform3iARB (GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glUniform4iARB (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glUniform1fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform2fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform3fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform4fvARB (GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glUniform1ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform2ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform3ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniform4ivARB (GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glUniformMatrix2fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix3fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glUniformMatrix4fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB obj, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB obj, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); +GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); +GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB programObj, const GLcharARB *name); +GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB programObj, GLint location, GLfloat *params); +GLAPI void APIENTRY glGetUniformivARB (GLhandleARB programObj, GLint location, GLint *params); +GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); +#endif +#endif /* GL_ARB_shader_objects */ + +#ifndef GL_ARB_shader_precision +#define GL_ARB_shader_precision 1 +#endif /* GL_ARB_shader_precision */ + +#ifndef GL_ARB_shader_stencil_export +#define GL_ARB_shader_stencil_export 1 +#endif /* GL_ARB_shader_stencil_export */ + +#ifndef GL_ARB_shader_storage_buffer_object +#define GL_ARB_shader_storage_buffer_object 1 +#endif /* GL_ARB_shader_storage_buffer_object */ + +#ifndef GL_ARB_shader_subroutine +#define GL_ARB_shader_subroutine 1 +#endif /* GL_ARB_shader_subroutine */ + +#ifndef GL_ARB_shader_texture_image_samples +#define GL_ARB_shader_texture_image_samples 1 +#endif /* GL_ARB_shader_texture_image_samples */ + +#ifndef GL_ARB_shader_texture_lod +#define GL_ARB_shader_texture_lod 1 +#endif /* GL_ARB_shader_texture_lod */ + +#ifndef GL_ARB_shading_language_100 +#define GL_ARB_shading_language_100 1 +#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C +#endif /* GL_ARB_shading_language_100 */ + +#ifndef GL_ARB_shading_language_420pack +#define GL_ARB_shading_language_420pack 1 +#endif /* GL_ARB_shading_language_420pack */ + +#ifndef GL_ARB_shading_language_include +#define GL_ARB_shading_language_include 1 +#define GL_SHADER_INCLUDE_ARB 0x8DAE +#define GL_NAMED_STRING_LENGTH_ARB 0x8DE9 +#define GL_NAMED_STRING_TYPE_ARB 0x8DEA +typedef void (APIENTRYP PFNGLNAMEDSTRINGARBPROC) (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string); +typedef void (APIENTRYP PFNGLDELETENAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name); +typedef void (APIENTRYP PFNGLCOMPILESHADERINCLUDEARBPROC) (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length); +typedef GLboolean (APIENTRYP PFNGLISNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name); +typedef void (APIENTRYP PFNGLGETNAMEDSTRINGARBPROC) (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string); +typedef void (APIENTRYP PFNGLGETNAMEDSTRINGIVARBPROC) (GLint namelen, const GLchar *name, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glNamedStringARB (GLenum type, GLint namelen, const GLchar *name, GLint stringlen, const GLchar *string); +GLAPI void APIENTRY glDeleteNamedStringARB (GLint namelen, const GLchar *name); +GLAPI void APIENTRY glCompileShaderIncludeARB (GLuint shader, GLsizei count, const GLchar *const*path, const GLint *length); +GLAPI GLboolean APIENTRY glIsNamedStringARB (GLint namelen, const GLchar *name); +GLAPI void APIENTRY glGetNamedStringARB (GLint namelen, const GLchar *name, GLsizei bufSize, GLint *stringlen, GLchar *string); +GLAPI void APIENTRY glGetNamedStringivARB (GLint namelen, const GLchar *name, GLenum pname, GLint *params); +#endif +#endif /* GL_ARB_shading_language_include */ + +#ifndef GL_ARB_shading_language_packing +#define GL_ARB_shading_language_packing 1 +#endif /* GL_ARB_shading_language_packing */ + +#ifndef GL_ARB_shadow +#define GL_ARB_shadow 1 +#define GL_TEXTURE_COMPARE_MODE_ARB 0x884C +#define GL_TEXTURE_COMPARE_FUNC_ARB 0x884D +#define GL_COMPARE_R_TO_TEXTURE_ARB 0x884E +#endif /* GL_ARB_shadow */ + +#ifndef GL_ARB_shadow_ambient +#define GL_ARB_shadow_ambient 1 +#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF +#endif /* GL_ARB_shadow_ambient */ + +#ifndef GL_ARB_sparse_buffer +#define GL_ARB_sparse_buffer 1 +#define GL_SPARSE_STORAGE_BIT_ARB 0x0400 +#define GL_SPARSE_BUFFER_PAGE_SIZE_ARB 0x82F8 +typedef void (APIENTRYP PFNGLBUFFERPAGECOMMITMENTARBPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit); +typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +typedef void (APIENTRYP PFNGLNAMEDBUFFERPAGECOMMITMENTARBPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferPageCommitmentARB (GLenum target, GLintptr offset, GLsizeiptr size, GLboolean commit); +GLAPI void APIENTRY glNamedBufferPageCommitmentEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +GLAPI void APIENTRY glNamedBufferPageCommitmentARB (GLuint buffer, GLintptr offset, GLsizeiptr size, GLboolean commit); +#endif +#endif /* GL_ARB_sparse_buffer */ + +#ifndef GL_ARB_sparse_texture +#define GL_ARB_sparse_texture 1 +#define GL_TEXTURE_SPARSE_ARB 0x91A6 +#define GL_VIRTUAL_PAGE_SIZE_INDEX_ARB 0x91A7 +#define GL_NUM_SPARSE_LEVELS_ARB 0x91AA +#define GL_NUM_VIRTUAL_PAGE_SIZES_ARB 0x91A8 +#define GL_VIRTUAL_PAGE_SIZE_X_ARB 0x9195 +#define GL_VIRTUAL_PAGE_SIZE_Y_ARB 0x9196 +#define GL_VIRTUAL_PAGE_SIZE_Z_ARB 0x9197 +#define GL_MAX_SPARSE_TEXTURE_SIZE_ARB 0x9198 +#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB 0x9199 +#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB 0x919A +#define GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB 0x91A9 +typedef void (APIENTRYP PFNGLTEXPAGECOMMITMENTARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean resident); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexPageCommitmentARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean resident); +#endif +#endif /* GL_ARB_sparse_texture */ + +#ifndef GL_ARB_stencil_texturing +#define GL_ARB_stencil_texturing 1 +#endif /* GL_ARB_stencil_texturing */ + +#ifndef GL_ARB_sync +#define GL_ARB_sync 1 +#endif /* GL_ARB_sync */ + +#ifndef GL_ARB_tessellation_shader +#define GL_ARB_tessellation_shader 1 +#endif /* GL_ARB_tessellation_shader */ + +#ifndef GL_ARB_texture_barrier +#define GL_ARB_texture_barrier 1 +#endif /* GL_ARB_texture_barrier */ + +#ifndef GL_ARB_texture_border_clamp +#define GL_ARB_texture_border_clamp 1 +#define GL_CLAMP_TO_BORDER_ARB 0x812D +#endif /* GL_ARB_texture_border_clamp */ + +#ifndef GL_ARB_texture_buffer_object +#define GL_ARB_texture_buffer_object 1 +#define GL_TEXTURE_BUFFER_ARB 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE_ARB 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER_ARB 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB 0x8C2D +#define GL_TEXTURE_BUFFER_FORMAT_ARB 0x8C2E +typedef void (APIENTRYP PFNGLTEXBUFFERARBPROC) (GLenum target, GLenum internalformat, GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBufferARB (GLenum target, GLenum internalformat, GLuint buffer); +#endif +#endif /* GL_ARB_texture_buffer_object */ + +#ifndef GL_ARB_texture_buffer_object_rgb32 +#define GL_ARB_texture_buffer_object_rgb32 1 +#endif /* GL_ARB_texture_buffer_object_rgb32 */ + +#ifndef GL_ARB_texture_buffer_range +#define GL_ARB_texture_buffer_range 1 +#endif /* GL_ARB_texture_buffer_range */ + +#ifndef GL_ARB_texture_compression +#define GL_ARB_texture_compression 1 +#define GL_COMPRESSED_ALPHA_ARB 0x84E9 +#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB +#define GL_COMPRESSED_INTENSITY_ARB 0x84EC +#define GL_COMPRESSED_RGB_ARB 0x84ED +#define GL_COMPRESSED_RGBA_ARB 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 +#define GL_TEXTURE_COMPRESSED_ARB 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, void *img); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *data); +GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum target, GLint level, void *img); +#endif +#endif /* GL_ARB_texture_compression */ + +#ifndef GL_ARB_texture_compression_bptc +#define GL_ARB_texture_compression_bptc 1 +#define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F +#endif /* GL_ARB_texture_compression_bptc */ + +#ifndef GL_ARB_texture_compression_rgtc +#define GL_ARB_texture_compression_rgtc 1 +#endif /* GL_ARB_texture_compression_rgtc */ + +#ifndef GL_ARB_texture_cube_map +#define GL_ARB_texture_cube_map 1 +#define GL_NORMAL_MAP_ARB 0x8511 +#define GL_REFLECTION_MAP_ARB 0x8512 +#define GL_TEXTURE_CUBE_MAP_ARB 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARB 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARB 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB 0x851C +#endif /* GL_ARB_texture_cube_map */ + +#ifndef GL_ARB_texture_cube_map_array +#define GL_ARB_texture_cube_map_array 1 +#define GL_TEXTURE_CUBE_MAP_ARRAY_ARB 0x9009 +#define GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB 0x900A +#define GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB 0x900B +#define GL_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900C +#define GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB 0x900D +#define GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900E +#define GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB 0x900F +#endif /* GL_ARB_texture_cube_map_array */ + +#ifndef GL_ARB_texture_env_add +#define GL_ARB_texture_env_add 1 +#endif /* GL_ARB_texture_env_add */ + +#ifndef GL_ARB_texture_env_combine +#define GL_ARB_texture_env_combine 1 +#define GL_COMBINE_ARB 0x8570 +#define GL_COMBINE_RGB_ARB 0x8571 +#define GL_COMBINE_ALPHA_ARB 0x8572 +#define GL_SOURCE0_RGB_ARB 0x8580 +#define GL_SOURCE1_RGB_ARB 0x8581 +#define GL_SOURCE2_RGB_ARB 0x8582 +#define GL_SOURCE0_ALPHA_ARB 0x8588 +#define GL_SOURCE1_ALPHA_ARB 0x8589 +#define GL_SOURCE2_ALPHA_ARB 0x858A +#define GL_OPERAND0_RGB_ARB 0x8590 +#define GL_OPERAND1_RGB_ARB 0x8591 +#define GL_OPERAND2_RGB_ARB 0x8592 +#define GL_OPERAND0_ALPHA_ARB 0x8598 +#define GL_OPERAND1_ALPHA_ARB 0x8599 +#define GL_OPERAND2_ALPHA_ARB 0x859A +#define GL_RGB_SCALE_ARB 0x8573 +#define GL_ADD_SIGNED_ARB 0x8574 +#define GL_INTERPOLATE_ARB 0x8575 +#define GL_SUBTRACT_ARB 0x84E7 +#define GL_CONSTANT_ARB 0x8576 +#define GL_PRIMARY_COLOR_ARB 0x8577 +#define GL_PREVIOUS_ARB 0x8578 +#endif /* GL_ARB_texture_env_combine */ + +#ifndef GL_ARB_texture_env_crossbar +#define GL_ARB_texture_env_crossbar 1 +#endif /* GL_ARB_texture_env_crossbar */ + +#ifndef GL_ARB_texture_env_dot3 +#define GL_ARB_texture_env_dot3 1 +#define GL_DOT3_RGB_ARB 0x86AE +#define GL_DOT3_RGBA_ARB 0x86AF +#endif /* GL_ARB_texture_env_dot3 */ + +#ifndef GL_ARB_texture_float +#define GL_ARB_texture_float 1 +#define GL_TEXTURE_RED_TYPE_ARB 0x8C10 +#define GL_TEXTURE_GREEN_TYPE_ARB 0x8C11 +#define GL_TEXTURE_BLUE_TYPE_ARB 0x8C12 +#define GL_TEXTURE_ALPHA_TYPE_ARB 0x8C13 +#define GL_TEXTURE_LUMINANCE_TYPE_ARB 0x8C14 +#define GL_TEXTURE_INTENSITY_TYPE_ARB 0x8C15 +#define GL_TEXTURE_DEPTH_TYPE_ARB 0x8C16 +#define GL_UNSIGNED_NORMALIZED_ARB 0x8C17 +#define GL_RGBA32F_ARB 0x8814 +#define GL_RGB32F_ARB 0x8815 +#define GL_ALPHA32F_ARB 0x8816 +#define GL_INTENSITY32F_ARB 0x8817 +#define GL_LUMINANCE32F_ARB 0x8818 +#define GL_LUMINANCE_ALPHA32F_ARB 0x8819 +#define GL_RGBA16F_ARB 0x881A +#define GL_RGB16F_ARB 0x881B +#define GL_ALPHA16F_ARB 0x881C +#define GL_INTENSITY16F_ARB 0x881D +#define GL_LUMINANCE16F_ARB 0x881E +#define GL_LUMINANCE_ALPHA16F_ARB 0x881F +#endif /* GL_ARB_texture_float */ + +#ifndef GL_ARB_texture_gather +#define GL_ARB_texture_gather 1 +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB 0x8E5F +#define GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB 0x8F9F +#endif /* GL_ARB_texture_gather */ + +#ifndef GL_ARB_texture_mirror_clamp_to_edge +#define GL_ARB_texture_mirror_clamp_to_edge 1 +#endif /* GL_ARB_texture_mirror_clamp_to_edge */ + +#ifndef GL_ARB_texture_mirrored_repeat +#define GL_ARB_texture_mirrored_repeat 1 +#define GL_MIRRORED_REPEAT_ARB 0x8370 +#endif /* GL_ARB_texture_mirrored_repeat */ + +#ifndef GL_ARB_texture_multisample +#define GL_ARB_texture_multisample 1 +#endif /* GL_ARB_texture_multisample */ + +#ifndef GL_ARB_texture_non_power_of_two +#define GL_ARB_texture_non_power_of_two 1 +#endif /* GL_ARB_texture_non_power_of_two */ + +#ifndef GL_ARB_texture_query_levels +#define GL_ARB_texture_query_levels 1 +#endif /* GL_ARB_texture_query_levels */ + +#ifndef GL_ARB_texture_query_lod +#define GL_ARB_texture_query_lod 1 +#endif /* GL_ARB_texture_query_lod */ + +#ifndef GL_ARB_texture_rectangle +#define GL_ARB_texture_rectangle 1 +#define GL_TEXTURE_RECTANGLE_ARB 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE_ARB 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE_ARB 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB 0x84F8 +#endif /* GL_ARB_texture_rectangle */ + +#ifndef GL_ARB_texture_rg +#define GL_ARB_texture_rg 1 +#endif /* GL_ARB_texture_rg */ + +#ifndef GL_ARB_texture_rgb10_a2ui +#define GL_ARB_texture_rgb10_a2ui 1 +#endif /* GL_ARB_texture_rgb10_a2ui */ + +#ifndef GL_ARB_texture_stencil8 +#define GL_ARB_texture_stencil8 1 +#endif /* GL_ARB_texture_stencil8 */ + +#ifndef GL_ARB_texture_storage +#define GL_ARB_texture_storage 1 +#endif /* GL_ARB_texture_storage */ + +#ifndef GL_ARB_texture_storage_multisample +#define GL_ARB_texture_storage_multisample 1 +#endif /* GL_ARB_texture_storage_multisample */ + +#ifndef GL_ARB_texture_swizzle +#define GL_ARB_texture_swizzle 1 +#endif /* GL_ARB_texture_swizzle */ + +#ifndef GL_ARB_texture_view +#define GL_ARB_texture_view 1 +#endif /* GL_ARB_texture_view */ + +#ifndef GL_ARB_timer_query +#define GL_ARB_timer_query 1 +#endif /* GL_ARB_timer_query */ + +#ifndef GL_ARB_transform_feedback2 +#define GL_ARB_transform_feedback2 1 +#endif /* GL_ARB_transform_feedback2 */ + +#ifndef GL_ARB_transform_feedback3 +#define GL_ARB_transform_feedback3 1 +#endif /* GL_ARB_transform_feedback3 */ + +#ifndef GL_ARB_transform_feedback_instanced +#define GL_ARB_transform_feedback_instanced 1 +#endif /* GL_ARB_transform_feedback_instanced */ + +#ifndef GL_ARB_transform_feedback_overflow_query +#define GL_ARB_transform_feedback_overflow_query 1 +#define GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB 0x82EC +#define GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB 0x82ED +#endif /* GL_ARB_transform_feedback_overflow_query */ + +#ifndef GL_ARB_transpose_matrix +#define GL_ARB_transpose_matrix 1 +#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX_ARB 0x84E6 +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *m); +GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *m); +GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *m); +GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *m); +#endif +#endif /* GL_ARB_transpose_matrix */ + +#ifndef GL_ARB_uniform_buffer_object +#define GL_ARB_uniform_buffer_object 1 +#endif /* GL_ARB_uniform_buffer_object */ + +#ifndef GL_ARB_vertex_array_bgra +#define GL_ARB_vertex_array_bgra 1 +#endif /* GL_ARB_vertex_array_bgra */ + +#ifndef GL_ARB_vertex_array_object +#define GL_ARB_vertex_array_object 1 +#endif /* GL_ARB_vertex_array_object */ + +#ifndef GL_ARB_vertex_attrib_64bit +#define GL_ARB_vertex_attrib_64bit 1 +#endif /* GL_ARB_vertex_attrib_64bit */ + +#ifndef GL_ARB_vertex_attrib_binding +#define GL_ARB_vertex_attrib_binding 1 +#endif /* GL_ARB_vertex_attrib_binding */ + +#ifndef GL_ARB_vertex_blend +#define GL_ARB_vertex_blend 1 +#define GL_MAX_VERTEX_UNITS_ARB 0x86A4 +#define GL_ACTIVE_VERTEX_UNITS_ARB 0x86A5 +#define GL_WEIGHT_SUM_UNITY_ARB 0x86A6 +#define GL_VERTEX_BLEND_ARB 0x86A7 +#define GL_CURRENT_WEIGHT_ARB 0x86A8 +#define GL_WEIGHT_ARRAY_TYPE_ARB 0x86A9 +#define GL_WEIGHT_ARRAY_STRIDE_ARB 0x86AA +#define GL_WEIGHT_ARRAY_SIZE_ARB 0x86AB +#define GL_WEIGHT_ARRAY_POINTER_ARB 0x86AC +#define GL_WEIGHT_ARRAY_ARB 0x86AD +#define GL_MODELVIEW0_ARB 0x1700 +#define GL_MODELVIEW1_ARB 0x850A +#define GL_MODELVIEW2_ARB 0x8722 +#define GL_MODELVIEW3_ARB 0x8723 +#define GL_MODELVIEW4_ARB 0x8724 +#define GL_MODELVIEW5_ARB 0x8725 +#define GL_MODELVIEW6_ARB 0x8726 +#define GL_MODELVIEW7_ARB 0x8727 +#define GL_MODELVIEW8_ARB 0x8728 +#define GL_MODELVIEW9_ARB 0x8729 +#define GL_MODELVIEW10_ARB 0x872A +#define GL_MODELVIEW11_ARB 0x872B +#define GL_MODELVIEW12_ARB 0x872C +#define GL_MODELVIEW13_ARB 0x872D +#define GL_MODELVIEW14_ARB 0x872E +#define GL_MODELVIEW15_ARB 0x872F +#define GL_MODELVIEW16_ARB 0x8730 +#define GL_MODELVIEW17_ARB 0x8731 +#define GL_MODELVIEW18_ARB 0x8732 +#define GL_MODELVIEW19_ARB 0x8733 +#define GL_MODELVIEW20_ARB 0x8734 +#define GL_MODELVIEW21_ARB 0x8735 +#define GL_MODELVIEW22_ARB 0x8736 +#define GL_MODELVIEW23_ARB 0x8737 +#define GL_MODELVIEW24_ARB 0x8738 +#define GL_MODELVIEW25_ARB 0x8739 +#define GL_MODELVIEW26_ARB 0x873A +#define GL_MODELVIEW27_ARB 0x873B +#define GL_MODELVIEW28_ARB 0x873C +#define GL_MODELVIEW29_ARB 0x873D +#define GL_MODELVIEW30_ARB 0x873E +#define GL_MODELVIEW31_ARB 0x873F +typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights); +typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights); +typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights); +typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights); +typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights); +typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights); +typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights); +typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights); +typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWeightbvARB (GLint size, const GLbyte *weights); +GLAPI void APIENTRY glWeightsvARB (GLint size, const GLshort *weights); +GLAPI void APIENTRY glWeightivARB (GLint size, const GLint *weights); +GLAPI void APIENTRY glWeightfvARB (GLint size, const GLfloat *weights); +GLAPI void APIENTRY glWeightdvARB (GLint size, const GLdouble *weights); +GLAPI void APIENTRY glWeightubvARB (GLint size, const GLubyte *weights); +GLAPI void APIENTRY glWeightusvARB (GLint size, const GLushort *weights); +GLAPI void APIENTRY glWeightuivARB (GLint size, const GLuint *weights); +GLAPI void APIENTRY glWeightPointerARB (GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glVertexBlendARB (GLint count); +#endif +#endif /* GL_ARB_vertex_blend */ + +#ifndef GL_ARB_vertex_buffer_object +#define GL_ARB_vertex_buffer_object 1 +// Unfortunate problem with the OS X SDK which defines these types incorrectly +#if !defined(MACOS_X) +typedef ptrdiff_t GLsizeiptrARB; +typedef ptrdiff_t GLintptrARB; +#endif +#define GL_BUFFER_SIZE_ARB 0x8764 +#define GL_BUFFER_USAGE_ARB 0x8765 +#define GL_ARRAY_BUFFER_ARB 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER_ARB 0x8893 +#define GL_ARRAY_BUFFER_BINDING_ARB 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895 +#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F +#define GL_READ_ONLY_ARB 0x88B8 +#define GL_WRITE_ONLY_ARB 0x88B9 +#define GL_READ_WRITE_ARB 0x88BA +#define GL_BUFFER_ACCESS_ARB 0x88BB +#define GL_BUFFER_MAPPED_ARB 0x88BC +#define GL_BUFFER_MAP_POINTER_ARB 0x88BD +#define GL_STREAM_DRAW_ARB 0x88E0 +#define GL_STREAM_READ_ARB 0x88E1 +#define GL_STREAM_COPY_ARB 0x88E2 +#define GL_STATIC_DRAW_ARB 0x88E4 +#define GL_STATIC_READ_ARB 0x88E5 +#define GL_STATIC_COPY_ARB 0x88E6 +#define GL_DYNAMIC_DRAW_ARB 0x88E8 +#define GL_DYNAMIC_READ_ARB 0x88E9 +#define GL_DYNAMIC_COPY_ARB 0x88EA +typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer); +typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers); +typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers); +typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data); +typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data); +typedef void *(APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindBufferARB (GLenum target, GLuint buffer); +GLAPI void APIENTRY glDeleteBuffersARB (GLsizei n, const GLuint *buffers); +GLAPI void APIENTRY glGenBuffersARB (GLsizei n, GLuint *buffers); +GLAPI GLboolean APIENTRY glIsBufferARB (GLuint buffer); +GLAPI void APIENTRY glBufferDataARB (GLenum target, GLsizeiptrARB size, const void *data, GLenum usage); +GLAPI void APIENTRY glBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const void *data); +GLAPI void APIENTRY glGetBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, void *data); +GLAPI void *APIENTRY glMapBufferARB (GLenum target, GLenum access); +GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum target); +GLAPI void APIENTRY glGetBufferParameterivARB (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetBufferPointervARB (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_ARB_vertex_buffer_object */ + +#ifndef GL_ARB_vertex_program +#define GL_ARB_vertex_program 1 +#define GL_COLOR_SUM_ARB 0x8458 +#define GL_VERTEX_PROGRAM_ARB 0x8620 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 +#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 +#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 +#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A +#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 +#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 +#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 +#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttrib1dARB (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1fARB (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1sARB (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2dARB (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2fARB (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2sARB (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3sARB (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttrib4dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttrib4sARB (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4svARB (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribPointerARB (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint index); +GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint index); +GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribivARB (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint index, GLenum pname, void **pointer); +#endif +#endif /* GL_ARB_vertex_program */ + +#ifndef GL_ARB_vertex_shader +#define GL_ARB_vertex_shader 1 +#define GL_VERTEX_SHADER_ARB 0x8B31 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A +#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D +#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89 +#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A +typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name); +typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB programObj, GLuint index, const GLcharARB *name); +GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); +GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB programObj, const GLcharARB *name); +#endif +#endif /* GL_ARB_vertex_shader */ + +#ifndef GL_ARB_vertex_type_10f_11f_11f_rev +#define GL_ARB_vertex_type_10f_11f_11f_rev 1 +#endif /* GL_ARB_vertex_type_10f_11f_11f_rev */ + +#ifndef GL_ARB_vertex_type_2_10_10_10_rev +#define GL_ARB_vertex_type_2_10_10_10_rev 1 +#endif /* GL_ARB_vertex_type_2_10_10_10_rev */ + +#ifndef GL_ARB_viewport_array +#define GL_ARB_viewport_array 1 +#endif /* GL_ARB_viewport_array */ + +#ifndef GL_ARB_window_pos +#define GL_ARB_window_pos 1 +typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowPos2dARB (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2fARB (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2iARB (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2ivARB (const GLint *v); +GLAPI void APIENTRY glWindowPos2sARB (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2svARB (const GLshort *v); +GLAPI void APIENTRY glWindowPos3dARB (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3fARB (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3iARB (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3ivARB (const GLint *v); +GLAPI void APIENTRY glWindowPos3sARB (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3svARB (const GLshort *v); +#endif +#endif /* GL_ARB_window_pos */ + +#ifndef GL_KHR_blend_equation_advanced +#define GL_KHR_blend_equation_advanced 1 +#define GL_MULTIPLY_KHR 0x9294 +#define GL_SCREEN_KHR 0x9295 +#define GL_OVERLAY_KHR 0x9296 +#define GL_DARKEN_KHR 0x9297 +#define GL_LIGHTEN_KHR 0x9298 +#define GL_COLORDODGE_KHR 0x9299 +#define GL_COLORBURN_KHR 0x929A +#define GL_HARDLIGHT_KHR 0x929B +#define GL_SOFTLIGHT_KHR 0x929C +#define GL_DIFFERENCE_KHR 0x929E +#define GL_EXCLUSION_KHR 0x92A0 +#define GL_HSL_HUE_KHR 0x92AD +#define GL_HSL_SATURATION_KHR 0x92AE +#define GL_HSL_COLOR_KHR 0x92AF +#define GL_HSL_LUMINOSITY_KHR 0x92B0 +typedef void (APIENTRYP PFNGLBLENDBARRIERKHRPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendBarrierKHR (void); +#endif +#endif /* GL_KHR_blend_equation_advanced */ + +#ifndef GL_KHR_blend_equation_advanced_coherent +#define GL_KHR_blend_equation_advanced_coherent 1 +#define GL_BLEND_ADVANCED_COHERENT_KHR 0x9285 +#endif /* GL_KHR_blend_equation_advanced_coherent */ + +#ifndef GL_KHR_context_flush_control +#define GL_KHR_context_flush_control 1 +#endif /* GL_KHR_context_flush_control */ + +#ifndef GL_KHR_debug +#define GL_KHR_debug 1 +#endif /* GL_KHR_debug */ + +#ifndef GL_KHR_robust_buffer_access_behavior +#define GL_KHR_robust_buffer_access_behavior 1 +#endif /* GL_KHR_robust_buffer_access_behavior */ + +#ifndef GL_KHR_robustness +#define GL_KHR_robustness 1 +#define GL_CONTEXT_ROBUST_ACCESS 0x90F3 +#endif /* GL_KHR_robustness */ + +#ifndef GL_KHR_texture_compression_astc_hdr +#define GL_KHR_texture_compression_astc_hdr 1 +#define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93B0 +#define GL_COMPRESSED_RGBA_ASTC_5x4_KHR 0x93B1 +#define GL_COMPRESSED_RGBA_ASTC_5x5_KHR 0x93B2 +#define GL_COMPRESSED_RGBA_ASTC_6x5_KHR 0x93B3 +#define GL_COMPRESSED_RGBA_ASTC_6x6_KHR 0x93B4 +#define GL_COMPRESSED_RGBA_ASTC_8x5_KHR 0x93B5 +#define GL_COMPRESSED_RGBA_ASTC_8x6_KHR 0x93B6 +#define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93B7 +#define GL_COMPRESSED_RGBA_ASTC_10x5_KHR 0x93B8 +#define GL_COMPRESSED_RGBA_ASTC_10x6_KHR 0x93B9 +#define GL_COMPRESSED_RGBA_ASTC_10x8_KHR 0x93BA +#define GL_COMPRESSED_RGBA_ASTC_10x10_KHR 0x93BB +#define GL_COMPRESSED_RGBA_ASTC_12x10_KHR 0x93BC +#define GL_COMPRESSED_RGBA_ASTC_12x12_KHR 0x93BD +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR 0x93D0 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR 0x93D1 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR 0x93D2 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR 0x93D3 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR 0x93D4 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR 0x93D5 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR 0x93D6 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR 0x93D7 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR 0x93D8 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR 0x93D9 +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR 0x93DA +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR 0x93DB +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR 0x93DC +#define GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR 0x93DD +#endif /* GL_KHR_texture_compression_astc_hdr */ + +#ifndef GL_KHR_texture_compression_astc_ldr +#define GL_KHR_texture_compression_astc_ldr 1 +#endif /* GL_KHR_texture_compression_astc_ldr */ + +#ifndef GL_OES_byte_coordinates +#define GL_OES_byte_coordinates 1 +typedef void (APIENTRYP PFNGLMULTITEXCOORD1BOESPROC) (GLenum texture, GLbyte s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2BOESPROC) (GLenum texture, GLbyte s, GLbyte t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3BOESPROC) (GLenum texture, GLbyte s, GLbyte t, GLbyte r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4BOESPROC) (GLenum texture, GLbyte s, GLbyte t, GLbyte r, GLbyte q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4BVOESPROC) (GLenum texture, const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD1BOESPROC) (GLbyte s); +typedef void (APIENTRYP PFNGLTEXCOORD1BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD2BOESPROC) (GLbyte s, GLbyte t); +typedef void (APIENTRYP PFNGLTEXCOORD2BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD3BOESPROC) (GLbyte s, GLbyte t, GLbyte r); +typedef void (APIENTRYP PFNGLTEXCOORD3BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLTEXCOORD4BOESPROC) (GLbyte s, GLbyte t, GLbyte r, GLbyte q); +typedef void (APIENTRYP PFNGLTEXCOORD4BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX2BOESPROC) (GLbyte x, GLbyte y); +typedef void (APIENTRYP PFNGLVERTEX2BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX3BOESPROC) (GLbyte x, GLbyte y, GLbyte z); +typedef void (APIENTRYP PFNGLVERTEX3BVOESPROC) (const GLbyte *coords); +typedef void (APIENTRYP PFNGLVERTEX4BOESPROC) (GLbyte x, GLbyte y, GLbyte z, GLbyte w); +typedef void (APIENTRYP PFNGLVERTEX4BVOESPROC) (const GLbyte *coords); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiTexCoord1bOES (GLenum texture, GLbyte s); +GLAPI void APIENTRY glMultiTexCoord1bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord2bOES (GLenum texture, GLbyte s, GLbyte t); +GLAPI void APIENTRY glMultiTexCoord2bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord3bOES (GLenum texture, GLbyte s, GLbyte t, GLbyte r); +GLAPI void APIENTRY glMultiTexCoord3bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glMultiTexCoord4bOES (GLenum texture, GLbyte s, GLbyte t, GLbyte r, GLbyte q); +GLAPI void APIENTRY glMultiTexCoord4bvOES (GLenum texture, const GLbyte *coords); +GLAPI void APIENTRY glTexCoord1bOES (GLbyte s); +GLAPI void APIENTRY glTexCoord1bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord2bOES (GLbyte s, GLbyte t); +GLAPI void APIENTRY glTexCoord2bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord3bOES (GLbyte s, GLbyte t, GLbyte r); +GLAPI void APIENTRY glTexCoord3bvOES (const GLbyte *coords); +GLAPI void APIENTRY glTexCoord4bOES (GLbyte s, GLbyte t, GLbyte r, GLbyte q); +GLAPI void APIENTRY glTexCoord4bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex2bOES (GLbyte x, GLbyte y); +GLAPI void APIENTRY glVertex2bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex3bOES (GLbyte x, GLbyte y, GLbyte z); +GLAPI void APIENTRY glVertex3bvOES (const GLbyte *coords); +GLAPI void APIENTRY glVertex4bOES (GLbyte x, GLbyte y, GLbyte z, GLbyte w); +GLAPI void APIENTRY glVertex4bvOES (const GLbyte *coords); +#endif +#endif /* GL_OES_byte_coordinates */ + +#ifndef GL_OES_compressed_paletted_texture +#define GL_OES_compressed_paletted_texture 1 +#define GL_PALETTE4_RGB8_OES 0x8B90 +#define GL_PALETTE4_RGBA8_OES 0x8B91 +#define GL_PALETTE4_R5_G6_B5_OES 0x8B92 +#define GL_PALETTE4_RGBA4_OES 0x8B93 +#define GL_PALETTE4_RGB5_A1_OES 0x8B94 +#define GL_PALETTE8_RGB8_OES 0x8B95 +#define GL_PALETTE8_RGBA8_OES 0x8B96 +#define GL_PALETTE8_R5_G6_B5_OES 0x8B97 +#define GL_PALETTE8_RGBA4_OES 0x8B98 +#define GL_PALETTE8_RGB5_A1_OES 0x8B99 +#endif /* GL_OES_compressed_paletted_texture */ + +#ifndef GL_OES_fixed_point +#define GL_OES_fixed_point 1 +typedef GLint GLfixed; +#define GL_FIXED_OES 0x140C +typedef void (APIENTRYP PFNGLALPHAFUNCXOESPROC) (GLenum func, GLfixed ref); +typedef void (APIENTRYP PFNGLCLEARCOLORXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCLEARDEPTHXOESPROC) (GLfixed depth); +typedef void (APIENTRYP PFNGLCLIPPLANEXOESPROC) (GLenum plane, const GLfixed *equation); +typedef void (APIENTRYP PFNGLCOLOR4XOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLDEPTHRANGEXOESPROC) (GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLFOGXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLFOGXVOESPROC) (GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLFRUSTUMXOESPROC) (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLGETCLIPPLANEXOESPROC) (GLenum plane, GLfixed *equation); +typedef void (APIENTRYP PFNGLGETFIXEDVOESPROC) (GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXENVXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLLIGHTMODELXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLLIGHTMODELXVOESPROC) (GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLLIGHTXVOESPROC) (GLenum light, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLLINEWIDTHXOESPROC) (GLfixed width); +typedef void (APIENTRYP PFNGLLOADMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLMATERIALXVOESPROC) (GLenum face, GLenum pname, const GLfixed *param); +typedef void (APIENTRYP PFNGLMULTMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4XOESPROC) (GLenum texture, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +typedef void (APIENTRYP PFNGLNORMAL3XOESPROC) (GLfixed nx, GLfixed ny, GLfixed nz); +typedef void (APIENTRYP PFNGLORTHOXOESPROC) (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +typedef void (APIENTRYP PFNGLPOINTPARAMETERXVOESPROC) (GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLPOINTSIZEXOESPROC) (GLfixed size); +typedef void (APIENTRYP PFNGLPOLYGONOFFSETXOESPROC) (GLfixed factor, GLfixed units); +typedef void (APIENTRYP PFNGLROTATEXOESPROC) (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLSAMPLECOVERAGEOESPROC) (GLfixed value, GLboolean invert); +typedef void (APIENTRYP PFNGLSCALEXOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLTEXENVXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXENVXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLTRANSLATEXOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLACCUMXOESPROC) (GLenum op, GLfixed value); +typedef void (APIENTRYP PFNGLBITMAPXOESPROC) (GLsizei width, GLsizei height, GLfixed xorig, GLfixed yorig, GLfixed xmove, GLfixed ymove, const GLubyte *bitmap); +typedef void (APIENTRYP PFNGLBLENDCOLORXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCLEARACCUMXOESPROC) (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +typedef void (APIENTRYP PFNGLCOLOR3XOESPROC) (GLfixed red, GLfixed green, GLfixed blue); +typedef void (APIENTRYP PFNGLCOLOR3XVOESPROC) (const GLfixed *components); +typedef void (APIENTRYP PFNGLCOLOR4XVOESPROC) (const GLfixed *components); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERXOESPROC) (GLenum target, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERXVOESPROC) (GLenum target, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLEVALCOORD1XOESPROC) (GLfixed u); +typedef void (APIENTRYP PFNGLEVALCOORD1XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLEVALCOORD2XOESPROC) (GLfixed u, GLfixed v); +typedef void (APIENTRYP PFNGLEVALCOORD2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLFEEDBACKBUFFERXOESPROC) (GLsizei n, GLenum type, const GLfixed *buffer); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERXVOESPROC) (GLenum target, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETLIGHTXOESPROC) (GLenum light, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETMAPXVOESPROC) (GLenum target, GLenum query, GLfixed *v); +typedef void (APIENTRYP PFNGLGETMATERIALXOESPROC) (GLenum face, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLGETPIXELMAPXVPROC) (GLenum map, GLint size, GLfixed *values); +typedef void (APIENTRYP PFNGLGETTEXGENXVOESPROC) (GLenum coord, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERXVOESPROC) (GLenum target, GLint level, GLenum pname, GLfixed *params); +typedef void (APIENTRYP PFNGLINDEXXOESPROC) (GLfixed component); +typedef void (APIENTRYP PFNGLINDEXXVOESPROC) (const GLfixed *component); +typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMAP1XOESPROC) (GLenum target, GLfixed u1, GLfixed u2, GLint stride, GLint order, GLfixed points); +typedef void (APIENTRYP PFNGLMAP2XOESPROC) (GLenum target, GLfixed u1, GLfixed u2, GLint ustride, GLint uorder, GLfixed v1, GLfixed v2, GLint vstride, GLint vorder, GLfixed points); +typedef void (APIENTRYP PFNGLMAPGRID1XOESPROC) (GLint n, GLfixed u1, GLfixed u2); +typedef void (APIENTRYP PFNGLMAPGRID2XOESPROC) (GLint n, GLfixed u1, GLfixed u2, GLfixed v1, GLfixed v2); +typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXXOESPROC) (const GLfixed *m); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1XOESPROC) (GLenum texture, GLfixed s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2XOESPROC) (GLenum texture, GLfixed s, GLfixed t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3XOESPROC) (GLenum texture, GLfixed s, GLfixed t, GLfixed r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4XVOESPROC) (GLenum texture, const GLfixed *coords); +typedef void (APIENTRYP PFNGLNORMAL3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLPASSTHROUGHXOESPROC) (GLfixed token); +typedef void (APIENTRYP PFNGLPIXELMAPXPROC) (GLenum map, GLint size, const GLfixed *values); +typedef void (APIENTRYP PFNGLPIXELSTOREXPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLPIXELTRANSFERXOESPROC) (GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLPIXELZOOMXOESPROC) (GLfixed xfactor, GLfixed yfactor); +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESXOESPROC) (GLsizei n, const GLuint *textures, const GLfixed *priorities); +typedef void (APIENTRYP PFNGLRASTERPOS2XOESPROC) (GLfixed x, GLfixed y); +typedef void (APIENTRYP PFNGLRASTERPOS2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRASTERPOS3XOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLRASTERPOS3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRASTERPOS4XOESPROC) (GLfixed x, GLfixed y, GLfixed z, GLfixed w); +typedef void (APIENTRYP PFNGLRASTERPOS4XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLRECTXOESPROC) (GLfixed x1, GLfixed y1, GLfixed x2, GLfixed y2); +typedef void (APIENTRYP PFNGLRECTXVOESPROC) (const GLfixed *v1, const GLfixed *v2); +typedef void (APIENTRYP PFNGLTEXCOORD1XOESPROC) (GLfixed s); +typedef void (APIENTRYP PFNGLTEXCOORD1XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD2XOESPROC) (GLfixed s, GLfixed t); +typedef void (APIENTRYP PFNGLTEXCOORD2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD3XOESPROC) (GLfixed s, GLfixed t, GLfixed r); +typedef void (APIENTRYP PFNGLTEXCOORD3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXCOORD4XOESPROC) (GLfixed s, GLfixed t, GLfixed r, GLfixed q); +typedef void (APIENTRYP PFNGLTEXCOORD4XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLTEXGENXOESPROC) (GLenum coord, GLenum pname, GLfixed param); +typedef void (APIENTRYP PFNGLTEXGENXVOESPROC) (GLenum coord, GLenum pname, const GLfixed *params); +typedef void (APIENTRYP PFNGLVERTEX2XOESPROC) (GLfixed x); +typedef void (APIENTRYP PFNGLVERTEX2XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLVERTEX3XOESPROC) (GLfixed x, GLfixed y); +typedef void (APIENTRYP PFNGLVERTEX3XVOESPROC) (const GLfixed *coords); +typedef void (APIENTRYP PFNGLVERTEX4XOESPROC) (GLfixed x, GLfixed y, GLfixed z); +typedef void (APIENTRYP PFNGLVERTEX4XVOESPROC) (const GLfixed *coords); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAlphaFuncxOES (GLenum func, GLfixed ref); +GLAPI void APIENTRY glClearColorxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glClearDepthxOES (GLfixed depth); +GLAPI void APIENTRY glClipPlanexOES (GLenum plane, const GLfixed *equation); +GLAPI void APIENTRY glColor4xOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glDepthRangexOES (GLfixed n, GLfixed f); +GLAPI void APIENTRY glFogxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glFogxvOES (GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glFrustumxOES (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +GLAPI void APIENTRY glGetClipPlanexOES (GLenum plane, GLfixed *equation); +GLAPI void APIENTRY glGetFixedvOES (GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexEnvxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glLightModelxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glLightModelxvOES (GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glLightxOES (GLenum light, GLenum pname, GLfixed param); +GLAPI void APIENTRY glLightxvOES (GLenum light, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glLineWidthxOES (GLfixed width); +GLAPI void APIENTRY glLoadMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMaterialxOES (GLenum face, GLenum pname, GLfixed param); +GLAPI void APIENTRY glMaterialxvOES (GLenum face, GLenum pname, const GLfixed *param); +GLAPI void APIENTRY glMultMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMultiTexCoord4xOES (GLenum texture, GLfixed s, GLfixed t, GLfixed r, GLfixed q); +GLAPI void APIENTRY glNormal3xOES (GLfixed nx, GLfixed ny, GLfixed nz); +GLAPI void APIENTRY glOrthoxOES (GLfixed l, GLfixed r, GLfixed b, GLfixed t, GLfixed n, GLfixed f); +GLAPI void APIENTRY glPointParameterxvOES (GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glPointSizexOES (GLfixed size); +GLAPI void APIENTRY glPolygonOffsetxOES (GLfixed factor, GLfixed units); +GLAPI void APIENTRY glRotatexOES (GLfixed angle, GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glSampleCoverageOES (GLfixed value, GLboolean invert); +GLAPI void APIENTRY glScalexOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glTexEnvxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexEnvxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glTexParameterxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexParameterxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glTranslatexOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glAccumxOES (GLenum op, GLfixed value); +GLAPI void APIENTRY glBitmapxOES (GLsizei width, GLsizei height, GLfixed xorig, GLfixed yorig, GLfixed xmove, GLfixed ymove, const GLubyte *bitmap); +GLAPI void APIENTRY glBlendColorxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glClearAccumxOES (GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha); +GLAPI void APIENTRY glColor3xOES (GLfixed red, GLfixed green, GLfixed blue); +GLAPI void APIENTRY glColor3xvOES (const GLfixed *components); +GLAPI void APIENTRY glColor4xvOES (const GLfixed *components); +GLAPI void APIENTRY glConvolutionParameterxOES (GLenum target, GLenum pname, GLfixed param); +GLAPI void APIENTRY glConvolutionParameterxvOES (GLenum target, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glEvalCoord1xOES (GLfixed u); +GLAPI void APIENTRY glEvalCoord1xvOES (const GLfixed *coords); +GLAPI void APIENTRY glEvalCoord2xOES (GLfixed u, GLfixed v); +GLAPI void APIENTRY glEvalCoord2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glFeedbackBufferxOES (GLsizei n, GLenum type, const GLfixed *buffer); +GLAPI void APIENTRY glGetConvolutionParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetHistogramParameterxvOES (GLenum target, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetLightxOES (GLenum light, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetMapxvOES (GLenum target, GLenum query, GLfixed *v); +GLAPI void APIENTRY glGetMaterialxOES (GLenum face, GLenum pname, GLfixed param); +GLAPI void APIENTRY glGetPixelMapxv (GLenum map, GLint size, GLfixed *values); +GLAPI void APIENTRY glGetTexGenxvOES (GLenum coord, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glGetTexLevelParameterxvOES (GLenum target, GLint level, GLenum pname, GLfixed *params); +GLAPI void APIENTRY glIndexxOES (GLfixed component); +GLAPI void APIENTRY glIndexxvOES (const GLfixed *component); +GLAPI void APIENTRY glLoadTransposeMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMap1xOES (GLenum target, GLfixed u1, GLfixed u2, GLint stride, GLint order, GLfixed points); +GLAPI void APIENTRY glMap2xOES (GLenum target, GLfixed u1, GLfixed u2, GLint ustride, GLint uorder, GLfixed v1, GLfixed v2, GLint vstride, GLint vorder, GLfixed points); +GLAPI void APIENTRY glMapGrid1xOES (GLint n, GLfixed u1, GLfixed u2); +GLAPI void APIENTRY glMapGrid2xOES (GLint n, GLfixed u1, GLfixed u2, GLfixed v1, GLfixed v2); +GLAPI void APIENTRY glMultTransposeMatrixxOES (const GLfixed *m); +GLAPI void APIENTRY glMultiTexCoord1xOES (GLenum texture, GLfixed s); +GLAPI void APIENTRY glMultiTexCoord1xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord2xOES (GLenum texture, GLfixed s, GLfixed t); +GLAPI void APIENTRY glMultiTexCoord2xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord3xOES (GLenum texture, GLfixed s, GLfixed t, GLfixed r); +GLAPI void APIENTRY glMultiTexCoord3xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glMultiTexCoord4xvOES (GLenum texture, const GLfixed *coords); +GLAPI void APIENTRY glNormal3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glPassThroughxOES (GLfixed token); +GLAPI void APIENTRY glPixelMapx (GLenum map, GLint size, const GLfixed *values); +GLAPI void APIENTRY glPixelStorex (GLenum pname, GLfixed param); +GLAPI void APIENTRY glPixelTransferxOES (GLenum pname, GLfixed param); +GLAPI void APIENTRY glPixelZoomxOES (GLfixed xfactor, GLfixed yfactor); +GLAPI void APIENTRY glPrioritizeTexturesxOES (GLsizei n, const GLuint *textures, const GLfixed *priorities); +GLAPI void APIENTRY glRasterPos2xOES (GLfixed x, GLfixed y); +GLAPI void APIENTRY glRasterPos2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRasterPos3xOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glRasterPos3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRasterPos4xOES (GLfixed x, GLfixed y, GLfixed z, GLfixed w); +GLAPI void APIENTRY glRasterPos4xvOES (const GLfixed *coords); +GLAPI void APIENTRY glRectxOES (GLfixed x1, GLfixed y1, GLfixed x2, GLfixed y2); +GLAPI void APIENTRY glRectxvOES (const GLfixed *v1, const GLfixed *v2); +GLAPI void APIENTRY glTexCoord1xOES (GLfixed s); +GLAPI void APIENTRY glTexCoord1xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord2xOES (GLfixed s, GLfixed t); +GLAPI void APIENTRY glTexCoord2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord3xOES (GLfixed s, GLfixed t, GLfixed r); +GLAPI void APIENTRY glTexCoord3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexCoord4xOES (GLfixed s, GLfixed t, GLfixed r, GLfixed q); +GLAPI void APIENTRY glTexCoord4xvOES (const GLfixed *coords); +GLAPI void APIENTRY glTexGenxOES (GLenum coord, GLenum pname, GLfixed param); +GLAPI void APIENTRY glTexGenxvOES (GLenum coord, GLenum pname, const GLfixed *params); +GLAPI void APIENTRY glVertex2xOES (GLfixed x); +GLAPI void APIENTRY glVertex2xvOES (const GLfixed *coords); +GLAPI void APIENTRY glVertex3xOES (GLfixed x, GLfixed y); +GLAPI void APIENTRY glVertex3xvOES (const GLfixed *coords); +GLAPI void APIENTRY glVertex4xOES (GLfixed x, GLfixed y, GLfixed z); +GLAPI void APIENTRY glVertex4xvOES (const GLfixed *coords); +#endif +#endif /* GL_OES_fixed_point */ + +#ifndef GL_OES_query_matrix +#define GL_OES_query_matrix 1 +typedef GLbitfield (APIENTRYP PFNGLQUERYMATRIXXOESPROC) (GLfixed *mantissa, GLint *exponent); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLbitfield APIENTRY glQueryMatrixxOES (GLfixed *mantissa, GLint *exponent); +#endif +#endif /* GL_OES_query_matrix */ + +#ifndef GL_OES_read_format +#define GL_OES_read_format 1 +#define GL_IMPLEMENTATION_COLOR_READ_TYPE_OES 0x8B9A +#define GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES 0x8B9B +#endif /* GL_OES_read_format */ + +#ifndef GL_OES_single_precision +#define GL_OES_single_precision 1 +typedef void (APIENTRYP PFNGLCLEARDEPTHFOESPROC) (GLclampf depth); +typedef void (APIENTRYP PFNGLCLIPPLANEFOESPROC) (GLenum plane, const GLfloat *equation); +typedef void (APIENTRYP PFNGLDEPTHRANGEFOESPROC) (GLclampf n, GLclampf f); +typedef void (APIENTRYP PFNGLFRUSTUMFOESPROC) (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +typedef void (APIENTRYP PFNGLGETCLIPPLANEFOESPROC) (GLenum plane, GLfloat *equation); +typedef void (APIENTRYP PFNGLORTHOFOESPROC) (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glClearDepthfOES (GLclampf depth); +GLAPI void APIENTRY glClipPlanefOES (GLenum plane, const GLfloat *equation); +GLAPI void APIENTRY glDepthRangefOES (GLclampf n, GLclampf f); +GLAPI void APIENTRY glFrustumfOES (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +GLAPI void APIENTRY glGetClipPlanefOES (GLenum plane, GLfloat *equation); +GLAPI void APIENTRY glOrthofOES (GLfloat l, GLfloat r, GLfloat b, GLfloat t, GLfloat n, GLfloat f); +#endif +#endif /* GL_OES_single_precision */ + +#ifndef GL_3DFX_multisample +#define GL_3DFX_multisample 1 +#define GL_MULTISAMPLE_3DFX 0x86B2 +#define GL_SAMPLE_BUFFERS_3DFX 0x86B3 +#define GL_SAMPLES_3DFX 0x86B4 +#define GL_MULTISAMPLE_BIT_3DFX 0x20000000 +#endif /* GL_3DFX_multisample */ + +#ifndef GL_3DFX_tbuffer +#define GL_3DFX_tbuffer 1 +typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTbufferMask3DFX (GLuint mask); +#endif +#endif /* GL_3DFX_tbuffer */ + +#ifndef GL_3DFX_texture_compression_FXT1 +#define GL_3DFX_texture_compression_FXT1 1 +#define GL_COMPRESSED_RGB_FXT1_3DFX 0x86B0 +#define GL_COMPRESSED_RGBA_FXT1_3DFX 0x86B1 +#endif /* GL_3DFX_texture_compression_FXT1 */ + +#ifndef GL_AMD_blend_minmax_factor +#define GL_AMD_blend_minmax_factor 1 +#define GL_FACTOR_MIN_AMD 0x901C +#define GL_FACTOR_MAX_AMD 0x901D +#endif /* GL_AMD_blend_minmax_factor */ + +#ifndef GL_AMD_conservative_depth +#define GL_AMD_conservative_depth 1 +#endif /* GL_AMD_conservative_depth */ + +#ifndef GL_AMD_debug_output +#define GL_AMD_debug_output 1 +typedef void (APIENTRY *GLDEBUGPROCAMD)(GLuint id,GLenum category,GLenum severity,GLsizei length,const GLchar *message,void *userParam); +#define GL_MAX_DEBUG_MESSAGE_LENGTH_AMD 0x9143 +#define GL_MAX_DEBUG_LOGGED_MESSAGES_AMD 0x9144 +#define GL_DEBUG_LOGGED_MESSAGES_AMD 0x9145 +#define GL_DEBUG_SEVERITY_HIGH_AMD 0x9146 +#define GL_DEBUG_SEVERITY_MEDIUM_AMD 0x9147 +#define GL_DEBUG_SEVERITY_LOW_AMD 0x9148 +#define GL_DEBUG_CATEGORY_API_ERROR_AMD 0x9149 +#define GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD 0x914A +#define GL_DEBUG_CATEGORY_DEPRECATION_AMD 0x914B +#define GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD 0x914C +#define GL_DEBUG_CATEGORY_PERFORMANCE_AMD 0x914D +#define GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD 0x914E +#define GL_DEBUG_CATEGORY_APPLICATION_AMD 0x914F +#define GL_DEBUG_CATEGORY_OTHER_AMD 0x9150 +typedef void (APIENTRYP PFNGLDEBUGMESSAGEENABLEAMDPROC) (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTAMDPROC) (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf); +typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKAMDPROC) (GLDEBUGPROCAMD callback, void *userParam); +typedef GLuint (APIENTRYP PFNGLGETDEBUGMESSAGELOGAMDPROC) (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDebugMessageEnableAMD (GLenum category, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); +GLAPI void APIENTRY glDebugMessageInsertAMD (GLenum category, GLenum severity, GLuint id, GLsizei length, const GLchar *buf); +GLAPI void APIENTRY glDebugMessageCallbackAMD (GLDEBUGPROCAMD callback, void *userParam); +GLAPI GLuint APIENTRY glGetDebugMessageLogAMD (GLuint count, GLsizei bufsize, GLenum *categories, GLuint *severities, GLuint *ids, GLsizei *lengths, GLchar *message); +#endif +#endif /* GL_AMD_debug_output */ + +#ifndef GL_AMD_depth_clamp_separate +#define GL_AMD_depth_clamp_separate 1 +#define GL_DEPTH_CLAMP_NEAR_AMD 0x901E +#define GL_DEPTH_CLAMP_FAR_AMD 0x901F +#endif /* GL_AMD_depth_clamp_separate */ + +#ifndef GL_AMD_draw_buffers_blend +#define GL_AMD_draw_buffers_blend 1 +typedef void (APIENTRYP PFNGLBLENDFUNCINDEXEDAMDPROC) (GLuint buf, GLenum src, GLenum dst); +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +typedef void (APIENTRYP PFNGLBLENDEQUATIONINDEXEDAMDPROC) (GLuint buf, GLenum mode); +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEINDEXEDAMDPROC) (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncIndexedAMD (GLuint buf, GLenum src, GLenum dst); +GLAPI void APIENTRY glBlendFuncSeparateIndexedAMD (GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); +GLAPI void APIENTRY glBlendEquationIndexedAMD (GLuint buf, GLenum mode); +GLAPI void APIENTRY glBlendEquationSeparateIndexedAMD (GLuint buf, GLenum modeRGB, GLenum modeAlpha); +#endif +#endif /* GL_AMD_draw_buffers_blend */ + +#ifndef GL_AMD_gcn_shader +#define GL_AMD_gcn_shader 1 +#endif /* GL_AMD_gcn_shader */ + +#ifndef GL_AMD_gpu_shader_int64 +#define GL_AMD_gpu_shader_int64 1 +typedef int64_t GLint64EXT; +#define GL_INT64_NV 0x140E +#define GL_UNSIGNED_INT64_NV 0x140F +#define GL_INT8_NV 0x8FE0 +#define GL_INT8_VEC2_NV 0x8FE1 +#define GL_INT8_VEC3_NV 0x8FE2 +#define GL_INT8_VEC4_NV 0x8FE3 +#define GL_INT16_NV 0x8FE4 +#define GL_INT16_VEC2_NV 0x8FE5 +#define GL_INT16_VEC3_NV 0x8FE6 +#define GL_INT16_VEC4_NV 0x8FE7 +#define GL_INT64_VEC2_NV 0x8FE9 +#define GL_INT64_VEC3_NV 0x8FEA +#define GL_INT64_VEC4_NV 0x8FEB +#define GL_UNSIGNED_INT8_NV 0x8FEC +#define GL_UNSIGNED_INT8_VEC2_NV 0x8FED +#define GL_UNSIGNED_INT8_VEC3_NV 0x8FEE +#define GL_UNSIGNED_INT8_VEC4_NV 0x8FEF +#define GL_UNSIGNED_INT16_NV 0x8FF0 +#define GL_UNSIGNED_INT16_VEC2_NV 0x8FF1 +#define GL_UNSIGNED_INT16_VEC3_NV 0x8FF2 +#define GL_UNSIGNED_INT16_VEC4_NV 0x8FF3 +#define GL_UNSIGNED_INT64_VEC2_NV 0x8FF5 +#define GL_UNSIGNED_INT64_VEC3_NV 0x8FF6 +#define GL_UNSIGNED_INT64_VEC4_NV 0x8FF7 +#define GL_FLOAT16_NV 0x8FF8 +#define GL_FLOAT16_VEC2_NV 0x8FF9 +#define GL_FLOAT16_VEC3_NV 0x8FFA +#define GL_FLOAT16_VEC4_NV 0x8FFB +typedef void (APIENTRYP PFNGLUNIFORM1I64NVPROC) (GLint location, GLint64EXT x); +typedef void (APIENTRYP PFNGLUNIFORM2I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLUNIFORM3I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLUNIFORM4I64NVPROC) (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLUNIFORM1I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM2I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM3I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM4I64VNVPROC) (GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM1UI64NVPROC) (GLint location, GLuint64EXT x); +typedef void (APIENTRYP PFNGLUNIFORM2UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLUNIFORM3UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLUNIFORM4UI64NVPROC) (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLUNIFORM1UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM2UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM3UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLUNIFORM4UI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLGETUNIFORMI64VNVPROC) (GLuint program, GLint location, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64NVPROC) (GLuint program, GLint location, GLint64EXT x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64NVPROC) (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4I64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64NVPROC) (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniform1i64NV (GLint location, GLint64EXT x); +GLAPI void APIENTRY glUniform2i64NV (GLint location, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glUniform3i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glUniform4i64NV (GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glUniform1i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform2i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform3i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform4i64vNV (GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glUniform1ui64NV (GLint location, GLuint64EXT x); +GLAPI void APIENTRY glUniform2ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glUniform3ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glUniform4ui64NV (GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glUniform1ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform2ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform3ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glUniform4ui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glGetUniformi64vNV (GLuint program, GLint location, GLint64EXT *params); +GLAPI void APIENTRY glGetUniformui64vNV (GLuint program, GLint location, GLuint64EXT *params); +GLAPI void APIENTRY glProgramUniform1i64NV (GLuint program, GLint location, GLint64EXT x); +GLAPI void APIENTRY glProgramUniform2i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glProgramUniform3i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glProgramUniform4i64NV (GLuint program, GLint location, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glProgramUniform1i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform2i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform3i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform4i64vNV (GLuint program, GLint location, GLsizei count, const GLint64EXT *value); +GLAPI void APIENTRY glProgramUniform1ui64NV (GLuint program, GLint location, GLuint64EXT x); +GLAPI void APIENTRY glProgramUniform2ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glProgramUniform3ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glProgramUniform4ui64NV (GLuint program, GLint location, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glProgramUniform1ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform2ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform3ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniform4ui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif +#endif /* GL_AMD_gpu_shader_int64 */ + +#ifndef GL_AMD_interleaved_elements +#define GL_AMD_interleaved_elements 1 +#define GL_VERTEX_ELEMENT_SWIZZLE_AMD 0x91A4 +#define GL_VERTEX_ID_SWIZZLE_AMD 0x91A5 +typedef void (APIENTRYP PFNGLVERTEXATTRIBPARAMETERIAMDPROC) (GLuint index, GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribParameteriAMD (GLuint index, GLenum pname, GLint param); +#endif +#endif /* GL_AMD_interleaved_elements */ + +#ifndef GL_AMD_multi_draw_indirect +#define GL_AMD_multi_draw_indirect 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTAMDPROC) (GLenum mode, const void *indirect, GLsizei primcount, GLsizei stride); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTAMDPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei primcount, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectAMD (GLenum mode, const void *indirect, GLsizei primcount, GLsizei stride); +GLAPI void APIENTRY glMultiDrawElementsIndirectAMD (GLenum mode, GLenum type, const void *indirect, GLsizei primcount, GLsizei stride); +#endif +#endif /* GL_AMD_multi_draw_indirect */ + +#ifndef GL_AMD_name_gen_delete +#define GL_AMD_name_gen_delete 1 +#define GL_DATA_BUFFER_AMD 0x9151 +#define GL_PERFORMANCE_MONITOR_AMD 0x9152 +#define GL_QUERY_OBJECT_AMD 0x9153 +#define GL_VERTEX_ARRAY_OBJECT_AMD 0x9154 +#define GL_SAMPLER_OBJECT_AMD 0x9155 +typedef void (APIENTRYP PFNGLGENNAMESAMDPROC) (GLenum identifier, GLuint num, GLuint *names); +typedef void (APIENTRYP PFNGLDELETENAMESAMDPROC) (GLenum identifier, GLuint num, const GLuint *names); +typedef GLboolean (APIENTRYP PFNGLISNAMEAMDPROC) (GLenum identifier, GLuint name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenNamesAMD (GLenum identifier, GLuint num, GLuint *names); +GLAPI void APIENTRY glDeleteNamesAMD (GLenum identifier, GLuint num, const GLuint *names); +GLAPI GLboolean APIENTRY glIsNameAMD (GLenum identifier, GLuint name); +#endif +#endif /* GL_AMD_name_gen_delete */ + +#ifndef GL_AMD_occlusion_query_event +#define GL_AMD_occlusion_query_event 1 +#define GL_OCCLUSION_QUERY_EVENT_MASK_AMD 0x874F +#define GL_QUERY_DEPTH_PASS_EVENT_BIT_AMD 0x00000001 +#define GL_QUERY_DEPTH_FAIL_EVENT_BIT_AMD 0x00000002 +#define GL_QUERY_STENCIL_FAIL_EVENT_BIT_AMD 0x00000004 +#define GL_QUERY_DEPTH_BOUNDS_FAIL_EVENT_BIT_AMD 0x00000008 +#define GL_QUERY_ALL_EVENT_BITS_AMD 0xFFFFFFFF +typedef void (APIENTRYP PFNGLQUERYOBJECTPARAMETERUIAMDPROC) (GLenum target, GLuint id, GLenum pname, GLuint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glQueryObjectParameteruiAMD (GLenum target, GLuint id, GLenum pname, GLuint param); +#endif +#endif /* GL_AMD_occlusion_query_event */ + +#ifndef GL_AMD_performance_monitor +#define GL_AMD_performance_monitor 1 +#define GL_COUNTER_TYPE_AMD 0x8BC0 +#define GL_COUNTER_RANGE_AMD 0x8BC1 +#define GL_UNSIGNED_INT64_AMD 0x8BC2 +#define GL_PERCENTAGE_AMD 0x8BC3 +#define GL_PERFMON_RESULT_AVAILABLE_AMD 0x8BC4 +#define GL_PERFMON_RESULT_SIZE_AMD 0x8BC5 +#define GL_PERFMON_RESULT_AMD 0x8BC6 +typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSAMDPROC) (GLint *numGroups, GLsizei groupsSize, GLuint *groups); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSAMDPROC) (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); +typedef void (APIENTRYP PFNGLGETPERFMONITORGROUPSTRINGAMDPROC) (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERSTRINGAMDPROC) (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERINFOAMDPROC) (GLuint group, GLuint counter, GLenum pname, void *data); +typedef void (APIENTRYP PFNGLGENPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); +typedef void (APIENTRYP PFNGLDELETEPERFMONITORSAMDPROC) (GLsizei n, GLuint *monitors); +typedef void (APIENTRYP PFNGLSELECTPERFMONITORCOUNTERSAMDPROC) (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); +typedef void (APIENTRYP PFNGLBEGINPERFMONITORAMDPROC) (GLuint monitor); +typedef void (APIENTRYP PFNGLENDPERFMONITORAMDPROC) (GLuint monitor); +typedef void (APIENTRYP PFNGLGETPERFMONITORCOUNTERDATAAMDPROC) (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetPerfMonitorGroupsAMD (GLint *numGroups, GLsizei groupsSize, GLuint *groups); +GLAPI void APIENTRY glGetPerfMonitorCountersAMD (GLuint group, GLint *numCounters, GLint *maxActiveCounters, GLsizei counterSize, GLuint *counters); +GLAPI void APIENTRY glGetPerfMonitorGroupStringAMD (GLuint group, GLsizei bufSize, GLsizei *length, GLchar *groupString); +GLAPI void APIENTRY glGetPerfMonitorCounterStringAMD (GLuint group, GLuint counter, GLsizei bufSize, GLsizei *length, GLchar *counterString); +GLAPI void APIENTRY glGetPerfMonitorCounterInfoAMD (GLuint group, GLuint counter, GLenum pname, void *data); +GLAPI void APIENTRY glGenPerfMonitorsAMD (GLsizei n, GLuint *monitors); +GLAPI void APIENTRY glDeletePerfMonitorsAMD (GLsizei n, GLuint *monitors); +GLAPI void APIENTRY glSelectPerfMonitorCountersAMD (GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint *counterList); +GLAPI void APIENTRY glBeginPerfMonitorAMD (GLuint monitor); +GLAPI void APIENTRY glEndPerfMonitorAMD (GLuint monitor); +GLAPI void APIENTRY glGetPerfMonitorCounterDataAMD (GLuint monitor, GLenum pname, GLsizei dataSize, GLuint *data, GLint *bytesWritten); +#endif +#endif /* GL_AMD_performance_monitor */ + +#ifndef GL_AMD_pinned_memory +#define GL_AMD_pinned_memory 1 +#define GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD 0x9160 +#endif /* GL_AMD_pinned_memory */ + +#ifndef GL_AMD_query_buffer_object +#define GL_AMD_query_buffer_object 1 +#define GL_QUERY_BUFFER_AMD 0x9192 +#define GL_QUERY_BUFFER_BINDING_AMD 0x9193 +#define GL_QUERY_RESULT_NO_WAIT_AMD 0x9194 +#endif /* GL_AMD_query_buffer_object */ + +#ifndef GL_AMD_sample_positions +#define GL_AMD_sample_positions 1 +#define GL_SUBSAMPLE_DISTANCE_AMD 0x883F +typedef void (APIENTRYP PFNGLSETMULTISAMPLEFVAMDPROC) (GLenum pname, GLuint index, const GLfloat *val); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSetMultisamplefvAMD (GLenum pname, GLuint index, const GLfloat *val); +#endif +#endif /* GL_AMD_sample_positions */ + +#ifndef GL_AMD_seamless_cubemap_per_texture +#define GL_AMD_seamless_cubemap_per_texture 1 +#endif /* GL_AMD_seamless_cubemap_per_texture */ + +#ifndef GL_AMD_shader_atomic_counter_ops +#define GL_AMD_shader_atomic_counter_ops 1 +#endif /* GL_AMD_shader_atomic_counter_ops */ + +#ifndef GL_AMD_shader_stencil_export +#define GL_AMD_shader_stencil_export 1 +#endif /* GL_AMD_shader_stencil_export */ + +#ifndef GL_AMD_shader_trinary_minmax +#define GL_AMD_shader_trinary_minmax 1 +#endif /* GL_AMD_shader_trinary_minmax */ + +#ifndef GL_AMD_sparse_texture +#define GL_AMD_sparse_texture 1 +#define GL_VIRTUAL_PAGE_SIZE_X_AMD 0x9195 +#define GL_VIRTUAL_PAGE_SIZE_Y_AMD 0x9196 +#define GL_VIRTUAL_PAGE_SIZE_Z_AMD 0x9197 +#define GL_MAX_SPARSE_TEXTURE_SIZE_AMD 0x9198 +#define GL_MAX_SPARSE_3D_TEXTURE_SIZE_AMD 0x9199 +#define GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS 0x919A +#define GL_MIN_SPARSE_LEVEL_AMD 0x919B +#define GL_MIN_LOD_WARNING_AMD 0x919C +#define GL_TEXTURE_STORAGE_SPARSE_BIT_AMD 0x00000001 +typedef void (APIENTRYP PFNGLTEXSTORAGESPARSEAMDPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +typedef void (APIENTRYP PFNGLTEXTURESTORAGESPARSEAMDPROC) (GLuint texture, GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexStorageSparseAMD (GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +GLAPI void APIENTRY glTextureStorageSparseAMD (GLuint texture, GLenum target, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLsizei layers, GLbitfield flags); +#endif +#endif /* GL_AMD_sparse_texture */ + +#ifndef GL_AMD_stencil_operation_extended +#define GL_AMD_stencil_operation_extended 1 +#define GL_SET_AMD 0x874A +#define GL_REPLACE_VALUE_AMD 0x874B +#define GL_STENCIL_OP_VALUE_AMD 0x874C +#define GL_STENCIL_BACK_OP_VALUE_AMD 0x874D +typedef void (APIENTRYP PFNGLSTENCILOPVALUEAMDPROC) (GLenum face, GLuint value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilOpValueAMD (GLenum face, GLuint value); +#endif +#endif /* GL_AMD_stencil_operation_extended */ + +#ifndef GL_AMD_texture_texture4 +#define GL_AMD_texture_texture4 1 +#endif /* GL_AMD_texture_texture4 */ + +#ifndef GL_AMD_transform_feedback3_lines_triangles +#define GL_AMD_transform_feedback3_lines_triangles 1 +#endif /* GL_AMD_transform_feedback3_lines_triangles */ + +#ifndef GL_AMD_transform_feedback4 +#define GL_AMD_transform_feedback4 1 +#define GL_STREAM_RASTERIZATION_AMD 0x91A0 +#endif /* GL_AMD_transform_feedback4 */ + +#ifndef GL_AMD_vertex_shader_layer +#define GL_AMD_vertex_shader_layer 1 +#endif /* GL_AMD_vertex_shader_layer */ + +#ifndef GL_AMD_vertex_shader_tessellator +#define GL_AMD_vertex_shader_tessellator 1 +#define GL_SAMPLER_BUFFER_AMD 0x9001 +#define GL_INT_SAMPLER_BUFFER_AMD 0x9002 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_AMD 0x9003 +#define GL_TESSELLATION_MODE_AMD 0x9004 +#define GL_TESSELLATION_FACTOR_AMD 0x9005 +#define GL_DISCRETE_AMD 0x9006 +#define GL_CONTINUOUS_AMD 0x9007 +typedef void (APIENTRYP PFNGLTESSELLATIONFACTORAMDPROC) (GLfloat factor); +typedef void (APIENTRYP PFNGLTESSELLATIONMODEAMDPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTessellationFactorAMD (GLfloat factor); +GLAPI void APIENTRY glTessellationModeAMD (GLenum mode); +#endif +#endif /* GL_AMD_vertex_shader_tessellator */ + +#ifndef GL_AMD_vertex_shader_viewport_index +#define GL_AMD_vertex_shader_viewport_index 1 +#endif /* GL_AMD_vertex_shader_viewport_index */ + +#ifndef GL_APPLE_aux_depth_stencil +#define GL_APPLE_aux_depth_stencil 1 +#define GL_AUX_DEPTH_STENCIL_APPLE 0x8A14 +#endif /* GL_APPLE_aux_depth_stencil */ + +#ifndef GL_APPLE_client_storage +#define GL_APPLE_client_storage 1 +#define GL_UNPACK_CLIENT_STORAGE_APPLE 0x85B2 +#endif /* GL_APPLE_client_storage */ + +#ifndef GL_APPLE_element_array +#define GL_APPLE_element_array 1 +#define GL_ELEMENT_ARRAY_APPLE 0x8A0C +#define GL_ELEMENT_ARRAY_TYPE_APPLE 0x8A0D +#define GL_ELEMENT_ARRAY_POINTER_APPLE 0x8A0E +typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glElementPointerAPPLE (GLenum type, const void *pointer); +GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum mode, GLint first, GLsizei count); +GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count); +GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount); +#endif +#endif /* GL_APPLE_element_array */ + +#ifndef GL_APPLE_fence +#define GL_APPLE_fence 1 +#define GL_DRAW_PIXELS_APPLE 0x8A0A +#define GL_FENCE_APPLE 0x8A0B +typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences); +typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences); +typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name); +typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenFencesAPPLE (GLsizei n, GLuint *fences); +GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei n, const GLuint *fences); +GLAPI void APIENTRY glSetFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint fence); +GLAPI void APIENTRY glFinishFenceAPPLE (GLuint fence); +GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum object, GLuint name); +GLAPI void APIENTRY glFinishObjectAPPLE (GLenum object, GLint name); +#endif +#endif /* GL_APPLE_fence */ + +#ifndef GL_APPLE_float_pixels +#define GL_APPLE_float_pixels 1 +#define GL_HALF_APPLE 0x140B +#define GL_RGBA_FLOAT32_APPLE 0x8814 +#define GL_RGB_FLOAT32_APPLE 0x8815 +#define GL_ALPHA_FLOAT32_APPLE 0x8816 +#define GL_INTENSITY_FLOAT32_APPLE 0x8817 +#define GL_LUMINANCE_FLOAT32_APPLE 0x8818 +#define GL_LUMINANCE_ALPHA_FLOAT32_APPLE 0x8819 +#define GL_RGBA_FLOAT16_APPLE 0x881A +#define GL_RGB_FLOAT16_APPLE 0x881B +#define GL_ALPHA_FLOAT16_APPLE 0x881C +#define GL_INTENSITY_FLOAT16_APPLE 0x881D +#define GL_LUMINANCE_FLOAT16_APPLE 0x881E +#define GL_LUMINANCE_ALPHA_FLOAT16_APPLE 0x881F +#define GL_COLOR_FLOAT_APPLE 0x8A0F +#endif /* GL_APPLE_float_pixels */ + +#ifndef GL_APPLE_flush_buffer_range +#define GL_APPLE_flush_buffer_range 1 +#define GL_BUFFER_SERIALIZED_MODIFY_APPLE 0x8A12 +#define GL_BUFFER_FLUSHING_UNMAP_APPLE 0x8A13 +typedef void (APIENTRYP PFNGLBUFFERPARAMETERIAPPLEPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDBUFFERRANGEAPPLEPROC) (GLenum target, GLintptr offset, GLsizeiptr size); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferParameteriAPPLE (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glFlushMappedBufferRangeAPPLE (GLenum target, GLintptr offset, GLsizeiptr size); +#endif +#endif /* GL_APPLE_flush_buffer_range */ + +#ifndef GL_APPLE_object_purgeable +#define GL_APPLE_object_purgeable 1 +#define GL_BUFFER_OBJECT_APPLE 0x85B3 +#define GL_RELEASED_APPLE 0x8A19 +#define GL_VOLATILE_APPLE 0x8A1A +#define GL_RETAINED_APPLE 0x8A1B +#define GL_UNDEFINED_APPLE 0x8A1C +#define GL_PURGEABLE_APPLE 0x8A1D +typedef GLenum (APIENTRYP PFNGLOBJECTPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option); +typedef GLenum (APIENTRYP PFNGLOBJECTUNPURGEABLEAPPLEPROC) (GLenum objectType, GLuint name, GLenum option); +typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVAPPLEPROC) (GLenum objectType, GLuint name, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLenum APIENTRY glObjectPurgeableAPPLE (GLenum objectType, GLuint name, GLenum option); +GLAPI GLenum APIENTRY glObjectUnpurgeableAPPLE (GLenum objectType, GLuint name, GLenum option); +GLAPI void APIENTRY glGetObjectParameterivAPPLE (GLenum objectType, GLuint name, GLenum pname, GLint *params); +#endif +#endif /* GL_APPLE_object_purgeable */ + +#ifndef GL_APPLE_rgb_422 +#define GL_APPLE_rgb_422 1 +#define GL_RGB_422_APPLE 0x8A1F +#define GL_UNSIGNED_SHORT_8_8_APPLE 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_APPLE 0x85BB +#define GL_RGB_RAW_422_APPLE 0x8A51 +#endif /* GL_APPLE_rgb_422 */ + +#ifndef GL_APPLE_row_bytes +#define GL_APPLE_row_bytes 1 +#define GL_PACK_ROW_BYTES_APPLE 0x8A15 +#define GL_UNPACK_ROW_BYTES_APPLE 0x8A16 +#endif /* GL_APPLE_row_bytes */ + +#ifndef GL_APPLE_specular_vector +#define GL_APPLE_specular_vector 1 +#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0 +#endif /* GL_APPLE_specular_vector */ + +#ifndef GL_APPLE_texture_range +#define GL_APPLE_texture_range 1 +#define GL_TEXTURE_RANGE_LENGTH_APPLE 0x85B7 +#define GL_TEXTURE_RANGE_POINTER_APPLE 0x85B8 +#define GL_TEXTURE_STORAGE_HINT_APPLE 0x85BC +#define GL_STORAGE_PRIVATE_APPLE 0x85BD +#define GL_STORAGE_CACHED_APPLE 0x85BE +#define GL_STORAGE_SHARED_APPLE 0x85BF +typedef void (APIENTRYP PFNGLTEXTURERANGEAPPLEPROC) (GLenum target, GLsizei length, const void *pointer); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERPOINTERVAPPLEPROC) (GLenum target, GLenum pname, void **params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureRangeAPPLE (GLenum target, GLsizei length, const void *pointer); +GLAPI void APIENTRY glGetTexParameterPointervAPPLE (GLenum target, GLenum pname, void **params); +#endif +#endif /* GL_APPLE_texture_range */ + +#ifndef GL_APPLE_transform_hint +#define GL_APPLE_transform_hint 1 +#define GL_TRANSFORM_HINT_APPLE 0x85B1 +#endif /* GL_APPLE_transform_hint */ + +#ifndef GL_APPLE_vertex_array_object +#define GL_APPLE_vertex_array_object 1 +#define GL_VERTEX_ARRAY_BINDING_APPLE 0x85B5 +typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array); +typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays); +typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, GLuint *arrays); +typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint array); +GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei n, const GLuint *arrays); +GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei n, GLuint *arrays); +GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint array); +#endif +#endif /* GL_APPLE_vertex_array_object */ + +#ifndef GL_APPLE_vertex_array_range +#define GL_APPLE_vertex_array_range 1 +#define GL_VERTEX_ARRAY_RANGE_APPLE 0x851D +#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E +#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F +#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521 +#define GL_STORAGE_CLIENT_APPLE 0x85B4 +typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void *pointer); +typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, void *pointer); +typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei length, void *pointer); +GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei length, void *pointer); +GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum pname, GLint param); +#endif +#endif /* GL_APPLE_vertex_array_range */ + +#ifndef GL_APPLE_vertex_program_evaluators +#define GL_APPLE_vertex_program_evaluators 1 +#define GL_VERTEX_ATTRIB_MAP1_APPLE 0x8A00 +#define GL_VERTEX_ATTRIB_MAP2_APPLE 0x8A01 +#define GL_VERTEX_ATTRIB_MAP1_SIZE_APPLE 0x8A02 +#define GL_VERTEX_ATTRIB_MAP1_COEFF_APPLE 0x8A03 +#define GL_VERTEX_ATTRIB_MAP1_ORDER_APPLE 0x8A04 +#define GL_VERTEX_ATTRIB_MAP1_DOMAIN_APPLE 0x8A05 +#define GL_VERTEX_ATTRIB_MAP2_SIZE_APPLE 0x8A06 +#define GL_VERTEX_ATTRIB_MAP2_COEFF_APPLE 0x8A07 +#define GL_VERTEX_ATTRIB_MAP2_ORDER_APPLE 0x8A08 +#define GL_VERTEX_ATTRIB_MAP2_DOMAIN_APPLE 0x8A09 +typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname); +typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBAPPLEPROC) (GLuint index, GLenum pname); +typedef GLboolean (APIENTRYP PFNGLISVERTEXATTRIBENABLEDAPPLEPROC) (GLuint index, GLenum pname); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB1FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2DAPPLEPROC) (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); +typedef void (APIENTRYP PFNGLMAPVERTEXATTRIB2FAPPLEPROC) (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glEnableVertexAttribAPPLE (GLuint index, GLenum pname); +GLAPI void APIENTRY glDisableVertexAttribAPPLE (GLuint index, GLenum pname); +GLAPI GLboolean APIENTRY glIsVertexAttribEnabledAPPLE (GLuint index, GLenum pname); +GLAPI void APIENTRY glMapVertexAttrib1dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); +GLAPI void APIENTRY glMapVertexAttrib1fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); +GLAPI void APIENTRY glMapVertexAttrib2dAPPLE (GLuint index, GLuint size, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); +GLAPI void APIENTRY glMapVertexAttrib2fAPPLE (GLuint index, GLuint size, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); +#endif +#endif /* GL_APPLE_vertex_program_evaluators */ + +#ifndef GL_APPLE_ycbcr_422 +#define GL_APPLE_ycbcr_422 1 +#define GL_YCBCR_422_APPLE 0x85B9 +#endif /* GL_APPLE_ycbcr_422 */ + +#ifndef GL_ATI_draw_buffers +#define GL_ATI_draw_buffers 1 +#define GL_MAX_DRAW_BUFFERS_ATI 0x8824 +#define GL_DRAW_BUFFER0_ATI 0x8825 +#define GL_DRAW_BUFFER1_ATI 0x8826 +#define GL_DRAW_BUFFER2_ATI 0x8827 +#define GL_DRAW_BUFFER3_ATI 0x8828 +#define GL_DRAW_BUFFER4_ATI 0x8829 +#define GL_DRAW_BUFFER5_ATI 0x882A +#define GL_DRAW_BUFFER6_ATI 0x882B +#define GL_DRAW_BUFFER7_ATI 0x882C +#define GL_DRAW_BUFFER8_ATI 0x882D +#define GL_DRAW_BUFFER9_ATI 0x882E +#define GL_DRAW_BUFFER10_ATI 0x882F +#define GL_DRAW_BUFFER11_ATI 0x8830 +#define GL_DRAW_BUFFER12_ATI 0x8831 +#define GL_DRAW_BUFFER13_ATI 0x8832 +#define GL_DRAW_BUFFER14_ATI 0x8833 +#define GL_DRAW_BUFFER15_ATI 0x8834 +typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawBuffersATI (GLsizei n, const GLenum *bufs); +#endif +#endif /* GL_ATI_draw_buffers */ + +#ifndef GL_ATI_element_array +#define GL_ATI_element_array 1 +#define GL_ELEMENT_ARRAY_ATI 0x8768 +#define GL_ELEMENT_ARRAY_TYPE_ATI 0x8769 +#define GL_ELEMENT_ARRAY_POINTER_ATI 0x876A +typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count); +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glElementPointerATI (GLenum type, const void *pointer); +GLAPI void APIENTRY glDrawElementArrayATI (GLenum mode, GLsizei count); +GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum mode, GLuint start, GLuint end, GLsizei count); +#endif +#endif /* GL_ATI_element_array */ + +#ifndef GL_ATI_envmap_bumpmap +#define GL_ATI_envmap_bumpmap 1 +#define GL_BUMP_ROT_MATRIX_ATI 0x8775 +#define GL_BUMP_ROT_MATRIX_SIZE_ATI 0x8776 +#define GL_BUMP_NUM_TEX_UNITS_ATI 0x8777 +#define GL_BUMP_TEX_UNITS_ATI 0x8778 +#define GL_DUDV_ATI 0x8779 +#define GL_DU8DV8_ATI 0x877A +#define GL_BUMP_ENVMAP_ATI 0x877B +#define GL_BUMP_TARGET_ATI 0x877C +typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param); +typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param); +typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBumpParameterivATI (GLenum pname, const GLint *param); +GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum pname, const GLfloat *param); +GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum pname, GLint *param); +GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum pname, GLfloat *param); +#endif +#endif /* GL_ATI_envmap_bumpmap */ + +#ifndef GL_ATI_fragment_shader +#define GL_ATI_fragment_shader 1 +#define GL_FRAGMENT_SHADER_ATI 0x8920 +#define GL_REG_0_ATI 0x8921 +#define GL_REG_1_ATI 0x8922 +#define GL_REG_2_ATI 0x8923 +#define GL_REG_3_ATI 0x8924 +#define GL_REG_4_ATI 0x8925 +#define GL_REG_5_ATI 0x8926 +#define GL_REG_6_ATI 0x8927 +#define GL_REG_7_ATI 0x8928 +#define GL_REG_8_ATI 0x8929 +#define GL_REG_9_ATI 0x892A +#define GL_REG_10_ATI 0x892B +#define GL_REG_11_ATI 0x892C +#define GL_REG_12_ATI 0x892D +#define GL_REG_13_ATI 0x892E +#define GL_REG_14_ATI 0x892F +#define GL_REG_15_ATI 0x8930 +#define GL_REG_16_ATI 0x8931 +#define GL_REG_17_ATI 0x8932 +#define GL_REG_18_ATI 0x8933 +#define GL_REG_19_ATI 0x8934 +#define GL_REG_20_ATI 0x8935 +#define GL_REG_21_ATI 0x8936 +#define GL_REG_22_ATI 0x8937 +#define GL_REG_23_ATI 0x8938 +#define GL_REG_24_ATI 0x8939 +#define GL_REG_25_ATI 0x893A +#define GL_REG_26_ATI 0x893B +#define GL_REG_27_ATI 0x893C +#define GL_REG_28_ATI 0x893D +#define GL_REG_29_ATI 0x893E +#define GL_REG_30_ATI 0x893F +#define GL_REG_31_ATI 0x8940 +#define GL_CON_0_ATI 0x8941 +#define GL_CON_1_ATI 0x8942 +#define GL_CON_2_ATI 0x8943 +#define GL_CON_3_ATI 0x8944 +#define GL_CON_4_ATI 0x8945 +#define GL_CON_5_ATI 0x8946 +#define GL_CON_6_ATI 0x8947 +#define GL_CON_7_ATI 0x8948 +#define GL_CON_8_ATI 0x8949 +#define GL_CON_9_ATI 0x894A +#define GL_CON_10_ATI 0x894B +#define GL_CON_11_ATI 0x894C +#define GL_CON_12_ATI 0x894D +#define GL_CON_13_ATI 0x894E +#define GL_CON_14_ATI 0x894F +#define GL_CON_15_ATI 0x8950 +#define GL_CON_16_ATI 0x8951 +#define GL_CON_17_ATI 0x8952 +#define GL_CON_18_ATI 0x8953 +#define GL_CON_19_ATI 0x8954 +#define GL_CON_20_ATI 0x8955 +#define GL_CON_21_ATI 0x8956 +#define GL_CON_22_ATI 0x8957 +#define GL_CON_23_ATI 0x8958 +#define GL_CON_24_ATI 0x8959 +#define GL_CON_25_ATI 0x895A +#define GL_CON_26_ATI 0x895B +#define GL_CON_27_ATI 0x895C +#define GL_CON_28_ATI 0x895D +#define GL_CON_29_ATI 0x895E +#define GL_CON_30_ATI 0x895F +#define GL_CON_31_ATI 0x8960 +#define GL_MOV_ATI 0x8961 +#define GL_ADD_ATI 0x8963 +#define GL_MUL_ATI 0x8964 +#define GL_SUB_ATI 0x8965 +#define GL_DOT3_ATI 0x8966 +#define GL_DOT4_ATI 0x8967 +#define GL_MAD_ATI 0x8968 +#define GL_LERP_ATI 0x8969 +#define GL_CND_ATI 0x896A +#define GL_CND0_ATI 0x896B +#define GL_DOT2_ADD_ATI 0x896C +#define GL_SECONDARY_INTERPOLATOR_ATI 0x896D +#define GL_NUM_FRAGMENT_REGISTERS_ATI 0x896E +#define GL_NUM_FRAGMENT_CONSTANTS_ATI 0x896F +#define GL_NUM_PASSES_ATI 0x8970 +#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI 0x8971 +#define GL_NUM_INSTRUCTIONS_TOTAL_ATI 0x8972 +#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973 +#define GL_NUM_LOOPBACK_COMPONENTS_ATI 0x8974 +#define GL_COLOR_ALPHA_PAIRING_ATI 0x8975 +#define GL_SWIZZLE_STR_ATI 0x8976 +#define GL_SWIZZLE_STQ_ATI 0x8977 +#define GL_SWIZZLE_STR_DR_ATI 0x8978 +#define GL_SWIZZLE_STQ_DQ_ATI 0x8979 +#define GL_SWIZZLE_STRQ_ATI 0x897A +#define GL_SWIZZLE_STRQ_DQ_ATI 0x897B +#define GL_RED_BIT_ATI 0x00000001 +#define GL_GREEN_BIT_ATI 0x00000002 +#define GL_BLUE_BIT_ATI 0x00000004 +#define GL_2X_BIT_ATI 0x00000001 +#define GL_4X_BIT_ATI 0x00000002 +#define GL_8X_BIT_ATI 0x00000004 +#define GL_HALF_BIT_ATI 0x00000008 +#define GL_QUARTER_BIT_ATI 0x00000010 +#define GL_EIGHTH_BIT_ATI 0x00000020 +#define GL_SATURATE_BIT_ATI 0x00000040 +#define GL_COMP_BIT_ATI 0x00000002 +#define GL_NEGATE_BIT_ATI 0x00000004 +#define GL_BIAS_BIT_ATI 0x00000008 +typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range); +typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id); +typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void); +typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void); +typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle); +typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint range); +GLAPI void APIENTRY glBindFragmentShaderATI (GLuint id); +GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint id); +GLAPI void APIENTRY glBeginFragmentShaderATI (void); +GLAPI void APIENTRY glEndFragmentShaderATI (void); +GLAPI void APIENTRY glPassTexCoordATI (GLuint dst, GLuint coord, GLenum swizzle); +GLAPI void APIENTRY glSampleMapATI (GLuint dst, GLuint interp, GLenum swizzle); +GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod); +GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod); +GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod); +GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint dst, const GLfloat *value); +#endif +#endif /* GL_ATI_fragment_shader */ + +#ifndef GL_ATI_map_object_buffer +#define GL_ATI_map_object_buffer 1 +typedef void *(APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void *APIENTRY glMapObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint buffer); +#endif +#endif /* GL_ATI_map_object_buffer */ + +#ifndef GL_ATI_meminfo +#define GL_ATI_meminfo 1 +#define GL_VBO_FREE_MEMORY_ATI 0x87FB +#define GL_TEXTURE_FREE_MEMORY_ATI 0x87FC +#define GL_RENDERBUFFER_FREE_MEMORY_ATI 0x87FD +#endif /* GL_ATI_meminfo */ + +#ifndef GL_ATI_pixel_format_float +#define GL_ATI_pixel_format_float 1 +#define GL_RGBA_FLOAT_MODE_ATI 0x8820 +#define GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI 0x8835 +#endif /* GL_ATI_pixel_format_float */ + +#ifndef GL_ATI_pn_triangles +#define GL_ATI_pn_triangles 1 +#define GL_PN_TRIANGLES_ATI 0x87F0 +#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1 +#define GL_PN_TRIANGLES_POINT_MODE_ATI 0x87F2 +#define GL_PN_TRIANGLES_NORMAL_MODE_ATI 0x87F3 +#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4 +#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5 +#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6 +#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7 +#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8 +typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPNTrianglesiATI (GLenum pname, GLint param); +GLAPI void APIENTRY glPNTrianglesfATI (GLenum pname, GLfloat param); +#endif +#endif /* GL_ATI_pn_triangles */ + +#ifndef GL_ATI_separate_stencil +#define GL_ATI_separate_stencil 1 +#define GL_STENCIL_BACK_FUNC_ATI 0x8800 +#define GL_STENCIL_BACK_FAIL_ATI 0x8801 +#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802 +#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803 +typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilOpSeparateATI (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask); +#endif +#endif /* GL_ATI_separate_stencil */ + +#ifndef GL_ATI_text_fragment_shader +#define GL_ATI_text_fragment_shader 1 +#define GL_TEXT_FRAGMENT_SHADER_ATI 0x8200 +#endif /* GL_ATI_text_fragment_shader */ + +#ifndef GL_ATI_texture_env_combine3 +#define GL_ATI_texture_env_combine3 1 +#define GL_MODULATE_ADD_ATI 0x8744 +#define GL_MODULATE_SIGNED_ADD_ATI 0x8745 +#define GL_MODULATE_SUBTRACT_ATI 0x8746 +#endif /* GL_ATI_texture_env_combine3 */ + +#ifndef GL_ATI_texture_float +#define GL_ATI_texture_float 1 +#define GL_RGBA_FLOAT32_ATI 0x8814 +#define GL_RGB_FLOAT32_ATI 0x8815 +#define GL_ALPHA_FLOAT32_ATI 0x8816 +#define GL_INTENSITY_FLOAT32_ATI 0x8817 +#define GL_LUMINANCE_FLOAT32_ATI 0x8818 +#define GL_LUMINANCE_ALPHA_FLOAT32_ATI 0x8819 +#define GL_RGBA_FLOAT16_ATI 0x881A +#define GL_RGB_FLOAT16_ATI 0x881B +#define GL_ALPHA_FLOAT16_ATI 0x881C +#define GL_INTENSITY_FLOAT16_ATI 0x881D +#define GL_LUMINANCE_FLOAT16_ATI 0x881E +#define GL_LUMINANCE_ALPHA_FLOAT16_ATI 0x881F +#endif /* GL_ATI_texture_float */ + +#ifndef GL_ATI_texture_mirror_once +#define GL_ATI_texture_mirror_once 1 +#define GL_MIRROR_CLAMP_ATI 0x8742 +#define GL_MIRROR_CLAMP_TO_EDGE_ATI 0x8743 +#endif /* GL_ATI_texture_mirror_once */ + +#ifndef GL_ATI_vertex_array_object +#define GL_ATI_vertex_array_object 1 +#define GL_STATIC_ATI 0x8760 +#define GL_DYNAMIC_ATI 0x8761 +#define GL_PRESERVE_ATI 0x8762 +#define GL_DISCARD_ATI 0x8763 +#define GL_OBJECT_BUFFER_SIZE_ATI 0x8764 +#define GL_OBJECT_BUFFER_USAGE_ATI 0x8765 +#define GL_ARRAY_OBJECT_BUFFER_ATI 0x8766 +#define GL_ARRAY_OBJECT_OFFSET_ATI 0x8767 +typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const void *pointer, GLenum usage); +typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const void *pointer, GLenum preserve); +typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei size, const void *pointer, GLenum usage); +GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint buffer, GLuint offset, GLsizei size, const void *pointer, GLenum preserve); +GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint buffer, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetObjectBufferivATI (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glFreeObjectBufferATI (GLuint buffer); +GLAPI void APIENTRY glArrayObjectATI (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum array, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetArrayObjectivATI (GLenum array, GLenum pname, GLint *params); +GLAPI void APIENTRY glVariantArrayObjectATI (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint id, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint id, GLenum pname, GLint *params); +#endif +#endif /* GL_ATI_vertex_array_object */ + +#ifndef GL_ATI_vertex_attrib_array_object +#define GL_ATI_vertex_attrib_array_object 1 +typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset); +GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint index, GLenum pname, GLint *params); +#endif +#endif /* GL_ATI_vertex_attrib_array_object */ + +#ifndef GL_ATI_vertex_streams +#define GL_ATI_vertex_streams 1 +#define GL_MAX_VERTEX_STREAMS_ATI 0x876B +#define GL_VERTEX_STREAM0_ATI 0x876C +#define GL_VERTEX_STREAM1_ATI 0x876D +#define GL_VERTEX_STREAM2_ATI 0x876E +#define GL_VERTEX_STREAM3_ATI 0x876F +#define GL_VERTEX_STREAM4_ATI 0x8770 +#define GL_VERTEX_STREAM5_ATI 0x8771 +#define GL_VERTEX_STREAM6_ATI 0x8772 +#define GL_VERTEX_STREAM7_ATI 0x8773 +#define GL_VERTEX_SOURCE_ATI 0x8774 +typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords); +typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz); +typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords); +typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream); +typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexStream1sATI (GLenum stream, GLshort x); +GLAPI void APIENTRY glVertexStream1svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream1iATI (GLenum stream, GLint x); +GLAPI void APIENTRY glVertexStream1ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream1fATI (GLenum stream, GLfloat x); +GLAPI void APIENTRY glVertexStream1fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream1dATI (GLenum stream, GLdouble x); +GLAPI void APIENTRY glVertexStream1dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream2sATI (GLenum stream, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexStream2svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream2iATI (GLenum stream, GLint x, GLint y); +GLAPI void APIENTRY glVertexStream2ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream2fATI (GLenum stream, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexStream2fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream2dATI (GLenum stream, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexStream2dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream3sATI (GLenum stream, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexStream3svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream3iATI (GLenum stream, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexStream3ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream3fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexStream3fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream3dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexStream3dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glVertexStream4sATI (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexStream4svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glVertexStream4iATI (GLenum stream, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexStream4ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glVertexStream4fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexStream4fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glVertexStream4dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexStream4dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glNormalStream3bATI (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz); +GLAPI void APIENTRY glNormalStream3bvATI (GLenum stream, const GLbyte *coords); +GLAPI void APIENTRY glNormalStream3sATI (GLenum stream, GLshort nx, GLshort ny, GLshort nz); +GLAPI void APIENTRY glNormalStream3svATI (GLenum stream, const GLshort *coords); +GLAPI void APIENTRY glNormalStream3iATI (GLenum stream, GLint nx, GLint ny, GLint nz); +GLAPI void APIENTRY glNormalStream3ivATI (GLenum stream, const GLint *coords); +GLAPI void APIENTRY glNormalStream3fATI (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz); +GLAPI void APIENTRY glNormalStream3fvATI (GLenum stream, const GLfloat *coords); +GLAPI void APIENTRY glNormalStream3dATI (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz); +GLAPI void APIENTRY glNormalStream3dvATI (GLenum stream, const GLdouble *coords); +GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum stream); +GLAPI void APIENTRY glVertexBlendEnviATI (GLenum pname, GLint param); +GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum pname, GLfloat param); +#endif +#endif /* GL_ATI_vertex_streams */ + +#ifndef GL_EXT_422_pixels +#define GL_EXT_422_pixels 1 +#define GL_422_EXT 0x80CC +#define GL_422_REV_EXT 0x80CD +#define GL_422_AVERAGE_EXT 0x80CE +#define GL_422_REV_AVERAGE_EXT 0x80CF +#endif /* GL_EXT_422_pixels */ + +#ifndef GL_EXT_abgr +#define GL_EXT_abgr 1 +#define GL_ABGR_EXT 0x8000 +#endif /* GL_EXT_abgr */ + +#ifndef GL_EXT_bgra +#define GL_EXT_bgra 1 +#define GL_BGR_EXT 0x80E0 +#define GL_BGRA_EXT 0x80E1 +#endif /* GL_EXT_bgra */ + +#ifndef GL_EXT_bindable_uniform +#define GL_EXT_bindable_uniform 1 +#define GL_MAX_VERTEX_BINDABLE_UNIFORMS_EXT 0x8DE2 +#define GL_MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT 0x8DE3 +#define GL_MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT 0x8DE4 +#define GL_MAX_BINDABLE_UNIFORM_SIZE_EXT 0x8DED +#define GL_UNIFORM_BUFFER_EXT 0x8DEE +#define GL_UNIFORM_BUFFER_BINDING_EXT 0x8DEF +typedef void (APIENTRYP PFNGLUNIFORMBUFFEREXTPROC) (GLuint program, GLint location, GLuint buffer); +typedef GLint (APIENTRYP PFNGLGETUNIFORMBUFFERSIZEEXTPROC) (GLuint program, GLint location); +typedef GLintptr (APIENTRYP PFNGLGETUNIFORMOFFSETEXTPROC) (GLuint program, GLint location); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUniformBufferEXT (GLuint program, GLint location, GLuint buffer); +GLAPI GLint APIENTRY glGetUniformBufferSizeEXT (GLuint program, GLint location); +GLAPI GLintptr APIENTRY glGetUniformOffsetEXT (GLuint program, GLint location); +#endif +#endif /* GL_EXT_bindable_uniform */ + +#ifndef GL_EXT_blend_color +#define GL_EXT_blend_color 1 +#define GL_CONSTANT_COLOR_EXT 0x8001 +#define GL_ONE_MINUS_CONSTANT_COLOR_EXT 0x8002 +#define GL_CONSTANT_ALPHA_EXT 0x8003 +#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT 0x8004 +#define GL_BLEND_COLOR_EXT 0x8005 +typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendColorEXT (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); +#endif +#endif /* GL_EXT_blend_color */ + +#ifndef GL_EXT_blend_equation_separate +#define GL_EXT_blend_equation_separate 1 +#define GL_BLEND_EQUATION_RGB_EXT 0x8009 +#define GL_BLEND_EQUATION_ALPHA_EXT 0x883D +typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum modeRGB, GLenum modeAlpha); +#endif +#endif /* GL_EXT_blend_equation_separate */ + +#ifndef GL_EXT_blend_func_separate +#define GL_EXT_blend_func_separate 1 +#define GL_BLEND_DST_RGB_EXT 0x80C8 +#define GL_BLEND_SRC_RGB_EXT 0x80C9 +#define GL_BLEND_DST_ALPHA_EXT 0x80CA +#define GL_BLEND_SRC_ALPHA_EXT 0x80CB +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#endif +#endif /* GL_EXT_blend_func_separate */ + +#ifndef GL_EXT_blend_logic_op +#define GL_EXT_blend_logic_op 1 +#endif /* GL_EXT_blend_logic_op */ + +#ifndef GL_EXT_blend_minmax +#define GL_EXT_blend_minmax 1 +#define GL_MIN_EXT 0x8007 +#define GL_MAX_EXT 0x8008 +#define GL_FUNC_ADD_EXT 0x8006 +#define GL_BLEND_EQUATION_EXT 0x8009 +typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendEquationEXT (GLenum mode); +#endif +#endif /* GL_EXT_blend_minmax */ + +#ifndef GL_EXT_blend_subtract +#define GL_EXT_blend_subtract 1 +#define GL_FUNC_SUBTRACT_EXT 0x800A +#define GL_FUNC_REVERSE_SUBTRACT_EXT 0x800B +#endif /* GL_EXT_blend_subtract */ + +#ifndef GL_EXT_clip_volume_hint +#define GL_EXT_clip_volume_hint 1 +#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT 0x80F0 +#endif /* GL_EXT_clip_volume_hint */ + +#ifndef GL_EXT_cmyka +#define GL_EXT_cmyka 1 +#define GL_CMYK_EXT 0x800C +#define GL_CMYKA_EXT 0x800D +#define GL_PACK_CMYK_HINT_EXT 0x800E +#define GL_UNPACK_CMYK_HINT_EXT 0x800F +#endif /* GL_EXT_cmyka */ + +#ifndef GL_EXT_color_subtable +#define GL_EXT_color_subtable 1 +typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorSubTableEXT (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width); +#endif +#endif /* GL_EXT_color_subtable */ + +#ifndef GL_EXT_compiled_vertex_array +#define GL_EXT_compiled_vertex_array 1 +#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT 0x81A8 +#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT 0x81A9 +typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLockArraysEXT (GLint first, GLsizei count); +GLAPI void APIENTRY glUnlockArraysEXT (void); +#endif +#endif /* GL_EXT_compiled_vertex_array */ + +#ifndef GL_EXT_convolution +#define GL_EXT_convolution 1 +#define GL_CONVOLUTION_1D_EXT 0x8010 +#define GL_CONVOLUTION_2D_EXT 0x8011 +#define GL_SEPARABLE_2D_EXT 0x8012 +#define GL_CONVOLUTION_BORDER_MODE_EXT 0x8013 +#define GL_CONVOLUTION_FILTER_SCALE_EXT 0x8014 +#define GL_CONVOLUTION_FILTER_BIAS_EXT 0x8015 +#define GL_REDUCE_EXT 0x8016 +#define GL_CONVOLUTION_FORMAT_EXT 0x8017 +#define GL_CONVOLUTION_WIDTH_EXT 0x8018 +#define GL_CONVOLUTION_HEIGHT_EXT 0x8019 +#define GL_MAX_CONVOLUTION_WIDTH_EXT 0x801A +#define GL_MAX_CONVOLUTION_HEIGHT_EXT 0x801B +#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C +#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D +#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E +#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F +#define GL_POST_CONVOLUTION_RED_BIAS_EXT 0x8020 +#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021 +#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022 +#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023 +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params); +typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, void *image); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *image); +GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum target, GLenum pname, GLfloat params); +GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum target, GLenum pname, GLint params); +GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum target, GLenum format, GLenum type, void *image); +GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum target, GLenum format, GLenum type, void *row, void *column, void *span); +GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *row, const void *column); +#endif +#endif /* GL_EXT_convolution */ + +#ifndef GL_EXT_coordinate_frame +#define GL_EXT_coordinate_frame 1 +#define GL_TANGENT_ARRAY_EXT 0x8439 +#define GL_BINORMAL_ARRAY_EXT 0x843A +#define GL_CURRENT_TANGENT_EXT 0x843B +#define GL_CURRENT_BINORMAL_EXT 0x843C +#define GL_TANGENT_ARRAY_TYPE_EXT 0x843E +#define GL_TANGENT_ARRAY_STRIDE_EXT 0x843F +#define GL_BINORMAL_ARRAY_TYPE_EXT 0x8440 +#define GL_BINORMAL_ARRAY_STRIDE_EXT 0x8441 +#define GL_TANGENT_ARRAY_POINTER_EXT 0x8442 +#define GL_BINORMAL_ARRAY_POINTER_EXT 0x8443 +#define GL_MAP1_TANGENT_EXT 0x8444 +#define GL_MAP2_TANGENT_EXT 0x8445 +#define GL_MAP1_BINORMAL_EXT 0x8446 +#define GL_MAP2_BINORMAL_EXT 0x8447 +typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz); +typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz); +typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz); +typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz); +typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz); +typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz); +typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz); +typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz); +typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz); +typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz); +typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTangent3bEXT (GLbyte tx, GLbyte ty, GLbyte tz); +GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glTangent3dEXT (GLdouble tx, GLdouble ty, GLdouble tz); +GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glTangent3fEXT (GLfloat tx, GLfloat ty, GLfloat tz); +GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glTangent3iEXT (GLint tx, GLint ty, GLint tz); +GLAPI void APIENTRY glTangent3ivEXT (const GLint *v); +GLAPI void APIENTRY glTangent3sEXT (GLshort tx, GLshort ty, GLshort tz); +GLAPI void APIENTRY glTangent3svEXT (const GLshort *v); +GLAPI void APIENTRY glBinormal3bEXT (GLbyte bx, GLbyte by, GLbyte bz); +GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glBinormal3dEXT (GLdouble bx, GLdouble by, GLdouble bz); +GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glBinormal3fEXT (GLfloat bx, GLfloat by, GLfloat bz); +GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glBinormal3iEXT (GLint bx, GLint by, GLint bz); +GLAPI void APIENTRY glBinormal3ivEXT (const GLint *v); +GLAPI void APIENTRY glBinormal3sEXT (GLshort bx, GLshort by, GLshort bz); +GLAPI void APIENTRY glBinormal3svEXT (const GLshort *v); +GLAPI void APIENTRY glTangentPointerEXT (GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glBinormalPointerEXT (GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_coordinate_frame */ + +#ifndef GL_EXT_copy_texture +#define GL_EXT_copy_texture 1 +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +#endif +#endif /* GL_EXT_copy_texture */ + +#ifndef GL_EXT_cull_vertex +#define GL_EXT_cull_vertex 1 +#define GL_CULL_VERTEX_EXT 0x81AA +#define GL_CULL_VERTEX_EYE_POSITION_EXT 0x81AB +#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC +typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCullParameterdvEXT (GLenum pname, GLdouble *params); +GLAPI void APIENTRY glCullParameterfvEXT (GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_cull_vertex */ + +#ifndef GL_EXT_debug_label +#define GL_EXT_debug_label 1 +#define GL_PROGRAM_PIPELINE_OBJECT_EXT 0x8A4F +#define GL_PROGRAM_OBJECT_EXT 0x8B40 +#define GL_SHADER_OBJECT_EXT 0x8B48 +#define GL_BUFFER_OBJECT_EXT 0x9151 +#define GL_QUERY_OBJECT_EXT 0x9153 +#define GL_VERTEX_ARRAY_OBJECT_EXT 0x9154 +typedef void (APIENTRYP PFNGLLABELOBJECTEXTPROC) (GLenum type, GLuint object, GLsizei length, const GLchar *label); +typedef void (APIENTRYP PFNGLGETOBJECTLABELEXTPROC) (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glLabelObjectEXT (GLenum type, GLuint object, GLsizei length, const GLchar *label); +GLAPI void APIENTRY glGetObjectLabelEXT (GLenum type, GLuint object, GLsizei bufSize, GLsizei *length, GLchar *label); +#endif +#endif /* GL_EXT_debug_label */ + +#ifndef GL_EXT_debug_marker +#define GL_EXT_debug_marker 1 +typedef void (APIENTRYP PFNGLINSERTEVENTMARKEREXTPROC) (GLsizei length, const GLchar *marker); +typedef void (APIENTRYP PFNGLPUSHGROUPMARKEREXTPROC) (GLsizei length, const GLchar *marker); +typedef void (APIENTRYP PFNGLPOPGROUPMARKEREXTPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glInsertEventMarkerEXT (GLsizei length, const GLchar *marker); +GLAPI void APIENTRY glPushGroupMarkerEXT (GLsizei length, const GLchar *marker); +GLAPI void APIENTRY glPopGroupMarkerEXT (void); +#endif +#endif /* GL_EXT_debug_marker */ + +#ifndef GL_EXT_depth_bounds_test +#define GL_EXT_depth_bounds_test 1 +#define GL_DEPTH_BOUNDS_TEST_EXT 0x8890 +#define GL_DEPTH_BOUNDS_EXT 0x8891 +typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDepthBoundsEXT (GLclampd zmin, GLclampd zmax); +#endif +#endif /* GL_EXT_depth_bounds_test */ + +#ifndef GL_EXT_direct_state_access +#define GL_EXT_direct_state_access 1 +#define GL_PROGRAM_MATRIX_EXT 0x8E2D +#define GL_TRANSPOSE_PROGRAM_MATRIX_EXT 0x8E2E +#define GL_PROGRAM_MATRIX_STACK_DEPTH_EXT 0x8E2F +typedef void (APIENTRYP PFNGLMATRIXLOADFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXMULTFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXLOADIDENTITYEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLMATRIXROTATEFEXTPROC) (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXROTATEDEXTPROC) (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXSCALEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXSCALEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXTRANSLATEFEXTPROC) (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLMATRIXTRANSLATEDEXTPROC) (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLMATRIXFRUSTUMEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLMATRIXORTHOEXTPROC) (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLMATRIXPOPEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLMATRIXPUSHEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLPUSHCLIENTATTRIBDEFAULTEXTPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERFVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETTEXTURELEVELPARAMETERIVEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLBINDMULTITEXTUREEXTPROC) (GLenum texunit, GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLMULTITEXCOORDPOINTEREXTPROC) (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLMULTITEXENVFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXENVIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXGENDEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble param); +typedef void (APIENTRYP PFNGLMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params); +typedef void (APIENTRYP PFNGLMULTITEXGENFEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXGENIEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXENVFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXENVIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENDVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENFVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXGENIVEXTPROC) (GLenum texunit, GLenum coord, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +typedef void (APIENTRYP PFNGLCOPYMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERFVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMULTITEXLEVELPARAMETERIVEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLCOPYMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEINDEXEDEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLGETFLOATINDEXEDVEXTPROC) (GLenum target, GLuint index, GLfloat *data); +typedef void (APIENTRYP PFNGLGETDOUBLEINDEXEDVEXTPROC) (GLenum target, GLuint index, GLdouble *data); +typedef void (APIENTRYP PFNGLGETPOINTERINDEXEDVEXTPROC) (GLenum target, GLuint index, void **data); +typedef void (APIENTRYP PFNGLENABLEINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef GLboolean (APIENTRYP PFNGLISENABLEDINDEXEDEXTPROC) (GLenum target, GLuint index); +typedef void (APIENTRYP PFNGLGETINTEGERINDEXEDVEXTPROC) (GLenum target, GLuint index, GLint *data); +typedef void (APIENTRYP PFNGLGETBOOLEANINDEXEDVEXTPROC) (GLenum target, GLuint index, GLboolean *data); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTUREIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE3DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE2DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDTEXTURESUBIMAGE1DEXTPROC) (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXTUREIMAGEEXTPROC) (GLuint texture, GLenum target, GLint lod, void *img); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE3DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE2DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLCOMPRESSEDMULTITEXSUBIMAGE1DEXTPROC) (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +typedef void (APIENTRYP PFNGLGETCOMPRESSEDMULTITEXIMAGEEXTPROC) (GLenum texunit, GLenum target, GLint lod, void *img); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEFEXTPROC) (GLenum mode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSEDEXTPROC) (GLenum mode, const GLdouble *m); +typedef void (APIENTRYP PFNGLNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFEREXTPROC) (GLuint buffer, GLenum access); +typedef GLboolean (APIENTRYP PFNGLUNMAPNAMEDBUFFEREXTPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERIVEXTPROC) (GLuint buffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPOINTERVEXTPROC) (GLuint buffer, GLenum pname, void **params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FEXTPROC) (GLuint program, GLint location, GLfloat v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FEXTPROC) (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IEXTPROC) (GLuint program, GLint location, GLint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IEXTPROC) (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4FVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4IVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3FVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +typedef void (APIENTRYP PFNGLTEXTUREBUFFEREXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLMULTITEXBUFFEREXTPROC) (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXTUREPARAMETERIUIVEXTPROC) (GLuint texture, GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMULTITEXPARAMETERIUIVEXTPROC) (GLenum texunit, GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIEXTPROC) (GLuint program, GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIEXTPROC) (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4UIVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IEXTPROC) (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4IVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETERSI4UIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERIUIVEXTPROC) (GLuint program, GLenum target, GLuint index, GLuint *params); +typedef void (APIENTRYP PFNGLENABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLDISABLECLIENTSTATEIEXTPROC) (GLenum array, GLuint index); +typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4DVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLdouble *params); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLNAMEDPROGRAMLOCALPARAMETER4FVEXTPROC) (GLuint program, GLenum target, GLuint index, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERDVEXTPROC) (GLuint program, GLenum target, GLuint index, GLdouble *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMLOCALPARAMETERFVEXTPROC) (GLuint program, GLenum target, GLuint index, GLfloat *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMIVEXTPROC) (GLuint program, GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETNAMEDPROGRAMSTRINGEXTPROC) (GLuint program, GLenum target, GLenum pname, void *string); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEEXTPROC) (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETNAMEDRENDERBUFFERPARAMETERIVEXTPROC) (GLuint renderbuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLNAMEDRENDERBUFFERSTORAGEMULTISAMPLECOVERAGEEXTPROC) (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +typedef GLenum (APIENTRYP PFNGLCHECKNAMEDFRAMEBUFFERSTATUSEXTPROC) (GLuint framebuffer, GLenum target); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE1DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE2DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURE3DEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERRENDERBUFFEREXTPROC) (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATETEXTUREMIPMAPEXTPROC) (GLuint texture, GLenum target); +typedef void (APIENTRYP PFNGLGENERATEMULTITEXMIPMAPEXTPROC) (GLenum texunit, GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFEREXTPROC) (GLuint framebuffer, GLenum mode); +typedef void (APIENTRYP PFNGLFRAMEBUFFERDRAWBUFFERSEXTPROC) (GLuint framebuffer, GLsizei n, const GLenum *bufs); +typedef void (APIENTRYP PFNGLFRAMEBUFFERREADBUFFEREXTPROC) (GLuint framebuffer, GLenum mode); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLNAMEDCOPYBUFFERSUBDATAEXTPROC) (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTURELAYEREXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERTEXTUREFACEEXTPROC) (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face); +typedef void (APIENTRYP PFNGLTEXTURERENDERBUFFEREXTPROC) (GLuint texture, GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLMULTITEXRENDERBUFFEREXTPROC) (GLenum texunit, GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYEDGEFLAGOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYINDEXOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYNORMALOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYTEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYMULTITEXCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYFOGCOORDOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYSECONDARYCOLOROFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYEXTPROC) (GLuint vaobj, GLenum array); +typedef void (APIENTRYP PFNGLENABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLDISABLEVERTEXARRAYATTRIBEXTPROC) (GLuint vaobj, GLuint index); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERVEXTPROC) (GLuint vaobj, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERVEXTPROC) (GLuint vaobj, GLenum pname, void **param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param); +typedef void *(APIENTRYP PFNGLMAPNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +typedef void (APIENTRYP PFNGLFLUSHMAPPEDNAMEDBUFFERRANGEEXTPROC) (GLuint buffer, GLintptr offset, GLsizeiptr length); +typedef void (APIENTRYP PFNGLNAMEDBUFFERSTORAGEEXTPROC) (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLCLEARNAMEDBUFFERSUBDATAEXTPROC) (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERPARAMETERIEXTPROC) (GLuint framebuffer, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLGETNAMEDFRAMEBUFFERPARAMETERIVEXTPROC) (GLuint framebuffer, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DEXTPROC) (GLuint program, GLint location, GLdouble x); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DEXTPROC) (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM1DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM2DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM3DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORM4DVEXTPROC) (GLuint program, GLint location, GLsizei count, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX2X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX3X4DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X2DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMMATRIX4X3DVEXTPROC) (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +typedef void (APIENTRYP PFNGLTEXTUREBUFFERRANGEEXTPROC) (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE1DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DEXTPROC) (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE2DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLTEXTURESTORAGE3DMULTISAMPLEEXTPROC) (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +typedef void (APIENTRYP PFNGLVERTEXARRAYBINDVERTEXBUFFEREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBIFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLFORMATEXTPROC) (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBBINDINGEXTPROC) (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXBINDINGDIVISOREXTPROC) (GLuint vaobj, GLuint bindingindex, GLuint divisor); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBLOFFSETEXTPROC) (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +typedef void (APIENTRYP PFNGLTEXTUREPAGECOMMITMENTEXTPROC) (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean resident); +typedef void (APIENTRYP PFNGLVERTEXARRAYVERTEXATTRIBDIVISOREXTPROC) (GLuint vaobj, GLuint index, GLuint divisor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMatrixLoadfEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoaddEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixMultfEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultdEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixLoadIdentityEXT (GLenum mode); +GLAPI void APIENTRY glMatrixRotatefEXT (GLenum mode, GLfloat angle, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixRotatedEXT (GLenum mode, GLdouble angle, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixScalefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixScaledEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixTranslatefEXT (GLenum mode, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glMatrixTranslatedEXT (GLenum mode, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glMatrixFrustumEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glMatrixOrthoEXT (GLenum mode, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glMatrixPopEXT (GLenum mode); +GLAPI void APIENTRY glMatrixPushEXT (GLenum mode); +GLAPI void APIENTRY glClientAttribDefaultEXT (GLbitfield mask); +GLAPI void APIENTRY glPushClientAttribDefaultEXT (GLbitfield mask); +GLAPI void APIENTRY glTextureParameterfEXT (GLuint texture, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glTextureParameteriEXT (GLuint texture, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetTextureImageEXT (GLuint texture, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI void APIENTRY glGetTextureParameterfvEXT (GLuint texture, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureParameterivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureLevelParameterfvEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetTextureLevelParameterivEXT (GLuint texture, GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glBindMultiTextureEXT (GLenum texunit, GLenum target, GLuint texture); +GLAPI void APIENTRY glMultiTexCoordPointerEXT (GLenum texunit, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glMultiTexEnvfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexEnviEXT (GLenum texunit, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexGendEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble param); +GLAPI void APIENTRY glMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLdouble *params); +GLAPI void APIENTRY glMultiTexGenfEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexGeniEXT (GLenum texunit, GLenum coord, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, const GLint *params); +GLAPI void APIENTRY glGetMultiTexEnvfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexEnvivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexGendvEXT (GLenum texunit, GLenum coord, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetMultiTexGenfvEXT (GLenum texunit, GLenum coord, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexGenivEXT (GLenum texunit, GLenum coord, GLenum pname, GLint *params); +GLAPI void APIENTRY glMultiTexParameteriEXT (GLenum texunit, GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexParameterfEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); +GLAPI void APIENTRY glCopyMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); +GLAPI void APIENTRY glCopyMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glCopyMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetMultiTexImageEXT (GLenum texunit, GLenum target, GLint level, GLenum format, GLenum type, void *pixels); +GLAPI void APIENTRY glGetMultiTexParameterfvEXT (GLenum texunit, GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexParameterivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexLevelParameterfvEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMultiTexLevelParameterivEXT (GLenum texunit, GLenum target, GLint level, GLenum pname, GLint *params); +GLAPI void APIENTRY glMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glCopyMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); +GLAPI void APIENTRY glEnableClientStateIndexedEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glDisableClientStateIndexedEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glGetFloatIndexedvEXT (GLenum target, GLuint index, GLfloat *data); +GLAPI void APIENTRY glGetDoubleIndexedvEXT (GLenum target, GLuint index, GLdouble *data); +GLAPI void APIENTRY glGetPointerIndexedvEXT (GLenum target, GLuint index, void **data); +GLAPI void APIENTRY glEnableIndexedEXT (GLenum target, GLuint index); +GLAPI void APIENTRY glDisableIndexedEXT (GLenum target, GLuint index); +GLAPI GLboolean APIENTRY glIsEnabledIndexedEXT (GLenum target, GLuint index); +GLAPI void APIENTRY glGetIntegerIndexedvEXT (GLenum target, GLuint index, GLint *data); +GLAPI void APIENTRY glGetBooleanIndexedvEXT (GLenum target, GLuint index, GLboolean *data); +GLAPI void APIENTRY glCompressedTextureImage3DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureImage2DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureImage1DEXT (GLuint texture, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage3DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage2DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedTextureSubImage1DEXT (GLuint texture, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glGetCompressedTextureImageEXT (GLuint texture, GLenum target, GLint lod, void *img); +GLAPI void APIENTRY glCompressedMultiTexImage3DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexImage2DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexImage1DEXT (GLenum texunit, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage3DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage2DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glCompressedMultiTexSubImage1DEXT (GLenum texunit, GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const void *bits); +GLAPI void APIENTRY glGetCompressedMultiTexImageEXT (GLenum texunit, GLenum target, GLint lod, void *img); +GLAPI void APIENTRY glMatrixLoadTransposefEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoadTransposedEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glMatrixMultTransposefEXT (GLenum mode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultTransposedEXT (GLenum mode, const GLdouble *m); +GLAPI void APIENTRY glNamedBufferDataEXT (GLuint buffer, GLsizeiptr size, const void *data, GLenum usage); +GLAPI void APIENTRY glNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, const void *data); +GLAPI void *APIENTRY glMapNamedBufferEXT (GLuint buffer, GLenum access); +GLAPI GLboolean APIENTRY glUnmapNamedBufferEXT (GLuint buffer); +GLAPI void APIENTRY glGetNamedBufferParameterivEXT (GLuint buffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedBufferPointervEXT (GLuint buffer, GLenum pname, void **params); +GLAPI void APIENTRY glGetNamedBufferSubDataEXT (GLuint buffer, GLintptr offset, GLsizeiptr size, void *data); +GLAPI void APIENTRY glProgramUniform1fEXT (GLuint program, GLint location, GLfloat v0); +GLAPI void APIENTRY glProgramUniform2fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1); +GLAPI void APIENTRY glProgramUniform3fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2); +GLAPI void APIENTRY glProgramUniform4fEXT (GLuint program, GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +GLAPI void APIENTRY glProgramUniform1iEXT (GLuint program, GLint location, GLint v0); +GLAPI void APIENTRY glProgramUniform2iEXT (GLuint program, GLint location, GLint v0, GLint v1); +GLAPI void APIENTRY glProgramUniform3iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2); +GLAPI void APIENTRY glProgramUniform4iEXT (GLuint program, GLint location, GLint v0, GLint v1, GLint v2, GLint v3); +GLAPI void APIENTRY glProgramUniform1fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform2fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform3fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform4fvEXT (GLuint program, GLint location, GLsizei count, const GLfloat *value); +GLAPI void APIENTRY glProgramUniform1ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform2ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform3ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniform4ivEXT (GLuint program, GLint location, GLsizei count, const GLint *value); +GLAPI void APIENTRY glProgramUniformMatrix2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3fvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); +GLAPI void APIENTRY glTextureBufferEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glMultiTexBufferEXT (GLenum texunit, GLenum target, GLenum internalformat, GLuint buffer); +GLAPI void APIENTRY glTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTextureParameterIivEXT (GLuint texture, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTextureParameterIuivEXT (GLuint texture, GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetMultiTexParameterIivEXT (GLenum texunit, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMultiTexParameterIuivEXT (GLenum texunit, GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glProgramUniform1uiEXT (GLuint program, GLint location, GLuint v0); +GLAPI void APIENTRY glProgramUniform2uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glProgramUniform3uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glProgramUniform4uiEXT (GLuint program, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glProgramUniform1uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform2uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform3uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glProgramUniform4uivEXT (GLuint program, GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glNamedProgramLocalParameters4fvEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glNamedProgramLocalParameterI4iEXT (GLuint program, GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glNamedProgramLocalParameterI4ivEXT (GLuint program, GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glNamedProgramLocalParametersI4ivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glNamedProgramLocalParameterI4uiEXT (GLuint program, GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glNamedProgramLocalParameterI4uivEXT (GLuint program, GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glNamedProgramLocalParametersI4uivEXT (GLuint program, GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterIivEXT (GLuint program, GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterIuivEXT (GLuint program, GLenum target, GLuint index, GLuint *params); +GLAPI void APIENTRY glEnableClientStateiEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glDisableClientStateiEXT (GLenum array, GLuint index); +GLAPI void APIENTRY glGetFloati_vEXT (GLenum pname, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetDoublei_vEXT (GLenum pname, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetPointeri_vEXT (GLenum pname, GLuint index, void **params); +GLAPI void APIENTRY glNamedProgramStringEXT (GLuint program, GLenum target, GLenum format, GLsizei len, const void *string); +GLAPI void APIENTRY glNamedProgramLocalParameter4dEXT (GLuint program, GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glNamedProgramLocalParameter4dvEXT (GLuint program, GLenum target, GLuint index, const GLdouble *params); +GLAPI void APIENTRY glNamedProgramLocalParameter4fEXT (GLuint program, GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glNamedProgramLocalParameter4fvEXT (GLuint program, GLenum target, GLuint index, const GLfloat *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterdvEXT (GLuint program, GLenum target, GLuint index, GLdouble *params); +GLAPI void APIENTRY glGetNamedProgramLocalParameterfvEXT (GLuint program, GLenum target, GLuint index, GLfloat *params); +GLAPI void APIENTRY glGetNamedProgramivEXT (GLuint program, GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetNamedProgramStringEXT (GLuint program, GLenum target, GLenum pname, void *string); +GLAPI void APIENTRY glNamedRenderbufferStorageEXT (GLuint renderbuffer, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetNamedRenderbufferParameterivEXT (GLuint renderbuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleEXT (GLuint renderbuffer, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glNamedRenderbufferStorageMultisampleCoverageEXT (GLuint renderbuffer, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI GLenum APIENTRY glCheckNamedFramebufferStatusEXT (GLuint framebuffer, GLenum target); +GLAPI void APIENTRY glNamedFramebufferTexture1DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTexture2DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTexture3DEXT (GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glNamedFramebufferRenderbufferEXT (GLuint framebuffer, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetNamedFramebufferAttachmentParameterivEXT (GLuint framebuffer, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateTextureMipmapEXT (GLuint texture, GLenum target); +GLAPI void APIENTRY glGenerateMultiTexMipmapEXT (GLenum texunit, GLenum target); +GLAPI void APIENTRY glFramebufferDrawBufferEXT (GLuint framebuffer, GLenum mode); +GLAPI void APIENTRY glFramebufferDrawBuffersEXT (GLuint framebuffer, GLsizei n, const GLenum *bufs); +GLAPI void APIENTRY glFramebufferReadBufferEXT (GLuint framebuffer, GLenum mode); +GLAPI void APIENTRY glGetFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glNamedCopyBufferSubDataEXT (GLuint readBuffer, GLuint writeBuffer, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size); +GLAPI void APIENTRY glNamedFramebufferTextureEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glNamedFramebufferTextureLayerEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); +GLAPI void APIENTRY glNamedFramebufferTextureFaceEXT (GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLenum face); +GLAPI void APIENTRY glTextureRenderbufferEXT (GLuint texture, GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glMultiTexRenderbufferEXT (GLenum texunit, GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glVertexArrayVertexOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayEdgeFlagOffsetEXT (GLuint vaobj, GLuint buffer, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayIndexOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayNormalOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayMultiTexCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum texunit, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayFogCoordOffsetEXT (GLuint vaobj, GLuint buffer, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArraySecondaryColorOffsetEXT (GLuint vaobj, GLuint buffer, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayVertexAttribOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glVertexArrayVertexAttribIOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glEnableVertexArrayEXT (GLuint vaobj, GLenum array); +GLAPI void APIENTRY glDisableVertexArrayEXT (GLuint vaobj, GLenum array); +GLAPI void APIENTRY glEnableVertexArrayAttribEXT (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glDisableVertexArrayAttribEXT (GLuint vaobj, GLuint index); +GLAPI void APIENTRY glGetVertexArrayIntegervEXT (GLuint vaobj, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayPointervEXT (GLuint vaobj, GLenum pname, void **param); +GLAPI void APIENTRY glGetVertexArrayIntegeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, GLint *param); +GLAPI void APIENTRY glGetVertexArrayPointeri_vEXT (GLuint vaobj, GLuint index, GLenum pname, void **param); +GLAPI void *APIENTRY glMapNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length, GLbitfield access); +GLAPI void APIENTRY glFlushMappedNamedBufferRangeEXT (GLuint buffer, GLintptr offset, GLsizeiptr length); +GLAPI void APIENTRY glNamedBufferStorageEXT (GLuint buffer, GLsizeiptr size, const void *data, GLbitfield flags); +GLAPI void APIENTRY glClearNamedBufferDataEXT (GLuint buffer, GLenum internalformat, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glClearNamedBufferSubDataEXT (GLuint buffer, GLenum internalformat, GLsizeiptr offset, GLsizeiptr size, GLenum format, GLenum type, const void *data); +GLAPI void APIENTRY glNamedFramebufferParameteriEXT (GLuint framebuffer, GLenum pname, GLint param); +GLAPI void APIENTRY glGetNamedFramebufferParameterivEXT (GLuint framebuffer, GLenum pname, GLint *params); +GLAPI void APIENTRY glProgramUniform1dEXT (GLuint program, GLint location, GLdouble x); +GLAPI void APIENTRY glProgramUniform2dEXT (GLuint program, GLint location, GLdouble x, GLdouble y); +GLAPI void APIENTRY glProgramUniform3dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glProgramUniform4dEXT (GLuint program, GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramUniform1dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform2dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform3dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniform4dvEXT (GLuint program, GLint location, GLsizei count, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix2x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix3x4dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x2dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glProgramUniformMatrix4x3dvEXT (GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLdouble *value); +GLAPI void APIENTRY glTextureBufferRangeEXT (GLuint texture, GLenum target, GLenum internalformat, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glTextureStorage1DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width); +GLAPI void APIENTRY glTextureStorage2DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glTextureStorage3DEXT (GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth); +GLAPI void APIENTRY glTextureStorage2DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glTextureStorage3DMultisampleEXT (GLuint texture, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedsamplelocations); +GLAPI void APIENTRY glVertexArrayBindVertexBufferEXT (GLuint vaobj, GLuint bindingindex, GLuint buffer, GLintptr offset, GLsizei stride); +GLAPI void APIENTRY glVertexArrayVertexAttribFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLboolean normalized, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribIFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribLFormatEXT (GLuint vaobj, GLuint attribindex, GLint size, GLenum type, GLuint relativeoffset); +GLAPI void APIENTRY glVertexArrayVertexAttribBindingEXT (GLuint vaobj, GLuint attribindex, GLuint bindingindex); +GLAPI void APIENTRY glVertexArrayVertexBindingDivisorEXT (GLuint vaobj, GLuint bindingindex, GLuint divisor); +GLAPI void APIENTRY glVertexArrayVertexAttribLOffsetEXT (GLuint vaobj, GLuint buffer, GLuint index, GLint size, GLenum type, GLsizei stride, GLintptr offset); +GLAPI void APIENTRY glTexturePageCommitmentEXT (GLuint texture, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLboolean resident); +GLAPI void APIENTRY glVertexArrayVertexAttribDivisorEXT (GLuint vaobj, GLuint index, GLuint divisor); +#endif +#endif /* GL_EXT_direct_state_access */ + +#ifndef GL_EXT_draw_buffers2 +#define GL_EXT_draw_buffers2 1 +typedef void (APIENTRYP PFNGLCOLORMASKINDEXEDEXTPROC) (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorMaskIndexedEXT (GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a); +#endif +#endif /* GL_EXT_draw_buffers2 */ + +#ifndef GL_EXT_draw_instanced +#define GL_EXT_draw_instanced 1 +typedef void (APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +typedef void (APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawArraysInstancedEXT (GLenum mode, GLint start, GLsizei count, GLsizei primcount); +GLAPI void APIENTRY glDrawElementsInstancedEXT (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); +#endif +#endif /* GL_EXT_draw_instanced */ + +#ifndef GL_EXT_draw_range_elements +#define GL_EXT_draw_range_elements 1 +#define GL_MAX_ELEMENTS_VERTICES_EXT 0x80E8 +#define GL_MAX_ELEMENTS_INDICES_EXT 0x80E9 +typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices); +#endif +#endif /* GL_EXT_draw_range_elements */ + +#ifndef GL_EXT_fog_coord +#define GL_EXT_fog_coord 1 +#define GL_FOG_COORDINATE_SOURCE_EXT 0x8450 +#define GL_FOG_COORDINATE_EXT 0x8451 +#define GL_FRAGMENT_DEPTH_EXT 0x8452 +#define GL_CURRENT_FOG_COORDINATE_EXT 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456 +#define GL_FOG_COORDINATE_ARRAY_EXT 0x8457 +typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord); +typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord); +typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord); +typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFogCoordfEXT (GLfloat coord); +GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *coord); +GLAPI void APIENTRY glFogCoorddEXT (GLdouble coord); +GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *coord); +GLAPI void APIENTRY glFogCoordPointerEXT (GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_fog_coord */ + +#ifndef GL_EXT_framebuffer_blit +#define GL_EXT_framebuffer_blit 1 +#define GL_READ_FRAMEBUFFER_EXT 0x8CA8 +#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 +#define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA +typedef void (APIENTRYP PFNGLBLITFRAMEBUFFEREXTPROC) (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlitFramebufferEXT (GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +#endif +#endif /* GL_EXT_framebuffer_blit */ + +#ifndef GL_EXT_framebuffer_multisample +#define GL_EXT_framebuffer_multisample 1 +#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 +#define GL_MAX_SAMPLES_EXT 0x8D57 +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLEEXTPROC) (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderbufferStorageMultisampleEXT (GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_EXT_framebuffer_multisample */ + +#ifndef GL_EXT_framebuffer_multisample_blit_scaled +#define GL_EXT_framebuffer_multisample_blit_scaled 1 +#define GL_SCALED_RESOLVE_FASTEST_EXT 0x90BA +#define GL_SCALED_RESOLVE_NICEST_EXT 0x90BB +#endif /* GL_EXT_framebuffer_multisample_blit_scaled */ + +#ifndef GL_EXT_framebuffer_object +#define GL_EXT_framebuffer_object 1 +#define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 +#define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 +#define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 +#define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 +#define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 +#define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 +#define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 +#define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA +#define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB +#define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC +#define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD +#define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 +#define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 +#define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 +#define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 +#define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 +#define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 +#define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 +#define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 +#define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 +#define GL_COLOR_ATTACHMENT10_EXT 0x8CEA +#define GL_COLOR_ATTACHMENT11_EXT 0x8CEB +#define GL_COLOR_ATTACHMENT12_EXT 0x8CEC +#define GL_COLOR_ATTACHMENT13_EXT 0x8CED +#define GL_COLOR_ATTACHMENT14_EXT 0x8CEE +#define GL_COLOR_ATTACHMENT15_EXT 0x8CEF +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#define GL_STENCIL_ATTACHMENT_EXT 0x8D20 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_RENDERBUFFER_EXT 0x8D41 +#define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 +#define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 +#define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 +#define GL_STENCIL_INDEX1_EXT 0x8D46 +#define GL_STENCIL_INDEX4_EXT 0x8D47 +#define GL_STENCIL_INDEX8_EXT 0x8D48 +#define GL_STENCIL_INDEX16_EXT 0x8D49 +#define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 +#define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 +#define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 +#define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 +#define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 +#define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 +typedef GLboolean (APIENTRYP PFNGLISRENDERBUFFEREXTPROC) (GLuint renderbuffer); +typedef void (APIENTRYP PFNGLBINDRENDERBUFFEREXTPROC) (GLenum target, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLDELETERENDERBUFFERSEXTPROC) (GLsizei n, const GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLGENRENDERBUFFERSEXTPROC) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRYP PFNGLGETRENDERBUFFERPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef GLboolean (APIENTRYP PFNGLISFRAMEBUFFEREXTPROC) (GLuint framebuffer); +typedef void (APIENTRYP PFNGLBINDFRAMEBUFFEREXTPROC) (GLenum target, GLuint framebuffer); +typedef void (APIENTRYP PFNGLDELETEFRAMEBUFFERSEXTPROC) (GLsizei n, const GLuint *framebuffers); +typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); +typedef GLenum (APIENTRYP PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) (GLenum target); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE1DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURE3DEXTPROC) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +typedef void (APIENTRYP PFNGLFRAMEBUFFERRENDERBUFFEREXTPROC) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +typedef void (APIENTRYP PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVEXTPROC) (GLenum target, GLenum attachment, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGENERATEMIPMAPEXTPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glIsRenderbufferEXT (GLuint renderbuffer); +GLAPI void APIENTRY glBindRenderbufferEXT (GLenum target, GLuint renderbuffer); +GLAPI void APIENTRY glDeleteRenderbuffersEXT (GLsizei n, const GLuint *renderbuffers); +GLAPI void APIENTRY glGenRenderbuffersEXT (GLsizei n, GLuint *renderbuffers); +GLAPI void APIENTRY glRenderbufferStorageEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +GLAPI void APIENTRY glGetRenderbufferParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI GLboolean APIENTRY glIsFramebufferEXT (GLuint framebuffer); +GLAPI void APIENTRY glBindFramebufferEXT (GLenum target, GLuint framebuffer); +GLAPI void APIENTRY glDeleteFramebuffersEXT (GLsizei n, const GLuint *framebuffers); +GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei n, GLuint *framebuffers); +GLAPI GLenum APIENTRY glCheckFramebufferStatusEXT (GLenum target); +GLAPI void APIENTRY glFramebufferTexture1DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture2DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTexture3DEXT (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); +GLAPI void APIENTRY glFramebufferRenderbufferEXT (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); +GLAPI void APIENTRY glGetFramebufferAttachmentParameterivEXT (GLenum target, GLenum attachment, GLenum pname, GLint *params); +GLAPI void APIENTRY glGenerateMipmapEXT (GLenum target); +#endif +#endif /* GL_EXT_framebuffer_object */ + +#ifndef GL_EXT_framebuffer_sRGB +#define GL_EXT_framebuffer_sRGB 1 +#define GL_FRAMEBUFFER_SRGB_EXT 0x8DB9 +#define GL_FRAMEBUFFER_SRGB_CAPABLE_EXT 0x8DBA +#endif /* GL_EXT_framebuffer_sRGB */ + +#ifndef GL_EXT_geometry_shader4 +#define GL_EXT_geometry_shader4 1 +#define GL_GEOMETRY_SHADER_EXT 0x8DD9 +#define GL_GEOMETRY_VERTICES_OUT_EXT 0x8DDA +#define GL_GEOMETRY_INPUT_TYPE_EXT 0x8DDB +#define GL_GEOMETRY_OUTPUT_TYPE_EXT 0x8DDC +#define GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT 0x8C29 +#define GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT 0x8DDD +#define GL_MAX_VERTEX_VARYING_COMPONENTS_EXT 0x8DDE +#define GL_MAX_VARYING_COMPONENTS_EXT 0x8B4B +#define GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT 0x8DDF +#define GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT 0x8DE0 +#define GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT 0x8DE1 +#define GL_LINES_ADJACENCY_EXT 0x000A +#define GL_LINE_STRIP_ADJACENCY_EXT 0x000B +#define GL_TRIANGLES_ADJACENCY_EXT 0x000C +#define GL_TRIANGLE_STRIP_ADJACENCY_EXT 0x000D +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT 0x8DA8 +#define GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT 0x8DA9 +#define GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT 0x8DA7 +#define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 +#define GL_PROGRAM_POINT_SIZE_EXT 0x8642 +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERIEXTPROC) (GLuint program, GLenum pname, GLint value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramParameteriEXT (GLuint program, GLenum pname, GLint value); +#endif +#endif /* GL_EXT_geometry_shader4 */ + +#ifndef GL_EXT_gpu_program_parameters +#define GL_EXT_gpu_program_parameters 1 +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERS4FVEXTPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramEnvParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glProgramLocalParameters4fvEXT (GLenum target, GLuint index, GLsizei count, const GLfloat *params); +#endif +#endif /* GL_EXT_gpu_program_parameters */ + +#ifndef GL_EXT_gpu_shader4 +#define GL_EXT_gpu_shader4 1 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_EXT 0x88FD +#define GL_SAMPLER_1D_ARRAY_EXT 0x8DC0 +#define GL_SAMPLER_2D_ARRAY_EXT 0x8DC1 +#define GL_SAMPLER_BUFFER_EXT 0x8DC2 +#define GL_SAMPLER_1D_ARRAY_SHADOW_EXT 0x8DC3 +#define GL_SAMPLER_2D_ARRAY_SHADOW_EXT 0x8DC4 +#define GL_SAMPLER_CUBE_SHADOW_EXT 0x8DC5 +#define GL_UNSIGNED_INT_VEC2_EXT 0x8DC6 +#define GL_UNSIGNED_INT_VEC3_EXT 0x8DC7 +#define GL_UNSIGNED_INT_VEC4_EXT 0x8DC8 +#define GL_INT_SAMPLER_1D_EXT 0x8DC9 +#define GL_INT_SAMPLER_2D_EXT 0x8DCA +#define GL_INT_SAMPLER_3D_EXT 0x8DCB +#define GL_INT_SAMPLER_CUBE_EXT 0x8DCC +#define GL_INT_SAMPLER_2D_RECT_EXT 0x8DCD +#define GL_INT_SAMPLER_1D_ARRAY_EXT 0x8DCE +#define GL_INT_SAMPLER_2D_ARRAY_EXT 0x8DCF +#define GL_INT_SAMPLER_BUFFER_EXT 0x8DD0 +#define GL_UNSIGNED_INT_SAMPLER_1D_EXT 0x8DD1 +#define GL_UNSIGNED_INT_SAMPLER_2D_EXT 0x8DD2 +#define GL_UNSIGNED_INT_SAMPLER_3D_EXT 0x8DD3 +#define GL_UNSIGNED_INT_SAMPLER_CUBE_EXT 0x8DD4 +#define GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT 0x8DD5 +#define GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT 0x8DD6 +#define GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT 0x8DD7 +#define GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT 0x8DD8 +#define GL_MIN_PROGRAM_TEXEL_OFFSET_EXT 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET_EXT 0x8905 +typedef void (APIENTRYP PFNGLGETUNIFORMUIVEXTPROC) (GLuint program, GLint location, GLuint *params); +typedef void (APIENTRYP PFNGLBINDFRAGDATALOCATIONEXTPROC) (GLuint program, GLuint color, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETFRAGDATALOCATIONEXTPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLUNIFORM1UIEXTPROC) (GLint location, GLuint v0); +typedef void (APIENTRYP PFNGLUNIFORM2UIEXTPROC) (GLint location, GLuint v0, GLuint v1); +typedef void (APIENTRYP PFNGLUNIFORM3UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2); +typedef void (APIENTRYP PFNGLUNIFORM4UIEXTPROC) (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +typedef void (APIENTRYP PFNGLUNIFORM1UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM2UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM3UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +typedef void (APIENTRYP PFNGLUNIFORM4UIVEXTPROC) (GLint location, GLsizei count, const GLuint *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetUniformuivEXT (GLuint program, GLint location, GLuint *params); +GLAPI void APIENTRY glBindFragDataLocationEXT (GLuint program, GLuint color, const GLchar *name); +GLAPI GLint APIENTRY glGetFragDataLocationEXT (GLuint program, const GLchar *name); +GLAPI void APIENTRY glUniform1uiEXT (GLint location, GLuint v0); +GLAPI void APIENTRY glUniform2uiEXT (GLint location, GLuint v0, GLuint v1); +GLAPI void APIENTRY glUniform3uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2); +GLAPI void APIENTRY glUniform4uiEXT (GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3); +GLAPI void APIENTRY glUniform1uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform2uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform3uivEXT (GLint location, GLsizei count, const GLuint *value); +GLAPI void APIENTRY glUniform4uivEXT (GLint location, GLsizei count, const GLuint *value); +#endif +#endif /* GL_EXT_gpu_shader4 */ + +#ifndef GL_EXT_histogram +#define GL_EXT_histogram 1 +#define GL_HISTOGRAM_EXT 0x8024 +#define GL_PROXY_HISTOGRAM_EXT 0x8025 +#define GL_HISTOGRAM_WIDTH_EXT 0x8026 +#define GL_HISTOGRAM_FORMAT_EXT 0x8027 +#define GL_HISTOGRAM_RED_SIZE_EXT 0x8028 +#define GL_HISTOGRAM_GREEN_SIZE_EXT 0x8029 +#define GL_HISTOGRAM_BLUE_SIZE_EXT 0x802A +#define GL_HISTOGRAM_ALPHA_SIZE_EXT 0x802B +#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT 0x802C +#define GL_HISTOGRAM_SINK_EXT 0x802D +#define GL_MINMAX_EXT 0x802E +#define GL_MINMAX_FORMAT_EXT 0x802F +#define GL_MINMAX_SINK_EXT 0x8030 +#define GL_TABLE_TOO_LARGE_EXT 0x8031 +typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink); +typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target); +typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetHistogramEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMinmaxEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, void *values); +GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glHistogramEXT (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glMinmaxEXT (GLenum target, GLenum internalformat, GLboolean sink); +GLAPI void APIENTRY glResetHistogramEXT (GLenum target); +GLAPI void APIENTRY glResetMinmaxEXT (GLenum target); +#endif +#endif /* GL_EXT_histogram */ + +#ifndef GL_EXT_index_array_formats +#define GL_EXT_index_array_formats 1 +#define GL_IUI_V2F_EXT 0x81AD +#define GL_IUI_V3F_EXT 0x81AE +#define GL_IUI_N3F_V2F_EXT 0x81AF +#define GL_IUI_N3F_V3F_EXT 0x81B0 +#define GL_T2F_IUI_V2F_EXT 0x81B1 +#define GL_T2F_IUI_V3F_EXT 0x81B2 +#define GL_T2F_IUI_N3F_V2F_EXT 0x81B3 +#define GL_T2F_IUI_N3F_V3F_EXT 0x81B4 +#endif /* GL_EXT_index_array_formats */ + +#ifndef GL_EXT_index_func +#define GL_EXT_index_func 1 +#define GL_INDEX_TEST_EXT 0x81B5 +#define GL_INDEX_TEST_FUNC_EXT 0x81B6 +#define GL_INDEX_TEST_REF_EXT 0x81B7 +typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIndexFuncEXT (GLenum func, GLclampf ref); +#endif +#endif /* GL_EXT_index_func */ + +#ifndef GL_EXT_index_material +#define GL_EXT_index_material 1 +#define GL_INDEX_MATERIAL_EXT 0x81B8 +#define GL_INDEX_MATERIAL_PARAMETER_EXT 0x81B9 +#define GL_INDEX_MATERIAL_FACE_EXT 0x81BA +typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIndexMaterialEXT (GLenum face, GLenum mode); +#endif +#endif /* GL_EXT_index_material */ + +#ifndef GL_EXT_index_texture +#define GL_EXT_index_texture 1 +#endif /* GL_EXT_index_texture */ + +#ifndef GL_EXT_light_texture +#define GL_EXT_light_texture 1 +#define GL_FRAGMENT_MATERIAL_EXT 0x8349 +#define GL_FRAGMENT_NORMAL_EXT 0x834A +#define GL_FRAGMENT_COLOR_EXT 0x834C +#define GL_ATTENUATION_EXT 0x834D +#define GL_SHADOW_ATTENUATION_EXT 0x834E +#define GL_TEXTURE_APPLICATION_MODE_EXT 0x834F +#define GL_TEXTURE_LIGHT_EXT 0x8350 +#define GL_TEXTURE_MATERIAL_FACE_EXT 0x8351 +#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352 +typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode); +typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname); +typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glApplyTextureEXT (GLenum mode); +GLAPI void APIENTRY glTextureLightEXT (GLenum pname); +GLAPI void APIENTRY glTextureMaterialEXT (GLenum face, GLenum mode); +#endif +#endif /* GL_EXT_light_texture */ + +#ifndef GL_EXT_misc_attribute +#define GL_EXT_misc_attribute 1 +#endif /* GL_EXT_misc_attribute */ + +#ifndef GL_EXT_multi_draw_arrays +#define GL_EXT_multi_draw_arrays 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount); +GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount); +#endif +#endif /* GL_EXT_multi_draw_arrays */ + +#ifndef GL_EXT_multisample +#define GL_EXT_multisample 1 +#define GL_MULTISAMPLE_EXT 0x809D +#define GL_SAMPLE_ALPHA_TO_MASK_EXT 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_EXT 0x809F +#define GL_SAMPLE_MASK_EXT 0x80A0 +#define GL_1PASS_EXT 0x80A1 +#define GL_2PASS_0_EXT 0x80A2 +#define GL_2PASS_1_EXT 0x80A3 +#define GL_4PASS_0_EXT 0x80A4 +#define GL_4PASS_1_EXT 0x80A5 +#define GL_4PASS_2_EXT 0x80A6 +#define GL_4PASS_3_EXT 0x80A7 +#define GL_SAMPLE_BUFFERS_EXT 0x80A8 +#define GL_SAMPLES_EXT 0x80A9 +#define GL_SAMPLE_MASK_VALUE_EXT 0x80AA +#define GL_SAMPLE_MASK_INVERT_EXT 0x80AB +#define GL_SAMPLE_PATTERN_EXT 0x80AC +#define GL_MULTISAMPLE_BIT_EXT 0x20000000 +typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleMaskEXT (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glSamplePatternEXT (GLenum pattern); +#endif +#endif /* GL_EXT_multisample */ + +#ifndef GL_EXT_packed_depth_stencil +#define GL_EXT_packed_depth_stencil 1 +#define GL_DEPTH_STENCIL_EXT 0x84F9 +#define GL_UNSIGNED_INT_24_8_EXT 0x84FA +#define GL_DEPTH24_STENCIL8_EXT 0x88F0 +#define GL_TEXTURE_STENCIL_SIZE_EXT 0x88F1 +#endif /* GL_EXT_packed_depth_stencil */ + +#ifndef GL_EXT_packed_float +#define GL_EXT_packed_float 1 +#define GL_R11F_G11F_B10F_EXT 0x8C3A +#define GL_UNSIGNED_INT_10F_11F_11F_REV_EXT 0x8C3B +#define GL_RGBA_SIGNED_COMPONENTS_EXT 0x8C3C +#endif /* GL_EXT_packed_float */ + +#ifndef GL_EXT_packed_pixels +#define GL_EXT_packed_pixels 1 +#define GL_UNSIGNED_BYTE_3_3_2_EXT 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4_EXT 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1_EXT 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8_EXT 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2_EXT 0x8036 +#endif /* GL_EXT_packed_pixels */ + +#ifndef GL_EXT_paletted_texture +#define GL_EXT_paletted_texture 1 +#define GL_COLOR_INDEX1_EXT 0x80E2 +#define GL_COLOR_INDEX2_EXT 0x80E3 +#define GL_COLOR_INDEX4_EXT 0x80E4 +#define GL_COLOR_INDEX8_EXT 0x80E5 +#define GL_COLOR_INDEX12_EXT 0x80E6 +#define GL_COLOR_INDEX16_EXT 0x80E7 +#define GL_TEXTURE_INDEX_SIZE_EXT 0x80ED +typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, void *data); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTableEXT (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glGetColorTableEXT (GLenum target, GLenum format, GLenum type, void *data); +GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_paletted_texture */ + +#ifndef GL_EXT_pixel_buffer_object +#define GL_EXT_pixel_buffer_object 1 +#define GL_PIXEL_PACK_BUFFER_EXT 0x88EB +#define GL_PIXEL_UNPACK_BUFFER_EXT 0x88EC +#define GL_PIXEL_PACK_BUFFER_BINDING_EXT 0x88ED +#define GL_PIXEL_UNPACK_BUFFER_BINDING_EXT 0x88EF +#endif /* GL_EXT_pixel_buffer_object */ + +#ifndef GL_EXT_pixel_transform +#define GL_EXT_pixel_transform 1 +#define GL_PIXEL_TRANSFORM_2D_EXT 0x8330 +#define GL_PIXEL_MAG_FILTER_EXT 0x8331 +#define GL_PIXEL_MIN_FILTER_EXT 0x8332 +#define GL_PIXEL_CUBIC_WEIGHT_EXT 0x8333 +#define GL_CUBIC_EXT 0x8334 +#define GL_AVERAGE_EXT 0x8335 +#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336 +#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337 +#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT 0x8338 +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetPixelTransformParameterivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetPixelTransformParameterfvEXT (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_EXT_pixel_transform */ + +#ifndef GL_EXT_pixel_transform_color_table +#define GL_EXT_pixel_transform_color_table 1 +#endif /* GL_EXT_pixel_transform_color_table */ + +#ifndef GL_EXT_point_parameters +#define GL_EXT_point_parameters 1 +#define GL_POINT_SIZE_MIN_EXT 0x8126 +#define GL_POINT_SIZE_MAX_EXT 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_EXT 0x8128 +#define GL_DISTANCE_ATTENUATION_EXT 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfEXT (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvEXT (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_EXT_point_parameters */ + +#ifndef GL_EXT_polygon_offset +#define GL_EXT_polygon_offset 1 +#define GL_POLYGON_OFFSET_EXT 0x8037 +#define GL_POLYGON_OFFSET_FACTOR_EXT 0x8038 +#define GL_POLYGON_OFFSET_BIAS_EXT 0x8039 +typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat factor, GLfloat bias); +#endif +#endif /* GL_EXT_polygon_offset */ + +#ifndef GL_EXT_polygon_offset_clamp +#define GL_EXT_polygon_offset_clamp 1 +#define GL_POLYGON_OFFSET_CLAMP_EXT 0x8E1B +typedef void (APIENTRYP PFNGLPOLYGONOFFSETCLAMPEXTPROC) (GLfloat factor, GLfloat units, GLfloat clamp); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPolygonOffsetClampEXT (GLfloat factor, GLfloat units, GLfloat clamp); +#endif +#endif /* GL_EXT_polygon_offset_clamp */ + +#ifndef GL_EXT_post_depth_coverage +#define GL_EXT_post_depth_coverage 1 +#endif /* GL_EXT_post_depth_coverage */ + +#ifndef GL_EXT_provoking_vertex +#define GL_EXT_provoking_vertex 1 +#define GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION_EXT 0x8E4C +#define GL_FIRST_VERTEX_CONVENTION_EXT 0x8E4D +#define GL_LAST_VERTEX_CONVENTION_EXT 0x8E4E +#define GL_PROVOKING_VERTEX_EXT 0x8E4F +typedef void (APIENTRYP PFNGLPROVOKINGVERTEXEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProvokingVertexEXT (GLenum mode); +#endif +#endif /* GL_EXT_provoking_vertex */ + +#ifndef GL_EXT_raster_multisample +#define GL_EXT_raster_multisample 1 +#define GL_RASTER_MULTISAMPLE_EXT 0x9327 +#define GL_RASTER_SAMPLES_EXT 0x9328 +#define GL_MAX_RASTER_SAMPLES_EXT 0x9329 +#define GL_RASTER_FIXED_SAMPLE_LOCATIONS_EXT 0x932A +#define GL_MULTISAMPLE_RASTERIZATION_ALLOWED_EXT 0x932B +#define GL_EFFECTIVE_RASTER_SAMPLES_EXT 0x932C +typedef void (APIENTRYP PFNGLRASTERSAMPLESEXTPROC) (GLuint samples, GLboolean fixedsamplelocations); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRasterSamplesEXT (GLuint samples, GLboolean fixedsamplelocations); +#endif +#endif /* GL_EXT_raster_multisample */ + +#ifndef GL_EXT_rescale_normal +#define GL_EXT_rescale_normal 1 +#define GL_RESCALE_NORMAL_EXT 0x803A +#endif /* GL_EXT_rescale_normal */ + +#ifndef GL_EXT_secondary_color +#define GL_EXT_secondary_color 1 +#define GL_COLOR_SUM_EXT 0x8458 +#define GL_CURRENT_SECONDARY_COLOR_EXT 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D +#define GL_SECONDARY_COLOR_ARRAY_EXT 0x845E +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte red, GLbyte green, GLbyte blue); +GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *v); +GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble red, GLdouble green, GLdouble blue); +GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *v); +GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat red, GLfloat green, GLfloat blue); +GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *v); +GLAPI void APIENTRY glSecondaryColor3iEXT (GLint red, GLint green, GLint blue); +GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *v); +GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort red, GLshort green, GLshort blue); +GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *v); +GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte red, GLubyte green, GLubyte blue); +GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *v); +GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint red, GLuint green, GLuint blue); +GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *v); +GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort red, GLushort green, GLushort blue); +GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *v); +GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_secondary_color */ + +#ifndef GL_EXT_separate_shader_objects +#define GL_EXT_separate_shader_objects 1 +#define GL_ACTIVE_PROGRAM_EXT 0x8B8D +typedef void (APIENTRYP PFNGLUSESHADERPROGRAMEXTPROC) (GLenum type, GLuint program); +typedef void (APIENTRYP PFNGLACTIVEPROGRAMEXTPROC) (GLuint program); +typedef GLuint (APIENTRYP PFNGLCREATESHADERPROGRAMEXTPROC) (GLenum type, const GLchar *string); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glUseShaderProgramEXT (GLenum type, GLuint program); +GLAPI void APIENTRY glActiveProgramEXT (GLuint program); +GLAPI GLuint APIENTRY glCreateShaderProgramEXT (GLenum type, const GLchar *string); +#endif +#endif /* GL_EXT_separate_shader_objects */ + +#ifndef GL_EXT_separate_specular_color +#define GL_EXT_separate_specular_color 1 +#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT 0x81F8 +#define GL_SINGLE_COLOR_EXT 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR_EXT 0x81FA +#endif /* GL_EXT_separate_specular_color */ + +#ifndef GL_EXT_shader_image_load_formatted +#define GL_EXT_shader_image_load_formatted 1 +#endif /* GL_EXT_shader_image_load_formatted */ + +#ifndef GL_EXT_shader_image_load_store +#define GL_EXT_shader_image_load_store 1 +#define GL_MAX_IMAGE_UNITS_EXT 0x8F38 +#define GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS_EXT 0x8F39 +#define GL_IMAGE_BINDING_NAME_EXT 0x8F3A +#define GL_IMAGE_BINDING_LEVEL_EXT 0x8F3B +#define GL_IMAGE_BINDING_LAYERED_EXT 0x8F3C +#define GL_IMAGE_BINDING_LAYER_EXT 0x8F3D +#define GL_IMAGE_BINDING_ACCESS_EXT 0x8F3E +#define GL_IMAGE_1D_EXT 0x904C +#define GL_IMAGE_2D_EXT 0x904D +#define GL_IMAGE_3D_EXT 0x904E +#define GL_IMAGE_2D_RECT_EXT 0x904F +#define GL_IMAGE_CUBE_EXT 0x9050 +#define GL_IMAGE_BUFFER_EXT 0x9051 +#define GL_IMAGE_1D_ARRAY_EXT 0x9052 +#define GL_IMAGE_2D_ARRAY_EXT 0x9053 +#define GL_IMAGE_CUBE_MAP_ARRAY_EXT 0x9054 +#define GL_IMAGE_2D_MULTISAMPLE_EXT 0x9055 +#define GL_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9056 +#define GL_INT_IMAGE_1D_EXT 0x9057 +#define GL_INT_IMAGE_2D_EXT 0x9058 +#define GL_INT_IMAGE_3D_EXT 0x9059 +#define GL_INT_IMAGE_2D_RECT_EXT 0x905A +#define GL_INT_IMAGE_CUBE_EXT 0x905B +#define GL_INT_IMAGE_BUFFER_EXT 0x905C +#define GL_INT_IMAGE_1D_ARRAY_EXT 0x905D +#define GL_INT_IMAGE_2D_ARRAY_EXT 0x905E +#define GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x905F +#define GL_INT_IMAGE_2D_MULTISAMPLE_EXT 0x9060 +#define GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x9061 +#define GL_UNSIGNED_INT_IMAGE_1D_EXT 0x9062 +#define GL_UNSIGNED_INT_IMAGE_2D_EXT 0x9063 +#define GL_UNSIGNED_INT_IMAGE_3D_EXT 0x9064 +#define GL_UNSIGNED_INT_IMAGE_2D_RECT_EXT 0x9065 +#define GL_UNSIGNED_INT_IMAGE_CUBE_EXT 0x9066 +#define GL_UNSIGNED_INT_IMAGE_BUFFER_EXT 0x9067 +#define GL_UNSIGNED_INT_IMAGE_1D_ARRAY_EXT 0x9068 +#define GL_UNSIGNED_INT_IMAGE_2D_ARRAY_EXT 0x9069 +#define GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT 0x906A +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_EXT 0x906B +#define GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT 0x906C +#define GL_MAX_IMAGE_SAMPLES_EXT 0x906D +#define GL_IMAGE_BINDING_FORMAT_EXT 0x906E +#define GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT_EXT 0x00000001 +#define GL_ELEMENT_ARRAY_BARRIER_BIT_EXT 0x00000002 +#define GL_UNIFORM_BARRIER_BIT_EXT 0x00000004 +#define GL_TEXTURE_FETCH_BARRIER_BIT_EXT 0x00000008 +#define GL_SHADER_IMAGE_ACCESS_BARRIER_BIT_EXT 0x00000020 +#define GL_COMMAND_BARRIER_BIT_EXT 0x00000040 +#define GL_PIXEL_BUFFER_BARRIER_BIT_EXT 0x00000080 +#define GL_TEXTURE_UPDATE_BARRIER_BIT_EXT 0x00000100 +#define GL_BUFFER_UPDATE_BARRIER_BIT_EXT 0x00000200 +#define GL_FRAMEBUFFER_BARRIER_BIT_EXT 0x00000400 +#define GL_TRANSFORM_FEEDBACK_BARRIER_BIT_EXT 0x00000800 +#define GL_ATOMIC_COUNTER_BARRIER_BIT_EXT 0x00001000 +#define GL_ALL_BARRIER_BITS_EXT 0xFFFFFFFF +typedef void (APIENTRYP PFNGLBINDIMAGETEXTUREEXTPROC) (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format); +typedef void (APIENTRYP PFNGLMEMORYBARRIEREXTPROC) (GLbitfield barriers); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindImageTextureEXT (GLuint index, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLint format); +GLAPI void APIENTRY glMemoryBarrierEXT (GLbitfield barriers); +#endif +#endif /* GL_EXT_shader_image_load_store */ + +#ifndef GL_EXT_shader_integer_mix +#define GL_EXT_shader_integer_mix 1 +#endif /* GL_EXT_shader_integer_mix */ + +#ifndef GL_EXT_shadow_funcs +#define GL_EXT_shadow_funcs 1 +#endif /* GL_EXT_shadow_funcs */ + +#ifndef GL_EXT_shared_texture_palette +#define GL_EXT_shared_texture_palette 1 +#define GL_SHARED_TEXTURE_PALETTE_EXT 0x81FB +#endif /* GL_EXT_shared_texture_palette */ + +#ifndef GL_EXT_sparse_texture2 +#define GL_EXT_sparse_texture2 1 +#endif /* GL_EXT_sparse_texture2 */ + +#ifndef GL_EXT_stencil_clear_tag +#define GL_EXT_stencil_clear_tag 1 +#define GL_STENCIL_TAG_BITS_EXT 0x88F2 +#define GL_STENCIL_CLEAR_TAG_VALUE_EXT 0x88F3 +typedef void (APIENTRYP PFNGLSTENCILCLEARTAGEXTPROC) (GLsizei stencilTagBits, GLuint stencilClearTag); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStencilClearTagEXT (GLsizei stencilTagBits, GLuint stencilClearTag); +#endif +#endif /* GL_EXT_stencil_clear_tag */ + +#ifndef GL_EXT_stencil_two_side +#define GL_EXT_stencil_two_side 1 +#define GL_STENCIL_TEST_TWO_SIDE_EXT 0x8910 +#define GL_ACTIVE_STENCIL_FACE_EXT 0x8911 +typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum face); +#endif +#endif /* GL_EXT_stencil_two_side */ + +#ifndef GL_EXT_stencil_wrap +#define GL_EXT_stencil_wrap 1 +#define GL_INCR_WRAP_EXT 0x8507 +#define GL_DECR_WRAP_EXT 0x8508 +#endif /* GL_EXT_stencil_wrap */ + +#ifndef GL_EXT_subtexture +#define GL_EXT_subtexture 1 +typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_EXT_subtexture */ + +#ifndef GL_EXT_texture +#define GL_EXT_texture 1 +#define GL_ALPHA4_EXT 0x803B +#define GL_ALPHA8_EXT 0x803C +#define GL_ALPHA12_EXT 0x803D +#define GL_ALPHA16_EXT 0x803E +#define GL_LUMINANCE4_EXT 0x803F +#define GL_LUMINANCE8_EXT 0x8040 +#define GL_LUMINANCE12_EXT 0x8041 +#define GL_LUMINANCE16_EXT 0x8042 +#define GL_LUMINANCE4_ALPHA4_EXT 0x8043 +#define GL_LUMINANCE6_ALPHA2_EXT 0x8044 +#define GL_LUMINANCE8_ALPHA8_EXT 0x8045 +#define GL_LUMINANCE12_ALPHA4_EXT 0x8046 +#define GL_LUMINANCE12_ALPHA12_EXT 0x8047 +#define GL_LUMINANCE16_ALPHA16_EXT 0x8048 +#define GL_INTENSITY_EXT 0x8049 +#define GL_INTENSITY4_EXT 0x804A +#define GL_INTENSITY8_EXT 0x804B +#define GL_INTENSITY12_EXT 0x804C +#define GL_INTENSITY16_EXT 0x804D +#define GL_RGB2_EXT 0x804E +#define GL_RGB4_EXT 0x804F +#define GL_RGB5_EXT 0x8050 +#define GL_RGB8_EXT 0x8051 +#define GL_RGB10_EXT 0x8052 +#define GL_RGB12_EXT 0x8053 +#define GL_RGB16_EXT 0x8054 +#define GL_RGBA2_EXT 0x8055 +#define GL_RGBA4_EXT 0x8056 +#define GL_RGB5_A1_EXT 0x8057 +#define GL_RGBA8_EXT 0x8058 +#define GL_RGB10_A2_EXT 0x8059 +#define GL_RGBA12_EXT 0x805A +#define GL_RGBA16_EXT 0x805B +#define GL_TEXTURE_RED_SIZE_EXT 0x805C +#define GL_TEXTURE_GREEN_SIZE_EXT 0x805D +#define GL_TEXTURE_BLUE_SIZE_EXT 0x805E +#define GL_TEXTURE_ALPHA_SIZE_EXT 0x805F +#define GL_TEXTURE_LUMINANCE_SIZE_EXT 0x8060 +#define GL_TEXTURE_INTENSITY_SIZE_EXT 0x8061 +#define GL_REPLACE_EXT 0x8062 +#define GL_PROXY_TEXTURE_1D_EXT 0x8063 +#define GL_PROXY_TEXTURE_2D_EXT 0x8064 +#define GL_TEXTURE_TOO_LARGE_EXT 0x8065 +#endif /* GL_EXT_texture */ + +#ifndef GL_EXT_texture3D +#define GL_EXT_texture3D 1 +#define GL_PACK_SKIP_IMAGES_EXT 0x806B +#define GL_PACK_IMAGE_HEIGHT_EXT 0x806C +#define GL_UNPACK_SKIP_IMAGES_EXT 0x806D +#define GL_UNPACK_IMAGE_HEIGHT_EXT 0x806E +#define GL_TEXTURE_3D_EXT 0x806F +#define GL_PROXY_TEXTURE_3D_EXT 0x8070 +#define GL_TEXTURE_DEPTH_EXT 0x8071 +#define GL_TEXTURE_WRAP_R_EXT 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE_EXT 0x8073 +typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage3DEXT (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_EXT_texture3D */ + +#ifndef GL_EXT_texture_array +#define GL_EXT_texture_array 1 +#define GL_TEXTURE_1D_ARRAY_EXT 0x8C18 +#define GL_PROXY_TEXTURE_1D_ARRAY_EXT 0x8C19 +#define GL_TEXTURE_2D_ARRAY_EXT 0x8C1A +#define GL_PROXY_TEXTURE_2D_ARRAY_EXT 0x8C1B +#define GL_TEXTURE_BINDING_1D_ARRAY_EXT 0x8C1C +#define GL_TEXTURE_BINDING_2D_ARRAY_EXT 0x8C1D +#define GL_MAX_ARRAY_TEXTURE_LAYERS_EXT 0x88FF +#define GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT 0x884E +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTURELAYEREXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferTextureLayerEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer); +#endif +#endif /* GL_EXT_texture_array */ + +#ifndef GL_EXT_texture_buffer_object +#define GL_EXT_texture_buffer_object 1 +#define GL_TEXTURE_BUFFER_EXT 0x8C2A +#define GL_MAX_TEXTURE_BUFFER_SIZE_EXT 0x8C2B +#define GL_TEXTURE_BINDING_BUFFER_EXT 0x8C2C +#define GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT 0x8C2D +#define GL_TEXTURE_BUFFER_FORMAT_EXT 0x8C2E +typedef void (APIENTRYP PFNGLTEXBUFFEREXTPROC) (GLenum target, GLenum internalformat, GLuint buffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexBufferEXT (GLenum target, GLenum internalformat, GLuint buffer); +#endif +#endif /* GL_EXT_texture_buffer_object */ + +#ifndef GL_EXT_texture_compression_latc +#define GL_EXT_texture_compression_latc 1 +#define GL_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70 +#define GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71 +#define GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72 +#define GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73 +#endif /* GL_EXT_texture_compression_latc */ + +#ifndef GL_EXT_texture_compression_rgtc +#define GL_EXT_texture_compression_rgtc 1 +#define GL_COMPRESSED_RED_RGTC1_EXT 0x8DBB +#define GL_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC +#define GL_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD +#define GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE +#endif /* GL_EXT_texture_compression_rgtc */ + +#ifndef GL_EXT_texture_compression_s3tc +#define GL_EXT_texture_compression_s3tc 1 +#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 +#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 +#endif /* GL_EXT_texture_compression_s3tc */ + +#ifndef GL_EXT_texture_cube_map +#define GL_EXT_texture_cube_map 1 +#define GL_NORMAL_MAP_EXT 0x8511 +#define GL_REFLECTION_MAP_EXT 0x8512 +#define GL_TEXTURE_CUBE_MAP_EXT 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP_EXT 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP_EXT 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT 0x851C +#endif /* GL_EXT_texture_cube_map */ + +#ifndef GL_EXT_texture_env_add +#define GL_EXT_texture_env_add 1 +#endif /* GL_EXT_texture_env_add */ + +#ifndef GL_EXT_texture_env_combine +#define GL_EXT_texture_env_combine 1 +#define GL_COMBINE_EXT 0x8570 +#define GL_COMBINE_RGB_EXT 0x8571 +#define GL_COMBINE_ALPHA_EXT 0x8572 +#define GL_RGB_SCALE_EXT 0x8573 +#define GL_ADD_SIGNED_EXT 0x8574 +#define GL_INTERPOLATE_EXT 0x8575 +#define GL_CONSTANT_EXT 0x8576 +#define GL_PRIMARY_COLOR_EXT 0x8577 +#define GL_PREVIOUS_EXT 0x8578 +#define GL_SOURCE0_RGB_EXT 0x8580 +#define GL_SOURCE1_RGB_EXT 0x8581 +#define GL_SOURCE2_RGB_EXT 0x8582 +#define GL_SOURCE0_ALPHA_EXT 0x8588 +#define GL_SOURCE1_ALPHA_EXT 0x8589 +#define GL_SOURCE2_ALPHA_EXT 0x858A +#define GL_OPERAND0_RGB_EXT 0x8590 +#define GL_OPERAND1_RGB_EXT 0x8591 +#define GL_OPERAND2_RGB_EXT 0x8592 +#define GL_OPERAND0_ALPHA_EXT 0x8598 +#define GL_OPERAND1_ALPHA_EXT 0x8599 +#define GL_OPERAND2_ALPHA_EXT 0x859A +#endif /* GL_EXT_texture_env_combine */ + +#ifndef GL_EXT_texture_env_dot3 +#define GL_EXT_texture_env_dot3 1 +#define GL_DOT3_RGB_EXT 0x8740 +#define GL_DOT3_RGBA_EXT 0x8741 +#endif /* GL_EXT_texture_env_dot3 */ + +#ifndef GL_EXT_texture_filter_anisotropic +#define GL_EXT_texture_filter_anisotropic 1 +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#endif /* GL_EXT_texture_filter_anisotropic */ + +#ifndef GL_EXT_texture_filter_minmax +#define GL_EXT_texture_filter_minmax 1 +#endif /* GL_EXT_texture_filter_minmax */ + +#ifndef GL_EXT_texture_integer +#define GL_EXT_texture_integer 1 +#define GL_RGBA32UI_EXT 0x8D70 +#define GL_RGB32UI_EXT 0x8D71 +#define GL_ALPHA32UI_EXT 0x8D72 +#define GL_INTENSITY32UI_EXT 0x8D73 +#define GL_LUMINANCE32UI_EXT 0x8D74 +#define GL_LUMINANCE_ALPHA32UI_EXT 0x8D75 +#define GL_RGBA16UI_EXT 0x8D76 +#define GL_RGB16UI_EXT 0x8D77 +#define GL_ALPHA16UI_EXT 0x8D78 +#define GL_INTENSITY16UI_EXT 0x8D79 +#define GL_LUMINANCE16UI_EXT 0x8D7A +#define GL_LUMINANCE_ALPHA16UI_EXT 0x8D7B +#define GL_RGBA8UI_EXT 0x8D7C +#define GL_RGB8UI_EXT 0x8D7D +#define GL_ALPHA8UI_EXT 0x8D7E +#define GL_INTENSITY8UI_EXT 0x8D7F +#define GL_LUMINANCE8UI_EXT 0x8D80 +#define GL_LUMINANCE_ALPHA8UI_EXT 0x8D81 +#define GL_RGBA32I_EXT 0x8D82 +#define GL_RGB32I_EXT 0x8D83 +#define GL_ALPHA32I_EXT 0x8D84 +#define GL_INTENSITY32I_EXT 0x8D85 +#define GL_LUMINANCE32I_EXT 0x8D86 +#define GL_LUMINANCE_ALPHA32I_EXT 0x8D87 +#define GL_RGBA16I_EXT 0x8D88 +#define GL_RGB16I_EXT 0x8D89 +#define GL_ALPHA16I_EXT 0x8D8A +#define GL_INTENSITY16I_EXT 0x8D8B +#define GL_LUMINANCE16I_EXT 0x8D8C +#define GL_LUMINANCE_ALPHA16I_EXT 0x8D8D +#define GL_RGBA8I_EXT 0x8D8E +#define GL_RGB8I_EXT 0x8D8F +#define GL_ALPHA8I_EXT 0x8D90 +#define GL_INTENSITY8I_EXT 0x8D91 +#define GL_LUMINANCE8I_EXT 0x8D92 +#define GL_LUMINANCE_ALPHA8I_EXT 0x8D93 +#define GL_RED_INTEGER_EXT 0x8D94 +#define GL_GREEN_INTEGER_EXT 0x8D95 +#define GL_BLUE_INTEGER_EXT 0x8D96 +#define GL_ALPHA_INTEGER_EXT 0x8D97 +#define GL_RGB_INTEGER_EXT 0x8D98 +#define GL_RGBA_INTEGER_EXT 0x8D99 +#define GL_BGR_INTEGER_EXT 0x8D9A +#define GL_BGRA_INTEGER_EXT 0x8D9B +#define GL_LUMINANCE_INTEGER_EXT 0x8D9C +#define GL_LUMINANCE_ALPHA_INTEGER_EXT 0x8D9D +#define GL_RGBA_INTEGER_MODE_EXT 0x8D9E +typedef void (APIENTRYP PFNGLTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, const GLuint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIIVEXTPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETTEXPARAMETERIUIVEXTPROC) (GLenum target, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLCLEARCOLORIIEXTPROC) (GLint red, GLint green, GLint blue, GLint alpha); +typedef void (APIENTRYP PFNGLCLEARCOLORIUIEXTPROC) (GLuint red, GLuint green, GLuint blue, GLuint alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexParameterIivEXT (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glTexParameterIuivEXT (GLenum target, GLenum pname, const GLuint *params); +GLAPI void APIENTRY glGetTexParameterIivEXT (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetTexParameterIuivEXT (GLenum target, GLenum pname, GLuint *params); +GLAPI void APIENTRY glClearColorIiEXT (GLint red, GLint green, GLint blue, GLint alpha); +GLAPI void APIENTRY glClearColorIuiEXT (GLuint red, GLuint green, GLuint blue, GLuint alpha); +#endif +#endif /* GL_EXT_texture_integer */ + +#ifndef GL_EXT_texture_lod_bias +#define GL_EXT_texture_lod_bias 1 +#define GL_MAX_TEXTURE_LOD_BIAS_EXT 0x84FD +#define GL_TEXTURE_FILTER_CONTROL_EXT 0x8500 +#define GL_TEXTURE_LOD_BIAS_EXT 0x8501 +#endif /* GL_EXT_texture_lod_bias */ + +#ifndef GL_EXT_texture_mirror_clamp +#define GL_EXT_texture_mirror_clamp 1 +#define GL_MIRROR_CLAMP_EXT 0x8742 +#define GL_MIRROR_CLAMP_TO_EDGE_EXT 0x8743 +#define GL_MIRROR_CLAMP_TO_BORDER_EXT 0x8912 +#endif /* GL_EXT_texture_mirror_clamp */ + +#ifndef GL_EXT_texture_object +#define GL_EXT_texture_object 1 +#define GL_TEXTURE_PRIORITY_EXT 0x8066 +#define GL_TEXTURE_RESIDENT_EXT 0x8067 +#define GL_TEXTURE_1D_BINDING_EXT 0x8068 +#define GL_TEXTURE_2D_BINDING_EXT 0x8069 +#define GL_TEXTURE_3D_BINDING_EXT 0x806A +typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences); +typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures); +typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei n, const GLuint *textures, GLboolean *residences); +GLAPI void APIENTRY glBindTextureEXT (GLenum target, GLuint texture); +GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei n, const GLuint *textures); +GLAPI void APIENTRY glGenTexturesEXT (GLsizei n, GLuint *textures); +GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint texture); +GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei n, const GLuint *textures, const GLclampf *priorities); +#endif +#endif /* GL_EXT_texture_object */ + +#ifndef GL_EXT_texture_perturb_normal +#define GL_EXT_texture_perturb_normal 1 +#define GL_PERTURB_EXT 0x85AE +#define GL_TEXTURE_NORMAL_EXT 0x85AF +typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureNormalEXT (GLenum mode); +#endif +#endif /* GL_EXT_texture_perturb_normal */ + +#ifndef GL_EXT_texture_sRGB +#define GL_EXT_texture_sRGB 1 +#define GL_SRGB_EXT 0x8C40 +#define GL_SRGB8_EXT 0x8C41 +#define GL_SRGB_ALPHA_EXT 0x8C42 +#define GL_SRGB8_ALPHA8_EXT 0x8C43 +#define GL_SLUMINANCE_ALPHA_EXT 0x8C44 +#define GL_SLUMINANCE8_ALPHA8_EXT 0x8C45 +#define GL_SLUMINANCE_EXT 0x8C46 +#define GL_SLUMINANCE8_EXT 0x8C47 +#define GL_COMPRESSED_SRGB_EXT 0x8C48 +#define GL_COMPRESSED_SRGB_ALPHA_EXT 0x8C49 +#define GL_COMPRESSED_SLUMINANCE_EXT 0x8C4A +#define GL_COMPRESSED_SLUMINANCE_ALPHA_EXT 0x8C4B +#define GL_COMPRESSED_SRGB_S3TC_DXT1_EXT 0x8C4C +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT 0x8C4D +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT 0x8C4E +#define GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT 0x8C4F +#endif /* GL_EXT_texture_sRGB */ + +#ifndef GL_EXT_texture_sRGB_decode +#define GL_EXT_texture_sRGB_decode 1 +#define GL_TEXTURE_SRGB_DECODE_EXT 0x8A48 +#define GL_DECODE_EXT 0x8A49 +#define GL_SKIP_DECODE_EXT 0x8A4A +#endif /* GL_EXT_texture_sRGB_decode */ + +#ifndef GL_EXT_texture_shared_exponent +#define GL_EXT_texture_shared_exponent 1 +#define GL_RGB9_E5_EXT 0x8C3D +#define GL_UNSIGNED_INT_5_9_9_9_REV_EXT 0x8C3E +#define GL_TEXTURE_SHARED_SIZE_EXT 0x8C3F +#endif /* GL_EXT_texture_shared_exponent */ + +#ifndef GL_EXT_texture_snorm +#define GL_EXT_texture_snorm 1 +#define GL_ALPHA_SNORM 0x9010 +#define GL_LUMINANCE_SNORM 0x9011 +#define GL_LUMINANCE_ALPHA_SNORM 0x9012 +#define GL_INTENSITY_SNORM 0x9013 +#define GL_ALPHA8_SNORM 0x9014 +#define GL_LUMINANCE8_SNORM 0x9015 +#define GL_LUMINANCE8_ALPHA8_SNORM 0x9016 +#define GL_INTENSITY8_SNORM 0x9017 +#define GL_ALPHA16_SNORM 0x9018 +#define GL_LUMINANCE16_SNORM 0x9019 +#define GL_LUMINANCE16_ALPHA16_SNORM 0x901A +#define GL_INTENSITY16_SNORM 0x901B +#define GL_RED_SNORM 0x8F90 +#define GL_RG_SNORM 0x8F91 +#define GL_RGB_SNORM 0x8F92 +#define GL_RGBA_SNORM 0x8F93 +#endif /* GL_EXT_texture_snorm */ + +#ifndef GL_EXT_texture_swizzle +#define GL_EXT_texture_swizzle 1 +#define GL_TEXTURE_SWIZZLE_R_EXT 0x8E42 +#define GL_TEXTURE_SWIZZLE_G_EXT 0x8E43 +#define GL_TEXTURE_SWIZZLE_B_EXT 0x8E44 +#define GL_TEXTURE_SWIZZLE_A_EXT 0x8E45 +#define GL_TEXTURE_SWIZZLE_RGBA_EXT 0x8E46 +#endif /* GL_EXT_texture_swizzle */ + +#ifndef GL_EXT_timer_query +#define GL_EXT_timer_query 1 +#define GL_TIME_ELAPSED_EXT 0x88BF +typedef void (APIENTRYP PFNGLGETQUERYOBJECTI64VEXTPROC) (GLuint id, GLenum pname, GLint64 *params); +typedef void (APIENTRYP PFNGLGETQUERYOBJECTUI64VEXTPROC) (GLuint id, GLenum pname, GLuint64 *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetQueryObjecti64vEXT (GLuint id, GLenum pname, GLint64 *params); +GLAPI void APIENTRY glGetQueryObjectui64vEXT (GLuint id, GLenum pname, GLuint64 *params); +#endif +#endif /* GL_EXT_timer_query */ + +#ifndef GL_EXT_transform_feedback +#define GL_EXT_transform_feedback 1 +#define GL_TRANSFORM_FEEDBACK_BUFFER_EXT 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_START_EXT 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_EXT 0x8C85 +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_EXT 0x8C8F +#define GL_INTERLEAVED_ATTRIBS_EXT 0x8C8C +#define GL_SEPARATE_ATTRIBS_EXT 0x8C8D +#define GL_PRIMITIVES_GENERATED_EXT 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT 0x8C88 +#define GL_RASTERIZER_DISCARD_EXT 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_EXT 0x8C8B +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT 0x8C80 +#define GL_TRANSFORM_FEEDBACK_VARYINGS_EXT 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_EXT 0x8C7F +#define GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT 0x8C76 +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKEXTPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKEXTPROC) (void); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGEEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETEXTPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +typedef void (APIENTRYP PFNGLBINDBUFFERBASEEXTPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSEXTPROC) (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGEXTPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginTransformFeedbackEXT (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedbackEXT (void); +GLAPI void APIENTRY glBindBufferRangeEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferOffsetEXT (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +GLAPI void APIENTRY glBindBufferBaseEXT (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryingsEXT (GLuint program, GLsizei count, const GLchar *const*varyings, GLenum bufferMode); +GLAPI void APIENTRY glGetTransformFeedbackVaryingEXT (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +#endif +#endif /* GL_EXT_transform_feedback */ + +#ifndef GL_EXT_vertex_array +#define GL_EXT_vertex_array 1 +#define GL_VERTEX_ARRAY_EXT 0x8074 +#define GL_NORMAL_ARRAY_EXT 0x8075 +#define GL_COLOR_ARRAY_EXT 0x8076 +#define GL_INDEX_ARRAY_EXT 0x8077 +#define GL_TEXTURE_COORD_ARRAY_EXT 0x8078 +#define GL_EDGE_FLAG_ARRAY_EXT 0x8079 +#define GL_VERTEX_ARRAY_SIZE_EXT 0x807A +#define GL_VERTEX_ARRAY_TYPE_EXT 0x807B +#define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C +#define GL_VERTEX_ARRAY_COUNT_EXT 0x807D +#define GL_NORMAL_ARRAY_TYPE_EXT 0x807E +#define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F +#define GL_NORMAL_ARRAY_COUNT_EXT 0x8080 +#define GL_COLOR_ARRAY_SIZE_EXT 0x8081 +#define GL_COLOR_ARRAY_TYPE_EXT 0x8082 +#define GL_COLOR_ARRAY_STRIDE_EXT 0x8083 +#define GL_COLOR_ARRAY_COUNT_EXT 0x8084 +#define GL_INDEX_ARRAY_TYPE_EXT 0x8085 +#define GL_INDEX_ARRAY_STRIDE_EXT 0x8086 +#define GL_INDEX_ARRAY_COUNT_EXT 0x8087 +#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A +#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B +#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C +#define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D +#define GL_VERTEX_ARRAY_POINTER_EXT 0x808E +#define GL_NORMAL_ARRAY_POINTER_EXT 0x808F +#define GL_COLOR_ARRAY_POINTER_EXT 0x8090 +#define GL_INDEX_ARRAY_POINTER_EXT 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093 +typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i); +typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count); +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer); +typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, void **params); +typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glArrayElementEXT (GLint i); +GLAPI void APIENTRY glColorPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glDrawArraysEXT (GLenum mode, GLint first, GLsizei count); +GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei stride, GLsizei count, const GLboolean *pointer); +GLAPI void APIENTRY glGetPointervEXT (GLenum pname, void **params); +GLAPI void APIENTRY glIndexPointerEXT (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glNormalPointerEXT (GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glTexCoordPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +GLAPI void APIENTRY glVertexPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const void *pointer); +#endif +#endif /* GL_EXT_vertex_array */ + +#ifndef GL_EXT_vertex_array_bgra +#define GL_EXT_vertex_array_bgra 1 +#endif /* GL_EXT_vertex_array_bgra */ + +#ifndef GL_EXT_vertex_attrib_64bit +#define GL_EXT_vertex_attrib_64bit 1 +#define GL_DOUBLE_VEC2_EXT 0x8FFC +#define GL_DOUBLE_VEC3_EXT 0x8FFD +#define GL_DOUBLE_VEC4_EXT 0x8FFE +#define GL_DOUBLE_MAT2_EXT 0x8F46 +#define GL_DOUBLE_MAT3_EXT 0x8F47 +#define GL_DOUBLE_MAT4_EXT 0x8F48 +#define GL_DOUBLE_MAT2x3_EXT 0x8F49 +#define GL_DOUBLE_MAT2x4_EXT 0x8F4A +#define GL_DOUBLE_MAT3x2_EXT 0x8F4B +#define GL_DOUBLE_MAT3x4_EXT 0x8F4C +#define GL_DOUBLE_MAT4x2_EXT 0x8F4D +#define GL_DOUBLE_MAT4x3_EXT 0x8F4E +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DEXTPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DEXTPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DEXTPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4DVEXTPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLDVEXTPROC) (GLuint index, GLenum pname, GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribL1dEXT (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttribL2dEXT (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttribL3dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttribL4dEXT (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttribL1dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL2dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL3dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribL4dvEXT (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribLPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribLdvEXT (GLuint index, GLenum pname, GLdouble *params); +#endif +#endif /* GL_EXT_vertex_attrib_64bit */ + +#ifndef GL_EXT_vertex_shader +#define GL_EXT_vertex_shader 1 +#define GL_VERTEX_SHADER_EXT 0x8780 +#define GL_VERTEX_SHADER_BINDING_EXT 0x8781 +#define GL_OP_INDEX_EXT 0x8782 +#define GL_OP_NEGATE_EXT 0x8783 +#define GL_OP_DOT3_EXT 0x8784 +#define GL_OP_DOT4_EXT 0x8785 +#define GL_OP_MUL_EXT 0x8786 +#define GL_OP_ADD_EXT 0x8787 +#define GL_OP_MADD_EXT 0x8788 +#define GL_OP_FRAC_EXT 0x8789 +#define GL_OP_MAX_EXT 0x878A +#define GL_OP_MIN_EXT 0x878B +#define GL_OP_SET_GE_EXT 0x878C +#define GL_OP_SET_LT_EXT 0x878D +#define GL_OP_CLAMP_EXT 0x878E +#define GL_OP_FLOOR_EXT 0x878F +#define GL_OP_ROUND_EXT 0x8790 +#define GL_OP_EXP_BASE_2_EXT 0x8791 +#define GL_OP_LOG_BASE_2_EXT 0x8792 +#define GL_OP_POWER_EXT 0x8793 +#define GL_OP_RECIP_EXT 0x8794 +#define GL_OP_RECIP_SQRT_EXT 0x8795 +#define GL_OP_SUB_EXT 0x8796 +#define GL_OP_CROSS_PRODUCT_EXT 0x8797 +#define GL_OP_MULTIPLY_MATRIX_EXT 0x8798 +#define GL_OP_MOV_EXT 0x8799 +#define GL_OUTPUT_VERTEX_EXT 0x879A +#define GL_OUTPUT_COLOR0_EXT 0x879B +#define GL_OUTPUT_COLOR1_EXT 0x879C +#define GL_OUTPUT_TEXTURE_COORD0_EXT 0x879D +#define GL_OUTPUT_TEXTURE_COORD1_EXT 0x879E +#define GL_OUTPUT_TEXTURE_COORD2_EXT 0x879F +#define GL_OUTPUT_TEXTURE_COORD3_EXT 0x87A0 +#define GL_OUTPUT_TEXTURE_COORD4_EXT 0x87A1 +#define GL_OUTPUT_TEXTURE_COORD5_EXT 0x87A2 +#define GL_OUTPUT_TEXTURE_COORD6_EXT 0x87A3 +#define GL_OUTPUT_TEXTURE_COORD7_EXT 0x87A4 +#define GL_OUTPUT_TEXTURE_COORD8_EXT 0x87A5 +#define GL_OUTPUT_TEXTURE_COORD9_EXT 0x87A6 +#define GL_OUTPUT_TEXTURE_COORD10_EXT 0x87A7 +#define GL_OUTPUT_TEXTURE_COORD11_EXT 0x87A8 +#define GL_OUTPUT_TEXTURE_COORD12_EXT 0x87A9 +#define GL_OUTPUT_TEXTURE_COORD13_EXT 0x87AA +#define GL_OUTPUT_TEXTURE_COORD14_EXT 0x87AB +#define GL_OUTPUT_TEXTURE_COORD15_EXT 0x87AC +#define GL_OUTPUT_TEXTURE_COORD16_EXT 0x87AD +#define GL_OUTPUT_TEXTURE_COORD17_EXT 0x87AE +#define GL_OUTPUT_TEXTURE_COORD18_EXT 0x87AF +#define GL_OUTPUT_TEXTURE_COORD19_EXT 0x87B0 +#define GL_OUTPUT_TEXTURE_COORD20_EXT 0x87B1 +#define GL_OUTPUT_TEXTURE_COORD21_EXT 0x87B2 +#define GL_OUTPUT_TEXTURE_COORD22_EXT 0x87B3 +#define GL_OUTPUT_TEXTURE_COORD23_EXT 0x87B4 +#define GL_OUTPUT_TEXTURE_COORD24_EXT 0x87B5 +#define GL_OUTPUT_TEXTURE_COORD25_EXT 0x87B6 +#define GL_OUTPUT_TEXTURE_COORD26_EXT 0x87B7 +#define GL_OUTPUT_TEXTURE_COORD27_EXT 0x87B8 +#define GL_OUTPUT_TEXTURE_COORD28_EXT 0x87B9 +#define GL_OUTPUT_TEXTURE_COORD29_EXT 0x87BA +#define GL_OUTPUT_TEXTURE_COORD30_EXT 0x87BB +#define GL_OUTPUT_TEXTURE_COORD31_EXT 0x87BC +#define GL_OUTPUT_FOG_EXT 0x87BD +#define GL_SCALAR_EXT 0x87BE +#define GL_VECTOR_EXT 0x87BF +#define GL_MATRIX_EXT 0x87C0 +#define GL_VARIANT_EXT 0x87C1 +#define GL_INVARIANT_EXT 0x87C2 +#define GL_LOCAL_CONSTANT_EXT 0x87C3 +#define GL_LOCAL_EXT 0x87C4 +#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5 +#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6 +#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7 +#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8 +#define GL_MAX_VERTEX_SHADER_LOCALS_EXT 0x87C9 +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD +#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE +#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF +#define GL_VERTEX_SHADER_VARIANTS_EXT 0x87D0 +#define GL_VERTEX_SHADER_INVARIANTS_EXT 0x87D1 +#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2 +#define GL_VERTEX_SHADER_LOCALS_EXT 0x87D3 +#define GL_VERTEX_SHADER_OPTIMIZED_EXT 0x87D4 +#define GL_X_EXT 0x87D5 +#define GL_Y_EXT 0x87D6 +#define GL_Z_EXT 0x87D7 +#define GL_W_EXT 0x87D8 +#define GL_NEGATIVE_X_EXT 0x87D9 +#define GL_NEGATIVE_Y_EXT 0x87DA +#define GL_NEGATIVE_Z_EXT 0x87DB +#define GL_NEGATIVE_W_EXT 0x87DC +#define GL_ZERO_EXT 0x87DD +#define GL_ONE_EXT 0x87DE +#define GL_NEGATIVE_ONE_EXT 0x87DF +#define GL_NORMALIZED_RANGE_EXT 0x87E0 +#define GL_FULL_RANGE_EXT 0x87E1 +#define GL_CURRENT_VERTEX_EXT 0x87E2 +#define GL_MVP_MATRIX_EXT 0x87E3 +#define GL_VARIANT_VALUE_EXT 0x87E4 +#define GL_VARIANT_DATATYPE_EXT 0x87E5 +#define GL_VARIANT_ARRAY_STRIDE_EXT 0x87E6 +#define GL_VARIANT_ARRAY_TYPE_EXT 0x87E7 +#define GL_VARIANT_ARRAY_EXT 0x87E8 +#define GL_VARIANT_ARRAY_POINTER_EXT 0x87E9 +#define GL_INVARIANT_VALUE_EXT 0x87EA +#define GL_INVARIANT_DATATYPE_EXT 0x87EB +#define GL_LOCAL_CONSTANT_VALUE_EXT 0x87EC +#define GL_LOCAL_CONSTANT_DATATYPE_EXT 0x87ED +typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void); +typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void); +typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id); +typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range); +typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id); +typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1); +typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2); +typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3); +typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); +typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num); +typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components); +typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const void *addr); +typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const void *addr); +typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr); +typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr); +typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr); +typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr); +typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr); +typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr); +typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr); +typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr); +typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const void *addr); +typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); +typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id); +typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value); +typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value); +typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap); +typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, void **data); +typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data); +typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginVertexShaderEXT (void); +GLAPI void APIENTRY glEndVertexShaderEXT (void); +GLAPI void APIENTRY glBindVertexShaderEXT (GLuint id); +GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint range); +GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint id); +GLAPI void APIENTRY glShaderOp1EXT (GLenum op, GLuint res, GLuint arg1); +GLAPI void APIENTRY glShaderOp2EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2); +GLAPI void APIENTRY glShaderOp3EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3); +GLAPI void APIENTRY glSwizzleEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +GLAPI void APIENTRY glWriteMaskEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW); +GLAPI void APIENTRY glInsertComponentEXT (GLuint res, GLuint src, GLuint num); +GLAPI void APIENTRY glExtractComponentEXT (GLuint res, GLuint src, GLuint num); +GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum datatype, GLenum storagetype, GLenum range, GLuint components); +GLAPI void APIENTRY glSetInvariantEXT (GLuint id, GLenum type, const void *addr); +GLAPI void APIENTRY glSetLocalConstantEXT (GLuint id, GLenum type, const void *addr); +GLAPI void APIENTRY glVariantbvEXT (GLuint id, const GLbyte *addr); +GLAPI void APIENTRY glVariantsvEXT (GLuint id, const GLshort *addr); +GLAPI void APIENTRY glVariantivEXT (GLuint id, const GLint *addr); +GLAPI void APIENTRY glVariantfvEXT (GLuint id, const GLfloat *addr); +GLAPI void APIENTRY glVariantdvEXT (GLuint id, const GLdouble *addr); +GLAPI void APIENTRY glVariantubvEXT (GLuint id, const GLubyte *addr); +GLAPI void APIENTRY glVariantusvEXT (GLuint id, const GLushort *addr); +GLAPI void APIENTRY glVariantuivEXT (GLuint id, const GLuint *addr); +GLAPI void APIENTRY glVariantPointerEXT (GLuint id, GLenum type, GLuint stride, const void *addr); +GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint id); +GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint id); +GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum light, GLenum value); +GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum face, GLenum value); +GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum unit, GLenum coord, GLenum value); +GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum unit, GLenum value); +GLAPI GLuint APIENTRY glBindParameterEXT (GLenum value); +GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint id, GLenum cap); +GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +GLAPI void APIENTRY glGetVariantPointervEXT (GLuint id, GLenum value, void **data); +GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint id, GLenum value, GLboolean *data); +GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint id, GLenum value, GLint *data); +GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint id, GLenum value, GLfloat *data); +#endif +#endif /* GL_EXT_vertex_shader */ + +#ifndef GL_EXT_vertex_weighting +#define GL_EXT_vertex_weighting 1 +#define GL_MODELVIEW0_STACK_DEPTH_EXT 0x0BA3 +#define GL_MODELVIEW1_STACK_DEPTH_EXT 0x8502 +#define GL_MODELVIEW0_MATRIX_EXT 0x0BA6 +#define GL_MODELVIEW1_MATRIX_EXT 0x8506 +#define GL_VERTEX_WEIGHTING_EXT 0x8509 +#define GL_MODELVIEW0_EXT 0x1700 +#define GL_MODELVIEW1_EXT 0x850A +#define GL_CURRENT_VERTEX_WEIGHT_EXT 0x850B +#define GL_VERTEX_WEIGHT_ARRAY_EXT 0x850C +#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT 0x850D +#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT 0x850E +#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F +#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510 +typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexWeightfEXT (GLfloat weight); +GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *weight); +GLAPI void APIENTRY glVertexWeightPointerEXT (GLint size, GLenum type, GLsizei stride, const void *pointer); +#endif +#endif /* GL_EXT_vertex_weighting */ + +#ifndef GL_EXT_x11_sync_object +#define GL_EXT_x11_sync_object 1 +#define GL_SYNC_X11_FENCE_EXT 0x90E1 +typedef GLsync (APIENTRYP PFNGLIMPORTSYNCEXTPROC) (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLsync APIENTRY glImportSyncEXT (GLenum external_sync_type, GLintptr external_sync, GLbitfield flags); +#endif +#endif /* GL_EXT_x11_sync_object */ + +#ifndef GL_GREMEDY_frame_terminator +#define GL_GREMEDY_frame_terminator 1 +typedef void (APIENTRYP PFNGLFRAMETERMINATORGREMEDYPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFrameTerminatorGREMEDY (void); +#endif +#endif /* GL_GREMEDY_frame_terminator */ + +#ifndef GL_GREMEDY_string_marker +#define GL_GREMEDY_string_marker 1 +typedef void (APIENTRYP PFNGLSTRINGMARKERGREMEDYPROC) (GLsizei len, const void *string); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glStringMarkerGREMEDY (GLsizei len, const void *string); +#endif +#endif /* GL_GREMEDY_string_marker */ + +#ifndef GL_HP_convolution_border_modes +#define GL_HP_convolution_border_modes 1 +#define GL_IGNORE_BORDER_HP 0x8150 +#define GL_CONSTANT_BORDER_HP 0x8151 +#define GL_REPLICATE_BORDER_HP 0x8153 +#define GL_CONVOLUTION_BORDER_COLOR_HP 0x8154 +#endif /* GL_HP_convolution_border_modes */ + +#ifndef GL_HP_image_transform +#define GL_HP_image_transform 1 +#define GL_IMAGE_SCALE_X_HP 0x8155 +#define GL_IMAGE_SCALE_Y_HP 0x8156 +#define GL_IMAGE_TRANSLATE_X_HP 0x8157 +#define GL_IMAGE_TRANSLATE_Y_HP 0x8158 +#define GL_IMAGE_ROTATE_ANGLE_HP 0x8159 +#define GL_IMAGE_ROTATE_ORIGIN_X_HP 0x815A +#define GL_IMAGE_ROTATE_ORIGIN_Y_HP 0x815B +#define GL_IMAGE_MAG_FILTER_HP 0x815C +#define GL_IMAGE_MIN_FILTER_HP 0x815D +#define GL_IMAGE_CUBIC_WEIGHT_HP 0x815E +#define GL_CUBIC_HP 0x815F +#define GL_AVERAGE_HP 0x8160 +#define GL_IMAGE_TRANSFORM_2D_HP 0x8161 +#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162 +#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163 +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glImageTransformParameteriHP (GLenum target, GLenum pname, GLint param); +GLAPI void APIENTRY glImageTransformParameterfHP (GLenum target, GLenum pname, GLfloat param); +GLAPI void APIENTRY glImageTransformParameterivHP (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum target, GLenum pname, GLfloat *params); +#endif +#endif /* GL_HP_image_transform */ + +#ifndef GL_HP_occlusion_test +#define GL_HP_occlusion_test 1 +#define GL_OCCLUSION_TEST_HP 0x8165 +#define GL_OCCLUSION_TEST_RESULT_HP 0x8166 +#endif /* GL_HP_occlusion_test */ + +#ifndef GL_HP_texture_lighting +#define GL_HP_texture_lighting 1 +#define GL_TEXTURE_LIGHTING_MODE_HP 0x8167 +#define GL_TEXTURE_POST_SPECULAR_HP 0x8168 +#define GL_TEXTURE_PRE_SPECULAR_HP 0x8169 +#endif /* GL_HP_texture_lighting */ + +#ifndef GL_IBM_cull_vertex +#define GL_IBM_cull_vertex 1 +#define GL_CULL_VERTEX_IBM 103050 +#endif /* GL_IBM_cull_vertex */ + +#ifndef GL_IBM_multimode_draw_arrays +#define GL_IBM_multimode_draw_arrays 1 +typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride); +typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, GLint modestride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride); +GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *mode, const GLsizei *count, GLenum type, const void *const*indices, GLsizei primcount, GLint modestride); +#endif +#endif /* GL_IBM_multimode_draw_arrays */ + +#ifndef GL_IBM_rasterpos_clip +#define GL_IBM_rasterpos_clip 1 +#define GL_RASTER_POSITION_UNCLIPPED_IBM 0x19262 +#endif /* GL_IBM_rasterpos_clip */ + +#ifndef GL_IBM_static_data +#define GL_IBM_static_data 1 +#define GL_ALL_STATIC_DATA_IBM 103060 +#define GL_STATIC_VERTEX_ARRAY_IBM 103061 +typedef void (APIENTRYP PFNGLFLUSHSTATICDATAIBMPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushStaticDataIBM (GLenum target); +#endif +#endif /* GL_IBM_static_data */ + +#ifndef GL_IBM_texture_mirrored_repeat +#define GL_IBM_texture_mirrored_repeat 1 +#define GL_MIRRORED_REPEAT_IBM 0x8370 +#endif /* GL_IBM_texture_mirrored_repeat */ + +#ifndef GL_IBM_vertex_array_lists +#define GL_IBM_vertex_array_lists 1 +#define GL_VERTEX_ARRAY_LIST_IBM 103070 +#define GL_NORMAL_ARRAY_LIST_IBM 103071 +#define GL_COLOR_ARRAY_LIST_IBM 103072 +#define GL_INDEX_ARRAY_LIST_IBM 103073 +#define GL_TEXTURE_COORD_ARRAY_LIST_IBM 103074 +#define GL_EDGE_FLAG_ARRAY_LIST_IBM 103075 +#define GL_FOG_COORDINATE_ARRAY_LIST_IBM 103076 +#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077 +#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM 103080 +#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM 103081 +#define GL_COLOR_ARRAY_LIST_STRIDE_IBM 103082 +#define GL_INDEX_ARRAY_LIST_STRIDE_IBM 103083 +#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084 +#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085 +#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086 +#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087 +typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint stride, const GLboolean **pointer, GLint ptrstride); +GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glIndexPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glNormalPointerListIBM (GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glTexCoordPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +GLAPI void APIENTRY glVertexPointerListIBM (GLint size, GLenum type, GLint stride, const void **pointer, GLint ptrstride); +#endif +#endif /* GL_IBM_vertex_array_lists */ + +#ifndef GL_INGR_blend_func_separate +#define GL_INGR_blend_func_separate 1 +typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); +#endif +#endif /* GL_INGR_blend_func_separate */ + +#ifndef GL_INGR_color_clamp +#define GL_INGR_color_clamp 1 +#define GL_RED_MIN_CLAMP_INGR 0x8560 +#define GL_GREEN_MIN_CLAMP_INGR 0x8561 +#define GL_BLUE_MIN_CLAMP_INGR 0x8562 +#define GL_ALPHA_MIN_CLAMP_INGR 0x8563 +#define GL_RED_MAX_CLAMP_INGR 0x8564 +#define GL_GREEN_MAX_CLAMP_INGR 0x8565 +#define GL_BLUE_MAX_CLAMP_INGR 0x8566 +#define GL_ALPHA_MAX_CLAMP_INGR 0x8567 +#endif /* GL_INGR_color_clamp */ + +#ifndef GL_INGR_interlace_read +#define GL_INGR_interlace_read 1 +#define GL_INTERLACE_READ_INGR 0x8568 +#endif /* GL_INGR_interlace_read */ + +#ifndef GL_INTEL_fragment_shader_ordering +#define GL_INTEL_fragment_shader_ordering 1 +#endif /* GL_INTEL_fragment_shader_ordering */ + +#ifndef GL_INTEL_map_texture +#define GL_INTEL_map_texture 1 +#define GL_TEXTURE_MEMORY_LAYOUT_INTEL 0x83FF +#define GL_LAYOUT_DEFAULT_INTEL 0 +#define GL_LAYOUT_LINEAR_INTEL 1 +#define GL_LAYOUT_LINEAR_CPU_CACHED_INTEL 2 +typedef void (APIENTRYP PFNGLSYNCTEXTUREINTELPROC) (GLuint texture); +typedef void (APIENTRYP PFNGLUNMAPTEXTURE2DINTELPROC) (GLuint texture, GLint level); +typedef void *(APIENTRYP PFNGLMAPTEXTURE2DINTELPROC) (GLuint texture, GLint level, GLbitfield access, GLint *stride, GLenum *layout); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSyncTextureINTEL (GLuint texture); +GLAPI void APIENTRY glUnmapTexture2DINTEL (GLuint texture, GLint level); +GLAPI void *APIENTRY glMapTexture2DINTEL (GLuint texture, GLint level, GLbitfield access, GLint *stride, GLenum *layout); +#endif +#endif /* GL_INTEL_map_texture */ + +#ifndef GL_INTEL_parallel_arrays +#define GL_INTEL_parallel_arrays 1 +#define GL_PARALLEL_ARRAYS_INTEL 0x83F4 +#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5 +#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6 +#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7 +#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8 +typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexPointervINTEL (GLint size, GLenum type, const void **pointer); +GLAPI void APIENTRY glNormalPointervINTEL (GLenum type, const void **pointer); +GLAPI void APIENTRY glColorPointervINTEL (GLint size, GLenum type, const void **pointer); +GLAPI void APIENTRY glTexCoordPointervINTEL (GLint size, GLenum type, const void **pointer); +#endif +#endif /* GL_INTEL_parallel_arrays */ + +#ifndef GL_INTEL_performance_query +#define GL_INTEL_performance_query 1 +#define GL_PERFQUERY_SINGLE_CONTEXT_INTEL 0x00000000 +#define GL_PERFQUERY_GLOBAL_CONTEXT_INTEL 0x00000001 +#define GL_PERFQUERY_WAIT_INTEL 0x83FB +#define GL_PERFQUERY_FLUSH_INTEL 0x83FA +#define GL_PERFQUERY_DONOT_FLUSH_INTEL 0x83F9 +#define GL_PERFQUERY_COUNTER_EVENT_INTEL 0x94F0 +#define GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL 0x94F1 +#define GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL 0x94F2 +#define GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL 0x94F3 +#define GL_PERFQUERY_COUNTER_RAW_INTEL 0x94F4 +#define GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL 0x94F5 +#define GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL 0x94F8 +#define GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL 0x94F9 +#define GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL 0x94FA +#define GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL 0x94FB +#define GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL 0x94FC +#define GL_PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL 0x94FD +#define GL_PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL 0x94FE +#define GL_PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL 0x94FF +#define GL_PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL 0x9500 +typedef void (APIENTRYP PFNGLBEGINPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLCREATEPERFQUERYINTELPROC) (GLuint queryId, GLuint *queryHandle); +typedef void (APIENTRYP PFNGLDELETEPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLENDPERFQUERYINTELPROC) (GLuint queryHandle); +typedef void (APIENTRYP PFNGLGETFIRSTPERFQUERYIDINTELPROC) (GLuint *queryId); +typedef void (APIENTRYP PFNGLGETNEXTPERFQUERYIDINTELPROC) (GLuint queryId, GLuint *nextQueryId); +typedef void (APIENTRYP PFNGLGETPERFCOUNTERINFOINTELPROC) (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); +typedef void (APIENTRYP PFNGLGETPERFQUERYDATAINTELPROC) (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); +typedef void (APIENTRYP PFNGLGETPERFQUERYIDBYNAMEINTELPROC) (GLchar *queryName, GLuint *queryId); +typedef void (APIENTRYP PFNGLGETPERFQUERYINFOINTELPROC) (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginPerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glCreatePerfQueryINTEL (GLuint queryId, GLuint *queryHandle); +GLAPI void APIENTRY glDeletePerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glEndPerfQueryINTEL (GLuint queryHandle); +GLAPI void APIENTRY glGetFirstPerfQueryIdINTEL (GLuint *queryId); +GLAPI void APIENTRY glGetNextPerfQueryIdINTEL (GLuint queryId, GLuint *nextQueryId); +GLAPI void APIENTRY glGetPerfCounterInfoINTEL (GLuint queryId, GLuint counterId, GLuint counterNameLength, GLchar *counterName, GLuint counterDescLength, GLchar *counterDesc, GLuint *counterOffset, GLuint *counterDataSize, GLuint *counterTypeEnum, GLuint *counterDataTypeEnum, GLuint64 *rawCounterMaxValue); +GLAPI void APIENTRY glGetPerfQueryDataINTEL (GLuint queryHandle, GLuint flags, GLsizei dataSize, GLvoid *data, GLuint *bytesWritten); +GLAPI void APIENTRY glGetPerfQueryIdByNameINTEL (GLchar *queryName, GLuint *queryId); +GLAPI void APIENTRY glGetPerfQueryInfoINTEL (GLuint queryId, GLuint queryNameLength, GLchar *queryName, GLuint *dataSize, GLuint *noCounters, GLuint *noInstances, GLuint *capsMask); +#endif +#endif /* GL_INTEL_performance_query */ + +#ifndef GL_MESAX_texture_stack +#define GL_MESAX_texture_stack 1 +#define GL_TEXTURE_1D_STACK_MESAX 0x8759 +#define GL_TEXTURE_2D_STACK_MESAX 0x875A +#define GL_PROXY_TEXTURE_1D_STACK_MESAX 0x875B +#define GL_PROXY_TEXTURE_2D_STACK_MESAX 0x875C +#define GL_TEXTURE_1D_STACK_BINDING_MESAX 0x875D +#define GL_TEXTURE_2D_STACK_BINDING_MESAX 0x875E +#endif /* GL_MESAX_texture_stack */ + +#ifndef GL_MESA_pack_invert +#define GL_MESA_pack_invert 1 +#define GL_PACK_INVERT_MESA 0x8758 +#endif /* GL_MESA_pack_invert */ + +#ifndef GL_MESA_resize_buffers +#define GL_MESA_resize_buffers 1 +typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glResizeBuffersMESA (void); +#endif +#endif /* GL_MESA_resize_buffers */ + +#ifndef GL_MESA_window_pos +#define GL_MESA_window_pos 1 +typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y); +typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v); +typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glWindowPos2dMESA (GLdouble x, GLdouble y); +GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos2fMESA (GLfloat x, GLfloat y); +GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos2iMESA (GLint x, GLint y); +GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos2sMESA (GLshort x, GLshort y); +GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *v); +GLAPI void APIENTRY glWindowPos3dMESA (GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos3fMESA (GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos3iMESA (GLint x, GLint y, GLint z); +GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos3sMESA (GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *v); +GLAPI void APIENTRY glWindowPos4dMESA (GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *v); +GLAPI void APIENTRY glWindowPos4fMESA (GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *v); +GLAPI void APIENTRY glWindowPos4iMESA (GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *v); +GLAPI void APIENTRY glWindowPos4sMESA (GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *v); +#endif +#endif /* GL_MESA_window_pos */ + +#ifndef GL_MESA_ycbcr_texture +#define GL_MESA_ycbcr_texture 1 +#define GL_UNSIGNED_SHORT_8_8_MESA 0x85BA +#define GL_UNSIGNED_SHORT_8_8_REV_MESA 0x85BB +#define GL_YCBCR_MESA 0x8757 +#endif /* GL_MESA_ycbcr_texture */ + +#ifndef GL_NVX_conditional_render +#define GL_NVX_conditional_render 1 +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVXPROC) (GLuint id); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginConditionalRenderNVX (GLuint id); +GLAPI void APIENTRY glEndConditionalRenderNVX (void); +#endif +#endif /* GL_NVX_conditional_render */ + +#ifndef GL_NVX_gpu_memory_info +#define GL_NVX_gpu_memory_info 1 +#define GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX 0x9047 +#define GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048 +#define GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049 +#define GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX 0x904A +#define GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX 0x904B +#endif /* GL_NVX_gpu_memory_info */ + +#ifndef GL_NV_bindless_multi_draw_indirect +#define GL_NV_bindless_multi_draw_indirect 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectBindlessNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +GLAPI void APIENTRY glMultiDrawElementsIndirectBindlessNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei stride, GLint vertexBufferCount); +#endif +#endif /* GL_NV_bindless_multi_draw_indirect */ + +#ifndef GL_NV_bindless_multi_draw_indirect_count +#define GL_NV_bindless_multi_draw_indirect_count 1 +typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSINDIRECTBINDLESSCOUNTNVPROC) (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSINDIRECTBINDLESSCOUNTNVPROC) (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMultiDrawArraysIndirectBindlessCountNV (GLenum mode, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +GLAPI void APIENTRY glMultiDrawElementsIndirectBindlessCountNV (GLenum mode, GLenum type, const void *indirect, GLsizei drawCount, GLsizei maxDrawCount, GLsizei stride, GLint vertexBufferCount); +#endif +#endif /* GL_NV_bindless_multi_draw_indirect_count */ + +#ifndef GL_NV_bindless_texture +#define GL_NV_bindless_texture 1 +typedef GLuint64 (APIENTRYP PFNGLGETTEXTUREHANDLENVPROC) (GLuint texture); +typedef GLuint64 (APIENTRYP PFNGLGETTEXTURESAMPLERHANDLENVPROC) (GLuint texture, GLuint sampler); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLMAKETEXTUREHANDLENONRESIDENTNVPROC) (GLuint64 handle); +typedef GLuint64 (APIENTRYP PFNGLGETIMAGEHANDLENVPROC) (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle, GLenum access); +typedef void (APIENTRYP PFNGLMAKEIMAGEHANDLENONRESIDENTNVPROC) (GLuint64 handle); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64NVPROC) (GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLUNIFORMHANDLEUI64VNVPROC) (GLint location, GLsizei count, const GLuint64 *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64NVPROC) (GLuint program, GLint location, GLuint64 value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMHANDLEUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +typedef GLboolean (APIENTRYP PFNGLISTEXTUREHANDLERESIDENTNVPROC) (GLuint64 handle); +typedef GLboolean (APIENTRYP PFNGLISIMAGEHANDLERESIDENTNVPROC) (GLuint64 handle); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint64 APIENTRY glGetTextureHandleNV (GLuint texture); +GLAPI GLuint64 APIENTRY glGetTextureSamplerHandleNV (GLuint texture, GLuint sampler); +GLAPI void APIENTRY glMakeTextureHandleResidentNV (GLuint64 handle); +GLAPI void APIENTRY glMakeTextureHandleNonResidentNV (GLuint64 handle); +GLAPI GLuint64 APIENTRY glGetImageHandleNV (GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum format); +GLAPI void APIENTRY glMakeImageHandleResidentNV (GLuint64 handle, GLenum access); +GLAPI void APIENTRY glMakeImageHandleNonResidentNV (GLuint64 handle); +GLAPI void APIENTRY glUniformHandleui64NV (GLint location, GLuint64 value); +GLAPI void APIENTRY glUniformHandleui64vNV (GLint location, GLsizei count, const GLuint64 *value); +GLAPI void APIENTRY glProgramUniformHandleui64NV (GLuint program, GLint location, GLuint64 value); +GLAPI void APIENTRY glProgramUniformHandleui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64 *values); +GLAPI GLboolean APIENTRY glIsTextureHandleResidentNV (GLuint64 handle); +GLAPI GLboolean APIENTRY glIsImageHandleResidentNV (GLuint64 handle); +#endif +#endif /* GL_NV_bindless_texture */ + +#ifndef GL_NV_blend_equation_advanced +#define GL_NV_blend_equation_advanced 1 +#define GL_BLEND_OVERLAP_NV 0x9281 +#define GL_BLEND_PREMULTIPLIED_SRC_NV 0x9280 +#define GL_BLUE_NV 0x1905 +#define GL_COLORBURN_NV 0x929A +#define GL_COLORDODGE_NV 0x9299 +#define GL_CONJOINT_NV 0x9284 +#define GL_CONTRAST_NV 0x92A1 +#define GL_DARKEN_NV 0x9297 +#define GL_DIFFERENCE_NV 0x929E +#define GL_DISJOINT_NV 0x9283 +#define GL_DST_ATOP_NV 0x928F +#define GL_DST_IN_NV 0x928B +#define GL_DST_NV 0x9287 +#define GL_DST_OUT_NV 0x928D +#define GL_DST_OVER_NV 0x9289 +#define GL_EXCLUSION_NV 0x92A0 +#define GL_GREEN_NV 0x1904 +#define GL_HARDLIGHT_NV 0x929B +#define GL_HARDMIX_NV 0x92A9 +#define GL_HSL_COLOR_NV 0x92AF +#define GL_HSL_HUE_NV 0x92AD +#define GL_HSL_LUMINOSITY_NV 0x92B0 +#define GL_HSL_SATURATION_NV 0x92AE +#define GL_INVERT_OVG_NV 0x92B4 +#define GL_INVERT_RGB_NV 0x92A3 +#define GL_LIGHTEN_NV 0x9298 +#define GL_LINEARBURN_NV 0x92A5 +#define GL_LINEARDODGE_NV 0x92A4 +#define GL_LINEARLIGHT_NV 0x92A7 +#define GL_MINUS_CLAMPED_NV 0x92B3 +#define GL_MINUS_NV 0x929F +#define GL_MULTIPLY_NV 0x9294 +#define GL_OVERLAY_NV 0x9296 +#define GL_PINLIGHT_NV 0x92A8 +#define GL_PLUS_CLAMPED_ALPHA_NV 0x92B2 +#define GL_PLUS_CLAMPED_NV 0x92B1 +#define GL_PLUS_DARKER_NV 0x9292 +#define GL_PLUS_NV 0x9291 +#define GL_RED_NV 0x1903 +#define GL_SCREEN_NV 0x9295 +#define GL_SOFTLIGHT_NV 0x929C +#define GL_SRC_ATOP_NV 0x928E +#define GL_SRC_IN_NV 0x928A +#define GL_SRC_NV 0x9286 +#define GL_SRC_OUT_NV 0x928C +#define GL_SRC_OVER_NV 0x9288 +#define GL_UNCORRELATED_NV 0x9282 +#define GL_VIVIDLIGHT_NV 0x92A6 +#define GL_XOR_NV 0x1506 +typedef void (APIENTRYP PFNGLBLENDPARAMETERINVPROC) (GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLBLENDBARRIERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBlendParameteriNV (GLenum pname, GLint value); +GLAPI void APIENTRY glBlendBarrierNV (void); +#endif +#endif /* GL_NV_blend_equation_advanced */ + +#ifndef GL_NV_blend_equation_advanced_coherent +#define GL_NV_blend_equation_advanced_coherent 1 +#define GL_BLEND_ADVANCED_COHERENT_NV 0x9285 +#endif /* GL_NV_blend_equation_advanced_coherent */ + +#ifndef GL_NV_blend_square +#define GL_NV_blend_square 1 +#endif /* GL_NV_blend_square */ + +#ifndef GL_NV_compute_program5 +#define GL_NV_compute_program5 1 +#define GL_COMPUTE_PROGRAM_NV 0x90FB +#define GL_COMPUTE_PROGRAM_PARAMETER_BUFFER_NV 0x90FC +#endif /* GL_NV_compute_program5 */ + +#ifndef GL_NV_conditional_render +#define GL_NV_conditional_render 1 +#define GL_QUERY_WAIT_NV 0x8E13 +#define GL_QUERY_NO_WAIT_NV 0x8E14 +#define GL_QUERY_BY_REGION_WAIT_NV 0x8E15 +#define GL_QUERY_BY_REGION_NO_WAIT_NV 0x8E16 +typedef void (APIENTRYP PFNGLBEGINCONDITIONALRENDERNVPROC) (GLuint id, GLenum mode); +typedef void (APIENTRYP PFNGLENDCONDITIONALRENDERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginConditionalRenderNV (GLuint id, GLenum mode); +GLAPI void APIENTRY glEndConditionalRenderNV (void); +#endif +#endif /* GL_NV_conditional_render */ + +#ifndef GL_NV_conservative_raster +#define GL_NV_conservative_raster 1 +#define GL_CONSERVATIVE_RASTERIZATION_NV 0x9346 +#define GL_SUBPIXEL_PRECISION_BIAS_X_BITS_NV 0x9347 +#define GL_SUBPIXEL_PRECISION_BIAS_Y_BITS_NV 0x9348 +#define GL_MAX_SUBPIXEL_PRECISION_BIAS_BITS_NV 0x9349 +typedef void (APIENTRYP PFNGLSUBPIXELPRECISIONBIASNVPROC) (GLuint xbits, GLuint ybits); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSubpixelPrecisionBiasNV (GLuint xbits, GLuint ybits); +#endif +#endif /* GL_NV_conservative_raster */ + +#ifndef GL_NV_copy_depth_to_color +#define GL_NV_copy_depth_to_color 1 +#define GL_DEPTH_STENCIL_TO_RGBA_NV 0x886E +#define GL_DEPTH_STENCIL_TO_BGRA_NV 0x886F +#endif /* GL_NV_copy_depth_to_color */ + +#ifndef GL_NV_copy_image +#define GL_NV_copy_image 1 +typedef void (APIENTRYP PFNGLCOPYIMAGESUBDATANVPROC) (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCopyImageSubDataNV (GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth); +#endif +#endif /* GL_NV_copy_image */ + +#ifndef GL_NV_deep_texture3D +#define GL_NV_deep_texture3D 1 +#define GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV 0x90D0 +#define GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV 0x90D1 +#endif /* GL_NV_deep_texture3D */ + +#ifndef GL_NV_depth_buffer_float +#define GL_NV_depth_buffer_float 1 +#define GL_DEPTH_COMPONENT32F_NV 0x8DAB +#define GL_DEPTH32F_STENCIL8_NV 0x8DAC +#define GL_FLOAT_32_UNSIGNED_INT_24_8_REV_NV 0x8DAD +#define GL_DEPTH_BUFFER_FLOAT_MODE_NV 0x8DAF +typedef void (APIENTRYP PFNGLDEPTHRANGEDNVPROC) (GLdouble zNear, GLdouble zFar); +typedef void (APIENTRYP PFNGLCLEARDEPTHDNVPROC) (GLdouble depth); +typedef void (APIENTRYP PFNGLDEPTHBOUNDSDNVPROC) (GLdouble zmin, GLdouble zmax); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDepthRangedNV (GLdouble zNear, GLdouble zFar); +GLAPI void APIENTRY glClearDepthdNV (GLdouble depth); +GLAPI void APIENTRY glDepthBoundsdNV (GLdouble zmin, GLdouble zmax); +#endif +#endif /* GL_NV_depth_buffer_float */ + +#ifndef GL_NV_depth_clamp +#define GL_NV_depth_clamp 1 +#define GL_DEPTH_CLAMP_NV 0x864F +#endif /* GL_NV_depth_clamp */ + +#ifndef GL_NV_draw_texture +#define GL_NV_draw_texture 1 +typedef void (APIENTRYP PFNGLDRAWTEXTURENVPROC) (GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawTextureNV (GLuint texture, GLuint sampler, GLfloat x0, GLfloat y0, GLfloat x1, GLfloat y1, GLfloat z, GLfloat s0, GLfloat t0, GLfloat s1, GLfloat t1); +#endif +#endif /* GL_NV_draw_texture */ + +#ifndef GL_NV_evaluators +#define GL_NV_evaluators 1 +#define GL_EVAL_2D_NV 0x86C0 +#define GL_EVAL_TRIANGULAR_2D_NV 0x86C1 +#define GL_MAP_TESSELLATION_NV 0x86C2 +#define GL_MAP_ATTRIB_U_ORDER_NV 0x86C3 +#define GL_MAP_ATTRIB_V_ORDER_NV 0x86C4 +#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5 +#define GL_EVAL_VERTEX_ATTRIB0_NV 0x86C6 +#define GL_EVAL_VERTEX_ATTRIB1_NV 0x86C7 +#define GL_EVAL_VERTEX_ATTRIB2_NV 0x86C8 +#define GL_EVAL_VERTEX_ATTRIB3_NV 0x86C9 +#define GL_EVAL_VERTEX_ATTRIB4_NV 0x86CA +#define GL_EVAL_VERTEX_ATTRIB5_NV 0x86CB +#define GL_EVAL_VERTEX_ATTRIB6_NV 0x86CC +#define GL_EVAL_VERTEX_ATTRIB7_NV 0x86CD +#define GL_EVAL_VERTEX_ATTRIB8_NV 0x86CE +#define GL_EVAL_VERTEX_ATTRIB9_NV 0x86CF +#define GL_EVAL_VERTEX_ATTRIB10_NV 0x86D0 +#define GL_EVAL_VERTEX_ATTRIB11_NV 0x86D1 +#define GL_EVAL_VERTEX_ATTRIB12_NV 0x86D2 +#define GL_EVAL_VERTEX_ATTRIB13_NV 0x86D3 +#define GL_EVAL_VERTEX_ATTRIB14_NV 0x86D4 +#define GL_EVAL_VERTEX_ATTRIB15_NV 0x86D5 +#define GL_MAX_MAP_TESSELLATION_NV 0x86D6 +#define GL_MAX_RATIONAL_EVAL_ORDER_NV 0x86D7 +typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const void *points); +typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, void *points); +typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const void *points); +GLAPI void APIENTRY glMapParameterivNV (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glMapParameterfvNV (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, void *points); +GLAPI void APIENTRY glGetMapParameterivNV (GLenum target, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMapParameterfvNV (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum target, GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glEvalMapsNV (GLenum target, GLenum mode); +#endif +#endif /* GL_NV_evaluators */ + +#ifndef GL_NV_explicit_multisample +#define GL_NV_explicit_multisample 1 +#define GL_SAMPLE_POSITION_NV 0x8E50 +#define GL_SAMPLE_MASK_NV 0x8E51 +#define GL_SAMPLE_MASK_VALUE_NV 0x8E52 +#define GL_TEXTURE_BINDING_RENDERBUFFER_NV 0x8E53 +#define GL_TEXTURE_RENDERBUFFER_DATA_STORE_BINDING_NV 0x8E54 +#define GL_TEXTURE_RENDERBUFFER_NV 0x8E55 +#define GL_SAMPLER_RENDERBUFFER_NV 0x8E56 +#define GL_INT_SAMPLER_RENDERBUFFER_NV 0x8E57 +#define GL_UNSIGNED_INT_SAMPLER_RENDERBUFFER_NV 0x8E58 +#define GL_MAX_SAMPLE_MASK_WORDS_NV 0x8E59 +typedef void (APIENTRYP PFNGLGETMULTISAMPLEFVNVPROC) (GLenum pname, GLuint index, GLfloat *val); +typedef void (APIENTRYP PFNGLSAMPLEMASKINDEXEDNVPROC) (GLuint index, GLbitfield mask); +typedef void (APIENTRYP PFNGLTEXRENDERBUFFERNVPROC) (GLenum target, GLuint renderbuffer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetMultisamplefvNV (GLenum pname, GLuint index, GLfloat *val); +GLAPI void APIENTRY glSampleMaskIndexedNV (GLuint index, GLbitfield mask); +GLAPI void APIENTRY glTexRenderbufferNV (GLenum target, GLuint renderbuffer); +#endif +#endif /* GL_NV_explicit_multisample */ + +#ifndef GL_NV_fence +#define GL_NV_fence 1 +#define GL_ALL_COMPLETED_NV 0x84F2 +#define GL_FENCE_STATUS_NV 0x84F3 +#define GL_FENCE_CONDITION_NV 0x84F4 +typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences); +typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences); +typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence); +typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence); +typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeleteFencesNV (GLsizei n, const GLuint *fences); +GLAPI void APIENTRY glGenFencesNV (GLsizei n, GLuint *fences); +GLAPI GLboolean APIENTRY glIsFenceNV (GLuint fence); +GLAPI GLboolean APIENTRY glTestFenceNV (GLuint fence); +GLAPI void APIENTRY glGetFenceivNV (GLuint fence, GLenum pname, GLint *params); +GLAPI void APIENTRY glFinishFenceNV (GLuint fence); +GLAPI void APIENTRY glSetFenceNV (GLuint fence, GLenum condition); +#endif +#endif /* GL_NV_fence */ + +#ifndef GL_NV_fill_rectangle +#define GL_NV_fill_rectangle 1 +#define GL_FILL_RECTANGLE_NV 0x933C +#endif /* GL_NV_fill_rectangle */ + +#ifndef GL_NV_float_buffer +#define GL_NV_float_buffer 1 +#define GL_FLOAT_R_NV 0x8880 +#define GL_FLOAT_RG_NV 0x8881 +#define GL_FLOAT_RGB_NV 0x8882 +#define GL_FLOAT_RGBA_NV 0x8883 +#define GL_FLOAT_R16_NV 0x8884 +#define GL_FLOAT_R32_NV 0x8885 +#define GL_FLOAT_RG16_NV 0x8886 +#define GL_FLOAT_RG32_NV 0x8887 +#define GL_FLOAT_RGB16_NV 0x8888 +#define GL_FLOAT_RGB32_NV 0x8889 +#define GL_FLOAT_RGBA16_NV 0x888A +#define GL_FLOAT_RGBA32_NV 0x888B +#define GL_TEXTURE_FLOAT_COMPONENTS_NV 0x888C +#define GL_FLOAT_CLEAR_COLOR_VALUE_NV 0x888D +#define GL_FLOAT_RGBA_MODE_NV 0x888E +#endif /* GL_NV_float_buffer */ + +#ifndef GL_NV_fog_distance +#define GL_NV_fog_distance 1 +#define GL_FOG_DISTANCE_MODE_NV 0x855A +#define GL_EYE_RADIAL_NV 0x855B +#define GL_EYE_PLANE_ABSOLUTE_NV 0x855C +#endif /* GL_NV_fog_distance */ + +#ifndef GL_NV_fragment_coverage_to_color +#define GL_NV_fragment_coverage_to_color 1 +#define GL_FRAGMENT_COVERAGE_TO_COLOR_NV 0x92DD +#define GL_FRAGMENT_COVERAGE_COLOR_NV 0x92DE +typedef void (APIENTRYP PFNGLFRAGMENTCOVERAGECOLORNVPROC) (GLuint color); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFragmentCoverageColorNV (GLuint color); +#endif +#endif /* GL_NV_fragment_coverage_to_color */ + +#ifndef GL_NV_fragment_program +#define GL_NV_fragment_program 1 +#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868 +#define GL_FRAGMENT_PROGRAM_NV 0x8870 +#define GL_MAX_TEXTURE_COORDS_NV 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872 +#define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873 +#define GL_PROGRAM_ERROR_STRING_NV 0x8874 +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v); +typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v); +GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v); +GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params); +GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params); +#endif +#endif /* GL_NV_fragment_program */ + +#ifndef GL_NV_fragment_program2 +#define GL_NV_fragment_program2 1 +#define GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV 0x88F4 +#define GL_MAX_PROGRAM_CALL_DEPTH_NV 0x88F5 +#define GL_MAX_PROGRAM_IF_DEPTH_NV 0x88F6 +#define GL_MAX_PROGRAM_LOOP_DEPTH_NV 0x88F7 +#define GL_MAX_PROGRAM_LOOP_COUNT_NV 0x88F8 +#endif /* GL_NV_fragment_program2 */ + +#ifndef GL_NV_fragment_program4 +#define GL_NV_fragment_program4 1 +#endif /* GL_NV_fragment_program4 */ + +#ifndef GL_NV_fragment_program_option +#define GL_NV_fragment_program_option 1 +#endif /* GL_NV_fragment_program_option */ + +#ifndef GL_NV_fragment_shader_interlock +#define GL_NV_fragment_shader_interlock 1 +#endif /* GL_NV_fragment_shader_interlock */ + +#ifndef GL_NV_framebuffer_mixed_samples +#define GL_NV_framebuffer_mixed_samples 1 +#define GL_COVERAGE_MODULATION_TABLE_NV 0x9331 +#define GL_COLOR_SAMPLES_NV 0x8E20 +#define GL_DEPTH_SAMPLES_NV 0x932D +#define GL_STENCIL_SAMPLES_NV 0x932E +#define GL_MIXED_DEPTH_SAMPLES_SUPPORTED_NV 0x932F +#define GL_MIXED_STENCIL_SAMPLES_SUPPORTED_NV 0x9330 +#define GL_COVERAGE_MODULATION_NV 0x9332 +#define GL_COVERAGE_MODULATION_TABLE_SIZE_NV 0x9333 +typedef void (APIENTRYP PFNGLCOVERAGEMODULATIONTABLENVPROC) (GLsizei n, const GLfloat *v); +typedef void (APIENTRYP PFNGLGETCOVERAGEMODULATIONTABLENVPROC) (GLsizei bufsize, GLfloat *v); +typedef void (APIENTRYP PFNGLCOVERAGEMODULATIONNVPROC) (GLenum components); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCoverageModulationTableNV (GLsizei n, const GLfloat *v); +GLAPI void APIENTRY glGetCoverageModulationTableNV (GLsizei bufsize, GLfloat *v); +GLAPI void APIENTRY glCoverageModulationNV (GLenum components); +#endif +#endif /* GL_NV_framebuffer_mixed_samples */ + +#ifndef GL_NV_framebuffer_multisample_coverage +#define GL_NV_framebuffer_multisample_coverage 1 +#define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB +#define GL_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E10 +#define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E11 +#define GL_MULTISAMPLE_COVERAGE_MODES_NV 0x8E12 +typedef void (APIENTRYP PFNGLRENDERBUFFERSTORAGEMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glRenderbufferStorageMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLenum internalformat, GLsizei width, GLsizei height); +#endif +#endif /* GL_NV_framebuffer_multisample_coverage */ + +#ifndef GL_NV_geometry_program4 +#define GL_NV_geometry_program4 1 +#define GL_GEOMETRY_PROGRAM_NV 0x8C26 +#define GL_MAX_PROGRAM_OUTPUT_VERTICES_NV 0x8C27 +#define GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV 0x8C28 +typedef void (APIENTRYP PFNGLPROGRAMVERTEXLIMITNVPROC) (GLenum target, GLint limit); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level); +typedef void (APIENTRYP PFNGLFRAMEBUFFERTEXTUREFACEEXTPROC) (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramVertexLimitNV (GLenum target, GLint limit); +GLAPI void APIENTRY glFramebufferTextureEXT (GLenum target, GLenum attachment, GLuint texture, GLint level); +GLAPI void APIENTRY glFramebufferTextureFaceEXT (GLenum target, GLenum attachment, GLuint texture, GLint level, GLenum face); +#endif +#endif /* GL_NV_geometry_program4 */ + +#ifndef GL_NV_geometry_shader4 +#define GL_NV_geometry_shader4 1 +#endif /* GL_NV_geometry_shader4 */ + +#ifndef GL_NV_geometry_shader_passthrough +#define GL_NV_geometry_shader_passthrough 1 +#endif /* GL_NV_geometry_shader_passthrough */ + +#ifndef GL_NV_gpu_program4 +#define GL_NV_gpu_program4 1 +#define GL_MIN_PROGRAM_TEXEL_OFFSET_NV 0x8904 +#define GL_MAX_PROGRAM_TEXEL_OFFSET_NV 0x8905 +#define GL_PROGRAM_ATTRIB_COMPONENTS_NV 0x8906 +#define GL_PROGRAM_RESULT_COMPONENTS_NV 0x8907 +#define GL_MAX_PROGRAM_ATTRIB_COMPONENTS_NV 0x8908 +#define GL_MAX_PROGRAM_RESULT_COMPONENTS_NV 0x8909 +#define GL_MAX_PROGRAM_GENERIC_ATTRIBS_NV 0x8DA5 +#define GL_MAX_PROGRAM_GENERIC_RESULTS_NV 0x8DA6 +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4INVPROC) (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4IVNVPROC) (GLenum target, GLuint index, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4IVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UINVPROC) (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERI4UIVNVPROC) (GLenum target, GLuint index, const GLuint *params); +typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETERSI4UIVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIIVNVPROC) (GLenum target, GLuint index, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERIUIVNVPROC) (GLenum target, GLuint index, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramLocalParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glProgramLocalParameterI4ivNV (GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glProgramLocalParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramLocalParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glProgramLocalParameterI4uivNV (GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glProgramLocalParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glProgramEnvParameterI4iNV (GLenum target, GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glProgramEnvParameterI4ivNV (GLenum target, GLuint index, const GLint *params); +GLAPI void APIENTRY glProgramEnvParametersI4ivNV (GLenum target, GLuint index, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramEnvParameterI4uiNV (GLenum target, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glProgramEnvParameterI4uivNV (GLenum target, GLuint index, const GLuint *params); +GLAPI void APIENTRY glProgramEnvParametersI4uivNV (GLenum target, GLuint index, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetProgramLocalParameterIivNV (GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetProgramLocalParameterIuivNV (GLenum target, GLuint index, GLuint *params); +GLAPI void APIENTRY glGetProgramEnvParameterIivNV (GLenum target, GLuint index, GLint *params); +GLAPI void APIENTRY glGetProgramEnvParameterIuivNV (GLenum target, GLuint index, GLuint *params); +#endif +#endif /* GL_NV_gpu_program4 */ + +#ifndef GL_NV_gpu_program5 +#define GL_NV_gpu_program5 1 +#define GL_MAX_GEOMETRY_PROGRAM_INVOCATIONS_NV 0x8E5A +#define GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5B +#define GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_NV 0x8E5C +#define GL_FRAGMENT_PROGRAM_INTERPOLATION_OFFSET_BITS_NV 0x8E5D +#define GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5E +#define GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_NV 0x8E5F +#define GL_MAX_PROGRAM_SUBROUTINE_PARAMETERS_NV 0x8F44 +#define GL_MAX_PROGRAM_SUBROUTINE_NUM_NV 0x8F45 +typedef void (APIENTRYP PFNGLPROGRAMSUBROUTINEPARAMETERSUIVNVPROC) (GLenum target, GLsizei count, const GLuint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSUBROUTINEPARAMETERUIVNVPROC) (GLenum target, GLuint index, GLuint *param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramSubroutineParametersuivNV (GLenum target, GLsizei count, const GLuint *params); +GLAPI void APIENTRY glGetProgramSubroutineParameteruivNV (GLenum target, GLuint index, GLuint *param); +#endif +#endif /* GL_NV_gpu_program5 */ + +#ifndef GL_NV_gpu_program5_mem_extended +#define GL_NV_gpu_program5_mem_extended 1 +#endif /* GL_NV_gpu_program5_mem_extended */ + +#ifndef GL_NV_gpu_shader5 +#define GL_NV_gpu_shader5 1 +#endif /* GL_NV_gpu_shader5 */ + +#ifndef GL_NV_half_float +#define GL_NV_half_float 1 +typedef unsigned short GLhalfNV; +#define GL_HALF_FLOAT_NV 0x140B +typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y); +typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z); +typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz); +typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha); +typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s); +typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t); +typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r); +typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s); +typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t); +typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r); +typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog); +typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight); +typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertex2hNV (GLhalfNV x, GLhalfNV y); +GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertex3hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z); +GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertex4hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glNormal3hNV (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz); +GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glColor4hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha); +GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV s); +GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV s, GLhalfNV t); +GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r); +GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum target, GLhalfNV s); +GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum target, GLhalfNV s, GLhalfNV t); +GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r); +GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q); +GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum target, const GLhalfNV *v); +GLAPI void APIENTRY glFogCoordhNV (GLhalfNV fog); +GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *fog); +GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue); +GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *v); +GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV weight); +GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *weight); +GLAPI void APIENTRY glVertexAttrib1hNV (GLuint index, GLhalfNV x); +GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib2hNV (GLuint index, GLhalfNV x, GLhalfNV y); +GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib3hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z); +GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttrib4hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w); +GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint index, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint index, GLsizei n, const GLhalfNV *v); +#endif +#endif /* GL_NV_half_float */ + +#ifndef GL_NV_internalformat_sample_query +#define GL_NV_internalformat_sample_query 1 +#define GL_MULTISAMPLES_NV 0x9371 +#define GL_SUPERSAMPLE_SCALE_X_NV 0x9372 +#define GL_SUPERSAMPLE_SCALE_Y_NV 0x9373 +#define GL_CONFORMANT_NV 0x9374 +typedef void (APIENTRYP PFNGLGETINTERNALFORMATSAMPLEIVNVPROC) (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetInternalformatSampleivNV (GLenum target, GLenum internalformat, GLsizei samples, GLenum pname, GLsizei bufSize, GLint *params); +#endif +#endif /* GL_NV_internalformat_sample_query */ + +#ifndef GL_NV_light_max_exponent +#define GL_NV_light_max_exponent 1 +#define GL_MAX_SHININESS_NV 0x8504 +#define GL_MAX_SPOT_EXPONENT_NV 0x8505 +#endif /* GL_NV_light_max_exponent */ + +#ifndef GL_NV_multisample_coverage +#define GL_NV_multisample_coverage 1 +#endif /* GL_NV_multisample_coverage */ + +#ifndef GL_NV_multisample_filter_hint +#define GL_NV_multisample_filter_hint 1 +#define GL_MULTISAMPLE_FILTER_HINT_NV 0x8534 +#endif /* GL_NV_multisample_filter_hint */ + +#ifndef GL_NV_occlusion_query +#define GL_NV_occlusion_query 1 +#define GL_PIXEL_COUNTER_BITS_NV 0x8864 +#define GL_CURRENT_OCCLUSION_QUERY_ID_NV 0x8865 +#define GL_PIXEL_COUNT_NV 0x8866 +#define GL_PIXEL_COUNT_AVAILABLE_NV 0x8867 +typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids); +typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void); +typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei n, GLuint *ids); +GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei n, const GLuint *ids); +GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint id); +GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint id); +GLAPI void APIENTRY glEndOcclusionQueryNV (void); +GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint id, GLenum pname, GLuint *params); +#endif +#endif /* GL_NV_occlusion_query */ + +#ifndef GL_NV_packed_depth_stencil +#define GL_NV_packed_depth_stencil 1 +#define GL_DEPTH_STENCIL_NV 0x84F9 +#define GL_UNSIGNED_INT_24_8_NV 0x84FA +#endif /* GL_NV_packed_depth_stencil */ + +#ifndef GL_NV_parameter_buffer_object +#define GL_NV_parameter_buffer_object 1 +#define GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV 0x8DA0 +#define GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV 0x8DA1 +#define GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV 0x8DA2 +#define GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV 0x8DA3 +#define GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV 0x8DA4 +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSFVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLfloat *params); +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIIVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLint *params); +typedef void (APIENTRYP PFNGLPROGRAMBUFFERPARAMETERSIUIVNVPROC) (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glProgramBufferParametersfvNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLfloat *params); +GLAPI void APIENTRY glProgramBufferParametersIivNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLint *params); +GLAPI void APIENTRY glProgramBufferParametersIuivNV (GLenum target, GLuint bindingIndex, GLuint wordIndex, GLsizei count, const GLuint *params); +#endif +#endif /* GL_NV_parameter_buffer_object */ + +#ifndef GL_NV_parameter_buffer_object2 +#define GL_NV_parameter_buffer_object2 1 +#endif /* GL_NV_parameter_buffer_object2 */ + +#ifndef GL_NV_path_rendering +#define GL_NV_path_rendering 1 +#define GL_PATH_FORMAT_SVG_NV 0x9070 +#define GL_PATH_FORMAT_PS_NV 0x9071 +#define GL_STANDARD_FONT_NAME_NV 0x9072 +#define GL_SYSTEM_FONT_NAME_NV 0x9073 +#define GL_FILE_NAME_NV 0x9074 +#define GL_PATH_STROKE_WIDTH_NV 0x9075 +#define GL_PATH_END_CAPS_NV 0x9076 +#define GL_PATH_INITIAL_END_CAP_NV 0x9077 +#define GL_PATH_TERMINAL_END_CAP_NV 0x9078 +#define GL_PATH_JOIN_STYLE_NV 0x9079 +#define GL_PATH_MITER_LIMIT_NV 0x907A +#define GL_PATH_DASH_CAPS_NV 0x907B +#define GL_PATH_INITIAL_DASH_CAP_NV 0x907C +#define GL_PATH_TERMINAL_DASH_CAP_NV 0x907D +#define GL_PATH_DASH_OFFSET_NV 0x907E +#define GL_PATH_CLIENT_LENGTH_NV 0x907F +#define GL_PATH_FILL_MODE_NV 0x9080 +#define GL_PATH_FILL_MASK_NV 0x9081 +#define GL_PATH_FILL_COVER_MODE_NV 0x9082 +#define GL_PATH_STROKE_COVER_MODE_NV 0x9083 +#define GL_PATH_STROKE_MASK_NV 0x9084 +#define GL_COUNT_UP_NV 0x9088 +#define GL_COUNT_DOWN_NV 0x9089 +#define GL_PATH_OBJECT_BOUNDING_BOX_NV 0x908A +#define GL_CONVEX_HULL_NV 0x908B +#define GL_BOUNDING_BOX_NV 0x908D +#define GL_TRANSLATE_X_NV 0x908E +#define GL_TRANSLATE_Y_NV 0x908F +#define GL_TRANSLATE_2D_NV 0x9090 +#define GL_TRANSLATE_3D_NV 0x9091 +#define GL_AFFINE_2D_NV 0x9092 +#define GL_AFFINE_3D_NV 0x9094 +#define GL_TRANSPOSE_AFFINE_2D_NV 0x9096 +#define GL_TRANSPOSE_AFFINE_3D_NV 0x9098 +#define GL_UTF8_NV 0x909A +#define GL_UTF16_NV 0x909B +#define GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV 0x909C +#define GL_PATH_COMMAND_COUNT_NV 0x909D +#define GL_PATH_COORD_COUNT_NV 0x909E +#define GL_PATH_DASH_ARRAY_COUNT_NV 0x909F +#define GL_PATH_COMPUTED_LENGTH_NV 0x90A0 +#define GL_PATH_FILL_BOUNDING_BOX_NV 0x90A1 +#define GL_PATH_STROKE_BOUNDING_BOX_NV 0x90A2 +#define GL_SQUARE_NV 0x90A3 +#define GL_ROUND_NV 0x90A4 +#define GL_TRIANGULAR_NV 0x90A5 +#define GL_BEVEL_NV 0x90A6 +#define GL_MITER_REVERT_NV 0x90A7 +#define GL_MITER_TRUNCATE_NV 0x90A8 +#define GL_SKIP_MISSING_GLYPH_NV 0x90A9 +#define GL_USE_MISSING_GLYPH_NV 0x90AA +#define GL_PATH_ERROR_POSITION_NV 0x90AB +#define GL_ACCUM_ADJACENT_PAIRS_NV 0x90AD +#define GL_ADJACENT_PAIRS_NV 0x90AE +#define GL_FIRST_TO_REST_NV 0x90AF +#define GL_PATH_GEN_MODE_NV 0x90B0 +#define GL_PATH_GEN_COEFF_NV 0x90B1 +#define GL_PATH_GEN_COMPONENTS_NV 0x90B3 +#define GL_PATH_STENCIL_FUNC_NV 0x90B7 +#define GL_PATH_STENCIL_REF_NV 0x90B8 +#define GL_PATH_STENCIL_VALUE_MASK_NV 0x90B9 +#define GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV 0x90BD +#define GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV 0x90BE +#define GL_PATH_COVER_DEPTH_FUNC_NV 0x90BF +#define GL_PATH_DASH_OFFSET_RESET_NV 0x90B4 +#define GL_MOVE_TO_RESETS_NV 0x90B5 +#define GL_MOVE_TO_CONTINUES_NV 0x90B6 +#define GL_CLOSE_PATH_NV 0x00 +#define GL_MOVE_TO_NV 0x02 +#define GL_RELATIVE_MOVE_TO_NV 0x03 +#define GL_LINE_TO_NV 0x04 +#define GL_RELATIVE_LINE_TO_NV 0x05 +#define GL_HORIZONTAL_LINE_TO_NV 0x06 +#define GL_RELATIVE_HORIZONTAL_LINE_TO_NV 0x07 +#define GL_VERTICAL_LINE_TO_NV 0x08 +#define GL_RELATIVE_VERTICAL_LINE_TO_NV 0x09 +#define GL_QUADRATIC_CURVE_TO_NV 0x0A +#define GL_RELATIVE_QUADRATIC_CURVE_TO_NV 0x0B +#define GL_CUBIC_CURVE_TO_NV 0x0C +#define GL_RELATIVE_CUBIC_CURVE_TO_NV 0x0D +#define GL_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0E +#define GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV 0x0F +#define GL_SMOOTH_CUBIC_CURVE_TO_NV 0x10 +#define GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV 0x11 +#define GL_SMALL_CCW_ARC_TO_NV 0x12 +#define GL_RELATIVE_SMALL_CCW_ARC_TO_NV 0x13 +#define GL_SMALL_CW_ARC_TO_NV 0x14 +#define GL_RELATIVE_SMALL_CW_ARC_TO_NV 0x15 +#define GL_LARGE_CCW_ARC_TO_NV 0x16 +#define GL_RELATIVE_LARGE_CCW_ARC_TO_NV 0x17 +#define GL_LARGE_CW_ARC_TO_NV 0x18 +#define GL_RELATIVE_LARGE_CW_ARC_TO_NV 0x19 +#define GL_RESTART_PATH_NV 0xF0 +#define GL_DUP_FIRST_CUBIC_CURVE_TO_NV 0xF2 +#define GL_DUP_LAST_CUBIC_CURVE_TO_NV 0xF4 +#define GL_RECT_NV 0xF6 +#define GL_CIRCULAR_CCW_ARC_TO_NV 0xF8 +#define GL_CIRCULAR_CW_ARC_TO_NV 0xFA +#define GL_CIRCULAR_TANGENT_ARC_TO_NV 0xFC +#define GL_ARC_TO_NV 0xFE +#define GL_RELATIVE_ARC_TO_NV 0xFF +#define GL_BOLD_BIT_NV 0x01 +#define GL_ITALIC_BIT_NV 0x02 +#define GL_GLYPH_WIDTH_BIT_NV 0x01 +#define GL_GLYPH_HEIGHT_BIT_NV 0x02 +#define GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV 0x04 +#define GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV 0x08 +#define GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV 0x10 +#define GL_GLYPH_VERTICAL_BEARING_X_BIT_NV 0x20 +#define GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV 0x40 +#define GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV 0x80 +#define GL_GLYPH_HAS_KERNING_BIT_NV 0x100 +#define GL_FONT_X_MIN_BOUNDS_BIT_NV 0x00010000 +#define GL_FONT_Y_MIN_BOUNDS_BIT_NV 0x00020000 +#define GL_FONT_X_MAX_BOUNDS_BIT_NV 0x00040000 +#define GL_FONT_Y_MAX_BOUNDS_BIT_NV 0x00080000 +#define GL_FONT_UNITS_PER_EM_BIT_NV 0x00100000 +#define GL_FONT_ASCENDER_BIT_NV 0x00200000 +#define GL_FONT_DESCENDER_BIT_NV 0x00400000 +#define GL_FONT_HEIGHT_BIT_NV 0x00800000 +#define GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV 0x01000000 +#define GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV 0x02000000 +#define GL_FONT_UNDERLINE_POSITION_BIT_NV 0x04000000 +#define GL_FONT_UNDERLINE_THICKNESS_BIT_NV 0x08000000 +#define GL_FONT_HAS_KERNING_BIT_NV 0x10000000 +#define GL_ROUNDED_RECT_NV 0xE8 +#define GL_RELATIVE_ROUNDED_RECT_NV 0xE9 +#define GL_ROUNDED_RECT2_NV 0xEA +#define GL_RELATIVE_ROUNDED_RECT2_NV 0xEB +#define GL_ROUNDED_RECT4_NV 0xEC +#define GL_RELATIVE_ROUNDED_RECT4_NV 0xED +#define GL_ROUNDED_RECT8_NV 0xEE +#define GL_RELATIVE_ROUNDED_RECT8_NV 0xEF +#define GL_RELATIVE_RECT_NV 0xF7 +#define GL_FONT_GLYPHS_AVAILABLE_NV 0x9368 +#define GL_FONT_TARGET_UNAVAILABLE_NV 0x9369 +#define GL_FONT_UNAVAILABLE_NV 0x936A +#define GL_FONT_UNINTELLIGIBLE_NV 0x936B +#define GL_CONIC_CURVE_TO_NV 0x1A +#define GL_RELATIVE_CONIC_CURVE_TO_NV 0x1B +#define GL_FONT_NUM_GLYPH_INDICES_BIT_NV 0x20000000 +#define GL_STANDARD_FONT_FORMAT_NV 0x936C +#define GL_2_BYTES_NV 0x1407 +#define GL_3_BYTES_NV 0x1408 +#define GL_4_BYTES_NV 0x1409 +#define GL_EYE_LINEAR_NV 0x2400 +#define GL_OBJECT_LINEAR_NV 0x2401 +#define GL_CONSTANT_NV 0x8576 +#define GL_PATH_FOG_GEN_MODE_NV 0x90AC +#define GL_PRIMARY_COLOR_NV 0x852C +#define GL_SECONDARY_COLOR_NV 0x852D +#define GL_PATH_GEN_COLOR_FORMAT_NV 0x90B2 +#define GL_PATH_PROJECTION_NV 0x1701 +#define GL_PATH_MODELVIEW_NV 0x1700 +#define GL_PATH_MODELVIEW_STACK_DEPTH_NV 0x0BA3 +#define GL_PATH_MODELVIEW_MATRIX_NV 0x0BA6 +#define GL_PATH_MAX_MODELVIEW_STACK_DEPTH_NV 0x0D36 +#define GL_PATH_TRANSPOSE_MODELVIEW_MATRIX_NV 0x84E3 +#define GL_PATH_PROJECTION_STACK_DEPTH_NV 0x0BA4 +#define GL_PATH_PROJECTION_MATRIX_NV 0x0BA7 +#define GL_PATH_MAX_PROJECTION_STACK_DEPTH_NV 0x0D38 +#define GL_PATH_TRANSPOSE_PROJECTION_MATRIX_NV 0x84E4 +#define GL_FRAGMENT_INPUT_NV 0x936D +typedef GLuint (APIENTRYP PFNGLGENPATHSNVPROC) (GLsizei range); +typedef void (APIENTRYP PFNGLDELETEPATHSNVPROC) (GLuint path, GLsizei range); +typedef GLboolean (APIENTRYP PFNGLISPATHNVPROC) (GLuint path); +typedef void (APIENTRYP PFNGLPATHCOMMANDSNVPROC) (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHCOORDSNVPROC) (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSUBCOMMANDSNVPROC) (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSUBCOORDSNVPROC) (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); +typedef void (APIENTRYP PFNGLPATHSTRINGNVPROC) (GLuint path, GLenum format, GLsizei length, const void *pathString); +typedef void (APIENTRYP PFNGLPATHGLYPHSNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLPATHGLYPHRANGENVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLWEIGHTPATHSNVPROC) (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); +typedef void (APIENTRYP PFNGLCOPYPATHNVPROC) (GLuint resultPath, GLuint srcPath); +typedef void (APIENTRYP PFNGLINTERPOLATEPATHSNVPROC) (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); +typedef void (APIENTRYP PFNGLTRANSFORMPATHNVPROC) (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, const GLint *value); +typedef void (APIENTRYP PFNGLPATHPARAMETERINVPROC) (GLuint path, GLenum pname, GLint value); +typedef void (APIENTRYP PFNGLPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, const GLfloat *value); +typedef void (APIENTRYP PFNGLPATHPARAMETERFNVPROC) (GLuint path, GLenum pname, GLfloat value); +typedef void (APIENTRYP PFNGLPATHDASHARRAYNVPROC) (GLuint path, GLsizei dashCount, const GLfloat *dashArray); +typedef void (APIENTRYP PFNGLPATHSTENCILFUNCNVPROC) (GLenum func, GLint ref, GLuint mask); +typedef void (APIENTRYP PFNGLPATHSTENCILDEPTHOFFSETNVPROC) (GLfloat factor, GLfloat units); +typedef void (APIENTRYP PFNGLSTENCILFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask); +typedef void (APIENTRYP PFNGLSTENCILFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLSTENCILSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLPATHCOVERDEPTHFUNCNVPROC) (GLenum func); +typedef void (APIENTRYP PFNGLCOVERFILLPATHNVPROC) (GLuint path, GLenum coverMode); +typedef void (APIENTRYP PFNGLCOVERSTROKEPATHNVPROC) (GLuint path, GLenum coverMode); +typedef void (APIENTRYP PFNGLCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLGETPATHPARAMETERIVNVPROC) (GLuint path, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHPARAMETERFVNVPROC) (GLuint path, GLenum pname, GLfloat *value); +typedef void (APIENTRYP PFNGLGETPATHCOMMANDSNVPROC) (GLuint path, GLubyte *commands); +typedef void (APIENTRYP PFNGLGETPATHCOORDSNVPROC) (GLuint path, GLfloat *coords); +typedef void (APIENTRYP PFNGLGETPATHDASHARRAYNVPROC) (GLuint path, GLfloat *dashArray); +typedef void (APIENTRYP PFNGLGETPATHMETRICSNVPROC) (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); +typedef void (APIENTRYP PFNGLGETPATHMETRICRANGENVPROC) (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); +typedef void (APIENTRYP PFNGLGETPATHSPACINGNVPROC) (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); +typedef GLboolean (APIENTRYP PFNGLISPOINTINFILLPATHNVPROC) (GLuint path, GLuint mask, GLfloat x, GLfloat y); +typedef GLboolean (APIENTRYP PFNGLISPOINTINSTROKEPATHNVPROC) (GLuint path, GLfloat x, GLfloat y); +typedef GLfloat (APIENTRYP PFNGLGETPATHLENGTHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments); +typedef GLboolean (APIENTRYP PFNGLPOINTALONGPATHNVPROC) (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); +typedef void (APIENTRYP PFNGLMATRIXLOAD3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOAD3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXLOADTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULT3X2FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULT3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLMATRIXMULTTRANSPOSE3X3FNVPROC) (GLenum matrixMode, const GLfloat *m); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHNVPROC) (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHNVPROC) (GLuint path, GLint reference, GLuint mask, GLenum coverMode); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERFILLPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef void (APIENTRYP PFNGLSTENCILTHENCOVERSTROKEPATHINSTANCEDNVPROC) (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +typedef GLenum (APIENTRYP PFNGLPATHGLYPHINDEXRANGENVPROC) (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]); +typedef GLenum (APIENTRYP PFNGLPATHGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef GLenum (APIENTRYP PFNGLPATHMEMORYGLYPHINDEXARRAYNVPROC) (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +typedef void (APIENTRYP PFNGLPROGRAMPATHFRAGMENTINPUTGENNVPROC) (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLGETPROGRAMRESOURCEFVNVPROC) (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params); +typedef void (APIENTRYP PFNGLPATHCOLORGENNVPROC) (GLenum color, GLenum genMode, GLenum colorFormat, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLPATHTEXGENNVPROC) (GLenum texCoordSet, GLenum genMode, GLint components, const GLfloat *coeffs); +typedef void (APIENTRYP PFNGLPATHFOGGENNVPROC) (GLenum genMode); +typedef void (APIENTRYP PFNGLGETPATHCOLORGENIVNVPROC) (GLenum color, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHCOLORGENFVNVPROC) (GLenum color, GLenum pname, GLfloat *value); +typedef void (APIENTRYP PFNGLGETPATHTEXGENIVNVPROC) (GLenum texCoordSet, GLenum pname, GLint *value); +typedef void (APIENTRYP PFNGLGETPATHTEXGENFVNVPROC) (GLenum texCoordSet, GLenum pname, GLfloat *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLuint APIENTRY glGenPathsNV (GLsizei range); +GLAPI void APIENTRY glDeletePathsNV (GLuint path, GLsizei range); +GLAPI GLboolean APIENTRY glIsPathNV (GLuint path); +GLAPI void APIENTRY glPathCommandsNV (GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathCoordsNV (GLuint path, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathSubCommandsNV (GLuint path, GLsizei commandStart, GLsizei commandsToDelete, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathSubCoordsNV (GLuint path, GLsizei coordStart, GLsizei numCoords, GLenum coordType, const void *coords); +GLAPI void APIENTRY glPathStringNV (GLuint path, GLenum format, GLsizei length, const void *pathString); +GLAPI void APIENTRY glPathGlyphsNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLsizei numGlyphs, GLenum type, const void *charcodes, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glPathGlyphRangeNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyph, GLsizei numGlyphs, GLenum handleMissingGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glWeightPathsNV (GLuint resultPath, GLsizei numPaths, const GLuint *paths, const GLfloat *weights); +GLAPI void APIENTRY glCopyPathNV (GLuint resultPath, GLuint srcPath); +GLAPI void APIENTRY glInterpolatePathsNV (GLuint resultPath, GLuint pathA, GLuint pathB, GLfloat weight); +GLAPI void APIENTRY glTransformPathNV (GLuint resultPath, GLuint srcPath, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glPathParameterivNV (GLuint path, GLenum pname, const GLint *value); +GLAPI void APIENTRY glPathParameteriNV (GLuint path, GLenum pname, GLint value); +GLAPI void APIENTRY glPathParameterfvNV (GLuint path, GLenum pname, const GLfloat *value); +GLAPI void APIENTRY glPathParameterfNV (GLuint path, GLenum pname, GLfloat value); +GLAPI void APIENTRY glPathDashArrayNV (GLuint path, GLsizei dashCount, const GLfloat *dashArray); +GLAPI void APIENTRY glPathStencilFuncNV (GLenum func, GLint ref, GLuint mask); +GLAPI void APIENTRY glPathStencilDepthOffsetNV (GLfloat factor, GLfloat units); +GLAPI void APIENTRY glStencilFillPathNV (GLuint path, GLenum fillMode, GLuint mask); +GLAPI void APIENTRY glStencilStrokePathNV (GLuint path, GLint reference, GLuint mask); +GLAPI void APIENTRY glStencilFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glStencilStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glPathCoverDepthFuncNV (GLenum func); +GLAPI void APIENTRY glCoverFillPathNV (GLuint path, GLenum coverMode); +GLAPI void APIENTRY glCoverStrokePathNV (GLuint path, GLenum coverMode); +GLAPI void APIENTRY glCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glGetPathParameterivNV (GLuint path, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathParameterfvNV (GLuint path, GLenum pname, GLfloat *value); +GLAPI void APIENTRY glGetPathCommandsNV (GLuint path, GLubyte *commands); +GLAPI void APIENTRY glGetPathCoordsNV (GLuint path, GLfloat *coords); +GLAPI void APIENTRY glGetPathDashArrayNV (GLuint path, GLfloat *dashArray); +GLAPI void APIENTRY glGetPathMetricsNV (GLbitfield metricQueryMask, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLsizei stride, GLfloat *metrics); +GLAPI void APIENTRY glGetPathMetricRangeNV (GLbitfield metricQueryMask, GLuint firstPathName, GLsizei numPaths, GLsizei stride, GLfloat *metrics); +GLAPI void APIENTRY glGetPathSpacingNV (GLenum pathListMode, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLfloat advanceScale, GLfloat kerningScale, GLenum transformType, GLfloat *returnedSpacing); +GLAPI GLboolean APIENTRY glIsPointInFillPathNV (GLuint path, GLuint mask, GLfloat x, GLfloat y); +GLAPI GLboolean APIENTRY glIsPointInStrokePathNV (GLuint path, GLfloat x, GLfloat y); +GLAPI GLfloat APIENTRY glGetPathLengthNV (GLuint path, GLsizei startSegment, GLsizei numSegments); +GLAPI GLboolean APIENTRY glPointAlongPathNV (GLuint path, GLsizei startSegment, GLsizei numSegments, GLfloat distance, GLfloat *x, GLfloat *y, GLfloat *tangentX, GLfloat *tangentY); +GLAPI void APIENTRY glMatrixLoad3x2fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoad3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixLoadTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMult3x2fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMult3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glMatrixMultTranspose3x3fNV (GLenum matrixMode, const GLfloat *m); +GLAPI void APIENTRY glStencilThenCoverFillPathNV (GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); +GLAPI void APIENTRY glStencilThenCoverStrokePathNV (GLuint path, GLint reference, GLuint mask, GLenum coverMode); +GLAPI void APIENTRY glStencilThenCoverFillPathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI void APIENTRY glStencilThenCoverStrokePathInstancedNV (GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); +GLAPI GLenum APIENTRY glPathGlyphIndexRangeNV (GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint pathParameterTemplate, GLfloat emScale, GLuint baseAndCount[2]); +GLAPI GLenum APIENTRY glPathGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, const void *fontName, GLbitfield fontStyle, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI GLenum APIENTRY glPathMemoryGlyphIndexArrayNV (GLuint firstPathName, GLenum fontTarget, GLsizeiptr fontSize, const void *fontData, GLsizei faceIndex, GLuint firstGlyphIndex, GLsizei numGlyphs, GLuint pathParameterTemplate, GLfloat emScale); +GLAPI void APIENTRY glProgramPathFragmentInputGenNV (GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); +GLAPI void APIENTRY glGetProgramResourcefvNV (GLuint program, GLenum programInterface, GLuint index, GLsizei propCount, const GLenum *props, GLsizei bufSize, GLsizei *length, GLfloat *params); +GLAPI void APIENTRY glPathColorGenNV (GLenum color, GLenum genMode, GLenum colorFormat, const GLfloat *coeffs); +GLAPI void APIENTRY glPathTexGenNV (GLenum texCoordSet, GLenum genMode, GLint components, const GLfloat *coeffs); +GLAPI void APIENTRY glPathFogGenNV (GLenum genMode); +GLAPI void APIENTRY glGetPathColorGenivNV (GLenum color, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathColorGenfvNV (GLenum color, GLenum pname, GLfloat *value); +GLAPI void APIENTRY glGetPathTexGenivNV (GLenum texCoordSet, GLenum pname, GLint *value); +GLAPI void APIENTRY glGetPathTexGenfvNV (GLenum texCoordSet, GLenum pname, GLfloat *value); +#endif +#endif /* GL_NV_path_rendering */ + +#ifndef GL_NV_path_rendering_shared_edge +#define GL_NV_path_rendering_shared_edge 1 +#define GL_SHARED_EDGE_NV 0xC0 +#endif /* GL_NV_path_rendering_shared_edge */ + +#ifndef GL_NV_pixel_data_range +#define GL_NV_pixel_data_range 1 +#define GL_WRITE_PIXEL_DATA_RANGE_NV 0x8878 +#define GL_READ_PIXEL_DATA_RANGE_NV 0x8879 +#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A +#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B +#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C +#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D +typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, const void *pointer); +typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelDataRangeNV (GLenum target, GLsizei length, const void *pointer); +GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum target); +#endif +#endif /* GL_NV_pixel_data_range */ + +#ifndef GL_NV_point_sprite +#define GL_NV_point_sprite 1 +#define GL_POINT_SPRITE_NV 0x8861 +#define GL_COORD_REPLACE_NV 0x8862 +#define GL_POINT_SPRITE_R_MODE_NV 0x8863 +typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameteriNV (GLenum pname, GLint param); +GLAPI void APIENTRY glPointParameterivNV (GLenum pname, const GLint *params); +#endif +#endif /* GL_NV_point_sprite */ + +#ifndef GL_NV_present_video +#define GL_NV_present_video 1 +#define GL_FRAME_NV 0x8E26 +#define GL_FIELDS_NV 0x8E27 +#define GL_CURRENT_TIME_NV 0x8E28 +#define GL_NUM_FILL_STREAMS_NV 0x8E29 +#define GL_PRESENT_TIME_NV 0x8E2A +#define GL_PRESENT_DURATION_NV 0x8E2B +typedef void (APIENTRYP PFNGLPRESENTFRAMEKEYEDNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1); +typedef void (APIENTRYP PFNGLPRESENTFRAMEDUALFILLNVPROC) (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3); +typedef void (APIENTRYP PFNGLGETVIDEOIVNVPROC) (GLuint video_slot, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOUIVNVPROC) (GLuint video_slot, GLenum pname, GLuint *params); +typedef void (APIENTRYP PFNGLGETVIDEOI64VNVPROC) (GLuint video_slot, GLenum pname, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETVIDEOUI64VNVPROC) (GLuint video_slot, GLenum pname, GLuint64EXT *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPresentFrameKeyedNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLuint key0, GLenum target1, GLuint fill1, GLuint key1); +GLAPI void APIENTRY glPresentFrameDualFillNV (GLuint video_slot, GLuint64EXT minPresentTime, GLuint beginPresentTimeId, GLuint presentDurationId, GLenum type, GLenum target0, GLuint fill0, GLenum target1, GLuint fill1, GLenum target2, GLuint fill2, GLenum target3, GLuint fill3); +GLAPI void APIENTRY glGetVideoivNV (GLuint video_slot, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideouivNV (GLuint video_slot, GLenum pname, GLuint *params); +GLAPI void APIENTRY glGetVideoi64vNV (GLuint video_slot, GLenum pname, GLint64EXT *params); +GLAPI void APIENTRY glGetVideoui64vNV (GLuint video_slot, GLenum pname, GLuint64EXT *params); +#endif +#endif /* GL_NV_present_video */ + +#ifndef GL_NV_primitive_restart +#define GL_NV_primitive_restart 1 +#define GL_PRIMITIVE_RESTART_NV 0x8558 +#define GL_PRIMITIVE_RESTART_INDEX_NV 0x8559 +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void); +typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPrimitiveRestartNV (void); +GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint index); +#endif +#endif /* GL_NV_primitive_restart */ + +#ifndef GL_NV_register_combiners +#define GL_NV_register_combiners 1 +#define GL_REGISTER_COMBINERS_NV 0x8522 +#define GL_VARIABLE_A_NV 0x8523 +#define GL_VARIABLE_B_NV 0x8524 +#define GL_VARIABLE_C_NV 0x8525 +#define GL_VARIABLE_D_NV 0x8526 +#define GL_VARIABLE_E_NV 0x8527 +#define GL_VARIABLE_F_NV 0x8528 +#define GL_VARIABLE_G_NV 0x8529 +#define GL_CONSTANT_COLOR0_NV 0x852A +#define GL_CONSTANT_COLOR1_NV 0x852B +#define GL_SPARE0_NV 0x852E +#define GL_SPARE1_NV 0x852F +#define GL_DISCARD_NV 0x8530 +#define GL_E_TIMES_F_NV 0x8531 +#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532 +#define GL_UNSIGNED_IDENTITY_NV 0x8536 +#define GL_UNSIGNED_INVERT_NV 0x8537 +#define GL_EXPAND_NORMAL_NV 0x8538 +#define GL_EXPAND_NEGATE_NV 0x8539 +#define GL_HALF_BIAS_NORMAL_NV 0x853A +#define GL_HALF_BIAS_NEGATE_NV 0x853B +#define GL_SIGNED_IDENTITY_NV 0x853C +#define GL_SIGNED_NEGATE_NV 0x853D +#define GL_SCALE_BY_TWO_NV 0x853E +#define GL_SCALE_BY_FOUR_NV 0x853F +#define GL_SCALE_BY_ONE_HALF_NV 0x8540 +#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV 0x8541 +#define GL_COMBINER_INPUT_NV 0x8542 +#define GL_COMBINER_MAPPING_NV 0x8543 +#define GL_COMBINER_COMPONENT_USAGE_NV 0x8544 +#define GL_COMBINER_AB_DOT_PRODUCT_NV 0x8545 +#define GL_COMBINER_CD_DOT_PRODUCT_NV 0x8546 +#define GL_COMBINER_MUX_SUM_NV 0x8547 +#define GL_COMBINER_SCALE_NV 0x8548 +#define GL_COMBINER_BIAS_NV 0x8549 +#define GL_COMBINER_AB_OUTPUT_NV 0x854A +#define GL_COMBINER_CD_OUTPUT_NV 0x854B +#define GL_COMBINER_SUM_OUTPUT_NV 0x854C +#define GL_MAX_GENERAL_COMBINERS_NV 0x854D +#define GL_NUM_GENERAL_COMBINERS_NV 0x854E +#define GL_COLOR_SUM_CLAMP_NV 0x854F +#define GL_COMBINER0_NV 0x8550 +#define GL_COMBINER1_NV 0x8551 +#define GL_COMBINER2_NV 0x8552 +#define GL_COMBINER3_NV 0x8553 +#define GL_COMBINER4_NV 0x8554 +#define GL_COMBINER5_NV 0x8555 +#define GL_COMBINER6_NV 0x8556 +#define GL_COMBINER7_NV 0x8557 +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); +typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCombinerParameterfvNV (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glCombinerParameterfNV (GLenum pname, GLfloat param); +GLAPI void APIENTRY glCombinerParameterivNV (GLenum pname, const GLint *params); +GLAPI void APIENTRY glCombinerParameteriNV (GLenum pname, GLint param); +GLAPI void APIENTRY glCombinerInputNV (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +GLAPI void APIENTRY glCombinerOutputNV (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum); +GLAPI void APIENTRY glFinalCombinerInputNV (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage); +GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum stage, GLenum portion, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum stage, GLenum portion, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum variable, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum variable, GLenum pname, GLint *params); +#endif +#endif /* GL_NV_register_combiners */ + +#ifndef GL_NV_register_combiners2 +#define GL_NV_register_combiners2 1 +#define GL_PER_STAGE_CONSTANTS_NV 0x8535 +typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum stage, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum stage, GLenum pname, GLfloat *params); +#endif +#endif /* GL_NV_register_combiners2 */ + +#ifndef GL_NV_sample_locations +#define GL_NV_sample_locations 1 +#define GL_SAMPLE_LOCATION_SUBPIXEL_BITS_NV 0x933D +#define GL_SAMPLE_LOCATION_PIXEL_GRID_WIDTH_NV 0x933E +#define GL_SAMPLE_LOCATION_PIXEL_GRID_HEIGHT_NV 0x933F +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_TABLE_SIZE_NV 0x9340 +#define GL_SAMPLE_LOCATION_NV 0x8E50 +#define GL_PROGRAMMABLE_SAMPLE_LOCATION_NV 0x9341 +#define GL_FRAMEBUFFER_PROGRAMMABLE_SAMPLE_LOCATIONS_NV 0x9342 +#define GL_FRAMEBUFFER_SAMPLE_LOCATION_PIXEL_GRID_NV 0x9343 +typedef void (APIENTRYP PFNGLFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLNAMEDFRAMEBUFFERSAMPLELOCATIONSFVNVPROC) (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLRESOLVEDEPTHVALUESNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFramebufferSampleLocationsfvNV (GLenum target, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glNamedFramebufferSampleLocationsfvNV (GLuint framebuffer, GLuint start, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glResolveDepthValuesNV (void); +#endif +#endif /* GL_NV_sample_locations */ + +#ifndef GL_NV_sample_mask_override_coverage +#define GL_NV_sample_mask_override_coverage 1 +#endif /* GL_NV_sample_mask_override_coverage */ + +#ifndef GL_NV_shader_atomic_counters +#define GL_NV_shader_atomic_counters 1 +#endif /* GL_NV_shader_atomic_counters */ + +#ifndef GL_NV_shader_atomic_float +#define GL_NV_shader_atomic_float 1 +#endif /* GL_NV_shader_atomic_float */ + +#ifndef GL_NV_shader_atomic_fp16_vector +#define GL_NV_shader_atomic_fp16_vector 1 +#endif /* GL_NV_shader_atomic_fp16_vector */ + +#ifndef GL_NV_shader_atomic_int64 +#define GL_NV_shader_atomic_int64 1 +#endif /* GL_NV_shader_atomic_int64 */ + +#ifndef GL_NV_shader_buffer_load +#define GL_NV_shader_buffer_load 1 +#define GL_BUFFER_GPU_ADDRESS_NV 0x8F1D +#define GL_GPU_ADDRESS_NV 0x8F34 +#define GL_MAX_SHADER_BUFFER_ADDRESS_NV 0x8F35 +typedef void (APIENTRYP PFNGLMAKEBUFFERRESIDENTNVPROC) (GLenum target, GLenum access); +typedef void (APIENTRYP PFNGLMAKEBUFFERNONRESIDENTNVPROC) (GLenum target); +typedef GLboolean (APIENTRYP PFNGLISBUFFERRESIDENTNVPROC) (GLenum target); +typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERRESIDENTNVPROC) (GLuint buffer, GLenum access); +typedef void (APIENTRYP PFNGLMAKENAMEDBUFFERNONRESIDENTNVPROC) (GLuint buffer); +typedef GLboolean (APIENTRYP PFNGLISNAMEDBUFFERRESIDENTNVPROC) (GLuint buffer); +typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERUI64VNVPROC) (GLenum target, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLGETNAMEDBUFFERPARAMETERUI64VNVPROC) (GLuint buffer, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLGETINTEGERUI64VNVPROC) (GLenum value, GLuint64EXT *result); +typedef void (APIENTRYP PFNGLUNIFORMUI64NVPROC) (GLint location, GLuint64EXT value); +typedef void (APIENTRYP PFNGLUNIFORMUI64VNVPROC) (GLint location, GLsizei count, const GLuint64EXT *value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64NVPROC) (GLuint program, GLint location, GLuint64EXT value); +typedef void (APIENTRYP PFNGLPROGRAMUNIFORMUI64VNVPROC) (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glMakeBufferResidentNV (GLenum target, GLenum access); +GLAPI void APIENTRY glMakeBufferNonResidentNV (GLenum target); +GLAPI GLboolean APIENTRY glIsBufferResidentNV (GLenum target); +GLAPI void APIENTRY glMakeNamedBufferResidentNV (GLuint buffer, GLenum access); +GLAPI void APIENTRY glMakeNamedBufferNonResidentNV (GLuint buffer); +GLAPI GLboolean APIENTRY glIsNamedBufferResidentNV (GLuint buffer); +GLAPI void APIENTRY glGetBufferParameterui64vNV (GLenum target, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glGetNamedBufferParameterui64vNV (GLuint buffer, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glGetIntegerui64vNV (GLenum value, GLuint64EXT *result); +GLAPI void APIENTRY glUniformui64NV (GLint location, GLuint64EXT value); +GLAPI void APIENTRY glUniformui64vNV (GLint location, GLsizei count, const GLuint64EXT *value); +GLAPI void APIENTRY glProgramUniformui64NV (GLuint program, GLint location, GLuint64EXT value); +GLAPI void APIENTRY glProgramUniformui64vNV (GLuint program, GLint location, GLsizei count, const GLuint64EXT *value); +#endif +#endif /* GL_NV_shader_buffer_load */ + +#ifndef GL_NV_shader_buffer_store +#define GL_NV_shader_buffer_store 1 +#define GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV 0x00000010 +#endif /* GL_NV_shader_buffer_store */ + +#ifndef GL_NV_shader_storage_buffer_object +#define GL_NV_shader_storage_buffer_object 1 +#endif /* GL_NV_shader_storage_buffer_object */ + +#ifndef GL_NV_shader_thread_group +#define GL_NV_shader_thread_group 1 +#define GL_WARP_SIZE_NV 0x9339 +#define GL_WARPS_PER_SM_NV 0x933A +#define GL_SM_COUNT_NV 0x933B +#endif /* GL_NV_shader_thread_group */ + +#ifndef GL_NV_shader_thread_shuffle +#define GL_NV_shader_thread_shuffle 1 +#endif /* GL_NV_shader_thread_shuffle */ + +#ifndef GL_NV_tessellation_program5 +#define GL_NV_tessellation_program5 1 +#define GL_MAX_PROGRAM_PATCH_ATTRIBS_NV 0x86D8 +#define GL_TESS_CONTROL_PROGRAM_NV 0x891E +#define GL_TESS_EVALUATION_PROGRAM_NV 0x891F +#define GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV 0x8C74 +#define GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV 0x8C75 +#endif /* GL_NV_tessellation_program5 */ + +#ifndef GL_NV_texgen_emboss +#define GL_NV_texgen_emboss 1 +#define GL_EMBOSS_LIGHT_NV 0x855D +#define GL_EMBOSS_CONSTANT_NV 0x855E +#define GL_EMBOSS_MAP_NV 0x855F +#endif /* GL_NV_texgen_emboss */ + +#ifndef GL_NV_texgen_reflection +#define GL_NV_texgen_reflection 1 +#define GL_NORMAL_MAP_NV 0x8511 +#define GL_REFLECTION_MAP_NV 0x8512 +#endif /* GL_NV_texgen_reflection */ + +#ifndef GL_NV_texture_barrier +#define GL_NV_texture_barrier 1 +typedef void (APIENTRYP PFNGLTEXTUREBARRIERNVPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureBarrierNV (void); +#endif +#endif /* GL_NV_texture_barrier */ + +#ifndef GL_NV_texture_compression_vtc +#define GL_NV_texture_compression_vtc 1 +#endif /* GL_NV_texture_compression_vtc */ + +#ifndef GL_NV_texture_env_combine4 +#define GL_NV_texture_env_combine4 1 +#define GL_COMBINE4_NV 0x8503 +#define GL_SOURCE3_RGB_NV 0x8583 +#define GL_SOURCE3_ALPHA_NV 0x858B +#define GL_OPERAND3_RGB_NV 0x8593 +#define GL_OPERAND3_ALPHA_NV 0x859B +#endif /* GL_NV_texture_env_combine4 */ + +#ifndef GL_NV_texture_expand_normal +#define GL_NV_texture_expand_normal 1 +#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F +#endif /* GL_NV_texture_expand_normal */ + +#ifndef GL_NV_texture_multisample +#define GL_NV_texture_multisample 1 +#define GL_TEXTURE_COVERAGE_SAMPLES_NV 0x9045 +#define GL_TEXTURE_COLOR_SAMPLES_NV 0x9046 +typedef void (APIENTRYP PFNGLTEXIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLENVPROC) (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE2DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +typedef void (APIENTRYP PFNGLTEXTUREIMAGE3DMULTISAMPLECOVERAGENVPROC) (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage2DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTexImage3DMultisampleCoverageNV (GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage2DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage3DMultisampleNV (GLuint texture, GLenum target, GLsizei samples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage2DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations); +GLAPI void APIENTRY glTextureImage3DMultisampleCoverageNV (GLuint texture, GLenum target, GLsizei coverageSamples, GLsizei colorSamples, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations); +#endif +#endif /* GL_NV_texture_multisample */ + +#ifndef GL_NV_texture_rectangle +#define GL_NV_texture_rectangle 1 +#define GL_TEXTURE_RECTANGLE_NV 0x84F5 +#define GL_TEXTURE_BINDING_RECTANGLE_NV 0x84F6 +#define GL_PROXY_TEXTURE_RECTANGLE_NV 0x84F7 +#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV 0x84F8 +#endif /* GL_NV_texture_rectangle */ + +#ifndef GL_NV_texture_shader +#define GL_NV_texture_shader 1 +#define GL_OFFSET_TEXTURE_RECTANGLE_NV 0x864C +#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D +#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E +#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9 +#define GL_UNSIGNED_INT_S8_S8_8_8_NV 0x86DA +#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV 0x86DB +#define GL_DSDT_MAG_INTENSITY_NV 0x86DC +#define GL_SHADER_CONSISTENT_NV 0x86DD +#define GL_TEXTURE_SHADER_NV 0x86DE +#define GL_SHADER_OPERATION_NV 0x86DF +#define GL_CULL_MODES_NV 0x86E0 +#define GL_OFFSET_TEXTURE_MATRIX_NV 0x86E1 +#define GL_OFFSET_TEXTURE_SCALE_NV 0x86E2 +#define GL_OFFSET_TEXTURE_BIAS_NV 0x86E3 +#define GL_OFFSET_TEXTURE_2D_MATRIX_NV 0x86E1 +#define GL_OFFSET_TEXTURE_2D_SCALE_NV 0x86E2 +#define GL_OFFSET_TEXTURE_2D_BIAS_NV 0x86E3 +#define GL_PREVIOUS_TEXTURE_INPUT_NV 0x86E4 +#define GL_CONST_EYE_NV 0x86E5 +#define GL_PASS_THROUGH_NV 0x86E6 +#define GL_CULL_FRAGMENT_NV 0x86E7 +#define GL_OFFSET_TEXTURE_2D_NV 0x86E8 +#define GL_DEPENDENT_AR_TEXTURE_2D_NV 0x86E9 +#define GL_DEPENDENT_GB_TEXTURE_2D_NV 0x86EA +#define GL_DOT_PRODUCT_NV 0x86EC +#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV 0x86ED +#define GL_DOT_PRODUCT_TEXTURE_2D_NV 0x86EE +#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0 +#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1 +#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2 +#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3 +#define GL_HILO_NV 0x86F4 +#define GL_DSDT_NV 0x86F5 +#define GL_DSDT_MAG_NV 0x86F6 +#define GL_DSDT_MAG_VIB_NV 0x86F7 +#define GL_HILO16_NV 0x86F8 +#define GL_SIGNED_HILO_NV 0x86F9 +#define GL_SIGNED_HILO16_NV 0x86FA +#define GL_SIGNED_RGBA_NV 0x86FB +#define GL_SIGNED_RGBA8_NV 0x86FC +#define GL_SIGNED_RGB_NV 0x86FE +#define GL_SIGNED_RGB8_NV 0x86FF +#define GL_SIGNED_LUMINANCE_NV 0x8701 +#define GL_SIGNED_LUMINANCE8_NV 0x8702 +#define GL_SIGNED_LUMINANCE_ALPHA_NV 0x8703 +#define GL_SIGNED_LUMINANCE8_ALPHA8_NV 0x8704 +#define GL_SIGNED_ALPHA_NV 0x8705 +#define GL_SIGNED_ALPHA8_NV 0x8706 +#define GL_SIGNED_INTENSITY_NV 0x8707 +#define GL_SIGNED_INTENSITY8_NV 0x8708 +#define GL_DSDT8_NV 0x8709 +#define GL_DSDT8_MAG8_NV 0x870A +#define GL_DSDT8_MAG8_INTENSITY8_NV 0x870B +#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV 0x870C +#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D +#define GL_HI_SCALE_NV 0x870E +#define GL_LO_SCALE_NV 0x870F +#define GL_DS_SCALE_NV 0x8710 +#define GL_DT_SCALE_NV 0x8711 +#define GL_MAGNITUDE_SCALE_NV 0x8712 +#define GL_VIBRANCE_SCALE_NV 0x8713 +#define GL_HI_BIAS_NV 0x8714 +#define GL_LO_BIAS_NV 0x8715 +#define GL_DS_BIAS_NV 0x8716 +#define GL_DT_BIAS_NV 0x8717 +#define GL_MAGNITUDE_BIAS_NV 0x8718 +#define GL_VIBRANCE_BIAS_NV 0x8719 +#define GL_TEXTURE_BORDER_VALUES_NV 0x871A +#define GL_TEXTURE_HI_SIZE_NV 0x871B +#define GL_TEXTURE_LO_SIZE_NV 0x871C +#define GL_TEXTURE_DS_SIZE_NV 0x871D +#define GL_TEXTURE_DT_SIZE_NV 0x871E +#define GL_TEXTURE_MAG_SIZE_NV 0x871F +#endif /* GL_NV_texture_shader */ + +#ifndef GL_NV_texture_shader2 +#define GL_NV_texture_shader2 1 +#define GL_DOT_PRODUCT_TEXTURE_3D_NV 0x86EF +#endif /* GL_NV_texture_shader2 */ + +#ifndef GL_NV_texture_shader3 +#define GL_NV_texture_shader3 1 +#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850 +#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851 +#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852 +#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853 +#define GL_OFFSET_HILO_TEXTURE_2D_NV 0x8854 +#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855 +#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856 +#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857 +#define GL_DEPENDENT_HILO_TEXTURE_2D_NV 0x8858 +#define GL_DEPENDENT_RGB_TEXTURE_3D_NV 0x8859 +#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A +#define GL_DOT_PRODUCT_PASS_THROUGH_NV 0x885B +#define GL_DOT_PRODUCT_TEXTURE_1D_NV 0x885C +#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D +#define GL_HILO8_NV 0x885E +#define GL_SIGNED_HILO8_NV 0x885F +#define GL_FORCE_BLUE_TO_ONE_NV 0x8860 +#endif /* GL_NV_texture_shader3 */ + +#ifndef GL_NV_transform_feedback +#define GL_NV_transform_feedback 1 +#define GL_BACK_PRIMARY_COLOR_NV 0x8C77 +#define GL_BACK_SECONDARY_COLOR_NV 0x8C78 +#define GL_TEXTURE_COORD_NV 0x8C79 +#define GL_CLIP_DISTANCE_NV 0x8C7A +#define GL_VERTEX_ID_NV 0x8C7B +#define GL_PRIMITIVE_ID_NV 0x8C7C +#define GL_GENERIC_ATTRIB_NV 0x8C7D +#define GL_TRANSFORM_FEEDBACK_ATTRIBS_NV 0x8C7E +#define GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV 0x8C7F +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV 0x8C80 +#define GL_ACTIVE_VARYINGS_NV 0x8C81 +#define GL_ACTIVE_VARYING_MAX_LENGTH_NV 0x8C82 +#define GL_TRANSFORM_FEEDBACK_VARYINGS_NV 0x8C83 +#define GL_TRANSFORM_FEEDBACK_BUFFER_START_NV 0x8C84 +#define GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV 0x8C85 +#define GL_TRANSFORM_FEEDBACK_RECORD_NV 0x8C86 +#define GL_PRIMITIVES_GENERATED_NV 0x8C87 +#define GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV 0x8C88 +#define GL_RASTERIZER_DISCARD_NV 0x8C89 +#define GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_NV 0x8C8A +#define GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV 0x8C8B +#define GL_INTERLEAVED_ATTRIBS_NV 0x8C8C +#define GL_SEPARATE_ATTRIBS_NV 0x8C8D +#define GL_TRANSFORM_FEEDBACK_BUFFER_NV 0x8C8E +#define GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV 0x8C8F +#define GL_LAYER_NV 0x8DAA +#define GL_NEXT_BUFFER_NV -2 +#define GL_SKIP_COMPONENTS4_NV -3 +#define GL_SKIP_COMPONENTS3_NV -4 +#define GL_SKIP_COMPONENTS2_NV -5 +#define GL_SKIP_COMPONENTS1_NV -6 +typedef void (APIENTRYP PFNGLBEGINTRANSFORMFEEDBACKNVPROC) (GLenum primitiveMode); +typedef void (APIENTRYP PFNGLENDTRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKATTRIBSNVPROC) (GLsizei count, const GLint *attribs, GLenum bufferMode); +typedef void (APIENTRYP PFNGLBINDBUFFERRANGENVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +typedef void (APIENTRYP PFNGLBINDBUFFEROFFSETNVPROC) (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +typedef void (APIENTRYP PFNGLBINDBUFFERBASENVPROC) (GLenum target, GLuint index, GLuint buffer); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKVARYINGSNVPROC) (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode); +typedef void (APIENTRYP PFNGLACTIVEVARYINGNVPROC) (GLuint program, const GLchar *name); +typedef GLint (APIENTRYP PFNGLGETVARYINGLOCATIONNVPROC) (GLuint program, const GLchar *name); +typedef void (APIENTRYP PFNGLGETACTIVEVARYINGNVPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKVARYINGNVPROC) (GLuint program, GLuint index, GLint *location); +typedef void (APIENTRYP PFNGLTRANSFORMFEEDBACKSTREAMATTRIBSNVPROC) (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginTransformFeedbackNV (GLenum primitiveMode); +GLAPI void APIENTRY glEndTransformFeedbackNV (void); +GLAPI void APIENTRY glTransformFeedbackAttribsNV (GLsizei count, const GLint *attribs, GLenum bufferMode); +GLAPI void APIENTRY glBindBufferRangeNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size); +GLAPI void APIENTRY glBindBufferOffsetNV (GLenum target, GLuint index, GLuint buffer, GLintptr offset); +GLAPI void APIENTRY glBindBufferBaseNV (GLenum target, GLuint index, GLuint buffer); +GLAPI void APIENTRY glTransformFeedbackVaryingsNV (GLuint program, GLsizei count, const GLint *locations, GLenum bufferMode); +GLAPI void APIENTRY glActiveVaryingNV (GLuint program, const GLchar *name); +GLAPI GLint APIENTRY glGetVaryingLocationNV (GLuint program, const GLchar *name); +GLAPI void APIENTRY glGetActiveVaryingNV (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLsizei *size, GLenum *type, GLchar *name); +GLAPI void APIENTRY glGetTransformFeedbackVaryingNV (GLuint program, GLuint index, GLint *location); +GLAPI void APIENTRY glTransformFeedbackStreamAttribsNV (GLsizei count, const GLint *attribs, GLsizei nbuffers, const GLint *bufstreams, GLenum bufferMode); +#endif +#endif /* GL_NV_transform_feedback */ + +#ifndef GL_NV_transform_feedback2 +#define GL_NV_transform_feedback2 1 +#define GL_TRANSFORM_FEEDBACK_NV 0x8E22 +#define GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED_NV 0x8E23 +#define GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE_NV 0x8E24 +#define GL_TRANSFORM_FEEDBACK_BINDING_NV 0x8E25 +typedef void (APIENTRYP PFNGLBINDTRANSFORMFEEDBACKNVPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETETRANSFORMFEEDBACKSNVPROC) (GLsizei n, const GLuint *ids); +typedef void (APIENTRYP PFNGLGENTRANSFORMFEEDBACKSNVPROC) (GLsizei n, GLuint *ids); +typedef GLboolean (APIENTRYP PFNGLISTRANSFORMFEEDBACKNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLPAUSETRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLRESUMETRANSFORMFEEDBACKNVPROC) (void); +typedef void (APIENTRYP PFNGLDRAWTRANSFORMFEEDBACKNVPROC) (GLenum mode, GLuint id); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBindTransformFeedbackNV (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteTransformFeedbacksNV (GLsizei n, const GLuint *ids); +GLAPI void APIENTRY glGenTransformFeedbacksNV (GLsizei n, GLuint *ids); +GLAPI GLboolean APIENTRY glIsTransformFeedbackNV (GLuint id); +GLAPI void APIENTRY glPauseTransformFeedbackNV (void); +GLAPI void APIENTRY glResumeTransformFeedbackNV (void); +GLAPI void APIENTRY glDrawTransformFeedbackNV (GLenum mode, GLuint id); +#endif +#endif /* GL_NV_transform_feedback2 */ + +#ifndef GL_NV_uniform_buffer_unified_memory +#define GL_NV_uniform_buffer_unified_memory 1 +#define GL_UNIFORM_BUFFER_UNIFIED_NV 0x936E +#define GL_UNIFORM_BUFFER_ADDRESS_NV 0x936F +#define GL_UNIFORM_BUFFER_LENGTH_NV 0x9370 +#endif /* GL_NV_uniform_buffer_unified_memory */ + +#ifndef GL_NV_vdpau_interop +#define GL_NV_vdpau_interop 1 +typedef GLintptr GLvdpauSurfaceNV; +#define GL_SURFACE_STATE_NV 0x86EB +#define GL_SURFACE_REGISTERED_NV 0x86FD +#define GL_SURFACE_MAPPED_NV 0x8700 +#define GL_WRITE_DISCARD_NV 0x88BE +typedef void (APIENTRYP PFNGLVDPAUINITNVPROC) (const void *vdpDevice, const void *getProcAddress); +typedef void (APIENTRYP PFNGLVDPAUFININVPROC) (void); +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTERVIDEOSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +typedef GLvdpauSurfaceNV (APIENTRYP PFNGLVDPAUREGISTEROUTPUTSURFACENVPROC) (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +typedef GLboolean (APIENTRYP PFNGLVDPAUISSURFACENVPROC) (GLvdpauSurfaceNV surface); +typedef void (APIENTRYP PFNGLVDPAUUNREGISTERSURFACENVPROC) (GLvdpauSurfaceNV surface); +typedef void (APIENTRYP PFNGLVDPAUGETSURFACEIVNVPROC) (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +typedef void (APIENTRYP PFNGLVDPAUSURFACEACCESSNVPROC) (GLvdpauSurfaceNV surface, GLenum access); +typedef void (APIENTRYP PFNGLVDPAUMAPSURFACESNVPROC) (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces); +typedef void (APIENTRYP PFNGLVDPAUUNMAPSURFACESNVPROC) (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVDPAUInitNV (const void *vdpDevice, const void *getProcAddress); +GLAPI void APIENTRY glVDPAUFiniNV (void); +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterVideoSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +GLAPI GLvdpauSurfaceNV APIENTRY glVDPAURegisterOutputSurfaceNV (const void *vdpSurface, GLenum target, GLsizei numTextureNames, const GLuint *textureNames); +GLAPI GLboolean APIENTRY glVDPAUIsSurfaceNV (GLvdpauSurfaceNV surface); +GLAPI void APIENTRY glVDPAUUnregisterSurfaceNV (GLvdpauSurfaceNV surface); +GLAPI void APIENTRY glVDPAUGetSurfaceivNV (GLvdpauSurfaceNV surface, GLenum pname, GLsizei bufSize, GLsizei *length, GLint *values); +GLAPI void APIENTRY glVDPAUSurfaceAccessNV (GLvdpauSurfaceNV surface, GLenum access); +GLAPI void APIENTRY glVDPAUMapSurfacesNV (GLsizei numSurfaces, const GLvdpauSurfaceNV *surfaces); +GLAPI void APIENTRY glVDPAUUnmapSurfacesNV (GLsizei numSurface, const GLvdpauSurfaceNV *surfaces); +#endif +#endif /* GL_NV_vdpau_interop */ + +#ifndef GL_NV_vertex_array_range +#define GL_NV_vertex_array_range 1 +#define GL_VERTEX_ARRAY_RANGE_NV 0x851D +#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV 0x851E +#define GL_VERTEX_ARRAY_RANGE_VALID_NV 0x851F +#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520 +#define GL_VERTEX_ARRAY_RANGE_POINTER_NV 0x8521 +typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void); +typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const void *pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushVertexArrayRangeNV (void); +GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei length, const void *pointer); +#endif +#endif /* GL_NV_vertex_array_range */ + +#ifndef GL_NV_vertex_array_range2 +#define GL_NV_vertex_array_range2 1 +#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533 +#endif /* GL_NV_vertex_array_range2 */ + +#ifndef GL_NV_vertex_attrib_integer_64bit +#define GL_NV_vertex_attrib_integer_64bit 1 +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64NVPROC) (GLuint index, GLint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64NVPROC) (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4I64VNVPROC) (GLuint index, const GLint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64NVPROC) (GLuint index, GLuint64EXT x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64NVPROC) (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL1UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL2UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL3UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBL4UI64VNVPROC) (GLuint index, const GLuint64EXT *v); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLI64VNVPROC) (GLuint index, GLenum pname, GLint64EXT *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBLUI64VNVPROC) (GLuint index, GLenum pname, GLuint64EXT *params); +typedef void (APIENTRYP PFNGLVERTEXATTRIBLFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribL1i64NV (GLuint index, GLint64EXT x); +GLAPI void APIENTRY glVertexAttribL2i64NV (GLuint index, GLint64EXT x, GLint64EXT y); +GLAPI void APIENTRY glVertexAttribL3i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z); +GLAPI void APIENTRY glVertexAttribL4i64NV (GLuint index, GLint64EXT x, GLint64EXT y, GLint64EXT z, GLint64EXT w); +GLAPI void APIENTRY glVertexAttribL1i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL2i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL3i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL4i64vNV (GLuint index, const GLint64EXT *v); +GLAPI void APIENTRY glVertexAttribL1ui64NV (GLuint index, GLuint64EXT x); +GLAPI void APIENTRY glVertexAttribL2ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y); +GLAPI void APIENTRY glVertexAttribL3ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z); +GLAPI void APIENTRY glVertexAttribL4ui64NV (GLuint index, GLuint64EXT x, GLuint64EXT y, GLuint64EXT z, GLuint64EXT w); +GLAPI void APIENTRY glVertexAttribL1ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL2ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL3ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glVertexAttribL4ui64vNV (GLuint index, const GLuint64EXT *v); +GLAPI void APIENTRY glGetVertexAttribLi64vNV (GLuint index, GLenum pname, GLint64EXT *params); +GLAPI void APIENTRY glGetVertexAttribLui64vNV (GLuint index, GLenum pname, GLuint64EXT *params); +GLAPI void APIENTRY glVertexAttribLFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride); +#endif +#endif /* GL_NV_vertex_attrib_integer_64bit */ + +#ifndef GL_NV_vertex_buffer_unified_memory +#define GL_NV_vertex_buffer_unified_memory 1 +#define GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV 0x8F1E +#define GL_ELEMENT_ARRAY_UNIFIED_NV 0x8F1F +#define GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV 0x8F20 +#define GL_VERTEX_ARRAY_ADDRESS_NV 0x8F21 +#define GL_NORMAL_ARRAY_ADDRESS_NV 0x8F22 +#define GL_COLOR_ARRAY_ADDRESS_NV 0x8F23 +#define GL_INDEX_ARRAY_ADDRESS_NV 0x8F24 +#define GL_TEXTURE_COORD_ARRAY_ADDRESS_NV 0x8F25 +#define GL_EDGE_FLAG_ARRAY_ADDRESS_NV 0x8F26 +#define GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV 0x8F27 +#define GL_FOG_COORD_ARRAY_ADDRESS_NV 0x8F28 +#define GL_ELEMENT_ARRAY_ADDRESS_NV 0x8F29 +#define GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV 0x8F2A +#define GL_VERTEX_ARRAY_LENGTH_NV 0x8F2B +#define GL_NORMAL_ARRAY_LENGTH_NV 0x8F2C +#define GL_COLOR_ARRAY_LENGTH_NV 0x8F2D +#define GL_INDEX_ARRAY_LENGTH_NV 0x8F2E +#define GL_TEXTURE_COORD_ARRAY_LENGTH_NV 0x8F2F +#define GL_EDGE_FLAG_ARRAY_LENGTH_NV 0x8F30 +#define GL_SECONDARY_COLOR_ARRAY_LENGTH_NV 0x8F31 +#define GL_FOG_COORD_ARRAY_LENGTH_NV 0x8F32 +#define GL_ELEMENT_ARRAY_LENGTH_NV 0x8F33 +#define GL_DRAW_INDIRECT_UNIFIED_NV 0x8F40 +#define GL_DRAW_INDIRECT_ADDRESS_NV 0x8F41 +#define GL_DRAW_INDIRECT_LENGTH_NV 0x8F42 +typedef void (APIENTRYP PFNGLBUFFERADDRESSRANGENVPROC) (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length); +typedef void (APIENTRYP PFNGLVERTEXFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLNORMALFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLINDEXFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLTEXCOORDFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLEDGEFLAGFORMATNVPROC) (GLsizei stride); +typedef void (APIENTRYP PFNGLSECONDARYCOLORFORMATNVPROC) (GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLFOGCOORDFORMATNVPROC) (GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIFORMATNVPROC) (GLuint index, GLint size, GLenum type, GLsizei stride); +typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBufferAddressRangeNV (GLenum pname, GLuint index, GLuint64EXT address, GLsizeiptr length); +GLAPI void APIENTRY glVertexFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glNormalFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glColorFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glIndexFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glTexCoordFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glEdgeFlagFormatNV (GLsizei stride); +GLAPI void APIENTRY glSecondaryColorFormatNV (GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glFogCoordFormatNV (GLenum type, GLsizei stride); +GLAPI void APIENTRY glVertexAttribFormatNV (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride); +GLAPI void APIENTRY glVertexAttribIFormatNV (GLuint index, GLint size, GLenum type, GLsizei stride); +GLAPI void APIENTRY glGetIntegerui64i_vNV (GLenum value, GLuint index, GLuint64EXT *result); +#endif +#endif /* GL_NV_vertex_buffer_unified_memory */ + +#ifndef GL_NV_vertex_program +#define GL_NV_vertex_program 1 +#define GL_VERTEX_PROGRAM_NV 0x8620 +#define GL_VERTEX_STATE_PROGRAM_NV 0x8621 +#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623 +#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624 +#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625 +#define GL_CURRENT_ATTRIB_NV 0x8626 +#define GL_PROGRAM_LENGTH_NV 0x8627 +#define GL_PROGRAM_STRING_NV 0x8628 +#define GL_MODELVIEW_PROJECTION_NV 0x8629 +#define GL_IDENTITY_NV 0x862A +#define GL_INVERSE_NV 0x862B +#define GL_TRANSPOSE_NV 0x862C +#define GL_INVERSE_TRANSPOSE_NV 0x862D +#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E +#define GL_MAX_TRACK_MATRICES_NV 0x862F +#define GL_MATRIX0_NV 0x8630 +#define GL_MATRIX1_NV 0x8631 +#define GL_MATRIX2_NV 0x8632 +#define GL_MATRIX3_NV 0x8633 +#define GL_MATRIX4_NV 0x8634 +#define GL_MATRIX5_NV 0x8635 +#define GL_MATRIX6_NV 0x8636 +#define GL_MATRIX7_NV 0x8637 +#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640 +#define GL_CURRENT_MATRIX_NV 0x8641 +#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643 +#define GL_PROGRAM_PARAMETER_NV 0x8644 +#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645 +#define GL_PROGRAM_TARGET_NV 0x8646 +#define GL_PROGRAM_RESIDENT_NV 0x8647 +#define GL_TRACK_MATRIX_NV 0x8648 +#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649 +#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A +#define GL_PROGRAM_ERROR_POSITION_NV 0x864B +#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650 +#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651 +#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652 +#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653 +#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654 +#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655 +#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656 +#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657 +#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658 +#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659 +#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A +#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B +#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C +#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D +#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E +#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F +#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660 +#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661 +#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662 +#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663 +#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664 +#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665 +#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666 +#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667 +#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668 +#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669 +#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A +#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B +#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C +#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D +#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E +#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F +#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670 +#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671 +#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672 +#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673 +#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674 +#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675 +#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676 +#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677 +#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678 +#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679 +#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A +#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B +#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C +#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D +#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E +#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F +typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences); +typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id); +typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params); +typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs); +typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program); +typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, void **pointer); +typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id); +typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs); +typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform); +typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x); +typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y); +typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z); +typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei n, const GLuint *programs, GLboolean *residences); +GLAPI void APIENTRY glBindProgramNV (GLenum target, GLuint id); +GLAPI void APIENTRY glDeleteProgramsNV (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glExecuteProgramNV (GLenum target, GLuint id, const GLfloat *params); +GLAPI void APIENTRY glGenProgramsNV (GLsizei n, GLuint *programs); +GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum target, GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetProgramivNV (GLuint id, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetProgramStringNV (GLuint id, GLenum pname, GLubyte *program); +GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum target, GLuint address, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint index, GLenum pname, GLdouble *params); +GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint index, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVertexAttribivNV (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint index, GLenum pname, void **pointer); +GLAPI GLboolean APIENTRY glIsProgramNV (GLuint id); +GLAPI void APIENTRY glLoadProgramNV (GLenum target, GLuint id, GLsizei len, const GLubyte *program); +GLAPI void APIENTRY glProgramParameter4dNV (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glProgramParameter4dvNV (GLenum target, GLuint index, const GLdouble *v); +GLAPI void APIENTRY glProgramParameter4fNV (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glProgramParameter4fvNV (GLenum target, GLuint index, const GLfloat *v); +GLAPI void APIENTRY glProgramParameters4dvNV (GLenum target, GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glProgramParameters4fvNV (GLenum target, GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei n, const GLuint *programs); +GLAPI void APIENTRY glTrackMatrixNV (GLenum target, GLuint address, GLenum matrix, GLenum transform); +GLAPI void APIENTRY glVertexAttribPointerNV (GLuint index, GLint fsize, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glVertexAttrib1dNV (GLuint index, GLdouble x); +GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib1fNV (GLuint index, GLfloat x); +GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib1sNV (GLuint index, GLshort x); +GLAPI void APIENTRY glVertexAttrib1svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib2dNV (GLuint index, GLdouble x, GLdouble y); +GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib2fNV (GLuint index, GLfloat x, GLfloat y); +GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib2sNV (GLuint index, GLshort x, GLshort y); +GLAPI void APIENTRY glVertexAttrib2svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib3dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z); +GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib3fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib3sNV (GLuint index, GLshort x, GLshort y, GLshort z); +GLAPI void APIENTRY glVertexAttrib3svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); +GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint index, const GLdouble *v); +GLAPI void APIENTRY glVertexAttrib4fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint index, const GLfloat *v); +GLAPI void APIENTRY glVertexAttrib4sNV (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); +GLAPI void APIENTRY glVertexAttrib4svNV (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); +GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs1svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs2svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs3svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint index, GLsizei count, const GLdouble *v); +GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint index, GLsizei count, const GLfloat *v); +GLAPI void APIENTRY glVertexAttribs4svNV (GLuint index, GLsizei count, const GLshort *v); +GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint index, GLsizei count, const GLubyte *v); +#endif +#endif /* GL_NV_vertex_program */ + +#ifndef GL_NV_vertex_program1_1 +#define GL_NV_vertex_program1_1 1 +#endif /* GL_NV_vertex_program1_1 */ + +#ifndef GL_NV_vertex_program2 +#define GL_NV_vertex_program2 1 +#endif /* GL_NV_vertex_program2 */ + +#ifndef GL_NV_vertex_program2_option +#define GL_NV_vertex_program2_option 1 +#endif /* GL_NV_vertex_program2_option */ + +#ifndef GL_NV_vertex_program3 +#define GL_NV_vertex_program3 1 +#endif /* GL_NV_vertex_program3 */ + +#ifndef GL_NV_vertex_program4 +#define GL_NV_vertex_program4 1 +#define GL_VERTEX_ATTRIB_ARRAY_INTEGER_NV 0x88FD +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IEXTPROC) (GLuint index, GLint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IEXTPROC) (GLuint index, GLint x, GLint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IEXTPROC) (GLuint index, GLint x, GLint y, GLint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IEXTPROC) (GLuint index, GLint x, GLint y, GLint z, GLint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIEXTPROC) (GLuint index, GLuint x); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIEXTPROC) (GLuint index, GLuint x, GLuint y); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIEXTPROC) (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4IVEXTPROC) (GLuint index, const GLint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI1UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI2UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI3UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UIVEXTPROC) (GLuint index, const GLuint *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4BVEXTPROC) (GLuint index, const GLbyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4SVEXTPROC) (GLuint index, const GLshort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4UBVEXTPROC) (GLuint index, const GLubyte *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBI4USVEXTPROC) (GLuint index, const GLushort *v); +typedef void (APIENTRYP PFNGLVERTEXATTRIBIPOINTEREXTPROC) (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIIVEXTPROC) (GLuint index, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIUIVEXTPROC) (GLuint index, GLenum pname, GLuint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glVertexAttribI1iEXT (GLuint index, GLint x); +GLAPI void APIENTRY glVertexAttribI2iEXT (GLuint index, GLint x, GLint y); +GLAPI void APIENTRY glVertexAttribI3iEXT (GLuint index, GLint x, GLint y, GLint z); +GLAPI void APIENTRY glVertexAttribI4iEXT (GLuint index, GLint x, GLint y, GLint z, GLint w); +GLAPI void APIENTRY glVertexAttribI1uiEXT (GLuint index, GLuint x); +GLAPI void APIENTRY glVertexAttribI2uiEXT (GLuint index, GLuint x, GLuint y); +GLAPI void APIENTRY glVertexAttribI3uiEXT (GLuint index, GLuint x, GLuint y, GLuint z); +GLAPI void APIENTRY glVertexAttribI4uiEXT (GLuint index, GLuint x, GLuint y, GLuint z, GLuint w); +GLAPI void APIENTRY glVertexAttribI1ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI2ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI3ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI4ivEXT (GLuint index, const GLint *v); +GLAPI void APIENTRY glVertexAttribI1uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI2uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI3uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4uivEXT (GLuint index, const GLuint *v); +GLAPI void APIENTRY glVertexAttribI4bvEXT (GLuint index, const GLbyte *v); +GLAPI void APIENTRY glVertexAttribI4svEXT (GLuint index, const GLshort *v); +GLAPI void APIENTRY glVertexAttribI4ubvEXT (GLuint index, const GLubyte *v); +GLAPI void APIENTRY glVertexAttribI4usvEXT (GLuint index, const GLushort *v); +GLAPI void APIENTRY glVertexAttribIPointerEXT (GLuint index, GLint size, GLenum type, GLsizei stride, const void *pointer); +GLAPI void APIENTRY glGetVertexAttribIivEXT (GLuint index, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVertexAttribIuivEXT (GLuint index, GLenum pname, GLuint *params); +#endif +#endif /* GL_NV_vertex_program4 */ + +#ifndef GL_NV_video_capture +#define GL_NV_video_capture 1 +#define GL_VIDEO_BUFFER_NV 0x9020 +#define GL_VIDEO_BUFFER_BINDING_NV 0x9021 +#define GL_FIELD_UPPER_NV 0x9022 +#define GL_FIELD_LOWER_NV 0x9023 +#define GL_NUM_VIDEO_CAPTURE_STREAMS_NV 0x9024 +#define GL_NEXT_VIDEO_CAPTURE_BUFFER_STATUS_NV 0x9025 +#define GL_VIDEO_CAPTURE_TO_422_SUPPORTED_NV 0x9026 +#define GL_LAST_VIDEO_CAPTURE_STATUS_NV 0x9027 +#define GL_VIDEO_BUFFER_PITCH_NV 0x9028 +#define GL_VIDEO_COLOR_CONVERSION_MATRIX_NV 0x9029 +#define GL_VIDEO_COLOR_CONVERSION_MAX_NV 0x902A +#define GL_VIDEO_COLOR_CONVERSION_MIN_NV 0x902B +#define GL_VIDEO_COLOR_CONVERSION_OFFSET_NV 0x902C +#define GL_VIDEO_BUFFER_INTERNAL_FORMAT_NV 0x902D +#define GL_PARTIAL_SUCCESS_NV 0x902E +#define GL_SUCCESS_NV 0x902F +#define GL_FAILURE_NV 0x9030 +#define GL_YCBYCR8_422_NV 0x9031 +#define GL_YCBAYCR8A_4224_NV 0x9032 +#define GL_Z6Y10Z6CB10Z6Y10Z6CR10_422_NV 0x9033 +#define GL_Z6Y10Z6CB10Z6A10Z6Y10Z6CR10Z6A10_4224_NV 0x9034 +#define GL_Z4Y12Z4CB12Z4Y12Z4CR12_422_NV 0x9035 +#define GL_Z4Y12Z4CB12Z4A12Z4Y12Z4CR12Z4A12_4224_NV 0x9036 +#define GL_Z4Y12Z4CB12Z4CR12_444_NV 0x9037 +#define GL_VIDEO_CAPTURE_FRAME_WIDTH_NV 0x9038 +#define GL_VIDEO_CAPTURE_FRAME_HEIGHT_NV 0x9039 +#define GL_VIDEO_CAPTURE_FIELD_UPPER_HEIGHT_NV 0x903A +#define GL_VIDEO_CAPTURE_FIELD_LOWER_HEIGHT_NV 0x903B +#define GL_VIDEO_CAPTURE_SURFACE_ORIGIN_NV 0x903C +typedef void (APIENTRYP PFNGLBEGINVIDEOCAPTURENVPROC) (GLuint video_capture_slot); +typedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMBUFFERNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset); +typedef void (APIENTRYP PFNGLBINDVIDEOCAPTURESTREAMTEXTURENVPROC) (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture); +typedef void (APIENTRYP PFNGLENDVIDEOCAPTURENVPROC) (GLuint video_capture_slot); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTUREIVNVPROC) (GLuint video_capture_slot, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETVIDEOCAPTURESTREAMDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params); +typedef GLenum (APIENTRYP PFNGLVIDEOCAPTURENVPROC) (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERIVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERFVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLVIDEOCAPTURESTREAMPARAMETERDVNVPROC) (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glBeginVideoCaptureNV (GLuint video_capture_slot); +GLAPI void APIENTRY glBindVideoCaptureStreamBufferNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLintptrARB offset); +GLAPI void APIENTRY glBindVideoCaptureStreamTextureNV (GLuint video_capture_slot, GLuint stream, GLenum frame_region, GLenum target, GLuint texture); +GLAPI void APIENTRY glEndVideoCaptureNV (GLuint video_capture_slot); +GLAPI void APIENTRY glGetVideoCaptureivNV (GLuint video_capture_slot, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideoCaptureStreamivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetVideoCaptureStreamfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetVideoCaptureStreamdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, GLdouble *params); +GLAPI GLenum APIENTRY glVideoCaptureNV (GLuint video_capture_slot, GLuint *sequence_num, GLuint64EXT *capture_time); +GLAPI void APIENTRY glVideoCaptureStreamParameterivNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLint *params); +GLAPI void APIENTRY glVideoCaptureStreamParameterfvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glVideoCaptureStreamParameterdvNV (GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble *params); +#endif +#endif /* GL_NV_video_capture */ + +#ifndef GL_OML_interlace +#define GL_OML_interlace 1 +#define GL_INTERLACE_OML 0x8980 +#define GL_INTERLACE_READ_OML 0x8981 +#endif /* GL_OML_interlace */ + +#ifndef GL_OML_resample +#define GL_OML_resample 1 +#define GL_PACK_RESAMPLE_OML 0x8984 +#define GL_UNPACK_RESAMPLE_OML 0x8985 +#define GL_RESAMPLE_REPLICATE_OML 0x8986 +#define GL_RESAMPLE_ZERO_FILL_OML 0x8987 +#define GL_RESAMPLE_AVERAGE_OML 0x8988 +#define GL_RESAMPLE_DECIMATE_OML 0x8989 +#endif /* GL_OML_resample */ + +#ifndef GL_OML_subsample +#define GL_OML_subsample 1 +#define GL_FORMAT_SUBSAMPLE_24_24_OML 0x8982 +#define GL_FORMAT_SUBSAMPLE_244_244_OML 0x8983 +#endif /* GL_OML_subsample */ + +#ifndef GL_PGI_misc_hints +#define GL_PGI_misc_hints 1 +#define GL_PREFER_DOUBLEBUFFER_HINT_PGI 0x1A1F8 +#define GL_CONSERVE_MEMORY_HINT_PGI 0x1A1FD +#define GL_RECLAIM_MEMORY_HINT_PGI 0x1A1FE +#define GL_NATIVE_GRAPHICS_HANDLE_PGI 0x1A202 +#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203 +#define GL_NATIVE_GRAPHICS_END_HINT_PGI 0x1A204 +#define GL_ALWAYS_FAST_HINT_PGI 0x1A20C +#define GL_ALWAYS_SOFT_HINT_PGI 0x1A20D +#define GL_ALLOW_DRAW_OBJ_HINT_PGI 0x1A20E +#define GL_ALLOW_DRAW_WIN_HINT_PGI 0x1A20F +#define GL_ALLOW_DRAW_FRG_HINT_PGI 0x1A210 +#define GL_ALLOW_DRAW_MEM_HINT_PGI 0x1A211 +#define GL_STRICT_DEPTHFUNC_HINT_PGI 0x1A216 +#define GL_STRICT_LIGHTING_HINT_PGI 0x1A217 +#define GL_STRICT_SCISSOR_HINT_PGI 0x1A218 +#define GL_FULL_STIPPLE_HINT_PGI 0x1A219 +#define GL_CLIP_NEAR_HINT_PGI 0x1A220 +#define GL_CLIP_FAR_HINT_PGI 0x1A221 +#define GL_WIDE_LINE_HINT_PGI 0x1A222 +#define GL_BACK_NORMALS_HINT_PGI 0x1A223 +typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glHintPGI (GLenum target, GLint mode); +#endif +#endif /* GL_PGI_misc_hints */ + +#ifndef GL_PGI_vertex_hints +#define GL_PGI_vertex_hints 1 +#define GL_VERTEX_DATA_HINT_PGI 0x1A22A +#define GL_VERTEX_CONSISTENT_HINT_PGI 0x1A22B +#define GL_MATERIAL_SIDE_HINT_PGI 0x1A22C +#define GL_MAX_VERTEX_HINT_PGI 0x1A22D +#define GL_COLOR3_BIT_PGI 0x00010000 +#define GL_COLOR4_BIT_PGI 0x00020000 +#define GL_EDGEFLAG_BIT_PGI 0x00040000 +#define GL_INDEX_BIT_PGI 0x00080000 +#define GL_MAT_AMBIENT_BIT_PGI 0x00100000 +#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000 +#define GL_MAT_DIFFUSE_BIT_PGI 0x00400000 +#define GL_MAT_EMISSION_BIT_PGI 0x00800000 +#define GL_MAT_COLOR_INDEXES_BIT_PGI 0x01000000 +#define GL_MAT_SHININESS_BIT_PGI 0x02000000 +#define GL_MAT_SPECULAR_BIT_PGI 0x04000000 +#define GL_NORMAL_BIT_PGI 0x08000000 +#define GL_TEXCOORD1_BIT_PGI 0x10000000 +#define GL_TEXCOORD2_BIT_PGI 0x20000000 +#define GL_TEXCOORD3_BIT_PGI 0x40000000 +#define GL_TEXCOORD4_BIT_PGI 0x80000000 +#define GL_VERTEX23_BIT_PGI 0x00000004 +#define GL_VERTEX4_BIT_PGI 0x00000008 +#endif /* GL_PGI_vertex_hints */ + +#ifndef GL_REND_screen_coordinates +#define GL_REND_screen_coordinates 1 +#define GL_SCREEN_COORDINATES_REND 0x8490 +#define GL_INVERTED_SCREEN_W_REND 0x8491 +#endif /* GL_REND_screen_coordinates */ + +#ifndef GL_S3_s3tc +#define GL_S3_s3tc 1 +#define GL_RGB_S3TC 0x83A0 +#define GL_RGB4_S3TC 0x83A1 +#define GL_RGBA_S3TC 0x83A2 +#define GL_RGBA4_S3TC 0x83A3 +#define GL_RGBA_DXT5_S3TC 0x83A4 +#define GL_RGBA4_DXT5_S3TC 0x83A5 +#endif /* GL_S3_s3tc */ + +#ifndef GL_SGIS_detail_texture +#define GL_SGIS_detail_texture 1 +#define GL_DETAIL_TEXTURE_2D_SGIS 0x8095 +#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096 +#define GL_LINEAR_DETAIL_SGIS 0x8097 +#define GL_LINEAR_DETAIL_ALPHA_SGIS 0x8098 +#define GL_LINEAR_DETAIL_COLOR_SGIS 0x8099 +#define GL_DETAIL_TEXTURE_LEVEL_SGIS 0x809A +#define GL_DETAIL_TEXTURE_MODE_SGIS 0x809B +#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C +typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum target, GLfloat *points); +#endif +#endif /* GL_SGIS_detail_texture */ + +#ifndef GL_SGIS_fog_function +#define GL_SGIS_fog_function 1 +#define GL_FOG_FUNC_SGIS 0x812A +#define GL_FOG_FUNC_POINTS_SGIS 0x812B +#define GL_MAX_FOG_FUNC_POINTS_SGIS 0x812C +typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFogFuncSGIS (GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *points); +#endif +#endif /* GL_SGIS_fog_function */ + +#ifndef GL_SGIS_generate_mipmap +#define GL_SGIS_generate_mipmap 1 +#define GL_GENERATE_MIPMAP_SGIS 0x8191 +#define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 +#endif /* GL_SGIS_generate_mipmap */ + +#ifndef GL_SGIS_multisample +#define GL_SGIS_multisample 1 +#define GL_MULTISAMPLE_SGIS 0x809D +#define GL_SAMPLE_ALPHA_TO_MASK_SGIS 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE_SGIS 0x809F +#define GL_SAMPLE_MASK_SGIS 0x80A0 +#define GL_1PASS_SGIS 0x80A1 +#define GL_2PASS_0_SGIS 0x80A2 +#define GL_2PASS_1_SGIS 0x80A3 +#define GL_4PASS_0_SGIS 0x80A4 +#define GL_4PASS_1_SGIS 0x80A5 +#define GL_4PASS_2_SGIS 0x80A6 +#define GL_4PASS_3_SGIS 0x80A7 +#define GL_SAMPLE_BUFFERS_SGIS 0x80A8 +#define GL_SAMPLES_SGIS 0x80A9 +#define GL_SAMPLE_MASK_VALUE_SGIS 0x80AA +#define GL_SAMPLE_MASK_INVERT_SGIS 0x80AB +#define GL_SAMPLE_PATTERN_SGIS 0x80AC +typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert); +typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSampleMaskSGIS (GLclampf value, GLboolean invert); +GLAPI void APIENTRY glSamplePatternSGIS (GLenum pattern); +#endif +#endif /* GL_SGIS_multisample */ + +#ifndef GL_SGIS_pixel_texture +#define GL_SGIS_pixel_texture 1 +#define GL_PIXEL_TEXTURE_SGIS 0x8353 +#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354 +#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355 +#define GL_PIXEL_GROUP_COLOR_SGIS 0x8356 +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum pname, GLint param); +GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum pname, const GLint *params); +GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum pname, GLint *params); +GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum pname, GLfloat *params); +#endif +#endif /* GL_SGIS_pixel_texture */ + +#ifndef GL_SGIS_point_line_texgen +#define GL_SGIS_point_line_texgen 1 +#define GL_EYE_DISTANCE_TO_POINT_SGIS 0x81F0 +#define GL_OBJECT_DISTANCE_TO_POINT_SGIS 0x81F1 +#define GL_EYE_DISTANCE_TO_LINE_SGIS 0x81F2 +#define GL_OBJECT_DISTANCE_TO_LINE_SGIS 0x81F3 +#define GL_EYE_POINT_SGIS 0x81F4 +#define GL_OBJECT_POINT_SGIS 0x81F5 +#define GL_EYE_LINE_SGIS 0x81F6 +#define GL_OBJECT_LINE_SGIS 0x81F7 +#endif /* GL_SGIS_point_line_texgen */ + +#ifndef GL_SGIS_point_parameters +#define GL_SGIS_point_parameters 1 +#define GL_POINT_SIZE_MIN_SGIS 0x8126 +#define GL_POINT_SIZE_MAX_SGIS 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128 +#define GL_DISTANCE_ATTENUATION_SGIS 0x8129 +typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPointParameterfSGIS (GLenum pname, GLfloat param); +GLAPI void APIENTRY glPointParameterfvSGIS (GLenum pname, const GLfloat *params); +#endif +#endif /* GL_SGIS_point_parameters */ + +#ifndef GL_SGIS_sharpen_texture +#define GL_SGIS_sharpen_texture 1 +#define GL_LINEAR_SHARPEN_SGIS 0x80AD +#define GL_LINEAR_SHARPEN_ALPHA_SGIS 0x80AE +#define GL_LINEAR_SHARPEN_COLOR_SGIS 0x80AF +#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0 +typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points); +typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points); +GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum target, GLfloat *points); +#endif +#endif /* GL_SGIS_sharpen_texture */ + +#ifndef GL_SGIS_texture4D +#define GL_SGIS_texture4D 1 +#define GL_PACK_SKIP_VOLUMES_SGIS 0x8130 +#define GL_PACK_IMAGE_DEPTH_SGIS 0x8131 +#define GL_UNPACK_SKIP_VOLUMES_SGIS 0x8132 +#define GL_UNPACK_IMAGE_DEPTH_SGIS 0x8133 +#define GL_TEXTURE_4D_SGIS 0x8134 +#define GL_PROXY_TEXTURE_4D_SGIS 0x8135 +#define GL_TEXTURE_4DSIZE_SGIS 0x8136 +#define GL_TEXTURE_WRAP_Q_SGIS 0x8137 +#define GL_MAX_4D_TEXTURE_SIZE_SGIS 0x8138 +#define GL_TEXTURE_4D_BINDING_SGIS 0x814F +typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const void *pixels); +typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const void *pixels); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTexImage4DSGIS (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const void *pixels); +GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const void *pixels); +#endif +#endif /* GL_SGIS_texture4D */ + +#ifndef GL_SGIS_texture_border_clamp +#define GL_SGIS_texture_border_clamp 1 +#define GL_CLAMP_TO_BORDER_SGIS 0x812D +#endif /* GL_SGIS_texture_border_clamp */ + +#ifndef GL_SGIS_texture_color_mask +#define GL_SGIS_texture_color_mask 1 +#define GL_TEXTURE_COLOR_WRITEMASK_SGIS 0x81EF +typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); +#endif +#endif /* GL_SGIS_texture_color_mask */ + +#ifndef GL_SGIS_texture_edge_clamp +#define GL_SGIS_texture_edge_clamp 1 +#define GL_CLAMP_TO_EDGE_SGIS 0x812F +#endif /* GL_SGIS_texture_edge_clamp */ + +#ifndef GL_SGIS_texture_filter4 +#define GL_SGIS_texture_filter4 1 +#define GL_FILTER4_SGIS 0x8146 +#define GL_TEXTURE_FILTER4_SIZE_SGIS 0x8147 +typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights); +typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum target, GLenum filter, GLfloat *weights); +GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights); +#endif +#endif /* GL_SGIS_texture_filter4 */ + +#ifndef GL_SGIS_texture_lod +#define GL_SGIS_texture_lod 1 +#define GL_TEXTURE_MIN_LOD_SGIS 0x813A +#define GL_TEXTURE_MAX_LOD_SGIS 0x813B +#define GL_TEXTURE_BASE_LEVEL_SGIS 0x813C +#define GL_TEXTURE_MAX_LEVEL_SGIS 0x813D +#endif /* GL_SGIS_texture_lod */ + +#ifndef GL_SGIS_texture_select +#define GL_SGIS_texture_select 1 +#define GL_DUAL_ALPHA4_SGIS 0x8110 +#define GL_DUAL_ALPHA8_SGIS 0x8111 +#define GL_DUAL_ALPHA12_SGIS 0x8112 +#define GL_DUAL_ALPHA16_SGIS 0x8113 +#define GL_DUAL_LUMINANCE4_SGIS 0x8114 +#define GL_DUAL_LUMINANCE8_SGIS 0x8115 +#define GL_DUAL_LUMINANCE12_SGIS 0x8116 +#define GL_DUAL_LUMINANCE16_SGIS 0x8117 +#define GL_DUAL_INTENSITY4_SGIS 0x8118 +#define GL_DUAL_INTENSITY8_SGIS 0x8119 +#define GL_DUAL_INTENSITY12_SGIS 0x811A +#define GL_DUAL_INTENSITY16_SGIS 0x811B +#define GL_DUAL_LUMINANCE_ALPHA4_SGIS 0x811C +#define GL_DUAL_LUMINANCE_ALPHA8_SGIS 0x811D +#define GL_QUAD_ALPHA4_SGIS 0x811E +#define GL_QUAD_ALPHA8_SGIS 0x811F +#define GL_QUAD_LUMINANCE4_SGIS 0x8120 +#define GL_QUAD_LUMINANCE8_SGIS 0x8121 +#define GL_QUAD_INTENSITY4_SGIS 0x8122 +#define GL_QUAD_INTENSITY8_SGIS 0x8123 +#define GL_DUAL_TEXTURE_SELECT_SGIS 0x8124 +#define GL_QUAD_TEXTURE_SELECT_SGIS 0x8125 +#endif /* GL_SGIS_texture_select */ + +#ifndef GL_SGIX_async +#define GL_SGIX_async 1 +#define GL_ASYNC_MARKER_SGIX 0x8329 +typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker); +typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp); +typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp); +typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range); +typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range); +typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint marker); +GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *markerp); +GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *markerp); +GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei range); +GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint marker, GLsizei range); +GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint marker); +#endif +#endif /* GL_SGIX_async */ + +#ifndef GL_SGIX_async_histogram +#define GL_SGIX_async_histogram 1 +#define GL_ASYNC_HISTOGRAM_SGIX 0x832C +#define GL_MAX_ASYNC_HISTOGRAM_SGIX 0x832D +#endif /* GL_SGIX_async_histogram */ + +#ifndef GL_SGIX_async_pixel +#define GL_SGIX_async_pixel 1 +#define GL_ASYNC_TEX_IMAGE_SGIX 0x835C +#define GL_ASYNC_DRAW_PIXELS_SGIX 0x835D +#define GL_ASYNC_READ_PIXELS_SGIX 0x835E +#define GL_MAX_ASYNC_TEX_IMAGE_SGIX 0x835F +#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX 0x8360 +#define GL_MAX_ASYNC_READ_PIXELS_SGIX 0x8361 +#endif /* GL_SGIX_async_pixel */ + +#ifndef GL_SGIX_blend_alpha_minmax +#define GL_SGIX_blend_alpha_minmax 1 +#define GL_ALPHA_MIN_SGIX 0x8320 +#define GL_ALPHA_MAX_SGIX 0x8321 +#endif /* GL_SGIX_blend_alpha_minmax */ + +#ifndef GL_SGIX_calligraphic_fragment +#define GL_SGIX_calligraphic_fragment 1 +#define GL_CALLIGRAPHIC_FRAGMENT_SGIX 0x8183 +#endif /* GL_SGIX_calligraphic_fragment */ + +#ifndef GL_SGIX_clipmap +#define GL_SGIX_clipmap 1 +#define GL_LINEAR_CLIPMAP_LINEAR_SGIX 0x8170 +#define GL_TEXTURE_CLIPMAP_CENTER_SGIX 0x8171 +#define GL_TEXTURE_CLIPMAP_FRAME_SGIX 0x8172 +#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX 0x8173 +#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174 +#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175 +#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX 0x8176 +#define GL_MAX_CLIPMAP_DEPTH_SGIX 0x8177 +#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178 +#define GL_NEAREST_CLIPMAP_NEAREST_SGIX 0x844D +#define GL_NEAREST_CLIPMAP_LINEAR_SGIX 0x844E +#define GL_LINEAR_CLIPMAP_NEAREST_SGIX 0x844F +#endif /* GL_SGIX_clipmap */ + +#ifndef GL_SGIX_convolution_accuracy +#define GL_SGIX_convolution_accuracy 1 +#define GL_CONVOLUTION_HINT_SGIX 0x8316 +#endif /* GL_SGIX_convolution_accuracy */ + +#ifndef GL_SGIX_depth_pass_instrument +#define GL_SGIX_depth_pass_instrument 1 +#endif /* GL_SGIX_depth_pass_instrument */ + +#ifndef GL_SGIX_depth_texture +#define GL_SGIX_depth_texture 1 +#define GL_DEPTH_COMPONENT16_SGIX 0x81A5 +#define GL_DEPTH_COMPONENT24_SGIX 0x81A6 +#define GL_DEPTH_COMPONENT32_SGIX 0x81A7 +#endif /* GL_SGIX_depth_texture */ + +#ifndef GL_SGIX_flush_raster +#define GL_SGIX_flush_raster 1 +typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFlushRasterSGIX (void); +#endif +#endif /* GL_SGIX_flush_raster */ + +#ifndef GL_SGIX_fog_offset +#define GL_SGIX_fog_offset 1 +#define GL_FOG_OFFSET_SGIX 0x8198 +#define GL_FOG_OFFSET_VALUE_SGIX 0x8199 +#endif /* GL_SGIX_fog_offset */ + +#ifndef GL_SGIX_fragment_lighting +#define GL_SGIX_fragment_lighting 1 +#define GL_FRAGMENT_LIGHTING_SGIX 0x8400 +#define GL_FRAGMENT_COLOR_MATERIAL_SGIX 0x8401 +#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402 +#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403 +#define GL_MAX_FRAGMENT_LIGHTS_SGIX 0x8404 +#define GL_MAX_ACTIVE_LIGHTS_SGIX 0x8405 +#define GL_CURRENT_RASTER_NORMAL_SGIX 0x8406 +#define GL_LIGHT_ENV_MODE_SGIX 0x8407 +#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408 +#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409 +#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A +#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B +#define GL_FRAGMENT_LIGHT0_SGIX 0x840C +#define GL_FRAGMENT_LIGHT1_SGIX 0x840D +#define GL_FRAGMENT_LIGHT2_SGIX 0x840E +#define GL_FRAGMENT_LIGHT3_SGIX 0x840F +#define GL_FRAGMENT_LIGHT4_SGIX 0x8410 +#define GL_FRAGMENT_LIGHT5_SGIX 0x8411 +#define GL_FRAGMENT_LIGHT6_SGIX 0x8412 +#define GL_FRAGMENT_LIGHT7_SGIX 0x8413 +typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum face, GLenum mode); +GLAPI void APIENTRY glFragmentLightfSGIX (GLenum light, GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum light, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentLightiSGIX (GLenum light, GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentLightivSGIX (GLenum light, GLenum pname, const GLint *params); +GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum pname, const GLint *params); +GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum face, GLenum pname, GLfloat param); +GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum face, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum face, GLenum pname, GLint param); +GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum face, GLenum pname, const GLint *params); +GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum light, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum light, GLenum pname, GLint *params); +GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum face, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum face, GLenum pname, GLint *params); +GLAPI void APIENTRY glLightEnviSGIX (GLenum pname, GLint param); +#endif +#endif /* GL_SGIX_fragment_lighting */ + +#ifndef GL_SGIX_framezoom +#define GL_SGIX_framezoom 1 +#define GL_FRAMEZOOM_SGIX 0x818B +#define GL_FRAMEZOOM_FACTOR_SGIX 0x818C +#define GL_MAX_FRAMEZOOM_FACTOR_SGIX 0x818D +typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFrameZoomSGIX (GLint factor); +#endif +#endif /* GL_SGIX_framezoom */ + +#ifndef GL_SGIX_igloo_interface +#define GL_SGIX_igloo_interface 1 +typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const void *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum pname, const void *params); +#endif +#endif /* GL_SGIX_igloo_interface */ + +#ifndef GL_SGIX_instruments +#define GL_SGIX_instruments 1 +#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180 +#define GL_INSTRUMENT_MEASUREMENTS_SGIX 0x8181 +typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void); +typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer); +typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p); +typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker); +typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void); +typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI GLint APIENTRY glGetInstrumentsSGIX (void); +GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei size, GLint *buffer); +GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *marker_p); +GLAPI void APIENTRY glReadInstrumentsSGIX (GLint marker); +GLAPI void APIENTRY glStartInstrumentsSGIX (void); +GLAPI void APIENTRY glStopInstrumentsSGIX (GLint marker); +#endif +#endif /* GL_SGIX_instruments */ + +#ifndef GL_SGIX_interlace +#define GL_SGIX_interlace 1 +#define GL_INTERLACE_SGIX 0x8094 +#endif /* GL_SGIX_interlace */ + +#ifndef GL_SGIX_ir_instrument1 +#define GL_SGIX_ir_instrument1 1 +#define GL_IR_INSTRUMENT1_SGIX 0x817F +#endif /* GL_SGIX_ir_instrument1 */ + +#ifndef GL_SGIX_list_priority +#define GL_SGIX_list_priority 1 +#define GL_LIST_PRIORITY_SGIX 0x8182 +typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params); +typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint list, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetListParameterivSGIX (GLuint list, GLenum pname, GLint *params); +GLAPI void APIENTRY glListParameterfSGIX (GLuint list, GLenum pname, GLfloat param); +GLAPI void APIENTRY glListParameterfvSGIX (GLuint list, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glListParameteriSGIX (GLuint list, GLenum pname, GLint param); +GLAPI void APIENTRY glListParameterivSGIX (GLuint list, GLenum pname, const GLint *params); +#endif +#endif /* GL_SGIX_list_priority */ + +#ifndef GL_SGIX_pixel_texture +#define GL_SGIX_pixel_texture 1 +#define GL_PIXEL_TEX_GEN_SGIX 0x8139 +#define GL_PIXEL_TEX_GEN_MODE_SGIX 0x832B +typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glPixelTexGenSGIX (GLenum mode); +#endif +#endif /* GL_SGIX_pixel_texture */ + +#ifndef GL_SGIX_pixel_tiles +#define GL_SGIX_pixel_tiles 1 +#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E +#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F +#define GL_PIXEL_TILE_WIDTH_SGIX 0x8140 +#define GL_PIXEL_TILE_HEIGHT_SGIX 0x8141 +#define GL_PIXEL_TILE_GRID_WIDTH_SGIX 0x8142 +#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX 0x8143 +#define GL_PIXEL_TILE_GRID_DEPTH_SGIX 0x8144 +#define GL_PIXEL_TILE_CACHE_SIZE_SGIX 0x8145 +#endif /* GL_SGIX_pixel_tiles */ + +#ifndef GL_SGIX_polynomial_ffd +#define GL_SGIX_polynomial_ffd 1 +#define GL_TEXTURE_DEFORMATION_BIT_SGIX 0x00000001 +#define GL_GEOMETRY_DEFORMATION_BIT_SGIX 0x00000002 +#define GL_GEOMETRY_DEFORMATION_SGIX 0x8194 +#define GL_TEXTURE_DEFORMATION_SGIX 0x8195 +#define GL_DEFORMATIONS_MASK_SGIX 0x8196 +#define GL_MAX_DEFORMATION_ORDER_SGIX 0x8197 +typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points); +typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points); +typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask); +typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points); +GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points); +GLAPI void APIENTRY glDeformSGIX (GLbitfield mask); +GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield mask); +#endif +#endif /* GL_SGIX_polynomial_ffd */ + +#ifndef GL_SGIX_reference_plane +#define GL_SGIX_reference_plane 1 +#define GL_REFERENCE_PLANE_SGIX 0x817D +#define GL_REFERENCE_PLANE_EQUATION_SGIX 0x817E +typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *equation); +#endif +#endif /* GL_SGIX_reference_plane */ + +#ifndef GL_SGIX_resample +#define GL_SGIX_resample 1 +#define GL_PACK_RESAMPLE_SGIX 0x842C +#define GL_UNPACK_RESAMPLE_SGIX 0x842D +#define GL_RESAMPLE_REPLICATE_SGIX 0x842E +#define GL_RESAMPLE_ZERO_FILL_SGIX 0x842F +#define GL_RESAMPLE_DECIMATE_SGIX 0x8430 +#endif /* GL_SGIX_resample */ + +#ifndef GL_SGIX_scalebias_hint +#define GL_SGIX_scalebias_hint 1 +#define GL_SCALEBIAS_HINT_SGIX 0x8322 +#endif /* GL_SGIX_scalebias_hint */ + +#ifndef GL_SGIX_shadow +#define GL_SGIX_shadow 1 +#define GL_TEXTURE_COMPARE_SGIX 0x819A +#define GL_TEXTURE_COMPARE_OPERATOR_SGIX 0x819B +#define GL_TEXTURE_LEQUAL_R_SGIX 0x819C +#define GL_TEXTURE_GEQUAL_R_SGIX 0x819D +#endif /* GL_SGIX_shadow */ + +#ifndef GL_SGIX_shadow_ambient +#define GL_SGIX_shadow_ambient 1 +#define GL_SHADOW_AMBIENT_SGIX 0x80BF +#endif /* GL_SGIX_shadow_ambient */ + +#ifndef GL_SGIX_sprite +#define GL_SGIX_sprite 1 +#define GL_SPRITE_SGIX 0x8148 +#define GL_SPRITE_MODE_SGIX 0x8149 +#define GL_SPRITE_AXIS_SGIX 0x814A +#define GL_SPRITE_TRANSLATION_SGIX 0x814B +#define GL_SPRITE_AXIAL_SGIX 0x814C +#define GL_SPRITE_OBJECT_ALIGNED_SGIX 0x814D +#define GL_SPRITE_EYE_ALIGNED_SGIX 0x814E +typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param); +typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum pname, GLfloat param); +GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum pname, GLint param); +GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum pname, const GLint *params); +#endif +#endif /* GL_SGIX_sprite */ + +#ifndef GL_SGIX_subsample +#define GL_SGIX_subsample 1 +#define GL_PACK_SUBSAMPLE_RATE_SGIX 0x85A0 +#define GL_UNPACK_SUBSAMPLE_RATE_SGIX 0x85A1 +#define GL_PIXEL_SUBSAMPLE_4444_SGIX 0x85A2 +#define GL_PIXEL_SUBSAMPLE_2424_SGIX 0x85A3 +#define GL_PIXEL_SUBSAMPLE_4242_SGIX 0x85A4 +#endif /* GL_SGIX_subsample */ + +#ifndef GL_SGIX_tag_sample_buffer +#define GL_SGIX_tag_sample_buffer 1 +typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glTagSampleBufferSGIX (void); +#endif +#endif /* GL_SGIX_tag_sample_buffer */ + +#ifndef GL_SGIX_texture_add_env +#define GL_SGIX_texture_add_env 1 +#define GL_TEXTURE_ENV_BIAS_SGIX 0x80BE +#endif /* GL_SGIX_texture_add_env */ + +#ifndef GL_SGIX_texture_coordinate_clamp +#define GL_SGIX_texture_coordinate_clamp 1 +#define GL_TEXTURE_MAX_CLAMP_S_SGIX 0x8369 +#define GL_TEXTURE_MAX_CLAMP_T_SGIX 0x836A +#define GL_TEXTURE_MAX_CLAMP_R_SGIX 0x836B +#endif /* GL_SGIX_texture_coordinate_clamp */ + +#ifndef GL_SGIX_texture_lod_bias +#define GL_SGIX_texture_lod_bias 1 +#define GL_TEXTURE_LOD_BIAS_S_SGIX 0x818E +#define GL_TEXTURE_LOD_BIAS_T_SGIX 0x818F +#define GL_TEXTURE_LOD_BIAS_R_SGIX 0x8190 +#endif /* GL_SGIX_texture_lod_bias */ + +#ifndef GL_SGIX_texture_multi_buffer +#define GL_SGIX_texture_multi_buffer 1 +#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E +#endif /* GL_SGIX_texture_multi_buffer */ + +#ifndef GL_SGIX_texture_scale_bias +#define GL_SGIX_texture_scale_bias 1 +#define GL_POST_TEXTURE_FILTER_BIAS_SGIX 0x8179 +#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A +#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B +#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C +#endif /* GL_SGIX_texture_scale_bias */ + +#ifndef GL_SGIX_vertex_preclip +#define GL_SGIX_vertex_preclip 1 +#define GL_VERTEX_PRECLIP_SGIX 0x83EE +#define GL_VERTEX_PRECLIP_HINT_SGIX 0x83EF +#endif /* GL_SGIX_vertex_preclip */ + +#ifndef GL_SGIX_ycrcb +#define GL_SGIX_ycrcb 1 +#define GL_YCRCB_422_SGIX 0x81BB +#define GL_YCRCB_444_SGIX 0x81BC +#endif /* GL_SGIX_ycrcb */ + +#ifndef GL_SGIX_ycrcb_subsample +#define GL_SGIX_ycrcb_subsample 1 +#endif /* GL_SGIX_ycrcb_subsample */ + +#ifndef GL_SGIX_ycrcba +#define GL_SGIX_ycrcba 1 +#define GL_YCRCB_SGIX 0x8318 +#define GL_YCRCBA_SGIX 0x8319 +#endif /* GL_SGIX_ycrcba */ + +#ifndef GL_SGI_color_matrix +#define GL_SGI_color_matrix 1 +#define GL_COLOR_MATRIX_SGI 0x80B1 +#define GL_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B2 +#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3 +#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4 +#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5 +#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6 +#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7 +#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8 +#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9 +#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA +#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB +#endif /* GL_SGI_color_matrix */ + +#ifndef GL_SGI_color_table +#define GL_SGI_color_table 1 +#define GL_COLOR_TABLE_SGI 0x80D0 +#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1 +#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2 +#define GL_PROXY_COLOR_TABLE_SGI 0x80D3 +#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4 +#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5 +#define GL_COLOR_TABLE_SCALE_SGI 0x80D6 +#define GL_COLOR_TABLE_BIAS_SGI 0x80D7 +#define GL_COLOR_TABLE_FORMAT_SGI 0x80D8 +#define GL_COLOR_TABLE_WIDTH_SGI 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE_SGI 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE_SGI 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE_SGI 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE_SGI 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF +typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params); +typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params); +typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, void *table); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params); +typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColorTableSGI (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const void *table); +GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum target, GLenum pname, const GLfloat *params); +GLAPI void APIENTRY glColorTableParameterivSGI (GLenum target, GLenum pname, const GLint *params); +GLAPI void APIENTRY glCopyColorTableSGI (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width); +GLAPI void APIENTRY glGetColorTableSGI (GLenum target, GLenum format, GLenum type, void *table); +GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum target, GLenum pname, GLfloat *params); +GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum target, GLenum pname, GLint *params); +#endif +#endif /* GL_SGI_color_table */ + +#ifndef GL_SGI_texture_color_table +#define GL_SGI_texture_color_table 1 +#define GL_TEXTURE_COLOR_TABLE_SGI 0x80BC +#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI 0x80BD +#endif /* GL_SGI_texture_color_table */ + +#ifndef GL_SUNX_constant_data +#define GL_SUNX_constant_data 1 +#define GL_UNPACK_CONSTANT_DATA_SUNX 0x81D5 +#define GL_TEXTURE_CONSTANT_DATA_SUNX 0x81D6 +typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glFinishTextureSUNX (void); +#endif +#endif /* GL_SUNX_constant_data */ + +#ifndef GL_SUN_convolution_border_modes +#define GL_SUN_convolution_border_modes 1 +#define GL_WRAP_BORDER_SUN 0x81D4 +#endif /* GL_SUN_convolution_border_modes */ + +#ifndef GL_SUN_global_alpha +#define GL_SUN_global_alpha 1 +#define GL_GLOBAL_ALPHA_SUN 0x81D9 +#define GL_GLOBAL_ALPHA_FACTOR_SUN 0x81DA +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor); +typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte factor); +GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort factor); +GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint factor); +GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat factor); +GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble factor); +GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte factor); +GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort factor); +GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint factor); +#endif +#endif /* GL_SUN_global_alpha */ + +#ifndef GL_SUN_mesh_array +#define GL_SUN_mesh_array 1 +#define GL_QUAD_MESH_SUN 0x8614 +#define GL_TRIANGLE_MESH_SUN 0x8615 +typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum mode, GLint first, GLsizei count, GLsizei width); +#endif +#endif /* GL_SUN_mesh_array */ + +#ifndef GL_SUN_slice_accum +#define GL_SUN_slice_accum 1 +#define GL_SLICE_ACCUM_SUN 0x85CC +#endif /* GL_SUN_slice_accum */ + +#ifndef GL_SUN_triangle_list +#define GL_SUN_triangle_list 1 +#define GL_RESTART_SUN 0x0001 +#define GL_REPLACE_MIDDLE_SUN 0x0002 +#define GL_REPLACE_OLDEST_SUN 0x0003 +#define GL_TRIANGLE_LIST_SUN 0x81D7 +#define GL_REPLACEMENT_CODE_SUN 0x81D8 +#define GL_REPLACEMENT_CODE_ARRAY_SUN 0x85C0 +#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1 +#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2 +#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3 +#define GL_R1UI_V3F_SUN 0x85C4 +#define GL_R1UI_C4UB_V3F_SUN 0x85C5 +#define GL_R1UI_C3F_V3F_SUN 0x85C6 +#define GL_R1UI_N3F_V3F_SUN 0x85C7 +#define GL_R1UI_C4F_N3F_V3F_SUN 0x85C8 +#define GL_R1UI_T2F_V3F_SUN 0x85C9 +#define GL_R1UI_T2F_N3F_V3F_SUN 0x85CA +#define GL_R1UI_T2F_C4F_N3F_V3F_SUN 0x85CB +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const void **pointer); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint code); +GLAPI void APIENTRY glReplacementCodeusSUN (GLushort code); +GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte code); +GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *code); +GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *code); +GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *code); +GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum type, GLsizei stride, const void **pointer); +#endif +#endif /* GL_SUN_triangle_list */ + +#ifndef GL_SUN_vertex +#define GL_SUN_vertex 1 +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +#ifdef GL_GLEXT_PROTOTYPES +GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y); +GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *tc, const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w); +GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint rc, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *rc, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *rc, const GLubyte *c, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z); +GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v); +#endif +#endif /* GL_SUN_vertex */ + +#ifndef GL_WIN_phong_shading +#define GL_WIN_phong_shading 1 +#define GL_PHONG_WIN 0x80EA +#define GL_PHONG_HINT_WIN 0x80EB +#endif /* GL_WIN_phong_shading */ + +#ifndef GL_WIN_specular_fog +#define GL_WIN_specular_fog 1 +#define GL_FOG_SPECULAR_TEXTURE_WIN 0x80EC +#endif /* GL_WIN_specular_fog */ + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/codemp/rd-rend2/glsl/bokeh.glsl b/codemp/rd-rend2/glsl/bokeh.glsl new file mode 100644 index 0000000000..c2337c28be --- /dev/null +++ b/codemp/rd-rend2/glsl/bokeh.glsl @@ -0,0 +1,86 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec4 attr_TexCoord0; + +uniform mat4 u_ModelViewProjectionMatrix; + +out vec2 var_TexCoords; + +void main() +{ + gl_Position = u_ModelViewProjectionMatrix * vec4(attr_Position, 1.0); + var_TexCoords = attr_TexCoord0.st; +} + +/*[Fragment]*/ +uniform sampler2D u_TextureMap; +uniform vec4 u_Color; +uniform vec2 u_InvTexRes; + +in vec2 var_TexCoords; + +out vec4 out_Color; + +void main() +{ + vec4 color; + vec2 tc; + +#if 0 + float c[7] = float[7](1.0, 0.9659258263, 0.8660254038, 0.7071067812, 0.5, 0.2588190451, 0.0); + + tc = var_TexCoords + u_InvTexRes * vec2( c[0], c[6]); color = texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[1], c[5]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[2], c[4]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[3], c[3]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[4], c[2]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[5], c[1]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[6], c[0]); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2( c[1], -c[5]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[2], -c[4]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[3], -c[3]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[4], -c[2]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[5], -c[1]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[6], -c[0]); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2( -c[0], c[6]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[1], c[5]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[2], c[4]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[3], c[3]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[4], c[2]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[5], c[1]); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2( -c[1], -c[5]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[2], -c[4]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[3], -c[3]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[4], -c[2]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[5], -c[1]); color += texture(u_TextureMap, tc); + + out_Color = color * 0.04166667 * u_Color; +#endif + + float c[5] = float[5](1.0, 0.9238795325, 0.7071067812, 0.3826834324, 0.0); + + tc = var_TexCoords + u_InvTexRes * vec2( c[0], c[4]); color = texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[1], c[3]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[2], c[2]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[3], c[1]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[4], c[0]); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2( c[1], -c[3]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[2], -c[2]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[3], -c[1]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( c[4], -c[0]); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2( -c[0], c[4]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[1], c[3]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[2], c[2]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[3], c[1]); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2( -c[1], -c[3]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[2], -c[2]); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( -c[3], -c[1]); color += texture(u_TextureMap, tc); + + out_Color = color * 0.0625 * u_Color; +} diff --git a/codemp/rd-rend2/glsl/calclevels4x.glsl b/codemp/rd-rend2/glsl/calclevels4x.glsl new file mode 100644 index 0000000000..4c9252230e --- /dev/null +++ b/codemp/rd-rend2/glsl/calclevels4x.glsl @@ -0,0 +1,74 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec4 attr_TexCoord0; + +uniform mat4 u_ModelViewProjectionMatrix; + +out vec2 var_TexCoords; + +void main() +{ + gl_Position = u_ModelViewProjectionMatrix * vec4(attr_Position, 1.0); + var_TexCoords = attr_TexCoord0.st; +} + +/*[Fragment]*/ +uniform sampler2D u_TextureMap; +uniform vec4 u_Color; +uniform vec2 u_InvTexRes; + +in vec2 var_TexCoords; + +out vec4 out_Color; + +const vec3 LUMINANCE_VECTOR = vec3(0.299, 0.587, 0.114); + +vec3 GetValues(vec2 offset, vec3 current) +{ + vec2 tc = var_TexCoords + u_InvTexRes * offset; + vec3 minAvgMax = texture(u_TextureMap, tc).rgb; + +#ifdef FIRST_PASS + float lumi = max(dot(LUMINANCE_VECTOR, minAvgMax), 0.000001); + float loglumi = clamp(log2(lumi), -10.0, 10.0); + minAvgMax = vec3(loglumi * 0.05 + 0.5); +#endif + + return vec3( + min(current.x, minAvgMax.x), + current.y + minAvgMax.y, + max(current.z, minAvgMax.z)); +} + +void main() +{ + vec3 current = vec3(1.0, 0.0, 0.0); + +#ifdef FIRST_PASS + current = GetValues(vec2( 0.0, 0.0), current); +#else + current = GetValues(vec2(-1.5, -1.5), current); + current = GetValues(vec2(-0.5, -1.5), current); + current = GetValues(vec2( 0.5, -1.5), current); + current = GetValues(vec2( 1.5, -1.5), current); + + current = GetValues(vec2(-1.5, -0.5), current); + current = GetValues(vec2(-0.5, -0.5), current); + current = GetValues(vec2( 0.5, -0.5), current); + current = GetValues(vec2( 1.5, -0.5), current); + + current = GetValues(vec2(-1.5, 0.5), current); + current = GetValues(vec2(-0.5, 0.5), current); + current = GetValues(vec2( 0.5, 0.5), current); + current = GetValues(vec2( 1.5, 0.5), current); + + current = GetValues(vec2(-1.5, 1.5), current); + current = GetValues(vec2(-0.5, 1.5), current); + current = GetValues(vec2( 0.5, 1.5), current); + current = GetValues(vec2( 1.5, 1.5), current); + + current.y *= 0.0625; +#endif + + out_Color = vec4(current, 1.0f); +} diff --git a/codemp/rd-rend2/glsl/compact.cpp b/codemp/rd-rend2/glsl/compact.cpp new file mode 100644 index 0000000000..89bd5252c6 --- /dev/null +++ b/codemp/rd-rend2/glsl/compact.cpp @@ -0,0 +1,221 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tr_local.h" +#include "tr_allocator.h" + +namespace +{ + +using StringList = std::vector; + +bool ShouldEscape( char c ) +{ + switch ( c ) + { + case '\\': + case '"': + return true; + default: + return false; + } +} + +std::string& Escape( std::string& s ) +{ + std::string::difference_type escapableCharacters = std::count_if( s.begin(), s.end(), ShouldEscape ); + if ( escapableCharacters == 0 ) + { + return s; + } + + if ( s.capacity() < (s.length() + escapableCharacters) ) + { + // Grow if necessary. + s.resize(s.length() + escapableCharacters); + } + + std::string::iterator it = s.begin(); + while ( it != s.end() ) + { + char c = *it; + if ( ShouldEscape(c) ) + { + it = s.insert(it, '\\'); + it += 2; + } + else + { + ++it; + } + } + + return s; +} + +bool EndsWith( const std::string& s, const std::string& suffix ) +{ + return s.compare(s.length() - suffix.length(), suffix.length(), suffix) == 0; +} + +const char *GetShaderSuffix( GPUShaderType type ) +{ + switch ( type ) + { + case GPUSHADER_VERTEX: return "_vp"; + case GPUSHADER_FRAGMENT: return "_fp"; + case GPUSHADER_GEOMETRY: return "_gp"; + default: assert(!"Invalid shader type"); + } + return nullptr; +} + +const char *ToString( GPUShaderType type ) +{ + switch ( type ) + { + case GPUSHADER_VERTEX: return "GPUSHADER_VERTEX"; + case GPUSHADER_FRAGMENT: return "GPUSHADER_FRAGMENT"; + case GPUSHADER_GEOMETRY: return "GPUSHADER_GEOMETRY"; + default: assert(!"Invalid shader type"); + } + return nullptr; +} + +} // anonymous namespace + +int main( int argc, char *argv[] ) +{ + StringList args(argv, argv + argc); + + if ( args.empty() ) + { + std::cerr << "No GLSL files were given.\n"; + return EXIT_FAILURE; + } + + if ( args.size() < 4 ) + { + // 0 = exe, 1 = cpp file, 2 = h file, 2+ = glsl files + return EXIT_FAILURE; + } + + std::string& shadersCppFile = args[1]; + std::string& shadersHeaderFile = args[2]; + StringList glslFiles(args.begin() + 3, args.end()); + + std::cout << "Outputting to '" << shadersCppFile << "' and '" << shadersHeaderFile << "'\n"; + + Allocator allocator(512 * 1024); + + std::ostringstream cppStream; + std::ostringstream headerStream; + std::string line; + + headerStream << "// This file is auto-generated. DO NOT EDIT BY HAND\n"; + headerStream << "#pragma once\n\n"; + headerStream << "#include \"tr_local.h\"\n\n"; + + cppStream << "// This file is auto-generated. DO NOT EDIT BY HAND\n"; + cppStream << "#include \"tr_local.h\"\n\n"; + for ( StringList::const_iterator it = glslFiles.begin(); + it != glslFiles.end(); ++it ) + { + // Get shader name from file name + if ( !EndsWith(*it, ".glsl") ) + { + std::cerr << *it << " doesn't end with .glsl extension.\n"; + continue; + } + + std::string::size_type lastSlash = it->find_last_of("\\/"); + std::string shaderName(it->begin() + lastSlash + 1, it->end() - 5); + + // Write, one line at a time to the output + std::ifstream fs(it->c_str()); + if ( !fs ) + { + std::cerr << *it << " could not be opened.\n"; + continue; + } + + //from: https://stackoverflow.com/questions/22984956/tellg-function-give-wrong-size-of-file/22986486 + fs.ignore(std::numeric_limits::max()); + std::streamsize fileSize = fs.gcount(); + fs.clear(); // Since ignore will have set eof. + fs.seekg(0, std::ios::beg); + + allocator.Reset(); + + char *programText = ojkAllocString(allocator, fileSize); + memset(programText, 0, (size_t)fileSize + 1); + fs.read(programText, fileSize); + + GPUProgramDesc programDesc = ParseProgramSource(allocator, programText); + for ( size_t i = 0, numShaders = programDesc.numShaders; i < numShaders; ++i ) + { + GPUShaderDesc& shaderDesc = programDesc.shaders[i]; + const char *suffix = GetShaderSuffix(shaderDesc.type); + + cppStream << "const char *fallback_" + shaderName + suffix + " = \""; + + const char *lineStart = shaderDesc.source; + const char *lineEnd = strchr(lineStart, '\n'); + while ( lineEnd ) + { + line.assign(lineStart, lineEnd - lineStart); + cppStream << Escape(line); + cppStream << "\\n\"\n\""; + + lineStart = lineEnd + 1; + lineEnd = strchr(lineStart, '\n'); + } + + line.assign(lineStart); + cppStream << Escape(line) << "\";\n"; + } + + cppStream << "GPUShaderDesc fallback_" << shaderName << "Shaders[] = {\n"; + for ( size_t i = 0, numShaders = programDesc.numShaders; i < numShaders; ++i ) + { + GPUShaderDesc& shaderDesc = programDesc.shaders[i]; + const char *suffix = GetShaderSuffix(shaderDesc.type); + + cppStream << " { " << ToString(shaderDesc.type) << ", " + "fallback_" << shaderName << suffix << ", " + << shaderDesc.firstLineNumber << " },\n"; + } + cppStream << "};\n"; + + cppStream << "extern const GPUProgramDesc fallback_" << shaderName << "Program = { " + << programDesc.numShaders << ", fallback_" << shaderName << "Shaders };\n\n"; + + headerStream << "extern const GPUProgramDesc fallback_" << shaderName << "Program;\n"; + } + + std::ofstream cppFile(shadersCppFile); + if ( !cppFile ) + { + std::cerr << "Could not create file '" << shadersCppFile << "'\n"; + } + else + { + cppFile << cppStream.str(); + } + + std::ofstream headerFile(shadersHeaderFile); + if (!headerFile) + { + std::cerr << "Could not create file '" << shadersHeaderFile << "'\n"; + } + else + { + headerFile << headerStream.str(); + } +} diff --git a/codemp/rd-rend2/glsl/depthblur.glsl b/codemp/rd-rend2/glsl/depthblur.glsl new file mode 100644 index 0000000000..ab32f9c000 --- /dev/null +++ b/codemp/rd-rend2/glsl/depthblur.glsl @@ -0,0 +1,82 @@ +/*[Vertex]*/ +out vec2 var_ScreenTex; + +void main() +{ + const vec2 positions[] = vec2[3]( + vec2(-1.0f, 1.0f), + vec2(-1.0f, -3.0f), + vec2( 3.0f, 1.0f) + ); + + const vec2 texcoords[] = vec2[3]( + vec2( 0.0f, 1.0f), + vec2( 0.0f, -1.0f), + vec2( 2.0f, 1.0f) + ); + + gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0); + var_ScreenTex = texcoords[gl_VertexID]; +} + +/*[Fragment]*/ +uniform sampler2D u_ScreenImageMap; +uniform sampler2D u_ScreenDepthMap; +uniform vec4 u_ViewInfo; // zfar / znear, zfar + +in vec2 var_ScreenTex; + +out vec4 out_Color; + +float gauss[5] = float[5](0.30, 0.23, 0.097, 0.024, 0.0033); +//float gauss[4] = float[4](0.40, 0.24, 0.054, 0.0044); +//float gauss[3] = float[3](0.60, 0.19, 0.0066); +#define GAUSS_SIZE 5 + +float getLinearDepth(sampler2D depthMap, const vec2 tex, const float zFarDivZNear) +{ + float sampleZDivW = texture(depthMap, tex).r; + return 1.0 / mix(zFarDivZNear, 1.0, sampleZDivW); +} + +vec4 depthGaussian1D(sampler2D imageMap, sampler2D depthMap, vec2 tex, float zFarDivZNear, float zFar) +{ + float scale = 1.0 / 256.0; + +#if defined(USE_HORIZONTAL_BLUR) + vec2 direction = vec2(1.0, 0.0) * scale; +#else // if defined(USE_VERTICAL_BLUR) + vec2 direction = vec2(0.0, 1.0) * scale; +#endif + + float depthCenter = zFar * getLinearDepth(depthMap, tex, zFarDivZNear); + vec2 centerSlope = vec2(dFdx(depthCenter), dFdy(depthCenter)) / vec2(dFdx(tex.x), dFdy(tex.y)); + + vec4 result = texture(imageMap, tex) * gauss[0]; + float total = gauss[0]; + + int i, j; + for (i = 0; i < 2; i++) + { + for (j = 1; j < GAUSS_SIZE; j++) + { + vec2 offset = direction * j; + float depthSample = zFar * getLinearDepth(depthMap, tex + offset, zFarDivZNear); + float depthExpected = depthCenter + dot(centerSlope, offset); + if(abs(depthSample - depthExpected) < 5.0) + { + result += texture(imageMap, tex + offset) * gauss[j]; + total += gauss[j]; + } + } + + direction = -direction; + } + + return result / total; +} + +void main() +{ + out_Color = depthGaussian1D(u_ScreenImageMap, u_ScreenDepthMap, var_ScreenTex, u_ViewInfo.x, u_ViewInfo.y); +} diff --git a/codemp/rd-rend2/glsl/dglow_downsample.glsl b/codemp/rd-rend2/glsl/dglow_downsample.glsl new file mode 100644 index 0000000000..e68b019605 --- /dev/null +++ b/codemp/rd-rend2/glsl/dglow_downsample.glsl @@ -0,0 +1,50 @@ +/*[Vertex]*/ +out vec2 var_TexCoords; + +void main() +{ + const vec2 positions[] = vec2[3]( + vec2(-1.0f, -1.0f), + vec2(-1.0f, 3.0f), + vec2( 3.0f, -1.0f) + ); + + const vec2 texcoords[] = vec2[3]( + vec2( 0.0f, 1.0f), + vec2( 0.0f, -1.0f), + vec2( 2.0f, 1.0f) + ); + + gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0); + var_TexCoords = texcoords[gl_VertexID]; +} + +/*[Fragment]*/ +uniform sampler2D u_TextureMap; +uniform vec2 u_InvTexRes; + +in vec2 var_TexCoords; + +out vec4 out_Color; + +void main() +{ + // Based on "Next Generation Post Processing in Call of Duty: Advanced Warfare": + // http://advances.realtimerendering.com/s2014/index.html + vec4 color = vec4(0.0); + color += 0.25 * 0.125 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2(-2.0, -2.0))); + color += 0.5 * 0.25 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2( 0.0, -2.0))); + color += 0.25 * 0.125 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2( 2.0, -2.0))); + color += 0.25 * 0.5 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2(-1.0, -1.0))); + color += 0.25 * 0.5 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2( 1.0, -1.0))); + color += 0.25 * 0.125 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2(-2.0, 0.0))); + color += 0.125 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2( 0.0, 0.0))); + color += 0.25 * 0.125 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2( 2.0, -2.0))); + color += 0.25 * 0.5 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2(-1.0, 1.0))); + color += 0.25 * 0.5 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2( 1.0, 1.0))); + color += 0.25 * 0.125 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2(-2.0, 2.0))); + color += 0.5 * 0.25 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2( 0.0, 2.0))); + color += 0.25 * 0.125 * texture(u_TextureMap, var_TexCoords + (u_InvTexRes * vec2( 2.0, 2.0))); + + out_Color = color; +} \ No newline at end of file diff --git a/codemp/rd-rend2/glsl/dglow_upsample.glsl b/codemp/rd-rend2/glsl/dglow_upsample.glsl new file mode 100644 index 0000000000..3cb3e1d79a --- /dev/null +++ b/codemp/rd-rend2/glsl/dglow_upsample.glsl @@ -0,0 +1,46 @@ +/*[Vertex]*/ +out vec2 var_TexCoords; + +void main() +{ + const vec2 positions[] = vec2[3]( + vec2(-1.0f, -1.0f), + vec2(-1.0f, 3.0f), + vec2( 3.0f, -1.0f) + ); + + const vec2 texcoords[] = vec2[3]( + vec2( 0.0f, 1.0f), + vec2( 0.0f, -1.0f), + vec2( 2.0f, 1.0f) + ); + + gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0); + var_TexCoords = texcoords[gl_VertexID]; +} + +/*[Fragment]*/ +uniform sampler2D u_TextureMap; +uniform vec2 u_InvTexRes; + +in vec2 var_TexCoords; + +out vec4 out_Color; + +void main() +{ + // Based on "Next Generation Post Processing in Call of Duty: Advanced Warfare": + // http://advances.realtimerendering.com/s2014/index.html + vec4 color = vec4(0.0); + color += 0.0625 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2(-1.0, -1.0)); + color += 0.125 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2( 0.0, -1.0)); + color += 0.0625 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2( 1.0, -1.0)); + color += 0.125 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2(-1.0, 0.0)); + color += 0.25 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2( 0.0, 0.0)); + color += 0.125 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2( 1.0, 0.0)); + color += 0.0625 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2(-1.0, 1.0)); + color += 0.125 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2( 0.0, 1.0)); + color += 0.0625 * texture(u_TextureMap, var_TexCoords + u_InvTexRes * vec2( 1.0, 1.0)); + + out_Color = color; +} \ No newline at end of file diff --git a/codemp/rd-rend2/glsl/down4x.glsl b/codemp/rd-rend2/glsl/down4x.glsl new file mode 100644 index 0000000000..7034cb81e9 --- /dev/null +++ b/codemp/rd-rend2/glsl/down4x.glsl @@ -0,0 +1,52 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec4 attr_TexCoord0; + +uniform mat4 u_ModelViewProjectionMatrix; + +out vec2 var_TexCoords; + + +void main() +{ + gl_Position = u_ModelViewProjectionMatrix * vec4(attr_Position, 1.0); + var_TexCoords = attr_TexCoord0.st; +} + +/*[Fragment]*/ +uniform sampler2D u_TextureMap; +uniform vec2 u_InvTexRes; + +in vec2 var_TexCoords; + +out vec4 out_Color; + +void main() +{ + vec4 color; + vec2 tc; + + tc = var_TexCoords + u_InvTexRes * vec2(-1.5, -1.5); color = texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2(-0.5, -1.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( 0.5, -1.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( 1.5, -1.5); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2(-1.5, -0.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2(-0.5, -0.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( 0.5, -0.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( 1.5, -0.5); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2(-1.5, 0.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2(-0.5, 0.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( 0.5, 0.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( 1.5, 0.5); color += texture(u_TextureMap, tc); + + tc = var_TexCoords + u_InvTexRes * vec2(-1.5, 1.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2(-0.5, 1.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( 0.5, 1.5); color += texture(u_TextureMap, tc); + tc = var_TexCoords + u_InvTexRes * vec2( 1.5, 1.5); color += texture(u_TextureMap, tc); + + color *= 0.0625; + + out_Color = color; +} diff --git a/codemp/rd-rend2/glsl/fogpass.glsl b/codemp/rd-rend2/glsl/fogpass.glsl new file mode 100644 index 0000000000..57dcf0ac87 --- /dev/null +++ b/codemp/rd-rend2/glsl/fogpass.glsl @@ -0,0 +1,378 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec3 attr_Normal; + +in vec2 attr_TexCoord0; + +#if defined(USE_VERTEX_ANIMATION) +in vec3 attr_Position2; +in vec3 attr_Normal2; +#elif defined(USE_SKELETAL_ANIMATION) +in uvec4 attr_BoneIndexes; +in vec4 attr_BoneWeights; +#endif + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; +}; + +layout(std140) uniform ShaderInstance +{ + vec4 u_DeformParams0; + vec4 u_DeformParams1; + float u_Time; + float u_PortalRange; + int u_DeformType; + int u_DeformFunc; +}; + +#if defined(USE_SKELETAL_ANIMATION) +layout(std140) uniform Bones +{ + mat3x4 u_BoneMatrices[MAX_G2_BONES]; +}; +#endif + +out vec3 var_WSPosition; +#if defined(USE_ALPHA_TEST) +out vec2 var_TexCoords; +#endif + +#if defined(USE_DEFORM_VERTEXES) +float GetNoiseValue( float x, float y, float z, float t ) +{ + // Variation on the 'one-liner random function'. + // Not sure if this is still 'correctly' random + return fract( sin( dot( + vec4( x, y, z, t ), + vec4( 12.9898, 78.233, 12.9898, 78.233 ) + )) * 43758.5453 ); +} + +float CalculateDeformScale( in int func, in float time, in float phase, in float frequency ) +{ + float value = phase + time * frequency; + + switch ( func ) + { + case WF_SIN: + return sin(value * 2.0 * M_PI); + case WF_SQUARE: + return sign(0.5 - fract(value)); + case WF_TRIANGLE: + return abs(fract(value + 0.75) - 0.5) * 4.0 - 1.0; + case WF_SAWTOOTH: + return fract(value); + case WF_INVERSE_SAWTOOTH: + return 1.0 - fract(value); + default: + return 0.0; + } +} + +vec3 DeformPosition(const vec3 pos, const vec3 normal, const vec2 st) +{ + switch ( u_DeformType ) + { + default: + { + return pos; + } + + case DEFORM_BULGE: + { + float bulgeHeight = u_DeformParams0.y; // amplitude + float bulgeWidth = u_DeformParams0.z; // phase + float bulgeSpeed = u_DeformParams0.w; // frequency + + float scale = CalculateDeformScale( WF_SIN, u_Time, bulgeWidth * st.x, bulgeSpeed ); + + return pos + normal * scale * bulgeHeight; + } + + case DEFORM_WAVE: + { + float base = u_DeformParams0.x; + float amplitude = u_DeformParams0.y; + float phase = u_DeformParams0.z; + float frequency = u_DeformParams0.w; + float spread = u_DeformParams1.x; + + float offset = dot( pos.xyz, vec3( spread ) ); + float scale = CalculateDeformScale( u_DeformFunc, u_Time, phase + offset, frequency ); + + return pos + normal * (base + scale * amplitude); + } + + case DEFORM_MOVE: + { + float base = u_DeformParams0.x; + float amplitude = u_DeformParams0.y; + float phase = u_DeformParams0.z; + float frequency = u_DeformParams0.w; + vec3 direction = u_DeformParams1.xyz; + + float scale = CalculateDeformScale( u_DeformFunc, u_Time, phase, frequency ); + + return pos + direction * (base + scale * amplitude); + } + + case DEFORM_PROJECTION_SHADOW: + { + vec3 ground = u_DeformParams0.xyz; + float groundDist = u_DeformParams0.w; + vec3 lightDir = u_DeformParams1.xyz; + + float d = dot( lightDir, ground ); + + lightDir = lightDir * max( 0.5 - d, 0.0 ) + ground; + d = 1.0 / dot( lightDir, ground ); + + vec3 lightPos = lightDir * d; + + return pos - lightPos * dot( pos, ground ) + groundDist; + } + } +} + +vec3 DeformNormal( const in vec3 position, const in vec3 normal ) +{ + if ( u_DeformType != DEFORM_NORMALS ) + { + return normal; + } + + float amplitude = u_DeformParams0.y; + float frequency = u_DeformParams0.w; + + vec3 outNormal = normal; + const float scale = 0.98; + + outNormal.x += amplitude * GetNoiseValue( + position.x * scale, + position.y * scale, + position.z * scale, + u_Time * frequency ); + + outNormal.y += amplitude * GetNoiseValue( + 100.0 * position.x * scale, + position.y * scale, + position.z * scale, + u_Time * frequency ); + + outNormal.z += amplitude * GetNoiseValue( + 200.0 * position.x * scale, + position.y * scale, + position.z * scale, + u_Time * frequency ); + + return outNormal; +} +#endif + +#if defined(USE_SKELETAL_ANIMATION) +mat4x3 GetBoneMatrix(uint index) +{ + mat3x4 bone = u_BoneMatrices[index]; + return mat4x3( + bone[0].x, bone[1].x, bone[2].x, + bone[0].y, bone[1].y, bone[2].y, + bone[0].z, bone[1].z, bone[2].z, + bone[0].w, bone[1].w, bone[2].w); +} +#endif + +void main() +{ +#if defined(USE_VERTEX_ANIMATION) + vec3 position = mix(attr_Position, attr_Position2, u_VertexLerp); + vec3 normal = mix(attr_Normal, attr_Normal2, u_VertexLerp); + normal = normalize(normal - vec3(0.5)); +#elif defined(USE_SKELETAL_ANIMATION) + mat4x3 influence = + GetBoneMatrix(attr_BoneIndexes[0]) * attr_BoneWeights[0] + + GetBoneMatrix(attr_BoneIndexes[1]) * attr_BoneWeights[1] + + GetBoneMatrix(attr_BoneIndexes[2]) * attr_BoneWeights[2] + + GetBoneMatrix(attr_BoneIndexes[3]) * attr_BoneWeights[3]; + + vec3 position = influence * vec4(attr_Position, 1.0); + vec3 normal = normalize(influence * vec4(attr_Normal - vec3(0.5), 0.0)); +#else + vec3 position = attr_Position; + vec3 normal = attr_Normal * 2.0 - vec3(1.0); +#endif + +#if defined(USE_DEFORM_VERTEXES) + position = DeformPosition(position, normal, attr_TexCoord0.st); + normal = DeformNormal( position, normal ); +#endif + + mat4 MVP = u_viewProjectionMatrix * u_ModelMatrix; + gl_Position = MVP * vec4(position, 1.0); + + var_WSPosition = (u_ModelMatrix * vec4(position, 1.0)).xyz; +#if defined(USE_ALPHA_TEST) + var_TexCoords = attr_TexCoord0; +#endif +} + +/*[Fragment]*/ +#if defined(USE_ALPHA_TEST) +uniform int u_AlphaTestType; +uniform sampler2D u_DiffuseMap; +#endif + +layout(std140) uniform Scene +{ + vec4 u_PrimaryLightOrigin; + vec3 u_PrimaryLightAmbient; + int u_globalFogIndex; + vec3 u_PrimaryLightColor; + float u_PrimaryLightRadius; + float u_frameTime; + float u_deltaTime; +}; + +struct Fog +{ + vec4 plane; + vec4 color; + float depthToOpaque; + bool hasPlane; +}; + +layout(std140) uniform Fogs +{ + int u_NumFogs; + Fog u_Fogs[16]; +}; + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; +}; + +uniform int u_FogIndex; + +in vec3 var_WSPosition; +#if defined(USE_ALPHA_TEST) +in vec2 var_TexCoords; +#endif + +out vec4 out_Color; +out vec4 out_Glow; + +vec4 CalcFog(in vec3 viewOrigin, in vec3 position, in Fog fog) +{ + bool inFog = dot(viewOrigin, fog.plane.xyz) - fog.plane.w >= 0.0 || !fog.hasPlane; + + // line: x = o + tv + // plane: (x . n) + d = 0 + // intersects: dot(o + tv, n) + d = 0 + // dot(o + tv, n) = -d + // dot(o, n) + t*dot(n, v) = -d + // t = -(d + dot(o, n)) / dot(n, v) + vec3 V = position - viewOrigin; + + // fogPlane is inverted in tr_bsp for some reason. + float t = -(fog.plane.w + dot(viewOrigin, -fog.plane.xyz)) / dot(V, -fog.plane.xyz); + + // only use this for objects with potentially two contibuting fogs + #if defined(USE_FALLBACK_GLOBAL_FOG) + bool intersects = (t > 0.0 && t < 0.995); + if (inFog == intersects) + { + Fog globalFog = u_Fogs[u_globalFogIndex]; + + float distToVertex = length(V); + float distFromIntersection = distToVertex - (t * distToVertex); + float z = globalFog.depthToOpaque * mix(distToVertex, distFromIntersection, intersects); + return vec4(globalFog.color.rgb, 1.0 - clamp(exp(-(z * z)), 0.0, 1.0)); + } + #else + bool intersects = (t > 0.0 && t < 0.995); + if (inFog == intersects) + return vec4(0.0); + #endif + + float distToVertexFromViewOrigin = length(V); + float distToIntersectionFromViewOrigin = t * distToVertexFromViewOrigin; + + float distOutsideFog = max(distToVertexFromViewOrigin - distToIntersectionFromViewOrigin, 0.0); + float distThroughFog = mix(distOutsideFog, distToVertexFromViewOrigin, inFog); + + float z = fog.depthToOpaque * distThroughFog; + return vec4(fog.color.rgb, 1.0 - clamp(exp(-(z * z)), 0.0, 1.0)); +} + +void main() +{ +#if defined(USE_ALPHA_TEST) + float alpha = texture(u_DiffuseMap, var_TexCoords).a; + if (u_AlphaTestType == ALPHA_TEST_GT0) + { + if (alpha == 0.0) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_LT128) + { + if (alpha >= 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE128) + { + if (alpha < 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE192) + { + if (alpha < 0.75) + discard; + } +#endif + Fog fog = u_Fogs[u_FogIndex]; + out_Color = CalcFog(u_ViewOrigin, var_WSPosition, fog); + +#if defined(USE_GLOW_BUFFER) + out_Glow = out_Color; +#else + out_Glow = vec4(0.0, 0.0, 0.0, out_Color.a); +#endif +} diff --git a/codemp/rd-rend2/glsl/gaussian_blur.glsl b/codemp/rd-rend2/glsl/gaussian_blur.glsl new file mode 100644 index 0000000000..e6593f56ce --- /dev/null +++ b/codemp/rd-rend2/glsl/gaussian_blur.glsl @@ -0,0 +1,74 @@ +/*[Vertex]*/ +out vec2 var_TexCoords; + +void main() +{ + const vec2 positions[4] = vec2[]( + vec2 (-1.0, -1.0), + vec2 (1.0, -1.0), + vec2 (1.0, 1.0), + vec2 (-1.0, 1.0) + ); + + const vec2 texcoords[4] = vec2[]( + vec2 (0.0, 0.0), + vec2 (1.0, 0.0), + vec2 (1.0, 1.0), + vec2 (0.0, 1.0) + ); + + gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0); + var_TexCoords = texcoords[gl_VertexID]; +} + +/*[Fragment]*/ +uniform sampler2D u_TextureMap; +uniform vec4 u_Color; +uniform vec2 u_InvTexRes; + +in vec2 var_TexCoords; + +out vec4 out_Color; + +#define NUM_TAPS 3 + +void main() +{ + vec4 color = vec4 (0.0); + +#if NUM_TAPS == 7 + const float weights[] = float[4](1.0 / 64.0, 6.0 / 64.0, 15.0 / 64.0, 20.0 / 64.0); + +#if defined(BLUR_X) + color += texture (u_TextureMap, vec2 (-3.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[0]; + color += texture (u_TextureMap, vec2 (-2.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[1]; + color += texture (u_TextureMap, vec2 (-1.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[2]; + color += texture (u_TextureMap, vec2 ( 0.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[3]; + color += texture (u_TextureMap, vec2 ( 1.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[2]; + color += texture (u_TextureMap, vec2 ( 2.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[1]; + color += texture (u_TextureMap, vec2 ( 3.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[0]; +#else + color += texture (u_TextureMap, vec2 (0.0, -3.0) * u_InvTexRes + var_TexCoords) * weights[0]; + color += texture (u_TextureMap, vec2 (0.0, -2.0) * u_InvTexRes + var_TexCoords) * weights[1]; + color += texture (u_TextureMap, vec2 (0.0, -1.0) * u_InvTexRes + var_TexCoords) * weights[2]; + color += texture (u_TextureMap, vec2 (0.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[3]; + color += texture (u_TextureMap, vec2 (0.0, 1.0) * u_InvTexRes + var_TexCoords) * weights[2]; + color += texture (u_TextureMap, vec2 (0.0, 2.0) * u_InvTexRes + var_TexCoords) * weights[1]; + color += texture (u_TextureMap, vec2 (0.0, 3.0) * u_InvTexRes + var_TexCoords) * weights[0]; +#endif +#elif NUM_TAPS == 3 + const float weights[] = float[2](0.25, 0.5); + +#if defined(BLUR_X) + color += texture (u_TextureMap, vec2 (-1.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[0]; + color += texture (u_TextureMap, vec2 ( 0.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[1]; + color += texture (u_TextureMap, vec2 ( 1.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[0]; +#else + color += texture (u_TextureMap, vec2 (0.0, -1.0) * u_InvTexRes + var_TexCoords) * weights[0]; + color += texture (u_TextureMap, vec2 (0.0, 0.0) * u_InvTexRes + var_TexCoords) * weights[1]; + color += texture (u_TextureMap, vec2 (0.0, 1.0) * u_InvTexRes + var_TexCoords) * weights[0]; +#endif +#endif + + out_Color = color * u_Color; +} \ No newline at end of file diff --git a/codemp/rd-rend2/glsl/generic.glsl b/codemp/rd-rend2/glsl/generic.glsl new file mode 100644 index 0000000000..f249657e89 --- /dev/null +++ b/codemp/rd-rend2/glsl/generic.glsl @@ -0,0 +1,591 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec3 attr_Normal; + +#if defined(USE_VERTEX_ANIMATION) +in vec3 attr_Position2; +in vec3 attr_Normal2; +#elif defined(USE_SKELETAL_ANIMATION) +in uvec4 attr_BoneIndexes; +in vec4 attr_BoneWeights; +#endif + +in vec4 attr_Color; +in vec2 attr_TexCoord0; + +#if defined(USE_TCGEN) +in vec2 attr_TexCoord1; +in vec2 attr_TexCoord2; +in vec2 attr_TexCoord3; +in vec2 attr_TexCoord4; +#endif + +layout(std140) uniform Scene +{ + vec4 u_PrimaryLightOrigin; + vec3 u_PrimaryLightAmbient; + int u_globalFogIndex; + vec3 u_PrimaryLightColor; + float u_PrimaryLightRadius; + float u_frameTime; + float u_deltaTime; +}; + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; + float u_entityTime; +}; + +#if defined(USE_DEFORM_VERTEXES) || defined(USE_RGBAGEN) +layout(std140) uniform ShaderInstance +{ + vec4 u_DeformParams0; + vec4 u_DeformParams1; + float u_Time; + float u_PortalRange; + int u_DeformType; + int u_DeformFunc; +}; +#endif + +#if defined(USE_SKELETAL_ANIMATION) +layout(std140) uniform Bones +{ + mat3x4 u_BoneMatrices[MAX_G2_BONES]; +}; +#endif + +uniform vec4 u_DiffuseTexMatrix; +uniform vec4 u_DiffuseTexOffTurb; + +#if defined(USE_TCGEN) +uniform int u_TCGen0; +uniform vec3 u_TCGen0Vector0; +uniform vec3 u_TCGen0Vector1; +#endif + +uniform vec4 u_BaseColor; +uniform vec4 u_VertColor; + +#if defined(USE_RGBAGEN) +uniform int u_ColorGen; +uniform int u_AlphaGen; +#endif + +#if defined(USE_RGBAGEN) || defined(USE_DEFORM_VERTEXES) +uniform vec4 u_Disintegration; // origin, threshhold +#endif + +out vec2 var_DiffuseTex; +out vec4 var_Color; +#if defined(USE_FOG) +out vec3 var_WSPosition; +#endif + +#if defined(USE_DEFORM_VERTEXES) +float GetNoiseValue( float x, float y, float z, float t ) +{ + // Variation on the 'one-liner random function'. + // Not sure if this is still 'correctly' random + return fract( sin( dot( + vec4( x, y, z, t ), + vec4( 12.9898, 78.233, 12.9898, 78.233 ) + )) * 43758.5453 ); +} + +float CalculateDeformScale( in int func, in float time, in float phase, in float frequency ) +{ + float value = phase + time * frequency; + + switch ( func ) + { + case WF_SIN: + return sin(value * 2.0 * M_PI); + case WF_SQUARE: + return sign(0.5 - fract(value)); + case WF_TRIANGLE: + return abs(fract(value + 0.75) - 0.5) * 4.0 - 1.0; + case WF_SAWTOOTH: + return fract(value); + case WF_INVERSE_SAWTOOTH: + return 1.0 - fract(value); + default: + return 0.0; + } +} + +vec3 DeformPosition(const vec3 pos, const vec3 normal, const vec2 st) +{ +#if defined(USE_RGBAGEN) + if (u_ColorGen == CGEN_DISINTEGRATION_2) + { + vec3 delta = u_Disintegration.xyz - pos; + float sqrDistance = dot(delta, delta); + vec3 normalScale = vec3(-0.01); + if ( sqrDistance < u_Disintegration.w ) + { + normalScale = vec3(2.0, 2.0, 0.5); + } + else if ( sqrDistance < u_Disintegration.w + 50 ) + { + normalScale = vec3(1.0, 1.0, 0.0); + } + return pos + normal * normalScale; + } +#endif + switch ( u_DeformType ) + { + default: + { + return pos; + } + + case DEFORM_BULGE: + { + float bulgeHeight = u_DeformParams0.y; // amplitude + float bulgeWidth = u_DeformParams0.z; // phase + float bulgeSpeed = u_DeformParams0.w; // frequency + + float scale = CalculateDeformScale( WF_SIN, (u_entityTime + u_frameTime + u_Time), bulgeWidth * st.x, bulgeSpeed ); + + return pos + normal * scale * bulgeHeight; + } + + case DEFORM_BULGE_UNIFORM: + { + float bulgeHeight = u_DeformParams0.y; // amplitude + + return pos + normal * bulgeHeight; + } + + case DEFORM_WAVE: + { + float base = u_DeformParams0.x; + float amplitude = u_DeformParams0.y; + float phase = u_DeformParams0.z; + float frequency = u_DeformParams0.w; + float spread = u_DeformParams1.x; + + float offset = dot( pos.xyz, vec3( spread ) ); + float scale = CalculateDeformScale( u_DeformFunc, (u_entityTime + u_frameTime + u_Time), phase + offset, frequency ); + + return pos + normal * (base + scale * amplitude); + } + + case DEFORM_MOVE: + { + float base = u_DeformParams0.x; + float amplitude = u_DeformParams0.y; + float phase = u_DeformParams0.z; + float frequency = u_DeformParams0.w; + vec3 direction = u_DeformParams1.xyz; + + float scale = CalculateDeformScale( u_DeformFunc, (u_entityTime + u_frameTime + u_Time), phase, frequency ); + + return pos + direction * (base + scale * amplitude); + } + + case DEFORM_PROJECTION_SHADOW: + { + vec3 ground = u_DeformParams0.xyz; + float groundDist = u_DeformParams0.w; + vec3 lightDir = u_DeformParams1.xyz; + + float d = dot( lightDir, ground ); + + lightDir = lightDir * max( 0.5 - d, 0.0 ) + ground; + d = 1.0 / dot( lightDir, ground ); + + vec3 lightPos = lightDir * d; + + return pos - lightPos * dot( pos, ground ) + groundDist; + } + //case DEFORM_DISINTEGRATION: + //{ + //} + } +} + +vec3 DeformNormal( const in vec3 position, const in vec3 normal ) +{ + if ( u_DeformType != DEFORM_NORMALS ) + { + return normal; + } + + float amplitude = u_DeformParams0.y; + float frequency = u_DeformParams0.w; + + vec3 outNormal = normal; + const float scale = 0.98; + + outNormal.x += amplitude * GetNoiseValue( + position.x * scale, + position.y * scale, + position.z * scale, + (u_entityTime + u_frameTime + u_Time) * frequency ); + + outNormal.y += amplitude * GetNoiseValue( + 100.0 * position.x * scale, + position.y * scale, + position.z * scale, + (u_entityTime + u_frameTime + u_Time) * frequency ); + + outNormal.z += amplitude * GetNoiseValue( + 200.0 * position.x * scale, + position.y * scale, + position.z * scale, + (u_entityTime + u_frameTime + u_Time) * frequency ); + + return outNormal; +} +#endif + +#if defined(USE_TCGEN) +vec2 GenTexCoords(int TCGen, vec3 position, vec3 normal, vec3 TCGenVector0, vec3 TCGenVector1) +{ + vec2 tex = attr_TexCoord0.st; + + switch (TCGen) + { + case TCGEN_LIGHTMAP: + tex = attr_TexCoord1; + break; + + case TCGEN_LIGHTMAP1: + tex = attr_TexCoord2; + break; + + case TCGEN_LIGHTMAP2: + tex = attr_TexCoord3; + break; + + case TCGEN_LIGHTMAP3: + tex = attr_TexCoord4; + break; + + case TCGEN_ENVIRONMENT_MAPPED: + { + vec3 viewer = normalize(u_LocalViewOrigin - position); + vec2 ref = reflect(viewer, normal).yz; + tex.s = ref.x * -0.5 + 0.5; + tex.t = ref.y * 0.5 + 0.5; + } + break; + + case TCGEN_VECTOR: + { + tex = vec2(dot(position, TCGenVector0), dot(position, TCGenVector1)); + } + break; + } + + return tex; +} +#endif + +#if defined(USE_TCMOD) +vec2 ModTexCoords(vec2 st, vec3 position, vec4 texMatrix, vec4 offTurb) +{ + float amplitude = offTurb.z; + float phase = offTurb.w * 2.0 * M_PI; + vec2 st2; + st2.x = st.x * texMatrix.x + (st.y * texMatrix.z + offTurb.x); + st2.y = st.x * texMatrix.y + (st.y * texMatrix.w + offTurb.y); + + vec2 offsetPos = vec2(position.x + position.z, position.y); + + vec2 texOffset = sin(offsetPos * (2.0 * M_PI / 1024.0) + vec2(phase)); + + return st2 + texOffset * amplitude; +} +#endif + +#if defined(USE_RGBAGEN) +vec4 CalcColor(vec3 position, vec3 normal) +{ + vec4 color = u_VertColor * attr_Color + u_BaseColor; + + if (u_ColorGen == CGEN_LIGHTING_DIFFUSE) + { + float incoming = clamp(dot(normal, u_ModelLightDir), 0.0, 1.0); + + color.rgb = clamp(u_DirectedLight * incoming + u_AmbientLight, 0.0, 1.0); + } + else if (u_ColorGen == CGEN_DISINTEGRATION_1) + { + vec3 delta = u_Disintegration.xyz - position; + float sqrDistance = dot(delta, delta); + if (sqrDistance < u_Disintegration.w) + { + color *= 0.0; + } + else if (sqrDistance < u_Disintegration.w + 60.0) + { + color *= vec4(0.0, 0.0, 0.0, 1.0); + } + else if (sqrDistance < u_Disintegration.w + 150.0) + { + color *= vec4(0.435295, 0.435295, 0.435295, 1.0); + } + else if (sqrDistance < u_Disintegration.w + 180.0) + { + color *= vec4(0.6862745, 0.6862745, 0.6862745, 1.0); + } + return color; + } + else if (u_ColorGen == CGEN_DISINTEGRATION_2) + { + vec3 delta = u_Disintegration.xyz - position; + float sqrDistance = dot(delta, delta); + if (sqrDistance < u_Disintegration.w) + { + return vec4(0.0); + } + return color; + } + + vec3 viewer = u_LocalViewOrigin - position; + + if (u_AlphaGen == AGEN_LIGHTING_SPECULAR) + { + vec3 lightDir = normalize(vec3(-960.0, 1980.0, 96.0) - position); + vec3 reflected = -reflect(lightDir, normal); + + color.a = clamp(dot(reflected, normalize(viewer)), 0.0, 1.0); + color.a *= color.a; + color.a *= color.a; + } + else if (u_AlphaGen == AGEN_PORTAL) + { + color.a = clamp(length(viewer) / u_PortalRange, 0.0, 1.0); + } + + return color; +} +#endif + +#if defined(USE_SKELETAL_ANIMATION) +mat4x3 GetBoneMatrix(uint index) +{ + mat3x4 bone = u_BoneMatrices[index]; + return mat4x3( + bone[0].x, bone[1].x, bone[2].x, + bone[0].y, bone[1].y, bone[2].y, + bone[0].z, bone[1].z, bone[2].z, + bone[0].w, bone[1].w, bone[2].w); +} +#endif + +void main() +{ +#if defined(USE_VERTEX_ANIMATION) + vec3 position = mix(attr_Position, attr_Position2, u_VertexLerp); + vec3 normal = mix(attr_Normal, attr_Normal2, u_VertexLerp); + normal = normalize(normal - vec3(0.5)); +#elif defined(USE_SKELETAL_ANIMATION) + mat4x3 influence = + GetBoneMatrix(attr_BoneIndexes[0]) * attr_BoneWeights[0] + + GetBoneMatrix(attr_BoneIndexes[1]) * attr_BoneWeights[1] + + GetBoneMatrix(attr_BoneIndexes[2]) * attr_BoneWeights[2] + + GetBoneMatrix(attr_BoneIndexes[3]) * attr_BoneWeights[3]; + + vec3 position = influence * vec4(attr_Position, 1.0); + vec3 normal = normalize(influence * vec4(attr_Normal - vec3(0.5), 0.0)); +#else + vec3 position = attr_Position; + vec3 normal = attr_Normal * 2.0 - vec3(1.0); +#endif + +#if defined(USE_DEFORM_VERTEXES) + position = DeformPosition(position, normal, attr_TexCoord0.st); + normal = DeformNormal( position, normal ); +#endif + + mat4 MVP = u_viewProjectionMatrix * u_ModelMatrix; + gl_Position = MVP * vec4(position, 1.0); + +#if defined(USE_TCGEN) + vec2 tex = GenTexCoords(u_TCGen0, position, normal, u_TCGen0Vector0, u_TCGen0Vector1); +#else + vec2 tex = attr_TexCoord0.st; +#endif + +#if defined(USE_TCMOD) + var_DiffuseTex = ModTexCoords(tex, position, u_DiffuseTexMatrix, u_DiffuseTexOffTurb); +#else + var_DiffuseTex = tex; +#endif + + if ( u_FXVolumetricBase >= 0.0 ) + { + vec3 viewForward = u_ViewForward.xyz; + float d = clamp(dot(normalize(viewForward), normalize(normal)), 0.0, 1.0); + d = d * d; + d = d * d; + + var_Color = vec4(u_FXVolumetricBase * (1.0 - d)); + } + else + { +#if defined(USE_RGBAGEN) + var_Color = CalcColor(position, normal); +#else + var_Color = u_VertColor * attr_Color + u_BaseColor; +#endif + } + +#if defined(USE_FOG) + var_WSPosition = (u_ModelMatrix * vec4(position, 1.0)).xyz; +#endif +} + + +/*[Fragment]*/ +struct Fog +{ + vec4 plane; + vec4 color; + float depthToOpaque; + bool hasPlane; +}; + +layout(std140) uniform Fogs +{ + int u_NumFogs; + Fog u_Fogs[16]; +}; + +uniform vec4 u_FogColorMask; + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; + float u_entityTime; +}; + +uniform sampler2D u_DiffuseMap; +#if defined(USE_ALPHA_TEST) +uniform int u_AlphaTestType; +#endif +uniform int u_FogIndex; + +in vec2 var_DiffuseTex; +in vec4 var_Color; +#if defined(USE_FOG) +in vec3 var_WSPosition; +#endif + +out vec4 out_Color; +out vec4 out_Glow; + + +#if defined(USE_FOG) +float CalcFog(in vec3 viewOrigin, in vec3 position, in Fog fog) +{ + bool inFog = dot(viewOrigin, fog.plane.xyz) - fog.plane.w >= 0.0 || !fog.hasPlane; + + // line: x = o + tv + // plane: (x . n) + d = 0 + // intersects: dot(o + tv, n) + d = 0 + // dot(o + tv, n) = -d + // dot(o, n) + t*dot(n, v) = -d + // t = -(d + dot(o, n)) / dot(n, v) + vec3 V = position - viewOrigin; + + // fogPlane is inverted in tr_bsp for some reason. + float t = -(fog.plane.w + dot(viewOrigin, -fog.plane.xyz)) / dot(V, -fog.plane.xyz); + + bool intersects = (t > 0.0 && t < 0.995); + if (inFog == intersects) + return 0.0; + + float distToVertexFromViewOrigin = length(V); + float distToIntersectionFromViewOrigin = t * distToVertexFromViewOrigin; + + float distOutsideFog = max(distToVertexFromViewOrigin - distToIntersectionFromViewOrigin, 0.0); + float distThroughFog = mix(distOutsideFog, distToVertexFromViewOrigin, inFog); + + float z = fog.depthToOpaque * distThroughFog; + return 1.0 - clamp(exp(-(z * z)), 0.0, 1.0); +} +#endif + +void main() +{ + vec4 color = texture(u_DiffuseMap, var_DiffuseTex); + color.a *= var_Color.a; +#if defined(USE_ALPHA_TEST) + if (u_AlphaTestType == ALPHA_TEST_GT0) + { + if (color.a == 0.0) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_LT128) + { + if (color.a >= 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE128) + { + if (color.a < 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE192) + { + if (color.a < 0.75) + discard; + } +#endif + +#if defined(USE_FOG) + Fog fog = u_Fogs[u_FogIndex]; + float fogFactor = CalcFog(u_ViewOrigin, var_WSPosition, fog); + color *= vec4(1.0) - u_FogColorMask * fogFactor; +#endif + + out_Color = vec4(color.rgb * var_Color.rgb, color.a); + +#if defined(USE_GLOW_BUFFER) + out_Glow = out_Color; +#else + out_Glow = vec4(0.0); +#endif +} diff --git a/codemp/rd-rend2/glsl/lightall.glsl b/codemp/rd-rend2/glsl/lightall.glsl new file mode 100644 index 0000000000..759bbc8144 --- /dev/null +++ b/codemp/rd-rend2/glsl/lightall.glsl @@ -0,0 +1,1188 @@ +/*[Vertex]*/ +#if defined(USE_LIGHT) && !defined(USE_FAST_LIGHT) +#define PER_PIXEL_LIGHTING +#endif +in vec2 attr_TexCoord0; +#if defined(USE_LIGHTMAP) || defined(USE_TCGEN) +in vec2 attr_TexCoord1; +in vec2 attr_TexCoord2; +in vec2 attr_TexCoord3; +in vec2 attr_TexCoord4; +#endif +in vec4 attr_Color; + +in vec3 attr_Position; +in vec3 attr_Normal; +#if defined(PER_PIXEL_LIGHTING) +in vec4 attr_Tangent; +#endif + +#if defined(USE_VERTEX_ANIMATION) +in vec3 attr_Position2; +in vec3 attr_Normal2; +in vec4 attr_Tangent2; +#elif defined(USE_SKELETAL_ANIMATION) +in uvec4 attr_BoneIndexes; +in vec4 attr_BoneWeights; +#endif + +#if defined(USE_LIGHT) && !defined(USE_LIGHT_VECTOR) +in vec3 attr_LightDirection; +#endif + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; + float u_entityTime; +}; + +#if defined(USE_SKELETAL_ANIMATION) +layout(std140) uniform Bones +{ + mat3x4 u_BoneMatrices[MAX_G2_BONES]; +}; +#endif + +#if defined(USE_DELUXEMAP) +uniform vec4 u_EnableTextures; // x = normal, y = deluxe, z = specular, w = cube +#endif + +#if defined(USE_TCGEN) || defined(USE_LIGHTMAP) +uniform int u_TCGen0; +uniform vec3 u_TCGen0Vector0; +uniform vec3 u_TCGen0Vector1; +uniform int u_TCGen1; +#endif + +#if defined(USE_TCMOD) +uniform vec4 u_DiffuseTexMatrix; +uniform vec4 u_DiffuseTexOffTurb; +#endif + +uniform vec4 u_BaseColor; +uniform vec4 u_VertColor; +uniform vec4 u_Disintegration; +uniform int u_ColorGen; + +out vec4 var_TexCoords; +out vec4 var_Color; + +#if defined(PER_PIXEL_LIGHTING) +out vec4 var_Normal; +out vec4 var_Tangent; +out vec4 var_ViewDir; +out vec4 var_TangentViewDir; +#endif + +#if defined(PER_PIXEL_LIGHTING) +out vec4 var_LightDir; +#endif + +vec4 CalcColor(vec3 position) +{ + vec4 color = vec4(1.0); + if (u_ColorGen == CGEN_DISINTEGRATION_1) + { + vec3 delta = u_Disintegration.xyz - position; + float sqrDistance = dot(delta, delta); + if (sqrDistance < u_Disintegration.w) + { + color = vec4(0.0); + } + else if (sqrDistance < u_Disintegration.w + 60.0) + { + color = vec4(0.0, 0.0, 0.0, 1.0); + } + else if (sqrDistance < u_Disintegration.w + 150.0) + { + color = vec4(0.435295, 0.435295, 0.435295, 1.0); + } + else if (sqrDistance < u_Disintegration.w + 180.0) + { + color = vec4(0.6862745, 0.6862745, 0.6862745, 1.0); + } + return color; + } + else if (u_ColorGen == CGEN_DISINTEGRATION_2) + { + vec3 delta = u_Disintegration.xyz - position; + float sqrDistance = dot(delta, delta); + if (sqrDistance < u_Disintegration.w) + { + return vec4(0.0); + } + return color; + } + return color; +} + +#if defined(USE_TCGEN) || defined(USE_LIGHTMAP) +vec2 GenTexCoords(int TCGen, vec3 position, vec3 normal, vec3 TCGenVector0, vec3 TCGenVector1) +{ + vec2 tex = attr_TexCoord0; + + switch (TCGen) + { + case TCGEN_LIGHTMAP: + tex = attr_TexCoord1; + break; + + case TCGEN_LIGHTMAP1: + tex = attr_TexCoord2; + break; + + case TCGEN_LIGHTMAP2: + tex = attr_TexCoord3; + break; + + case TCGEN_LIGHTMAP3: + tex = attr_TexCoord4; + break; + + case TCGEN_ENVIRONMENT_MAPPED: + { + vec3 viewer = normalize(u_LocalViewOrigin - position); + vec2 ref = reflect(viewer, normal).yz; + tex.s = ref.x * -0.5 + 0.5; + tex.t = ref.y * 0.5 + 0.5; + } + break; + + case TCGEN_VECTOR: + { + tex = vec2(dot(position, TCGenVector0), dot(position, TCGenVector1)); + } + break; + } + + return tex; +} +#endif + +#if defined(USE_TCMOD) +vec2 ModTexCoords(vec2 st, vec3 position, vec4 texMatrix, vec4 offTurb) +{ + float amplitude = offTurb.z; + float phase = offTurb.w * 2.0 * M_PI; + vec2 st2; + st2.x = st.x * texMatrix.x + (st.y * texMatrix.z + offTurb.x); + st2.y = st.x * texMatrix.y + (st.y * texMatrix.w + offTurb.y); + + vec2 offsetPos = vec2(position.x + position.z, position.y); + + vec2 texOffset = sin(offsetPos * (2.0 * M_PI / 1024.0) + vec2(phase)); + + return st2 + texOffset * amplitude; +} +#endif + +#if defined(USE_SKELETAL_ANIMATION) +mat4x3 GetBoneMatrix(uint index) +{ + mat3x4 bone = u_BoneMatrices[index]; + return mat4x3( + bone[0].x, bone[1].x, bone[2].x, + bone[0].y, bone[1].y, bone[2].y, + bone[0].z, bone[1].z, bone[2].z, + bone[0].w, bone[1].w, bone[2].w); +} +#endif + +void main() +{ +#if defined(USE_VERTEX_ANIMATION) + vec3 position = mix(attr_Position, attr_Position2, u_VertexLerp); + vec3 normal = mix(attr_Normal, attr_Normal2, u_VertexLerp); + #if defined(PER_PIXEL_LIGHTING) + vec3 tangent = mix(attr_Tangent.xyz, attr_Tangent2.xyz, u_VertexLerp); + #endif +#elif defined(USE_SKELETAL_ANIMATION) + mat4x3 influence = + GetBoneMatrix(attr_BoneIndexes[0]) * attr_BoneWeights[0] + + GetBoneMatrix(attr_BoneIndexes[1]) * attr_BoneWeights[1] + + GetBoneMatrix(attr_BoneIndexes[2]) * attr_BoneWeights[2] + + GetBoneMatrix(attr_BoneIndexes[3]) * attr_BoneWeights[3]; + + vec3 position = influence * vec4(attr_Position, 1.0); + vec3 normal = normalize(influence * vec4(attr_Normal - vec3(0.5), 0.0)); + #if defined(PER_PIXEL_LIGHTING) + vec3 tangent = normalize(influence * vec4(attr_Tangent.xyz - vec3(0.5), 0.0)); + #endif +#else + vec3 position = attr_Position; + vec3 normal = attr_Normal; + #if defined(PER_PIXEL_LIGHTING) + vec3 tangent = attr_Tangent.xyz; + #endif +#endif + +#if !defined(USE_SKELETAL_ANIMATION) + normal = normal * 2.0 - vec3(1.0); + #if defined(PER_PIXEL_LIGHTING) + tangent = tangent * 2.0 - vec3(1.0); + #endif +#endif + +#if defined(USE_TCGEN) + vec2 texCoords = GenTexCoords(u_TCGen0, position, normal, u_TCGen0Vector0, u_TCGen0Vector1); +#else + vec2 texCoords = attr_TexCoord0.st; +#endif + +#if defined(USE_TCMOD) + var_TexCoords.xy = ModTexCoords(texCoords, position, u_DiffuseTexMatrix, u_DiffuseTexOffTurb); +#else + var_TexCoords.xy = texCoords; +#endif + + vec4 disintegration = CalcColor(position); + + mat4 MVP = u_viewProjectionMatrix * u_ModelMatrix; + gl_Position = MVP * vec4(position, 1.0); + + position = (u_ModelMatrix * vec4(position, 1.0)).xyz; + normal = normalize(mat3(u_ModelMatrix) * normal); + #if defined(PER_PIXEL_LIGHTING) + tangent = normalize(mat3(u_ModelMatrix) * tangent); + #endif + +#if defined(USE_LIGHT_VECTOR) + vec3 L = u_LocalLightOrigin.xyz - (position * u_LocalLightOrigin.w); +#elif defined(PER_PIXEL_LIGHTING) + vec3 L = attr_LightDirection * 2.0 - vec3(1.0); + L = (u_ModelMatrix * vec4(L, 0.0)).xyz; +#endif + +#if defined(USE_LIGHTMAP) + var_TexCoords.zw = GenTexCoords(u_TCGen1, vec3(0.0), vec3(0.0), vec3(0.0), vec3(0.0)); +#endif + + if ( u_FXVolumetricBase > 0.0 ) + { + vec3 viewForward = u_ViewForward.xyz; + + float d = clamp(dot(normalize(viewForward), normal), 0.0, 1.0); + d = d * d; + d = d * d; + + var_Color = vec4(u_FXVolumetricBase * (1.0 - d)); + } + else + { + var_Color = u_VertColor * attr_Color + u_BaseColor; + + #if defined(USE_LIGHT_VECTOR) && defined(USE_FAST_LIGHT) + float sqrLightDist = dot(L, L); + float NL = clamp(dot(normal, L) / sqrt(sqrLightDist), 0.0, 1.0); + + var_Color.rgb *= u_DirectedLight * NL + u_AmbientLight; + #endif + } + var_Color *= disintegration; + +#if defined(PER_PIXEL_LIGHTING) + var_LightDir = vec4(L, 0.0); + #if defined(USE_DELUXEMAP) + var_LightDir -= u_EnableTextures.y * var_LightDir; + #endif +#endif + +#if defined(PER_PIXEL_LIGHTING) + vec3 viewDir = u_ViewOrigin.xyz - position; + + // store view direction in tangent space to save on outs + var_Normal = vec4(normal, 0.0); + var_Tangent = vec4(tangent, (attr_Tangent.w * 2.0 - 1.0)); + var_ViewDir = vec4(viewDir.xyz, 0.0); + + vec3 bitangent = cross(normal, tangent) * var_Tangent.w; + mat3 TBN = mat3(tangent, bitangent, normal); + var_TangentViewDir = vec4(var_ViewDir.xyz * TBN, 0.0); +#endif +} + +/*[Fragment]*/ +#if defined(USE_LIGHT) && !defined(USE_FAST_LIGHT) +#define PER_PIXEL_LIGHTING +#endif + +layout(std140) uniform Scene +{ + vec4 u_PrimaryLightOrigin; + vec3 u_PrimaryLightAmbient; + int u_globalFogIndex; + vec3 u_PrimaryLightColor; + float u_PrimaryLightRadius; + float u_frameTime; + float u_deltaTime; +}; + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; + float u_entityTime; +}; + +struct Light +{ + vec4 origin; + vec3 color; + float radius; +}; + +layout(std140) uniform Lights +{ + uniform mat4 u_ShadowMvp; + uniform mat4 u_ShadowMvp2; + uniform mat4 u_ShadowMvp3; + int u_NumLights; + Light u_Lights[32]; +}; + +uniform int u_LightMask; +uniform sampler2D u_DiffuseMap; + +#if defined(USE_LIGHTMAP) +uniform sampler2D u_LightMap; +#endif + +#if defined(USE_NORMALMAP) +uniform sampler2D u_NormalMap; +#endif + +#if defined(USE_DELUXEMAP) +uniform sampler2D u_DeluxeMap; +#endif + +#if defined(USE_SPECULARMAP) +uniform sampler2D u_SpecularMap; +#endif + +#if defined(USE_SHADOWMAP) +uniform sampler2DArrayShadow u_ShadowMap; +#endif + +#if defined(USE_SSAO) +uniform sampler2D u_SSAOMap; +#endif + +#if defined(USE_DSHADOWS) +uniform sampler2DArrayShadow u_ShadowMap2; +#endif + +#if defined(USE_CUBEMAP) +uniform samplerCube u_CubeMap; +uniform sampler2D u_EnvBrdfMap; +#endif + +#if defined(USE_NORMALMAP) || defined(USE_DELUXEMAP) || defined(USE_SPECULARMAP) || defined(USE_CUBEMAP) +// y = deluxe, w = cube +uniform vec4 u_EnableTextures; +#endif + +uniform vec4 u_NormalScale; +uniform vec4 u_SpecularScale; +uniform float u_ParallaxBias; + +#if defined(PER_PIXEL_LIGHTING) && defined(USE_CUBEMAP) +uniform vec4 u_CubeMapInfo; +#endif + +#if defined(USE_ALPHA_TEST) +uniform int u_AlphaTestType; +#endif + + +in vec4 var_TexCoords; +in vec4 var_Color; + +#if defined(PER_PIXEL_LIGHTING) +in vec4 var_Normal; +in vec4 var_Tangent; +in vec4 var_ViewDir; +in vec4 var_TangentViewDir; +in vec4 var_LightDir; +#endif + +out vec4 out_Color; +out vec4 out_Glow; + +#if defined(USE_SHADOWMAP) +// depth is GL_DEPTH_COMPONENT16 +// so the maximum error is 1.0 / 2^16 +#define DEPTH_MAX_ERROR 0.0000152587890625 + +// Input: It uses texture coords as the random number seed. +// Output: Random number: [0,1), that is between 0.0 and 0.999999... inclusive. +// Author: Michael Pohoreski +// Copyright: Copyleft 2012 :-) +// Source: http://stackoverflow.com/questions/5149544/can-i-generate-a-random-number-inside-a-pixel-shader + +float random( const vec2 p ) +{ + // We need irrationals for pseudo randomness. + // Most (all?) known transcendental numbers will (generally) work. + const vec2 r = vec2( + 23.1406926327792690, // e^pi (Gelfond's constant) + 2.6651441426902251); // 2^sqrt(2) (Gelfond-Schneider constant) + //return fract( cos( mod( 123456789., 1e-7 + 256. * dot(p,r) ) ) ); + return mod( 123456789., 1e-7 + 256. * dot(p,r) ); +} + +const vec2 poissonDisk[16] = vec2[16]( + vec2( -0.94201624, -0.39906216 ), + vec2( 0.94558609, -0.76890725 ), + vec2( -0.094184101, -0.92938870 ), + vec2( 0.34495938, 0.29387760 ), + vec2( -0.91588581, 0.45771432 ), + vec2( -0.81544232, -0.87912464 ), + vec2( -0.38277543, 0.27676845 ), + vec2( 0.97484398, 0.75648379 ), + vec2( 0.44323325, -0.97511554 ), + vec2( 0.53742981, -0.47373420 ), + vec2( -0.26496911, -0.41893023 ), + vec2( 0.79197514, 0.19090188 ), + vec2( -0.24188840, 0.99706507 ), + vec2( -0.81409955, 0.91437590 ), + vec2( 0.19984126, 0.78641367 ), + vec2( 0.14383161, -0.14100790 ) +); + +float PCF(const sampler2DArrayShadow shadowmap, const float layer, const vec2 st, const float dist, float PCFScale) +{ + float mult; + float scale = PCFScale / r_shadowMapSize; + +#if defined(USE_SHADOW_FILTER) + float r = random(gl_FragCoord.xy / r_FBufScale); + float sinr = sin(r); + float cosr = cos(r); + mat2 rmat = mat2(cosr, sinr, -sinr, cosr) * scale; + + mult = texture(shadowmap, vec4(st + rmat * vec2(-0.7055767, 0.196515), layer, dist)); + mult += texture(shadowmap, vec4(st + rmat * vec2(0.3524343, -0.7791386), layer, dist)); + mult += texture(shadowmap, vec4(st + rmat * vec2(0.2391056, 0.9189604), layer, dist)); + #if defined(USE_SHADOW_FILTER2) + mult += texture(shadowmap, vec4(st + rmat * vec2(-0.07580382, -0.09224417), layer, dist)); + mult += texture(shadowmap, vec4(st + rmat * vec2(0.5784913, -0.002528916), layer, dist)); + mult += texture(shadowmap, vec4(st + rmat * vec2(0.192888, 0.4064181), layer, dist)); + mult += texture(shadowmap, vec4(st + rmat * vec2(-0.6335801, -0.5247476), layer, dist)); + mult += texture(shadowmap, vec4(st + rmat * vec2(-0.5579782, 0.7491854), layer, dist)); + mult += texture(shadowmap, vec4(st + rmat * vec2(0.7320465, 0.6317794), layer, dist)); + + mult *= 0.11111; + #else + mult *= 0.33333; + #endif +#else + float r = random(gl_FragCoord.xy / r_FBufScale); + float sinr = sin(r); + float cosr = cos(r); + mat2 rmat = mat2(cosr, sinr, -sinr, cosr) * scale; + + mult = texture(shadowmap, vec4(st, layer, dist)); + for (int i = 0; i < 16; i++) + { + vec2 delta = rmat * poissonDisk[i]; + mult += texture(shadowmap, vec4(st + delta, layer, dist)); + } + mult *= 1.0 / 17.0; +#endif + + return mult; +} + +float sunShadow(in vec3 viewOrigin, in vec3 viewDir, in vec3 biasOffset) +{ + vec4 biasPos = vec4(viewOrigin - viewDir + biasOffset, 1.0); + float cameraDistance = length(viewDir); + + const float PCFScale = 1.5; + const float edgeBias = 0.5 - ( 4.0 * PCFScale / r_shadowMapSize ); + float edgefactor = 0.0; + const float fadeTo = 1.0; + float result = 1.0; + + vec4 shadowpos = u_ShadowMvp * biasPos; + shadowpos.xyz = shadowpos.xyz / shadowpos.w * 0.5 + 0.5; + if (all(lessThanEqual(abs(shadowpos.xyz - vec3(0.5)), vec3(edgeBias)))) + { + vec3 dCoords = smoothstep(0.3, 0.45, abs(shadowpos.xyz - vec3(0.5))); + edgefactor = 2.0 * PCFScale * clamp(dCoords.x + dCoords.y + dCoords.z, 0.0, 1.0); + result = PCF(u_ShadowMap, + 0.0, + shadowpos.xy, + shadowpos.z, + PCFScale + edgefactor); + } + else + { + shadowpos = u_ShadowMvp2 * (biasPos + vec4(biasOffset, 0.0)); + shadowpos.xyz = shadowpos.xyz / shadowpos.w * 0.5 + 0.5; + if (all(lessThanEqual(abs(shadowpos.xyz - vec3(0.5)), vec3(edgeBias)))) + { + vec3 dCoords = smoothstep(0.3, 0.45, abs(shadowpos.xyz - vec3(0.5))); + edgefactor = 0.5 * PCFScale * clamp(dCoords.x + dCoords.y + dCoords.z, 0.0, 1.0); + result = PCF(u_ShadowMap, + 1.0, + shadowpos.xy, + shadowpos.z, + PCFScale + edgefactor); + } + else + { + shadowpos = u_ShadowMvp3 * (biasPos + vec4(biasOffset, 0.0)); + shadowpos.xyz = shadowpos.xyz / shadowpos.w * 0.5 + 0.5; + if (all(lessThanEqual(abs(shadowpos.xyz - vec3(0.5)), vec3(1.0)))) + { + result = PCF(u_ShadowMap, + 2.0, + shadowpos.xy, + shadowpos.z, + PCFScale); + float fade = clamp(cameraDistance / r_shadowCascadeZFar * 10.0 - 9.0, 0.0, 1.0); + result = mix(result, fadeTo, fade); + } + } + } + + return result; +} +#endif + +#if defined(USE_PARALLAXMAP) +float RayIntersectDisplaceMap(in vec2 inDp, in vec2 ds, in sampler2D normalMap, in float parallaxBias) +{ + const int linearSearchSteps = 16; + const int binarySearchSteps = 8; + + vec2 dp = inDp - parallaxBias * ds; + + // current size of search window + float size = 1.0 / float(linearSearchSteps); + + // current depth position + float depth = 0.0; + + // best match found (starts with last position 1.0) + float bestDepth = 1.0; + + vec2 dx = dFdx(inDp); + vec2 dy = dFdy(inDp); + + // search front to back for first point inside object + for(int i = 0; i < linearSearchSteps - 1; ++i) + { + depth += size; + + // height is flipped before uploaded to the gpu + float t = textureGrad(normalMap, dp + ds * depth, dx, dy).r; + + if(depth >= t) + { + bestDepth = depth; // store best depth + break; + } + } + + depth = bestDepth; + + // recurse around first point (depth) for closest match + for(int i = 0; i < binarySearchSteps; ++i) + { + size *= 0.5; + + // height is flipped before uploaded to the gpu + float t = textureGrad(normalMap, dp + ds * depth, dx, dy).r; + + if(depth >= t) + { + bestDepth = depth; + depth -= 2.0 * size; + } + + depth += size; + } + + float beforeDepth = textureGrad(normalMap, dp + ds * (depth-size), dx, dy).r - depth + size; + float afterDepth = textureGrad(normalMap, dp + ds * depth, dx, dy).r - depth; + float deltaDepth = beforeDepth - afterDepth; + float weight = mix(0.0, beforeDepth / deltaDepth , deltaDepth > 0); + bestDepth += weight*size; + + return bestDepth - parallaxBias; +} +#endif + +vec2 GetParallaxOffset(in vec2 texCoords, in vec3 tangentDir) +{ +#if defined(USE_PARALLAXMAP) + ivec2 normalSize = textureSize(u_NormalMap, 0); + vec3 nonSquareScale = mix(vec3(normalSize.y / normalSize.x, 1.0, 1.0), vec3(1.0, normalSize.x / normalSize.y, 1.0), float(normalSize.y <= normalSize.x)); + vec3 offsetDir = normalize(tangentDir * nonSquareScale); + offsetDir.xy *= -u_NormalScale.a / offsetDir.z; + + return offsetDir.xy * RayIntersectDisplaceMap(texCoords, offsetDir.xy, u_NormalMap, u_ParallaxBias); +#else + return vec2(0.0); +#endif +} + +float D_Charlie(in float a, in float NH) +{ + // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF" + float invAlpha = 1.0 / a; + float cos2h = NH * NH; + float sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16 + return (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * M_PI); +} + +float V_Neubelt(in float NV, in float NL) +{ + // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" + return 1.0 / (4.0 * (NL + NV - NL * NV)); +} + +float D_Ashikhmin(float roughness, float nh){ + float a2 = roughness * roughness; + float cos2h = nh * nh ; + float sin2h = max(1.0 - cos2h, 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16 + float sin4h = sin2h * sin2h; + float cot2 = -cos2h / (a2 * sin2h); + return 1.0 / (M_PI * (4.0 * a2 + 1.0) * sin4h) * (4.0 * exp(cot2) + sin4h); + + } + +vec3 Specular_CharlieSheen(float Roughness, float NoH, float NoV, float NoL, vec3 SpecularColor, float cloth) +{ + float D = cloth > 0.f ? D_Ashikhmin(Roughness, NoH) : D_Charlie(Roughness, NoH); + + return (D * V_Neubelt(NoV, NoL)) * SpecularColor; //No fresnel in the documentation. +} + +vec3 Fresnel_Schlick(const vec3 f0, float f90, float VoH) +{ + // Schlick 1994, "An Inexpensive BRDF Model for Physically-Based Rendering" + return f0 + (f90 - f0) * pow(1.0 - VoH, 5.f); +} + +vec3 Diff_Burley(float roughness, float NoV, float NoL, float LoH) +{ + // Burley 2012, "Physically-Based Shading at Disney" + float f90 = 0.5 + 2.0 * roughness * LoH * LoH; + vec3 lightScatter = Fresnel_Schlick(vec3(1.0), f90, NoL); + vec3 viewScatter = Fresnel_Schlick(vec3(1.0), f90, NoV); + return lightScatter * viewScatter * (1.0 / M_PI); +} + +vec3 F_Schlick(in vec3 SpecularColor, in float VH) +{ + float Fc = pow(1 - VH, 5); + return clamp(50.0 * SpecularColor.g, 0.0, 1.0) * Fc + (1 - Fc) * SpecularColor; //hacky way to decide if reflectivity is too low (< 2%) +} + +float D_GGX( in float NH, in float a ) +{ + /*float alphaSq = roughness*roughness; + float f = (NH * alphaSq - NH) * NH + 1.0; + return alphaSq / (f * f);*/ + + float a2 = a * a; + float d = (NH * a2 - NH) * NH + 1; + return a2 / (M_PI * d * d); +} + +// Appoximation of joint Smith term for GGX +// [Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs"] +float V_SmithJointApprox(in float a, in float NV, in float NL) +{ + float Vis_SmithV = NL * (NV * (1 - a) + a); + float Vis_SmithL = NV * (NL * (1 - a) + a); + return 0.5 * (1.0 / (Vis_SmithV + Vis_SmithL)); +} + +float CalcVisibility(in float NL, in float NE, in float roughness) +{ + float alphaSq = roughness * roughness; + + float lambdaE = NL * sqrt((-NE * alphaSq + NE) * NE + alphaSq); + float lambdaL = NE * sqrt((-NL * alphaSq + NL) * NL + alphaSq); + + return 0.5 / (lambdaE + lambdaL); +} + +// http://www.frostbite.com/2014/11/moving-frostbite-to-pbr/ +vec3 CalcSpecular( + in vec3 specular, + in float NH, + in float NL, + in float NE, + in float LH, + in float VH, + in float roughness +) +{ + //Using #if to define our BRDF's is a good idea. +#if !defined(USE_CLOTH_BRDF) //should define this as the base BRDF + vec3 F = F_Schlick(specular, VH); + float D = D_GGX(NH, roughness); + float V = V_SmithJointApprox(roughness, NE, NL); +#else //and define this as the cloth BRDF + //this cloth model essentially uses the metallic input to help transition from isotropic to anisotropic reflections. + //as cloth is a microfibre structure, cloth like velevet and silk tends to have anisotropy. + vec3 F = specular; //this shading model omits fresnel + float D = D_Charlie(roughness, NH); + float V = V_Neubelt(NE, NL); +#endif + + return D * F * V; +} + +//Energy conserving wrap term. +float WrapLambert(in float NL, in float w) +{ + return clamp((NL + w) / pow(1.0 + w, 2.0), 0.0, 1.0); +} + +vec3 Diffuse_Lambert(in vec3 DiffuseColor) +{ + return DiffuseColor * (1.0 / M_PI); +} + +vec3 CalcDiffuse( + in vec3 diffuse, + in float NE, + in float NL, + in float LH, + in float roughness +) +{ + //Using #if to define our diffuse's is a good idea. +#if !defined(USE_CLOTH_BRDF) //should define this as the base BRDF + return Diffuse_Lambert(diffuse); +#else //and define this as the cloth diffuse + //this cloth model has a wrapped diffuse, we can be energy conservant here. + vec3 d = Diffuse_Lambert(diffuse); + d *= WrapLambert(NL, 0.5); + // Cheap subsurface scatter + // ideally we should actually have a new colour for subsurface, but for cloth most times it makes sense to just use the diffuse. + d *= clamp(diffuse + NL, 0.0, 1.0); + return d; +#endif +} + +float CalcLightAttenuation(float normDist) +{ + // zero light at 1.0, approximating q3 style + float attenuation = 0.5 * normDist - 0.5; + return clamp(attenuation, 0.0, 1.0); +} + +#if defined(USE_DSHADOWS) +#define DEPTH_MAX_ERROR 0.0000152587890625 + +vec2 poissonDiscPolar[9] = vec2[9] +( +vec2(-0.7055767, 0.196515), vec2(0.3524343, -0.7791386), +vec2(0.2391056, 0.9189604), vec2(-0.07580382, -0.09224417), +vec2(0.5784913, -0.002528916), vec2(0.192888, 0.4064181), +vec2(-0.6335801, -0.5247476), vec2(-0.5579782, 0.7491854), +vec2(0.7320465, 0.6317794) +); + +// based on https://www.gamedev.net/forums/topic/687535-implementing-a-cube-map-lookup-function/5337472/ +vec3 sampleCube(in vec3 v) +{ + vec3 vAbs = abs(v); + float ma = 0.0; + vec2 uv = vec2(0.0); + float faceIndex = 0.0; + if(vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) + { + faceIndex = v.z < 0.0 ? 5.0 : 4.0; + ma = 0.5 / vAbs.z; + uv = vec2(v.z < 0.0 ? -v.x : v.x, -v.y); + } + else if(vAbs.y >= vAbs.x) + { + faceIndex = v.y < 0.0 ? 3.0 : 2.0; + ma = 0.5 / vAbs.y; + uv = vec2(v.x, v.y < 0.0 ? -v.z : v.z); + } + else + { + faceIndex = v.x < 0.0 ? 1.0 : 0.0; + ma = 0.5 / vAbs.x; + uv = vec2(v.x < 0.0 ? v.z : -v.z, -v.y); + } + return vec3(uv * ma + 0.5, faceIndex); +} + +float pcfShadow(in sampler2DArrayShadow depthMap, in vec3 L, in float distance, in int lightId) +{ + const int samples = 9; + const float diskRadius = M_PI / 512.0; + + vec2 polarL = vec2(atan(L.z, L.x), acos(L.y)); + float shadow = 0.0; + + for (int i = 0; i < samples; ++i) + { + vec2 samplePolar = poissonDiscPolar[i] * diskRadius + polarL; + vec3 sampleVec = vec3(0.0); + sampleVec.x = cos(samplePolar.x) * sin(samplePolar.y); + sampleVec.z = sin(samplePolar.x) * sin(samplePolar.y); + sampleVec.y = cos(samplePolar.y); + + vec3 lookup = sampleCube(sampleVec) + vec3(0.0, 0.0, lightId * 6.0); + + shadow += texture(depthMap, vec4(lookup, distance)); + } + shadow /= float(samples); + return shadow; +} + +float getLightDepth(in vec3 Vec, in float f) +{ + vec3 AbsVec = abs(Vec); + float Z = max(AbsVec.x, max(AbsVec.y, AbsVec.z)); + + const float n = 1.0; + + float NormZComp = (f + n) / (f - n) - 2 * f*n / (Z* (f - n)); + + return ((NormZComp + 1.0) * 0.5); +} +#endif + +vec3 CalcDynamicLightContribution( + in float roughness, + in vec3 N, + in vec3 E, + in vec3 viewOrigin, + in vec3 viewDir, + in float NE, + in vec3 diffuse, + in vec3 specular, + in vec3 vertexNormal +) +{ + vec3 outColor = vec3(0.0); + vec3 position = viewOrigin - viewDir; + + for ( int i = 0; i < u_NumLights; i++ ) + { + if ( ( u_LightMask & ( 1 << i ) ) == 0 ) { + continue; + } + Light light = u_Lights[i]; + + vec3 L = light.origin.xyz - position; + float sqrLightDist = dot(L, L); + + float attenuation = CalcLightAttenuation(light.radius * light.radius / sqrLightDist); + + #if defined(USE_DSHADOWS) + vec3 sampleVector = L; + L /= sqrt(sqrLightDist); + sampleVector += L * tan(acos(dot(vertexNormal, -L))); + float distance = getLightDepth(sampleVector, light.radius); + attenuation *= pcfShadow(u_ShadowMap2, L, distance, i); + #else + L /= sqrt(sqrLightDist); + #endif + + vec3 H = normalize(L + E); + float NL = clamp(dot(N, L), 0.0, 1.0); + float LH = clamp(dot(L, H), 0.0, 1.0); + float NH = clamp(dot(N, H), 0.0, 1.0); + float VH = clamp(dot(E, H), 0.0, 1.0); + + vec3 reflectance = diffuse + CalcSpecular(specular, NH, NL, NE, LH, VH, roughness); + + outColor += light.color * reflectance * attenuation * NL; + } + return outColor; +} + +vec3 CalcIBLContribution( + in float roughness, + in vec3 N, + in vec3 E, + in vec3 viewOrigin, + in vec3 viewDir, + in float NE, + in vec3 specular +) +{ +#if defined(PER_PIXEL_LIGHTING) && defined(USE_CUBEMAP) + vec3 R = reflect(-E, N); + + // parallax corrected cubemap (cheaper trick) + // from http://seblagarde.wordpress.com/2012/09/29/image-based-lighting-approaches-and-parallax-corrected-cubemap/ + vec3 parallax = u_CubeMapInfo.xyz + u_CubeMapInfo.w * viewDir; + vec3 cubeLightColor = textureLod(u_CubeMap, R - parallax, roughness * ROUGHNESS_MIPS).rgb * u_EnableTextures.w; + + // Base BRDF + #if !defined(USE_CLOTH_BRDF) + vec2 EnvBRDF = texture(u_EnvBrdfMap, vec2(roughness, NE)).rg; + return cubeLightColor * (specular.rgb * EnvBRDF.x + EnvBRDF.y); + // Cloth BRDF + #else + float EnvBRDF = texture(u_EnvBrdfMap, vec2(roughness, NE)).b; + return cubeLightColor * EnvBRDF; + #endif +#else + return vec3(0.0); +#endif +} + +vec3 CalcNormal( in vec3 vertexNormal, in vec4 vertexTangent, in vec2 texCoords ) +{ +#if defined(USE_NORMALMAP) + vec3 biTangent = vertexTangent.w * cross(vertexNormal, vertexTangent.xyz); + vec3 N = texture(u_NormalMap, texCoords).agb - vec3(0.5); + N.xy *= u_NormalScale.xy; + N.z = sqrt(clamp((0.25 - N.x * N.x) - N.y * N.y, 0.0, 1.0)); + N = N.x * vertexTangent.xyz + N.y * biTangent + N.z * vertexNormal; + return normalize(N); +#else + return normalize(vertexNormal); +#endif +} + +void main() +{ + vec3 viewDir, lightColor, ambientColor; + vec3 L, N, E; + + vec2 texCoords = var_TexCoords.xy; + vec2 lmCoords = var_TexCoords.zw; +#if defined(PER_PIXEL_LIGHTING) + vec2 tex_offset = GetParallaxOffset(texCoords, var_TangentViewDir.xyz); + texCoords += tex_offset; +#endif + + vec4 diffuse = texture(u_DiffuseMap, texCoords); + diffuse.a *= var_Color.a; +#if defined(USE_ALPHA_TEST) + if (u_AlphaTestType == ALPHA_TEST_GT0) + { + if (diffuse.a == 0.0) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_LT128) + { + if (diffuse.a >= 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE128) + { + if (diffuse.a < 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE192) + { + if (diffuse.a < 0.75) + discard; + } +#endif + +#if defined(PER_PIXEL_LIGHTING) + viewDir = var_ViewDir.xyz; + E = normalize(viewDir); + L = var_LightDir.xyz; + #if defined(USE_DELUXEMAP) + L += (texture(u_DeluxeMap, lmCoords).xyz - vec3(0.5)) * u_EnableTextures.y; + #endif + float sqrLightDist = dot(L, L); +#endif + +#if defined(USE_LIGHTMAP) + vec4 lightmapColor = texture(u_LightMap, lmCoords); +#endif + +#if defined(PER_PIXEL_LIGHTING) + float attenuation; + + #if defined(USE_LIGHTMAP) + lightColor = lightmapColor.rgb * var_Color.rgb; + ambientColor = vec3 (0.0); + attenuation = 1.0; + #elif defined(USE_LIGHT_VECTOR) + lightColor = u_DirectedLight * var_Color.rgb; + ambientColor = u_AmbientLight * var_Color.rgb; + attenuation = 1.0; + #elif defined(USE_LIGHT_VERTEX) + lightColor = var_Color.rgb; + ambientColor = vec3 (0.0); + attenuation = 1.0; + #endif + + vec3 vertexNormal = mix(var_Normal.xyz, -var_Normal.xyz, float(gl_FrontFacing)) * u_NormalScale.z; + N = CalcNormal(vertexNormal, var_Tangent, texCoords); + L /= sqrt(sqrLightDist); + + #if defined(USE_SHADOWMAP) + vec3 primaryLightDir = normalize(u_PrimaryLightOrigin.xyz); + float NPL = clamp(dot(N, primaryLightDir), -1.0, 1.0); + vec3 normalBias = vertexNormal * (1.0 - NPL); + float shadowValue = sunShadow(u_ViewOrigin, viewDir, normalBias) * NPL; + + // surfaces not facing the light are always shadowed + + //shadowValue = mix(0.0, shadowValue, dot(N, primaryLightDir) > 0.0); + + #if defined(SHADOWMAP_MODULATE) + vec3 ambientScale = mix(vec3(1.0), u_PrimaryLightAmbient, u_EnableTextures.z); + lightColor = mix(ambientScale * lightColor, lightColor, shadowValue); + #endif + #endif + + #if defined(USE_LIGHTMAP) || defined(USE_LIGHT_VERTEX) + ambientColor = lightColor; + float surfNL = clamp(dot(vertexNormal, L), 0.0, 1.0); + + // Scale the incoming light to compensate for the baked-in light angle + // attenuation. + lightColor /= max(surfNL, 0.25); + + // Recover any unused light as ambient, in case attenuation is over 4x or + // light is below the surface + ambientColor = max(ambientColor - lightColor * surfNL, 0.0); + #endif + + // Scale lightColor by PI because we need want to have the same output intensity + // as in vanilla, but we also want correct computation formulas + // Lambiertian Diffuse divides by PI, so multiply light before to get the same intensity + // HDR Lightsources are scaled on upload accordingly + lightColor *= M_PI; + + // Dont scale ambient as we dont compute lambertian diffuse for it + // We dont compute it because cloth diffuse is dependent on NL + // So we just skip this. Reconsider this again when more BRDFS are added + + float AO = 1.0; + #if defined (USE_SSAO) + vec2 windowTex = gl_FragCoord.xy / r_FBufScale; + AO = texture(u_SSAOMap, windowTex).r; + #endif + + vec4 specular = vec4(1.0); + float roughness = 0.99; + #if defined(USE_SPECULARMAP) + #if !defined(USE_SPECGLOSS) + vec4 ORMS = texture(u_SpecularMap, texCoords); + ORMS.xyzw *= u_SpecularScale.zwxy; + + specular.rgb = mix(vec3(0.08) * ORMS.w, diffuse.rgb, ORMS.z); + diffuse.rgb *= vec3(1.0 - ORMS.z); + + roughness = mix(0.01, 1.0, ORMS.y); + AO = min(ORMS.x, AO); + #else + specular = texture(u_SpecularMap, texCoords); + specular.rgb *= u_SpecularScale.xyz; + roughness = mix(1.0, 0.01, specular.a * (1.0 - u_SpecularScale.w)); + #endif + #endif + ambientColor *= AO; + + vec3 H = normalize(L + E); + float NE = abs(dot(N, E)) + 1e-5; + float NL = clamp(dot(N, L), 0.0, 1.0); + float LH = clamp(dot(L, H), 0.0, 1.0); + + vec3 Fd = CalcDiffuse(diffuse.rgb, NE, NL, LH, roughness); + vec3 Fs = vec3(0.0); + + #if defined(USE_LIGHT_VECTOR) + float NH = clamp(dot(N, H), 0.0, 1.0); + float VH = clamp(dot(E, H), 0.0, 1.0); + Fs = CalcSpecular(specular.rgb, NH, NL, NE, LH, VH, roughness); + #endif + + #if ((defined(USE_LIGHTMAP) && defined(USE_DELUXEMAP)) || defined(USE_LIGHT_VERTEX)) && defined(r_deluxeSpecular) + float NH = clamp(dot(N, H), 0.0, 1.0); + float VH = clamp(dot(E, H), 0.0, 1.0); + Fs = CalcSpecular(specular.rgb, NH, NL, NE, LH, VH, roughness) * r_deluxeSpecular; + #endif + + vec3 reflectance = Fd + Fs; + + out_Color.rgb = lightColor * reflectance * (attenuation * NL); + out_Color.rgb += ambientColor * diffuse.rgb; + + #if defined(USE_PRIMARY_LIGHT) + vec3 L2 = normalize(u_PrimaryLightOrigin.xyz); + vec3 H2 = normalize(L2 + E); + float NL2 = clamp(dot(N, L2), 0.0, 1.0); + float L2H2 = clamp(dot(L2, H2), 0.0, 1.0); + float NH2 = clamp(dot(N, H2), 0.0, 1.0); + float VH2 = clamp(dot(E, H), 0.0, 1.0); + reflectance = CalcDiffuse(diffuse.rgb, NE, NL2, L2H2, roughness); + reflectance += CalcSpecular(specular.rgb, NH2, NL2, NE, L2H2, VH2, roughness); + + lightColor = u_PrimaryLightColor; + #if defined(USE_SHADOWMAP) + lightColor *= shadowValue; + #endif + + out_Color.rgb += lightColor * reflectance * NL2; + #endif + + out_Color.rgb += CalcDynamicLightContribution(roughness, N, E, u_ViewOrigin, viewDir, NE, diffuse.rgb, specular.rgb, vertexNormal); + out_Color.rgb += CalcIBLContribution(roughness, N, E, u_ViewOrigin, viewDir, NE, specular.rgb * AO); +#else + lightColor = var_Color.rgb; + #if defined(USE_LIGHTMAP) + lightColor *= lightmapColor.rgb; + #endif + + out_Color.rgb = diffuse.rgb * lightColor; +#endif + + out_Color.a = diffuse.a; + +#if defined(USE_GLOW_BUFFER) + out_Glow = out_Color; +#else + out_Glow = vec4(0.0, 0.0, 0.0, out_Color.a); +#endif +} diff --git a/codemp/rd-rend2/glsl/prefilterEnvMap.glsl b/codemp/rd-rend2/glsl/prefilterEnvMap.glsl new file mode 100644 index 0000000000..6df85b582b --- /dev/null +++ b/codemp/rd-rend2/glsl/prefilterEnvMap.glsl @@ -0,0 +1,141 @@ +/*[Vertex]*/ +out vec2 var_TexCoords; + +void main() +{ + vec2 position = vec2(2.0 * float(gl_VertexID & 2) - 1.0, 4.0 * float(gl_VertexID & 1) - 1.0); + gl_Position = vec4(position, 0.0, 1.0); + var_TexCoords = gl_Position.xy; +} + +/*[Geometry]*/ +layout(triangles) in; +layout(triangle_strip, max_vertices = 18) out; + +in vec2 var_TexCoords[]; + +out vec2 var_ScreenTex; +flat out int cubeFace; + +void main() +{ + for (int face = 0; face < 6; ++face) + { + for (int i = 0; i < 3; ++i) + { + gl_Layer = face; + gl_Position = vec4(var_TexCoords[i], -1.0, 1.0); + var_ScreenTex = var_TexCoords[i]; + cubeFace = face; + EmitVertex(); + } + EndPrimitive(); + } +} + +/*[Fragment]*/ +uniform vec4 u_ViewInfo; // cubeface, mip_level, max_mip_level, roughness +uniform samplerCube u_CubeMap; +in vec2 var_ScreenTex; +flat in int cubeFace; + +out vec4 out_Color; + +// from http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html +float radicalInverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 +} + +vec2 hammersley2D(uint i, uint N) { + return vec2(float(i)/float(N), radicalInverse_VdC(i)); +} + +float D_GGX( in float NH, in float a ) +{ + float a2 = a * a; + float d = (NH * a2 - NH) * NH + 1; + return a2 / (M_PI * d * d); +} + +vec3 ImportanceSampleGGX(vec2 Xi, float Roughness, vec3 N) +{ + float a = Roughness * Roughness; + float Phi = 2.0 * M_PI * Xi.x; + float CosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a * a - 1.0) * Xi.y)); + float SinTheta = sqrt( 1.0 - CosTheta * CosTheta); + + vec3 H; + H.x = SinTheta * cos( Phi ); + H.y = SinTheta * sin( Phi ); + H.z = CosTheta; + + vec3 UpVector = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 TangentX = normalize(cross(UpVector , N)); + vec3 TangentY = cross(N , TangentX); + + return TangentX * H.x + TangentY * H.y + N * H.z; +} + +vec3 PrefilterEnvMap( float Roughness, vec3 R ) +{ + vec3 N = R; + vec3 V = R; + vec3 PrefilteredColor = vec3(0.0); + float TotalWeight = 0.0; + uint NumSamples = 256u; + for ( uint i = 0u; i < NumSamples; i++ ) + { + vec2 Xi = hammersley2D(i, NumSamples); + vec3 H = ImportanceSampleGGX(Xi, Roughness, N); + vec3 L = 2.0 * dot(V, H) * H - V; + float NoL = clamp(dot(N, L), 0.0, 1.0); + if ( NoL > 0.0 ) + { + float NH = max(dot ( N, H ), 0.0); + float HV = max(dot ( H, V ), 0.0); + float D = D_GGX(NH, Roughness); + float pdf = (D * NH / (4.0 * HV)) + 0.0001; + + float saTexel = 4.0 * M_PI / (6.0 * CUBEMAP_RESOLUTION * CUBEMAP_RESOLUTION); + float saSample = 1.0 / (float(NumSamples) * pdf + 0.0001); + + float mipLevel = Roughness == 0.0 ? 0.0 : 0.5 * log2(saSample / saTexel); + + PrefilteredColor += textureLod(u_CubeMap, L, mipLevel).rgb * NoL; + TotalWeight += NoL; + } + } + return PrefilteredColor / TotalWeight; +} + +void main() +{ + vec2 vector = var_ScreenTex; + // from http://www.codinglabs.net/article_physically_based_rendering.aspx + + vec3 normal = normalize(vec3(-vector.x, -vector.y, -1.0)); + + if (cubeFace == 0) + normal = normalize(vec3(1.0, -vector.y, -vector.x)); + else if (cubeFace == 1) + normal = normalize(vec3(-1.0, -vector.y, vector.x)); + else if (cubeFace == 2) + normal = normalize(vec3(vector.x, 1.0, vector.y)); + else if (cubeFace == 3) + normal = normalize(vec3(vector.x, -1.0, -vector.y)); + else if (cubeFace == 4) + normal = normalize(vec3(vector.x, -vector.y, 1.0)); + + float roughness = u_ViewInfo.w; + + vec3 result = PrefilterEnvMap(roughness, normal); + if (roughness == 0.0) + result = textureLod(u_CubeMap, normal, 0.0).rgb; + + out_Color = vec4(result, 1.0); +} \ No newline at end of file diff --git a/codemp/rd-rend2/glsl/pshadow.glsl b/codemp/rd-rend2/glsl/pshadow.glsl new file mode 100644 index 0000000000..371ce92eed --- /dev/null +++ b/codemp/rd-rend2/glsl/pshadow.glsl @@ -0,0 +1,106 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec3 attr_Normal; + +uniform mat4 u_ModelViewProjectionMatrix; + +out vec3 var_Position; +out vec3 var_Normal; + + +void main() +{ + gl_Position = u_ModelViewProjectionMatrix * vec4(attr_Position, 1.0); + + var_Position = attr_Position; + var_Normal = attr_Normal * 2.0 - vec3(1.0); +} + +/*[Fragment]*/ +uniform sampler2DArrayShadow u_ShadowMap; +uniform vec3 u_LightForward; +uniform vec3 u_LightUp; +uniform vec3 u_LightRight; +uniform vec4 u_LightOrigin; +uniform float u_LightRadius; + +in vec3 var_Position; +in vec3 var_Normal; + +out vec4 out_Color; + +#define PCF_SAMPLES 9 +#define TEXTURE_SCALE float(1.0/1024.0) + +const vec2 poissonDisc[PCF_SAMPLES] = vec2[PCF_SAMPLES]( +vec2(-0.7055767, 0.196515), vec2(0.3524343, -0.7791386), +vec2(0.2391056, 0.9189604), vec2(-0.07580382, -0.09224417), +vec2(0.5784913, -0.002528916), vec2(0.192888, 0.4064181), +vec2(-0.6335801, -0.5247476), vec2(-0.5579782, 0.7491854), +vec2(0.7320465, 0.6317794) +); + +void main() +{ + vec3 lightToPos = var_Position - u_LightOrigin.xyz; + vec2 st = vec2(-dot(u_LightRight, lightToPos), dot(u_LightUp, lightToPos)); + vec3 L = normalize(-lightToPos); + vec3 normal = normalize(var_Normal); + + float fade = length(st); + +#if defined(USE_DISCARD) + if (fade >= 1.0) + { + discard; + } +#endif + + fade = clamp(8.0 - fade * 8.0, 0.0, 1.0); + + st = st * 0.5 + vec2(0.5); + + float intensity = clamp((1.0 - dot(lightToPos, lightToPos) / (u_LightRadius * u_LightRadius)) * 2.0, 0.0, 1.0); + float lightDist = length(lightToPos); + +#if defined(USE_DISCARD) + if (dot(normalize(-u_LightForward), L) <= 0.0) + { + discard; + } + + if (dot(normal, L) <= 0.0) + { + discard; + } +#endif + + intensity *= max(dot(normal, L), 0.0); + intensity *= fade; + + float part = 0.0; +#if defined(USE_PCF) + float offsetScale = pow(lightDist, 4.0) * TEXTURE_SCALE * 0.00000001; + offsetScale = max(TEXTURE_SCALE, offsetScale); + for (int i = 0; i < PCF_SAMPLES; ++i) + { + part += 1.0 - float(texture(u_ShadowMap, vec4(st + offsetScale * poissonDisc[i], u_LightOrigin.w, 1.0))); + } +#else + part = 1.0 - float(texture(u_ShadowMap, vec4(st, u_LightOrigin.w, 1.0))); +#endif + + if (part <= 0.0) + { + discard; + } + +#if defined(USE_PCF) + intensity *= part * 0.111; +#else + intensity *= part; +#endif + + out_Color.rgb = vec3(.0,.0,.0); + out_Color.a = clamp(intensity, 0.0, 0.75); +} \ No newline at end of file diff --git a/codemp/rd-rend2/glsl/refraction.glsl b/codemp/rd-rend2/glsl/refraction.glsl new file mode 100644 index 0000000000..dfee37f149 --- /dev/null +++ b/codemp/rd-rend2/glsl/refraction.glsl @@ -0,0 +1,522 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec3 attr_Normal; + +#if defined(USE_VERTEX_ANIMATION) +in vec3 attr_Position2; +in vec3 attr_Normal2; +#elif defined(USE_SKELETAL_ANIMATION) +in uvec4 attr_BoneIndexes; +in vec4 attr_BoneWeights; +#endif + +in vec4 attr_Color; +in vec2 attr_TexCoord0; + +#if defined(USE_TCGEN) +in vec2 attr_TexCoord1; +#endif + +layout(std140) uniform Scene +{ + vec4 u_PrimaryLightOrigin; + vec3 u_PrimaryLightAmbient; + int u_globalFogIndex; + vec3 u_PrimaryLightColor; + float u_PrimaryLightRadius; + float u_frameTime; + float u_deltaTime; +}; + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; + float u_entityTime; +}; + +#if defined(USE_DEFORM_VERTEXES) || defined(USE_RGBAGEN) +layout(std140) uniform ShaderInstance +{ + vec4 u_DeformParams0; + vec4 u_DeformParams1; + float u_Time; + float u_PortalRange; + int u_DeformType; + int u_DeformFunc; +}; +#endif + +#if defined(USE_SKELETAL_ANIMATION) +layout(std140) uniform Bones +{ + mat3x4 u_BoneMatrices[MAX_G2_BONES]; +}; +#endif + +#if defined(USE_TCMOD) +uniform vec4 u_DiffuseTexMatrix; +uniform vec4 u_DiffuseTexOffTurb; +#endif + +#if defined(USE_TCGEN) +uniform int u_TCGen0; +uniform vec3 u_TCGen0Vector0; +uniform vec3 u_TCGen0Vector1; +#endif + +uniform vec4 u_BaseColor; +uniform vec4 u_VertColor; +uniform vec4 u_Color; + +#if defined(USE_RGBAGEN) +uniform int u_ColorGen; +uniform int u_AlphaGen; +#endif + +out vec2 var_DiffuseTex; +out vec4 var_Color; +out vec4 var_RefractPosR; +out vec4 var_RefractPosG; +out vec4 var_RefractPosB; + +#if defined(USE_DEFORM_VERTEXES) +float GetNoiseValue( float x, float y, float z, float t ) +{ + // Variation on the 'one-liner random function'. + // Not sure if this is still 'correctly' random + return fract( sin( dot( + vec4( x, y, z, t ), + vec4( 12.9898, 78.233, 12.9898, 78.233 ) + )) * 43758.5453 ); +} + +float CalculateDeformScale( in int func, in float time, in float phase, in float frequency ) +{ + float value = phase + time * frequency; + + switch ( func ) + { + case WF_SIN: + return sin(value * 2.0 * M_PI); + case WF_SQUARE: + return sign(0.5 - fract(value)); + case WF_TRIANGLE: + return abs(fract(value + 0.75) - 0.5) * 4.0 - 1.0; + case WF_SAWTOOTH: + return fract(value); + case WF_INVERSE_SAWTOOTH: + return 1.0 - fract(value); + default: + return 0.0; + } +} + +vec3 DeformPosition(const vec3 pos, const vec3 normal, const vec2 st) +{ + switch ( u_DeformType ) + { + default: + { + return pos; + } + + case DEFORM_BULGE: + { + float bulgeHeight = u_DeformParams0.y; // amplitude + float bulgeWidth = u_DeformParams0.z; // phase + float bulgeSpeed = u_DeformParams0.w; // frequency + + float scale = CalculateDeformScale( WF_SIN, (u_entityTime + u_frameTime + u_Time), bulgeWidth * st.x, bulgeSpeed ); + + return pos + normal * scale * bulgeHeight; + } + + case DEFORM_BULGE_UNIFORM: + { + float bulgeHeight = u_DeformParams0.y; // amplitude + + return pos + normal * bulgeHeight; + } + + case DEFORM_WAVE: + { + float base = u_DeformParams0.x; + float amplitude = u_DeformParams0.y; + float phase = u_DeformParams0.z; + float frequency = u_DeformParams0.w; + float spread = u_DeformParams1.x; + + float offset = dot( pos.xyz, vec3( spread ) ); + float scale = CalculateDeformScale( u_DeformFunc, (u_entityTime + u_frameTime + u_Time), phase + offset, frequency ); + + return pos + normal * (base + scale * amplitude); + } + + case DEFORM_MOVE: + { + float base = u_DeformParams0.x; + float amplitude = u_DeformParams0.y; + float phase = u_DeformParams0.z; + float frequency = u_DeformParams0.w; + vec3 direction = u_DeformParams1.xyz; + + float scale = CalculateDeformScale( u_DeformFunc, (u_entityTime + u_frameTime + u_Time), phase, frequency ); + + return pos + direction * (base + scale * amplitude); + } + } +} + +vec3 DeformNormal( const in vec3 position, const in vec3 normal ) +{ + if ( u_DeformType != DEFORM_NORMALS ) + { + return normal; + } + + float amplitude = u_DeformParams0.y; + float frequency = u_DeformParams0.w; + + vec3 outNormal = normal; + const float scale = 0.98; + + outNormal.x += amplitude * GetNoiseValue( + position.x * scale, + position.y * scale, + position.z * scale, + (u_entityTime + u_frameTime + u_Time) * frequency ); + + outNormal.y += amplitude * GetNoiseValue( + 100.0 * position.x * scale, + position.y * scale, + position.z * scale, + (u_entityTime + u_frameTime + u_Time) * frequency ); + + outNormal.z += amplitude * GetNoiseValue( + 200.0 * position.x * scale, + position.y * scale, + position.z * scale, + (u_entityTime + u_frameTime + u_Time) * frequency ); + + return outNormal; +} +#endif + +#if defined(USE_TCGEN) +vec2 GenTexCoords(int TCGen, vec3 position, vec3 normal, vec3 TCGenVector0, vec3 TCGenVector1) +{ + vec2 tex = attr_TexCoord0.st; + + if (TCGen >= TCGEN_LIGHTMAP && TCGen <= TCGEN_LIGHTMAP3) + { + tex = attr_TexCoord1.st; + } + else if (TCGen == TCGEN_ENVIRONMENT_MAPPED) + { + vec3 viewer = normalize(u_LocalViewOrigin - position); + vec2 ref = reflect(viewer, normal).yz; + tex.s = ref.x * -0.5 + 0.5; + tex.t = ref.y * 0.5 + 0.5; + } + else if (TCGen == TCGEN_VECTOR) + { + tex = vec2(dot(position, TCGenVector0), dot(position, TCGenVector1)); + } + + return tex; +} +#endif + +#if defined(USE_TCMOD) +vec2 ModTexCoords(vec2 st, vec3 position, vec4 texMatrix, vec4 offTurb) +{ + float amplitude = offTurb.z; + float phase = offTurb.w * 2.0 * M_PI; + vec2 st2; + st2.x = st.x * texMatrix.x + (st.y * texMatrix.z + offTurb.x); + st2.y = st.x * texMatrix.y + (st.y * texMatrix.w + offTurb.y); + + vec2 offsetPos = vec2(position.x + position.z, position.y); + + vec2 texOffset = sin(offsetPos * (2.0 * M_PI / 1024.0) + vec2(phase)); + + return st2 + texOffset * amplitude; +} +#endif + +#if defined(USE_RGBAGEN) +vec4 CalcColor(vec3 position, vec3 normal) +{ + vec4 color = u_VertColor * attr_Color + u_BaseColor; + + if (u_ColorGen == CGEN_LIGHTING_DIFFUSE) + { + float incoming = clamp(dot(normal, u_ModelLightDir), 0.0, 1.0); + + color.rgb = clamp(u_DirectedLight * incoming + u_AmbientLight, 0.0, 1.0); + } + + vec3 viewer = u_LocalViewOrigin - position; + + if (u_AlphaGen == AGEN_LIGHTING_SPECULAR) + { + vec3 lightDir = normalize(vec3(-960.0, 1980.0, 96.0) - position); + vec3 reflected = -reflect(lightDir, normal); + + color.a = clamp(dot(reflected, normalize(viewer)), 0.0, 1.0); + color.a *= color.a; + color.a *= color.a; + } + else if (u_AlphaGen == AGEN_PORTAL) + { + color.a = clamp(length(viewer) / u_PortalRange, 0.0, 1.0); + } + + return color; +} +#endif + +#if defined(USE_SKELETAL_ANIMATION) +mat4x3 GetBoneMatrix(uint index) +{ + mat3x4 bone = u_BoneMatrices[index]; + return mat4x3( + bone[0].x, bone[1].x, bone[2].x, + bone[0].y, bone[1].y, bone[2].y, + bone[0].z, bone[1].z, bone[2].z, + bone[0].w, bone[1].w, bone[2].w); +} +#endif + +const float etaR = 1.0 / 1.35; +const float etaG = 1.0 / 1.20; +const float etaB = 1.0 / 1.05; + +void main() +{ +#if defined(USE_VERTEX_ANIMATION) + vec3 position = mix(attr_Position, attr_Position2, u_VertexLerp); + vec3 normal = mix(attr_Normal, attr_Normal2, u_VertexLerp); + normal = normalize(normal - vec3(0.5)); +#elif defined(USE_SKELETAL_ANIMATION) + mat4x3 influence = + GetBoneMatrix(attr_BoneIndexes[0]) * attr_BoneWeights[0] + + GetBoneMatrix(attr_BoneIndexes[1]) * attr_BoneWeights[1] + + GetBoneMatrix(attr_BoneIndexes[2]) * attr_BoneWeights[2] + + GetBoneMatrix(attr_BoneIndexes[3]) * attr_BoneWeights[3]; + + vec3 position = influence * vec4(attr_Position, 1.0); + vec3 normal = normalize(influence * vec4(attr_Normal - vec3(0.5), 0.0)); +#else + vec3 position = attr_Position; + vec3 normal = attr_Normal * 2.0 - vec3(1.0); +#endif + +#if defined(USE_DEFORM_VERTEXES) + position = DeformPosition(position, normal, attr_TexCoord0.st); + normal = DeformNormal( position, normal ); +#endif + + mat4 MVP = u_viewProjectionMatrix * u_ModelMatrix; + gl_Position = MVP * vec4(position, 1.0); + +#if defined(USE_TCGEN) + vec2 tex = GenTexCoords(u_TCGen0, position, normal, u_TCGen0Vector0, u_TCGen0Vector1); +#else + vec2 tex = attr_TexCoord0.st; +#endif + +#if defined(USE_TCMOD) + var_DiffuseTex = ModTexCoords(tex, position, u_DiffuseTexMatrix, u_DiffuseTexOffTurb); +#else + var_DiffuseTex = tex; +#endif + + if ( u_FXVolumetricBase >= 0.0 ) + { + vec3 viewForward = u_ViewForward.xyz; + float d = clamp(dot(normalize(viewForward), normalize(normal)), 0.0, 1.0); + d = d * d; + d = d * d; + + var_Color = vec4(u_FXVolumetricBase * (1.0 - d)); + } + else + { +#if defined(USE_RGBAGEN) + var_Color = CalcColor(position, normal); +#else + var_Color = u_VertColor * attr_Color + u_BaseColor; +#endif + } + + vec3 ws_Position = mat3(u_ModelMatrix) * position; + vec3 ws_Normal = normalize(mat3(u_ModelMatrix) * normal); + vec3 ws_ViewDir = (u_ViewForward + u_ViewLeft * -gl_Position.x) + u_ViewUp * gl_Position.y; + + #if defined(USE_TCMOD) + float distance = u_Color.a * clamp(1.0 - distance(tex, var_DiffuseTex), 0.0, 1.0); + #else + float distance = u_Color.a; + #endif + + mat3 inverseModel = inverse(mat3(u_ModelMatrix)); + + vec3 refraction_vec = normalize(refract(ws_ViewDir, ws_Normal, etaR)); + vec3 new_pos = (distance * refraction_vec) + ws_Position; + var_RefractPosR = vec4(inverseModel * new_pos, 1.0); + var_RefractPosR = MVP * var_RefractPosR; + + refraction_vec = normalize(refract(ws_ViewDir, ws_Normal, etaG)); + new_pos = (distance * refraction_vec) + ws_Position; + var_RefractPosG = vec4(inverseModel * new_pos, 1.0); + var_RefractPosG = MVP * var_RefractPosG; + + refraction_vec = normalize(refract(ws_ViewDir, ws_Normal, etaB)); + new_pos = (distance * refraction_vec) + ws_Position; + var_RefractPosB = vec4(inverseModel * new_pos, 1.0); + var_RefractPosB = MVP * var_RefractPosB; +} + + +/*[Fragment]*/ + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; + float u_entityTime; +}; + +uniform sampler2D u_TextureMap; +uniform sampler2D u_LevelsMap; +uniform sampler2D u_ScreenDepthMap; +uniform vec4 u_Color; +uniform vec2 u_AutoExposureMinMax; +uniform vec3 u_ToneMinAvgMaxLinear; + +#if defined(USE_ALPHA_TEST) +uniform int u_AlphaTestType; +#endif + +in vec2 var_DiffuseTex; +in vec4 var_Color; +in vec4 var_RefractPosR; +in vec4 var_RefractPosG; +in vec4 var_RefractPosB; + +out vec4 out_Color; + +vec3 LinearTosRGB( in vec3 color ) +{ + vec3 lo = 12.92 * color; + vec3 hi = 1.055 * pow(color, vec3(0.4166666)) - 0.055; + return mix(lo, hi, greaterThanEqual(color, vec3(0.0031308))); +} + +vec3 FilmicTonemap(vec3 x) +{ + const float SS = 0.22; // Shoulder Strength + const float LS = 0.30; // Linear Strength + const float LA = 0.10; // Linear Angle + const float TS = 0.20; // Toe Strength + const float TAN = 0.01; // Toe Angle Numerator + const float TAD = 0.30; // Toe Angle Denominator + + vec3 SSxx = SS * x * x; + vec3 LSx = LS * x; + vec3 LALSx = LSx * LA; + + return ((SSxx + LALSx + TS * TAN) / (SSxx + LSx + TS * TAD)) - TAN / TAD; +} + +void main() +{ + vec2 texR = (var_RefractPosR.xy / var_RefractPosR.w) * 0.5 + 0.5; + vec2 texG = (var_RefractPosG.xy / var_RefractPosG.w) * 0.5 + 0.5; + vec2 texB = (var_RefractPosB.xy / var_RefractPosB.w) * 0.5 + 0.5; + + vec4 color; + color.r = texture(u_TextureMap, texR).r; + color.g = texture(u_TextureMap, texG).g; + color.b = texture(u_TextureMap, texB).b; + color.a = var_Color.a; + color.rgb *= var_Color.rgb; + color.rgb *= u_Color.rgb; + +#if defined(USE_ALPHA_TEST) + if (u_AlphaTestType == ALPHA_TEST_GT0) + { + if (color.a == 0.0) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_LT128) + { + if (color.a >= 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE128) + { + if (color.a < 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE192) + { + if (color.a < 0.75) + discard; + } +#endif + +#if defined(USE_TONEMAPPING) + vec3 minAvgMax = texture(u_LevelsMap, texG).rgb; + vec3 logMinAvgMaxLum = clamp(minAvgMax * 20.0 - 10.0, -u_AutoExposureMinMax.y, -u_AutoExposureMinMax.x); + float avgLum = exp2(logMinAvgMaxLum.y); + + color.rgb *= u_ToneMinAvgMaxLinear.y / avgLum; + color.rgb = max(vec3(0.0), color.rgb - vec3(u_ToneMinAvgMaxLinear.x)); + + vec3 fWhite = 1.0 / FilmicTonemap(vec3(u_ToneMinAvgMaxLinear.z - u_ToneMinAvgMaxLinear.x)); + color.rgb = FilmicTonemap(color.rgb) * fWhite; + + #if defined(USE_LINEAR_LIGHT) + color.rgb = LinearTosRGB(color.rgb); + #endif +#endif + + out_Color = clamp(color, 0.0, 1.0); +} diff --git a/codemp/rd-rend2/glsl/shadowvolume.glsl b/codemp/rd-rend2/glsl/shadowvolume.glsl new file mode 100644 index 0000000000..e0a1dcbb03 --- /dev/null +++ b/codemp/rd-rend2/glsl/shadowvolume.glsl @@ -0,0 +1,142 @@ +/*[Vertex]*/ +in vec3 attr_Position; +#if defined(USE_VERTEX_ANIMATION) +in vec3 attr_Position2; +#elif defined(USE_SKELETAL_ANIMATION) +in uvec4 attr_BoneIndexes; +in vec4 attr_BoneWeights; +#endif + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; +}; + +#if defined(USE_SKELETAL_ANIMATION) +layout(std140) uniform Bones +{ + mat3x4 u_BoneMatrices[MAX_G2_BONES]; +}; + +mat4x3 GetBoneMatrix(uint index) +{ + mat3x4 bone = u_BoneMatrices[index]; + return mat4x3( + bone[0].x, bone[1].x, bone[2].x, + bone[0].y, bone[1].y, bone[2].y, + bone[0].z, bone[1].z, bone[2].z, + bone[0].w, bone[1].w, bone[2].w); +} +#endif + +out vec3 var_Position; + +void main() +{ +#if defined(USE_VERTEX_ANIMATION) + vec3 position = mix(attr_Position, attr_Position2, u_VertexLerp); +#elif defined(USE_SKELETAL_ANIMATION) + mat4x3 influence = + GetBoneMatrix(attr_BoneIndexes[0]) * attr_BoneWeights[0] + + GetBoneMatrix(attr_BoneIndexes[1]) * attr_BoneWeights[1] + + GetBoneMatrix(attr_BoneIndexes[2]) * attr_BoneWeights[2] + + GetBoneMatrix(attr_BoneIndexes[3]) * attr_BoneWeights[3]; + + vec3 position = influence * vec4(attr_Position, 1.0); +#else + vec3 position = attr_Position; +#endif + var_Position = position; +} + +/*[Geometry]*/ +layout(triangles) in; +layout(triangle_strip, max_vertices = 18) out; + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform Entity +{ + mat4 u_ModelMatrix; + vec4 u_LocalLightOrigin; + vec3 u_AmbientLight; + float u_LocalLightRadius; + vec3 u_DirectedLight; + float u_FXVolumetricBase; + vec3 u_ModelLightDir; + float u_VertexLerp; + vec3 u_LocalViewOrigin; +}; + +in vec3 var_Position[]; + +void quad(in vec3 first, in vec3 second, in vec3 L, in mat4 MVP) +{ + gl_Position = MVP * vec4(first, 1.0); + EmitVertex(); + gl_Position = MVP * vec4(first - L, 1.0); + EmitVertex(); + gl_Position = MVP * vec4(second, 1.0); + EmitVertex(); + gl_Position = MVP * vec4(second - L, 1.0); + EmitVertex(); + EndPrimitive(); +} + +void main() +{ + vec3 BmA = var_Position[1].xyz - var_Position[0].xyz; + vec3 CmA = var_Position[2].xyz - var_Position[0].xyz; + + mat4 MVP = u_viewProjectionMatrix * u_ModelMatrix; + + if (dot(cross(BmA,CmA), -u_ModelLightDir.xyz) > 0.0) { + vec3 L = u_ModelLightDir.xyz*u_LocalLightRadius; + + // front cap + gl_Position = MVP * vec4(var_Position[0].xyz, 1.0); + EmitVertex(); + gl_Position = MVP * vec4(var_Position[1].xyz, 1.0); + EmitVertex(); + gl_Position = MVP * vec4(var_Position[2].xyz, 1.0); + EmitVertex(); + EndPrimitive(); + + // sides + quad(var_Position[0], var_Position[1], L, MVP); + quad(var_Position[1], var_Position[2], L, MVP); + quad(var_Position[2], var_Position[0], L, MVP); + + // back cap + gl_Position = MVP * vec4(var_Position[2].xyz - L, 1.0); + EmitVertex(); + gl_Position = MVP * vec4(var_Position[1].xyz - L, 1.0); + EmitVertex(); + gl_Position = MVP * vec4(var_Position[0].xyz - L, 1.0); + EmitVertex(); + EndPrimitive(); + } +} + +/*[Fragment]*/ +out vec4 out_Color; +void main() +{ + out_Color = vec4(0.0, 0.0, 0.0, 1.0); +} \ No newline at end of file diff --git a/codemp/rd-rend2/glsl/ssao.glsl b/codemp/rd-rend2/glsl/ssao.glsl new file mode 100644 index 0000000000..53aeb67630 --- /dev/null +++ b/codemp/rd-rend2/glsl/ssao.glsl @@ -0,0 +1,109 @@ +/*[Vertex]*/ +out vec2 var_ScreenTex; + +void main() +{ + const vec2 positions[] = vec2[3]( + vec2(-1.0f, 1.0f), + vec2(-1.0f, -3.0f), + vec2( 3.0f, 1.0f) + ); + + const vec2 texcoords[] = vec2[3]( + vec2( 0.0f, 1.0f), + vec2( 0.0f, -1.0f), + vec2( 2.0f, 1.0f) + ); + + gl_Position = vec4(positions[gl_VertexID], 0.0, 1.0); + var_ScreenTex = texcoords[gl_VertexID]; +} + +/*[Fragment]*/ +uniform sampler2D u_ScreenDepthMap; +uniform vec4 u_ViewInfo; // zfar / znear, zfar + +in vec2 var_ScreenTex; + +out vec4 out_Color; + +vec2 poissonDisc[9] = vec2[9]( +vec2(-0.7055767, 0.196515), vec2(0.3524343, -0.7791386), +vec2(0.2391056, 0.9189604), vec2(-0.07580382, -0.09224417), +vec2(0.5784913, -0.002528916), vec2(0.192888, 0.4064181), +vec2(-0.6335801, -0.5247476), vec2(-0.5579782, 0.7491854), +vec2(0.7320465, 0.6317794) +); + +// Input: It uses texture coords as the random number seed. +// Output: Random number: [0,1), that is between 0.0 and 0.999999... inclusive. +// Author: Michael Pohoreski +// Copyright: Copyleft 2012 :-) +// Source: http://stackoverflow.com/questions/5149544/can-i-generate-a-random-number-inside-a-pixel-shader + +float random( const vec2 p ) +{ + // We need irrationals for pseudo randomness. + // Most (all?) known transcendental numbers will (generally) work. + const vec2 r = vec2( + 23.1406926327792690, // e^pi (Gelfond's constant) + 2.6651441426902251); // 2^sqrt(2) (Gelfond-Schneider constant) + //return fract( cos( mod( 123456789., 1e-7 + 256. * dot(p,r) ) ) ); + return mod( 123456789., 1e-7 + 256. * dot(p,r) ); +} + +mat2 randomRotation( const vec2 p ) +{ + float r = random(p); + float sinr = sin(r); + float cosr = cos(r); + return mat2(cosr, sinr, -sinr, cosr); +} + +float getLinearDepth(sampler2D depthMap, const vec2 tex, const float zFarDivZNear) +{ + float sampleZDivW = texture(depthMap, tex).r; + return 1.0 / mix(zFarDivZNear, 1.0, sampleZDivW); +} + +float ambientOcclusion(sampler2D depthMap, const vec2 tex, const float zFarDivZNear, const float zFar) +{ + float result = 0; + + float sampleZ = zFar * getLinearDepth(depthMap, tex, zFarDivZNear); + + vec2 expectedSlope = vec2(dFdx(sampleZ), dFdy(sampleZ)) / vec2(dFdx(tex.x), dFdy(tex.y)); + + if (length(expectedSlope) > 5000.0) + return 1.0; + + vec2 offsetScale = vec2(3.0 / sampleZ); + + mat2 rmat = randomRotation(tex); + + int i; + for (i = 0; i < 9; i++) + { + vec2 offset = rmat * poissonDisc[i] * offsetScale; + float sampleZ2 = zFar * getLinearDepth(depthMap, tex + offset, zFarDivZNear); + + if (abs(sampleZ - sampleZ2) > 20.0) + result += 1.0; + else + { + float expectedZ = sampleZ + dot(expectedSlope, offset); + result += step(expectedZ - 1.0, sampleZ2); + } + } + + result *= 0.11111; + + return result; +} + +void main() +{ + float result = ambientOcclusion(u_ScreenDepthMap, var_ScreenTex, u_ViewInfo.x, u_ViewInfo.y); + + out_Color = vec4(vec3(result), 1.0); +} diff --git a/codemp/rd-rend2/glsl/surface_sprites.glsl b/codemp/rd-rend2/glsl/surface_sprites.glsl new file mode 100644 index 0000000000..338f7a421e --- /dev/null +++ b/codemp/rd-rend2/glsl/surface_sprites.glsl @@ -0,0 +1,297 @@ +/*[Vertex]*/ +in vec4 attr_Position; // x, y, z, random value [0.0, 1.0] +in vec3 attr_Normal; +in vec3 attr_Color; +in vec4 attr_Position2; // width, height, skew.x, skew.y + +layout(std140) uniform Scene +{ + vec4 u_PrimaryLightOrigin; + vec3 u_PrimaryLightAmbient; + int u_globalFogIndex; + vec3 u_PrimaryLightColor; + float u_PrimaryLightRadius; + float u_frameTime; + float u_deltaTime; +}; + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +layout(std140) uniform SurfaceSprite +{ + vec2 u_FxGrow; + float u_FxDuration; + float u_FadeStartDistance; + float u_FadeEndDistance; + float u_FadeScale; + float u_Wind; + float u_WindIdle; + float u_FxAlphaStart; + float u_FxAlphaEnd; +}; + +out vec2 var_TexCoords; +out float var_Alpha; +out vec3 var_Color; + +#if defined(FX_SPRITE) +out float var_Effectpos; +#endif + +#if defined(USE_FOG) +out vec3 var_WSPosition; +#endif + +void main() +{ + vec3 V = u_ViewOrigin - attr_Position.xyz; + + float width = attr_Position2.x; + float height = attr_Position2.y; + vec2 skew = attr_Position2.zw; + + float distanceToCamera = length(V); + float fadeScale = smoothstep(u_FadeStartDistance, u_FadeEndDistance, + distanceToCamera); + width += u_FadeScale * fadeScale * width; + +#if defined(FX_SPRITE) + float sprite_time = u_frameTime * 1000.0; + var_Effectpos = fract((sprite_time+10000.0*attr_Position.w) / u_FxDuration); + width += var_Effectpos * width * u_FxGrow.x; + height += var_Effectpos * height * u_FxGrow.y; +#endif + + float halfWidth = width * 0.5; + vec3 offsets[] = vec3[]( +#if defined(FACE_UP) + vec3( halfWidth, -halfWidth, 0.0), + vec3( halfWidth, halfWidth, 0.0), + vec3(-halfWidth, halfWidth, 0.0), + vec3(-halfWidth, -halfWidth, 0.0) +#else + vec3( halfWidth, 0.0, 0.0), + vec3( halfWidth, 0.0, height), + vec3(-halfWidth, 0.0, height), + vec3(-halfWidth, 0.0, 0.0) +#endif + ); + + const vec2 texcoords[] = vec2[]( + vec2(1.0, 1.0), + vec2(1.0, 0.0), + vec2(0.0, 0.0), + vec2(0.0, 1.0) + ); + + vec3 offset = offsets[gl_VertexID % 4]; + + +#if defined(FACE_CAMERA) + vec2 toCamera = normalize(V.xy); + offset.xy = offset.x*vec2(toCamera.y, -toCamera.x); +#elif defined(FACE_FLATTENED) + // Make this sprite face in some direction + offset.xy = offset.x * attr_Normal.xy; +#elif !defined(FACE_UP) + // Make this sprite face in some direction in direction of the camera + vec2 toCamera = normalize(V.xy); + offset.xy = offset.x * (attr_Normal.xy + 3.0 * vec2(toCamera.y, -toCamera.x)) * 0.25; +#endif + +#if !defined(FACE_UP) && !defined(FX_SPRITE) + float isLowerVertex = float(offset.z == 0.0); + offset.xy += mix(skew, vec2(0.0), isLowerVertex); + float sprite_time = u_frameTime * 1000.0; + float angle = (attr_Position.x + attr_Position.y) * 0.02 + (sprite_time * 0.0015); + float windsway = mix(height* u_WindIdle * 0.075, 0.0, isLowerVertex); + offset.xy += vec2(cos(angle), sin(angle)) * windsway; +#endif + + vec4 worldPos = vec4(attr_Position.xyz + offset, 1.0); + gl_Position = u_viewProjectionMatrix * worldPos; + var_TexCoords = texcoords[gl_VertexID % 4]; + var_Color = attr_Color; + var_Alpha = 1.0 - fadeScale; + #if defined(USE_FOG) + var_WSPosition = worldPos.xyz; + #endif +} + +/*[Fragment]*/ +uniform sampler2D u_DiffuseMap; + +in vec2 var_TexCoords; +in vec3 var_Color; +in float var_Alpha; + +#if defined(FX_SPRITE) +in float var_Effectpos; +#endif + +#if defined(USE_FOG) +in vec3 var_WSPosition; +#endif + +layout(std140) uniform SurfaceSprite +{ + vec2 u_FxGrow; + float u_FxDuration; + float u_FadeStartDistance; + float u_FadeEndDistance; + float u_FadeScale; + float u_Wind; + float u_WindIdle; + float u_FxAlphaStart; + float u_FxAlphaEnd; +}; + +#if defined(USE_FOG) +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +struct Fog +{ + vec4 plane; + vec4 color; + float depthToOpaque; + bool hasPlane; +}; + +layout(std140) uniform Fogs +{ + int u_NumFogs; + Fog u_Fogs[16]; +}; + +uniform int u_FogIndex; +uniform vec4 u_FogColorMask; +#endif + +#if defined(ALPHA_TEST) +uniform int u_AlphaTestType; +#endif + +out vec4 out_Color; +out vec4 out_Glow; + +#if defined(USE_FOG) +float CalcFog(in vec3 viewOrigin, in vec3 position, in Fog fog) +{ + bool inFog = dot(viewOrigin, fog.plane.xyz) - fog.plane.w >= 0.0 || !fog.hasPlane; + + // line: x = o + tv + // plane: (x . n) + d = 0 + // intersects: dot(o + tv, n) + d = 0 + // dot(o + tv, n) = -d + // dot(o, n) + t*dot(n, v) = -d + // t = -(d + dot(o, n)) / dot(n, v) + vec3 V = position - viewOrigin; + + // fogPlane is inverted in tr_bsp for some reason. + float t = -(fog.plane.w + dot(viewOrigin, -fog.plane.xyz)) / dot(V, -fog.plane.xyz); + + bool intersects = (t > 0.0 && t <= 1.0); + if (inFog == intersects) + return 0.0; + + float distToVertexFromViewOrigin = length(V); + float distToIntersectionFromViewOrigin = t * distToVertexFromViewOrigin; + + float distOutsideFog = max(distToVertexFromViewOrigin - distToIntersectionFromViewOrigin, 0.0); + float distThroughFog = mix(distOutsideFog, distToVertexFromViewOrigin, inFog); + + float z = fog.depthToOpaque * distThroughFog; + return 1.0 - clamp(exp(-(z * z)), 0.0, 1.0); +} +#endif + +void main() +{ +#if defined(ALPHA_TEST) + float alphaTestValue = 0.5; + if (u_AlphaTestType == ALPHA_TEST_GT0) + { + alphaTestValue = 0.0; + } + else if (u_AlphaTestType == ALPHA_TEST_GE192) + { + alphaTestValue = 0.75; + } +#else + const float alphaTestValue = 0.5; +#endif + + out_Color = texture(u_DiffuseMap, var_TexCoords); + out_Color.rgb *= var_Color; + out_Color.a *= var_Alpha*(1.0 - alphaTestValue) + alphaTestValue; + +#if defined(FX_SPRITE) + float fxalpha = u_FxAlphaEnd - u_FxAlphaStart; + if (u_FxAlphaEnd < 0.05) + { + if (var_Effectpos > 0.5) + out_Color.a *= u_FxAlphaStart + (fxalpha * (var_Effectpos - 0.5) * 2.0); + else + out_Color.a *= u_FxAlphaStart + (fxalpha * (0.5 - var_Effectpos) * 2.0); + } + else + { + out_Color.a *= u_FxAlphaStart + (fxalpha * var_Effectpos); + } +#endif + +#if defined(ALPHA_TEST) + if (u_AlphaTestType == ALPHA_TEST_GT0) + { + if (out_Color.a == 0.0) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_LT128) + { + if (out_Color.a >= 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE128) + { + if (out_Color.a < 0.5) + discard; + } + else if (u_AlphaTestType == ALPHA_TEST_GE192) + { + if (out_Color.a < 0.75) + discard; + } +#endif + +#if defined(USE_FOG) + Fog fog = u_Fogs[u_FogIndex]; + float fogFactor = CalcFog(u_ViewOrigin, var_WSPosition, fog); +#if defined(ADDITIVE_BLEND) + out_Color.rgb *= fog.color.rgb * (1.0 - fogFactor); +#else + out_Color.rgb = mix(out_Color.rgb, fog.color.rgb, fogFactor); +#endif +#endif + +#if defined(ADDITIVE_BLEND) + out_Color.rgb *= out_Color.a; +#endif + + out_Glow = vec4(0.0); +} diff --git a/codemp/rd-rend2/glsl/texturecolor.glsl b/codemp/rd-rend2/glsl/texturecolor.glsl new file mode 100644 index 0000000000..751a62e0e0 --- /dev/null +++ b/codemp/rd-rend2/glsl/texturecolor.glsl @@ -0,0 +1,28 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec4 attr_TexCoord0; + +uniform mat4 u_ModelViewProjectionMatrix; + +out vec2 var_Tex1; + + +void main() +{ + gl_Position = u_ModelViewProjectionMatrix * vec4(attr_Position, 1.0); + var_Tex1 = attr_TexCoord0.st; +} + +/*[Fragment]*/ +uniform sampler2D u_DiffuseMap; +uniform vec4 u_Color; + +in vec2 var_Tex1; + +out vec4 out_Color; + + +void main() +{ + out_Color = texture(u_DiffuseMap, var_Tex1) * u_Color; +} diff --git a/codemp/rd-rend2/glsl/tonemap.glsl b/codemp/rd-rend2/glsl/tonemap.glsl new file mode 100644 index 0000000000..58162d7ed2 --- /dev/null +++ b/codemp/rd-rend2/glsl/tonemap.glsl @@ -0,0 +1,114 @@ +/*[Vertex]*/ +in vec3 attr_Position; +in vec4 attr_TexCoord0; + +uniform mat4 u_ModelViewProjectionMatrix; + +out vec2 var_TexCoords; + + +void main() +{ + gl_Position = u_ModelViewProjectionMatrix * vec4(attr_Position, 1.0); + var_TexCoords = attr_TexCoord0.st; +} + +/*[Fragment]*/ +uniform sampler2D u_TextureMap; +uniform sampler2D u_LevelsMap; +uniform vec4 u_Color; +uniform vec2 u_AutoExposureMinMax; +uniform vec3 u_ToneMinAvgMaxLinear; + +in vec2 var_TexCoords; + +out vec4 out_Color; + +vec3 LinearTosRGB( in vec3 color ) +{ + vec3 lo = 12.92 * color; + vec3 hi = 1.055 * pow(color, vec3(0.4166666)) - 0.055; + return mix(lo, hi, greaterThanEqual(color, vec3(0.0031308))); +} + +vec3 FilmicTonemap(vec3 x) +{ + const float SS = 0.22; // Shoulder Strength + const float LS = 0.30; // Linear Strength + const float LA = 0.10; // Linear Angle + const float TS = 0.20; // Toe Strength + const float TAN = 0.01; // Toe Angle Numerator + const float TAD = 0.30; // Toe Angle Denominator + + vec3 SSxx = SS * x * x; + vec3 LSx = LS * x; + vec3 LALSx = LSx * LA; + + return ((SSxx + LALSx + TS * TAN) / (SSxx + LSx + TS * TAD)) - TAN / TAD; + + //return ((x*(SS*x+LA*LS)+TS*TAN)/(x*(SS*x+LS)+TS*TAD)) - TAN/TAD; +} + +// The ACES code in this file was originally written by Stephen Hill (@self_shadow), who deserves all +// credit for coming up with this fit and implementing it. Buy him a beer next time you see him. :) + +// sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT +const mat3 ACESInputMat = mat3 +( + vec3(0.59719, 0.35458, 0.04823), + vec3(0.07600, 0.90834, 0.01566), + vec3(0.02840, 0.13383, 0.83777) +); + +// ODT_SAT => XYZ => D60_2_D65 => sRGB +const mat3 ACESOutputMat = mat3 +( + vec3( 1.60475, -0.53108, -0.07367), + vec3(-0.10208, 1.10813, -0.00605), + vec3(-0.00327, -0.07276, 1.07602) +); + +vec3 RRTAndODTFit(vec3 v) +{ + vec3 a = v * (v + 0.0245786f) - 0.000090537f; + vec3 b = v * (0.983729f * v + 0.4329510f) + 0.238081f; + return a / b; +} + +vec3 ACESFitted(vec3 color) +{ + color = color * ACESInputMat; + + // Apply RRT and ODT + color = RRTAndODTFit(color); + + color = color * ACESOutputMat; + + // Clamp to [0, 1] + color = clamp(color, 0.0, 1.0); + + return color; +} + + +void main() +{ + vec4 color = texture(u_TextureMap, var_TexCoords) * u_Color; + vec3 minAvgMax = texture(u_LevelsMap, var_TexCoords).rgb; + vec3 logMinAvgMaxLum = clamp(minAvgMax * 20.0 - 10.0, -u_AutoExposureMinMax.y, -u_AutoExposureMinMax.x); + + float avgLum = exp2(logMinAvgMaxLum.y); + //float maxLum = exp2(logMinAvgMaxLum.z); + + color.rgb *= u_ToneMinAvgMaxLinear.y / avgLum; + color.rgb = max(vec3(0.0), color.rgb - vec3(u_ToneMinAvgMaxLinear.x)); + + vec3 fWhite = 1.0 / FilmicTonemap(vec3(u_ToneMinAvgMaxLinear.z - u_ToneMinAvgMaxLinear.x)); + color.rgb = FilmicTonemap(color.rgb) * fWhite; + + #if defined(USE_LINEAR_LIGHT) + color.rgb = LinearTosRGB(color.rgb); + #endif + + out_Color = clamp(color, 0.0, 1.0); +} diff --git a/codemp/rd-rend2/glsl/weather.glsl b/codemp/rd-rend2/glsl/weather.glsl new file mode 100644 index 0000000000..0c6eef6372 --- /dev/null +++ b/codemp/rd-rend2/glsl/weather.glsl @@ -0,0 +1,116 @@ +/*[Vertex]*/ +uniform vec2 u_ZoneOffset[9]; + +uniform sampler2D u_ShadowMap; +uniform mat4 u_ShadowMvp; +uniform vec4 u_ViewInfo; + +in vec3 attr_Position; +in vec3 attr_Color; // velocity + +out vec3 var_Velocity; +out int var_Culled; + +void main() +{ + gl_Position = vec4( + attr_Position.xy + u_ZoneOffset[0], + attr_Position.z, + 1.0); + var_Velocity = attr_Color; + + vec4 velocitiyOffset = u_ViewInfo.y * vec4(-var_Velocity.xy/var_Velocity.z, var_Velocity.z, 0.0); + velocitiyOffset.xyz = mix(vec3(0.0), velocitiyOffset.xyz, float(var_Velocity.z != 0.0)); + var_Velocity.z *= u_ViewInfo.z; + + vec4 depthPosition = u_ShadowMvp * (gl_Position + velocitiyOffset); + depthPosition.xyz = depthPosition.xyz / depthPosition.w * 0.5 + 0.5; + float depthSample = texture(u_ShadowMap, depthPosition.xy).r; + + //TODO: Do this to the texture instead of sampling the texture 5 times here over and over again + vec2 dx = vec2(0.5 / 1024.0, 0.0); + vec2 dy = vec2(0.0, 0.5 / 1024.0); + depthSample = min(texture(u_ShadowMap, depthPosition.xy + dx).r, depthSample); + depthSample = min(texture(u_ShadowMap, depthPosition.xy - dx).r, depthSample); + depthSample = min(texture(u_ShadowMap, depthPosition.xy - dy).r, depthSample); + depthSample = min(texture(u_ShadowMap, depthPosition.xy + dy).r, depthSample); + + var_Culled = int(depthPosition.z > depthSample); +} + +/*[Geometry]*/ +layout(points) in; +layout(triangle_strip, max_vertices = 4) out; + +layout(std140) uniform Camera +{ + mat4 u_viewProjectionMatrix; + vec4 _u_ViewInfo; + vec3 u_ViewOrigin; + vec3 u_ViewForward; + vec3 u_ViewLeft; + vec3 u_ViewUp; +}; + +uniform vec4 u_ViewInfo; + +in vec3 var_Velocity[]; +in int var_Culled[]; + +out vec3 var_TexCoordAlpha; + +void main() +{ + vec3 offsets[] = vec3[]( + vec3(-u_ViewInfo.x, -u_ViewInfo.y, 0.0), + vec3( u_ViewInfo.x, -u_ViewInfo.y, 0.0), + vec3(-u_ViewInfo.x, u_ViewInfo.y, 0.0), + vec3( u_ViewInfo.x, u_ViewInfo.y, 0.0) + ); + + const vec2 texcoords[] = vec2[]( + vec2(1.0, 1.0), + vec2(0.0, 1.0), + vec2(1.0, 0.0), + vec2(0.0, 0.0) + ); + + if (var_Culled[0] == 0) + { + vec3 P = gl_in[0].gl_Position.xyz; + vec3 V = u_ViewOrigin - P; + vec2 toCamera = normalize(vec2(V.y, -V.x)); + for (int i = 0; i < 4; ++i) + { + vec3 offset = vec3(offsets[i].x * toCamera.xy, offsets[i].y); + if (var_Velocity[0].z != 0.0) + offset.xy += offset.z * var_Velocity[0].xy / var_Velocity[0].z; + vec4 worldPos = vec4(P + offset, 1.0); + gl_Position = u_viewProjectionMatrix * worldPos; + + float distance = distance(u_ViewOrigin, worldPos.xyz); + float alpha = (u_ViewInfo.w - distance) / u_ViewInfo.w; + + var_TexCoordAlpha = vec3(texcoords[i], clamp(alpha, 0.0, 1.0)); + EmitVertex(); + } + EndPrimitive(); + } +} + +/*[Fragment]*/ +uniform vec4 u_Color; +uniform sampler2D u_DiffuseMap; + +in vec3 var_TexCoordAlpha; +out vec4 out_Color; +out vec4 out_Glow; + +void main() +{ + vec4 textureColor = texture(u_DiffuseMap, var_TexCoordAlpha.xy); + out_Color = textureColor * u_Color * var_TexCoordAlpha.z; + + out_Glow.rgb = vec3(0.0); + out_Glow.a = out_Color.a; +} diff --git a/codemp/rd-rend2/glsl/weatherUpdate.glsl b/codemp/rd-rend2/glsl/weatherUpdate.glsl new file mode 100644 index 0000000000..677cfdf6d5 --- /dev/null +++ b/codemp/rd-rend2/glsl/weatherUpdate.glsl @@ -0,0 +1,64 @@ +/*[Vertex]*/ + +layout(std140) uniform Scene +{ + vec4 u_PrimaryLightOrigin; + vec3 u_PrimaryLightAmbient; + int u_globalFogIndex; + vec3 u_PrimaryLightColor; + float u_PrimaryLightRadius; + float u_frameTime; + float u_deltaTime; +}; + +uniform vec2 u_MapZExtents; +uniform vec3 u_EnvForce; +uniform vec4 u_RandomOffset; +uniform vec2 u_ZoneOffset[9]; +uniform int u_ChunkParticles; + +in vec3 attr_Position; +in vec3 attr_Color; + +out vec3 var_Position; +out vec3 var_Velocity; + +const float CHUNK_EXTENDS = 2000.0; +const float HALF_CHUNK_EXTENDS = CHUNK_EXTENDS * 0.5; +const float THREE_HALF_CHUNK_EXTENDS = 3.0 * HALF_CHUNK_EXTENDS; + +vec3 NewParticleZPosition( in vec3 in_position ) +{ + vec3 position = in_position; + position.xy += u_RandomOffset.xy; + position.z += u_MapZExtents.y - u_MapZExtents.x; + + return position; +} + +void main() +{ + var_Velocity = attr_Color; + var_Velocity = mix(var_Velocity, u_EnvForce, u_deltaTime * 0.002); + var_Position = attr_Position; + var_Position += var_Velocity * u_deltaTime; + + if (var_Position.z < u_MapZExtents.x) + { + var_Position = NewParticleZPosition(var_Position); + var_Velocity.xy = u_EnvForce.xy; + } + + int zone = gl_VertexID / u_ChunkParticles; + vec2 zoneOffset = u_ZoneOffset[zone] * CHUNK_EXTENDS; + vec2 sim_Position = var_Position.xy + zoneOffset; + + if (any(greaterThan(abs(sim_Position).xy, vec2(THREE_HALF_CHUNK_EXTENDS)))) + { + vec2 signs = sign(sim_Position.xy); + vec2 absPos = abs(sim_Position.xy) + vec2(THREE_HALF_CHUNK_EXTENDS); + sim_Position.xy = -signs * (THREE_HALF_CHUNK_EXTENDS - mod(absPos, 3.0 * CHUNK_EXTENDS)); + + var_Position.xy = sim_Position - zoneOffset; + } +} diff --git a/codemp/rd-rend2/iqm.h b/codemp/rd-rend2/iqm.h new file mode 100644 index 0000000000..ab2247acd8 --- /dev/null +++ b/codemp/rd-rend2/iqm.h @@ -0,0 +1,129 @@ +/* +=========================================================================== +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +#ifndef __IQM_H__ +#define __IQM_H__ + +#define IQM_MAGIC "INTERQUAKEMODEL" +#define IQM_VERSION 2 + +#define IQM_MAX_JOINTS 128 + +typedef struct iqmheader +{ + char magic[16]; + unsigned int version; + unsigned int filesize; + unsigned int flags; + unsigned int num_text, ofs_text; + unsigned int num_meshes, ofs_meshes; + unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays; + unsigned int num_triangles, ofs_triangles, ofs_adjacency; + unsigned int num_joints, ofs_joints; + unsigned int num_poses, ofs_poses; + unsigned int num_anims, ofs_anims; + unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds; + unsigned int num_comment, ofs_comment; + unsigned int num_extensions, ofs_extensions; +} iqmHeader_t; + +typedef struct iqmmesh +{ + unsigned int name; + unsigned int material; + unsigned int first_vertex, num_vertexes; + unsigned int first_triangle, num_triangles; +} iqmMesh_t; + +enum +{ + IQM_POSITION = 0, + IQM_TEXCOORD = 1, + IQM_NORMAL = 2, + IQM_TANGENT = 3, + IQM_BLENDINDEXES = 4, + IQM_BLENDWEIGHTS = 5, + IQM_COLOR = 6, + IQM_CUSTOM = 0x10 +}; + +enum +{ + IQM_BYTE = 0, + IQM_UBYTE = 1, + IQM_SHORT = 2, + IQM_USHORT = 3, + IQM_INT = 4, + IQM_UINT = 5, + IQM_HALF = 6, + IQM_FLOAT = 7, + IQM_DOUBLE = 8, +}; + +typedef struct iqmtriangle +{ + unsigned int vertex[3]; +} iqmTriangle_t; + +typedef struct iqmjoint +{ + unsigned int name; + int parent; + float translate[3], rotate[4], scale[3]; +} iqmJoint_t; + +typedef struct iqmpose +{ + int parent; + unsigned int mask; + float channeloffset[10]; + float channelscale[10]; +} iqmPose_t; + +typedef struct iqmanim +{ + unsigned int name; + unsigned int first_frame, num_frames; + float framerate; + unsigned int flags; +} iqmAnim_t; + +enum +{ + IQM_LOOP = 1<<0 +}; + +typedef struct iqmvertexarray +{ + unsigned int type; + unsigned int flags; + unsigned int format; + unsigned int size; + unsigned int offset; +} iqmVertexArray_t; + +typedef struct iqmbounds +{ + float bbmin[3], bbmax[3]; + float xyradius, radius; +} iqmBounds_t; + +#endif + diff --git a/codemp/rd-rend2/json.h b/codemp/rd-rend2/json.h new file mode 100644 index 0000000000..cfc5b3cac6 --- /dev/null +++ b/codemp/rd-rend2/json.h @@ -0,0 +1,353 @@ +/* +=========================================================================== +Copyright (C) 2016 James Canete + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +=========================================================================== +*/ + +#ifndef JSON_H +#define JSON_H + +enum +{ + JSONTYPE_STRING, // string + JSONTYPE_OBJECT, // object + JSONTYPE_ARRAY, // array + JSONTYPE_VALUE, // number, true, false, or null + JSONTYPE_ERROR // out of data +}; + +// -------------------------------------------------------------------------- +// Array Functions +// -------------------------------------------------------------------------- + +// Get pointer to first value in array +// When given pointer to an array, returns pointer to the first +// returns NULL if array is empty or not an array. +const char *JSON_ArrayGetFirstValue(const char *json, const char *jsonEnd); + +// Get pointer to next value in array +// When given pointer to a value, returns pointer to the next value +// returns NULL when no next value. +const char *JSON_ArrayGetNextValue(const char *json, const char *jsonEnd); + +// Get pointers to values in an array +// returns 0 if not an array, array is empty, or out of data +// returns number of values in the array and copies into index if successful +unsigned int JSON_ArrayGetIndex(const char *json, const char *jsonEnd, const char **indexes, unsigned int numIndexes); + +// Get pointer to indexed value from array +// returns NULL if not an array, no index, or out of data +const char *JSON_ArrayGetValue(const char *json, const char *jsonEnd, unsigned int index); + +// -------------------------------------------------------------------------- +// Object Functions +// -------------------------------------------------------------------------- + +// Get pointer to named value from object +// returns NULL if not an object, name not found, or out of data +const char *JSON_ObjectGetNamedValue(const char *json, const char *jsonEnd, const char *name); + +// -------------------------------------------------------------------------- +// Value Functions +// -------------------------------------------------------------------------- + +// Get type of value +// returns JSONTYPE_ERROR if out of data +unsigned int JSON_ValueGetType(const char *json, const char *jsonEnd); + +// Get value as string +// returns 0 if out of data +// returns length and copies into string if successful, including terminating nul. +// string values are stripped of enclosing quotes but not escaped +unsigned int JSON_ValueGetString(const char *json, const char *jsonEnd, char *outString, unsigned int stringLen); + +// Get value as appropriate type +// returns 0 if value is false, value is null, or out of data +// returns 1 if value is true +// returns value otherwise +double JSON_ValueGetDouble(const char *json, const char *jsonEnd); +float JSON_ValueGetFloat(const char *json, const char *jsonEnd); +int JSON_ValueGetInt(const char *json, const char *jsonEnd); + +#endif + +#ifdef JSON_IMPLEMENTATION +#include + +// -------------------------------------------------------------------------- +// Internal Functions +// -------------------------------------------------------------------------- + +static const char *JSON_SkipSeparators(const char *json, const char *jsonEnd); +static const char *JSON_SkipString(const char *json, const char *jsonEnd); +static const char *JSON_SkipStruct(const char *json, const char *jsonEnd); +static const char *JSON_SkipValue(const char *json, const char *jsonEnd); +static const char *JSON_SkipValueAndSeparators(const char *json, const char *jsonEnd); + +#define IS_SEPARATOR(x) ((x) == ' ' || (x) == '\t' || (x) == '\n' || (x) == '\r' || (x) == ',' || (x) == ':') +#define IS_STRUCT_OPEN(x) ((x) == '{' || (x) == '[') +#define IS_STRUCT_CLOSE(x) ((x) == '}' || (x) == ']') + +static const char *JSON_SkipSeparators(const char *json, const char *jsonEnd) +{ + while (json < jsonEnd && IS_SEPARATOR(*json)) + json++; + + return json; +} + +static const char *JSON_SkipString(const char *json, const char *jsonEnd) +{ + for (json++; json < jsonEnd && *json != '"'; json++) + if (*json == '\\') + json++; + + return (json + 1 > jsonEnd) ? jsonEnd : json + 1; +} + +static const char *JSON_SkipStruct(const char *json, const char *jsonEnd) +{ + json = JSON_SkipSeparators(json + 1, jsonEnd); + while (json < jsonEnd && !IS_STRUCT_CLOSE(*json)) + json = JSON_SkipValueAndSeparators(json, jsonEnd); + + return (json + 1 > jsonEnd) ? jsonEnd : json + 1; +} + +static const char *JSON_SkipValue(const char *json, const char *jsonEnd) +{ + if (json >= jsonEnd) + return jsonEnd; + else if (*json == '"') + json = JSON_SkipString(json, jsonEnd); + else if (IS_STRUCT_OPEN(*json)) + json = JSON_SkipStruct(json, jsonEnd); + else + { + while (json < jsonEnd && !IS_SEPARATOR(*json) && !IS_STRUCT_CLOSE(*json)) + json++; + } + + return json; +} + +static const char *JSON_SkipValueAndSeparators(const char *json, const char *jsonEnd) +{ + json = JSON_SkipValue(json, jsonEnd); + return JSON_SkipSeparators(json, jsonEnd); +} + +// returns 0 if value requires more parsing, 1 if no more data/false/null, 2 if true +static unsigned int JSON_NoParse(const char *json, const char *jsonEnd) +{ + if (!json || json >= jsonEnd || *json == 'f' || *json == 'n') + return 1; + + if (*json == 't') + return 2; + + return 0; +} + +// -------------------------------------------------------------------------- +// Array Functions +// -------------------------------------------------------------------------- + +const char *JSON_ArrayGetFirstValue(const char *json, const char *jsonEnd) +{ + if (!json || json >= jsonEnd || !IS_STRUCT_OPEN(*json)) + return NULL; + + json = JSON_SkipSeparators(json + 1, jsonEnd); + + return (json >= jsonEnd || IS_STRUCT_CLOSE(*json)) ? NULL : json; +} + +const char *JSON_ArrayGetNextValue(const char *json, const char *jsonEnd) +{ + if (!json || json >= jsonEnd || IS_STRUCT_CLOSE(*json)) + return NULL; + + json = JSON_SkipValueAndSeparators(json, jsonEnd); + + return (json >= jsonEnd || IS_STRUCT_CLOSE(*json)) ? NULL : json; +} + +unsigned int JSON_ArrayGetIndex(const char *json, const char *jsonEnd, const char **indexes, unsigned int numIndexes) +{ + unsigned int length = 0; + + for (json = JSON_ArrayGetFirstValue(json, jsonEnd); json; json = JSON_ArrayGetNextValue(json, jsonEnd)) + { + if (indexes && numIndexes) + { + *indexes++ = json; + numIndexes--; + } + length++; + } + + return length; +} + +const char *JSON_ArrayGetValue(const char *json, const char *jsonEnd, unsigned int index) +{ + for (json = JSON_ArrayGetFirstValue(json, jsonEnd); json && index; json = JSON_ArrayGetNextValue(json, jsonEnd)) + index--; + + return json; +} + +// -------------------------------------------------------------------------- +// Object Functions +// -------------------------------------------------------------------------- + +const char *JSON_ObjectGetNamedValue(const char *json, const char *jsonEnd, const char *name) +{ + unsigned int nameLen = strlen(name); + + for (json = JSON_ArrayGetFirstValue(json, jsonEnd); json; json = JSON_ArrayGetNextValue(json, jsonEnd)) + { + if (*json == '"') + { + const char *thisNameStart, *thisNameEnd; + + thisNameStart = json + 1; + json = JSON_SkipString(json, jsonEnd); + thisNameEnd = json - 1; + json = JSON_SkipSeparators(json, jsonEnd); + + if ((unsigned int)(thisNameEnd - thisNameStart) == nameLen) + if (strncmp(thisNameStart, name, nameLen) == 0) + return json; + } + } + + return NULL; +} + +// -------------------------------------------------------------------------- +// Value Functions +// -------------------------------------------------------------------------- + +unsigned int JSON_ValueGetType(const char *json, const char *jsonEnd) +{ + if (!json || json >= jsonEnd) + return JSONTYPE_ERROR; + else if (*json == '"') + return JSONTYPE_STRING; + else if (*json == '{') + return JSONTYPE_OBJECT; + else if (*json == '[') + return JSONTYPE_ARRAY; + + return JSONTYPE_VALUE; +} + +unsigned int JSON_ValueGetString(const char *json, const char *jsonEnd, char *outString, unsigned int stringLen) +{ + const char *stringEnd, *stringStart; + + if (!json) + { + *outString = '\0'; + return 0; + } + + stringStart = json; + stringEnd = JSON_SkipValue(stringStart, jsonEnd); + if (stringEnd >= jsonEnd) + { + *outString = '\0'; + return 0; + } + + // skip enclosing quotes if they exist + if (*stringStart == '"') + stringStart++; + + if (*(stringEnd - 1) == '"') + stringEnd--; + + stringLen--; + if (stringLen > stringEnd - stringStart) + stringLen = stringEnd - stringStart; + + json = stringStart; + while (stringLen--) + *outString++ = *json++; + *outString = '\0'; + + return stringEnd - stringStart; +} + +double JSON_ValueGetDouble(const char *json, const char *jsonEnd) +{ + char cValue[256]; + double dValue = 0.0; + unsigned int np = JSON_NoParse(json, jsonEnd); + + if (np) + return (double)(np - 1); + + if (!JSON_ValueGetString(json, jsonEnd, cValue, 256)) + return 0.0; + + sscanf(cValue, "%lf", &dValue); + + return dValue; +} + +float JSON_ValueGetFloat(const char *json, const char *jsonEnd) +{ + char cValue[256]; + float fValue = 0.0f; + unsigned int np = JSON_NoParse(json, jsonEnd); + + if (np) + return (float)(np - 1); + + if (!JSON_ValueGetString(json, jsonEnd, cValue, 256)) + return 0.0f; + + sscanf(cValue, "%f", &fValue); + + return fValue; +} + +int JSON_ValueGetInt(const char *json, const char *jsonEnd) +{ + char cValue[256]; + int iValue = 0; + unsigned int np = JSON_NoParse(json, jsonEnd); + + if (np) + return np - 1; + + if (!JSON_ValueGetString(json, jsonEnd, cValue, 256)) + return 0; + + sscanf(cValue, "%d", &iValue); + + return iValue; +} + +#undef IS_SEPARATOR +#undef IS_STRUCT_OPEN +#undef IS_STRUCT_CLOSE + +#endif diff --git a/codemp/rd-rend2/qgl.h b/codemp/rd-rend2/qgl.h new file mode 100644 index 0000000000..949413610b --- /dev/null +++ b/codemp/rd-rend2/qgl.h @@ -0,0 +1,616 @@ +#pragma once + +#if defined( __LINT__ ) +# include +#elif defined( _WIN32 ) +# include +# include +#elif defined(MACOS_X) +# include +#elif defined( __linux__ ) +# include +# include +// bk001129 - from cvs1.17 (mkv) +# if defined(__FX__) +# include +# endif +#elif defined( __FreeBSD__ ) // rb010123 +# include +# include +# if defined(__FX__) +# include +# endif +#else +# include +#endif + +#include "glext.h" + +#define qglAccum glAccum +//#define qglAlphaFunc glAlphaFunc +#define qglAreTexturesResident glAreTexturesResident +#define qglArrayElement glArrayElement +#define qglBegin glBegin +#define qglBindTexture glBindTexture +#define qglBitmap glBitmap +#define qglBlendFunc glBlendFunc +#define qglCallList glCallList +#define qglCallLists glCallLists +#define qglClear glClear +#define qglClearAccum glClearAccum +#define qglClearColor glClearColor +#define qglClearDepth glClearDepth +#define qglClearIndex glClearIndex +#define qglClearStencil glClearStencil +#define qglClipPlane glClipPlane +#define qglColor3b glColor3b +#define qglColor3bv glColor3bv +#define qglColor3d glColor3d +#define qglColor3dv glColor3dv +#define qglColor3f glColor3f +#define qglColor3fv glColor3fv +#define qglColor3i glColor3i +#define qglColor3iv glColor3iv +#define qglColor3s glColor3s +#define qglColor3sv glColor3sv +#define qglColor3ub glColor3ub +#define qglColor3ubv glColor3ubv +#define qglColor3ui glColor3ui +#define qglColor3uiv glColor3uiv +#define qglColor3us glColor3us +#define qglColor3usv glColor3usv +#define qglColor4b glColor4b +#define qglColor4bv glColor4bv +#define qglColor4d glColor4d +#define qglColor4dv glColor4dv +#define qglColor4f glColor4f +#define qglColor4fv glColor4fv +#define qglColor4i glColor4i +#define qglColor4iv glColor4iv +#define qglColor4s glColor4s +#define qglColor4sv glColor4sv +#define qglColor4ub glColor4ub +#define qglColor4ubv glColor4ubv +#define qglColor4ui glColor4ui +#define qglColor4uiv glColor4uiv +#define qglColor4us glColor4us +#define qglColor4usv glColor4usv +#define qglColorMask glColorMask +#define qglColorMaterial glColorMaterial +#define qglColorPointer glColorPointer +#define qglCopyPixels glCopyPixels +#define qglCopyTexImage1D glCopyTexImage1D +#define qglCopyTexImage2D glCopyTexImage2D +#define qglCopyTexSubImage1D glCopyTexSubImage1D +#define qglCopyTexSubImage2D glCopyTexSubImage2D +#define qglCullFace glCullFace +#define qglDeleteLists glDeleteLists +#define qglDeleteTextures glDeleteTextures +#define qglDepthFunc glDepthFunc +#define qglDepthMask glDepthMask +#define qglDepthRange glDepthRange +#define qglDisable glDisable +#define qglDisableClientState glDisableClientState +#define qglDrawArrays glDrawArrays +#define qglDrawBuffer glDrawBuffer +#define qglDrawElements glDrawElements +#define qglDrawPixels glDrawPixels +#define qglEdgeFlag glEdgeFlag +#define qglEdgeFlagPointer glEdgeFlagPointer +#define qglEdgeFlagv glEdgeFlagv +#define qglEnable glEnable +#define qglEnableClientState glEnableClientState +#define qglEnd glEnd +#define qglEndList glEndList +#define qglEvalCoord1d glEvalCoord1d +#define qglEvalCoord1dv glEvalCoord1dv +#define qglEvalCoord1f glEvalCoord1f +#define qglEvalCoord1fv glEvalCoord1fv +#define qglEvalCoord2d glEvalCoord2d +#define qglEvalCoord2dv glEvalCoord2dv +#define qglEvalCoord2f glEvalCoord2f +#define qglEvalCoord2fv glEvalCoord2fv +#define qglEvalMesh1 glEvalMesh1 +#define qglEvalMesh2 glEvalMesh2 +#define qglEvalPoint1 glEvalPoint1 +#define qglEvalPoint2 glEvalPoint2 +#define qglFeedbackBuffer glFeedbackBuffer +#define qglFinish glFinish +#define qglFlush glFlush +#define qglFogf glFogf +#define qglFogfv glFogfv +#define qglFogi glFogi +#define qglFogiv glFogiv +#define qglFrontFace glFrontFace +#define qglFrustum glFrustum +#define qglGenLists glGenLists +#define qglGenTextures glGenTextures +#define qglGetBooleanv glGetBooleanv +#define qglGetClipPlane glGetClipPlane +#define qglGetDoublev glGetDoublev +#define qglGetError glGetError +#define qglGetFloatv glGetFloatv +#define qglGetIntegerv glGetIntegerv +#define qglGetLightfv glGetLightfv +#define qglGetLightiv glGetLightiv +#define qglGetMapdv glGetMapdv +#define qglGetMapfv glGetMapfv +#define qglGetMapiv glGetMapiv +#define qglGetMaterialfv glGetMaterialfv +#define qglGetMaterialiv glGetMaterialiv +#define qglGetPixelMapfv glGetPixelMapfv +#define qglGetPixelMapuiv glGetPixelMapuiv +#define qglGetPixelMapusv glGetPixelMapusv +#define qglGetPointerv glGetPointerv +#define qglGetPolygonStipple glGetPolygonStipple +#define qglGetString glGetString +#define qglGetTexGendv glGetTexGendv +#define qglGetTexGenfv glGetTexGenfv +#define qglGetTexGeniv glGetTexGeniv +#define qglGetTexImage glGetTexImage +#define qglGetTexLevelParameterfv glGetTexLevelParameterfv +#define qglGetTexLevelParameteriv glGetTexLevelParameteriv +#define qglGetTexParameterfv glGetTexParameterfv +#define qglGetTexParameteriv glGetTexParameteriv +#define qglHint glHint +#define qglIndexMask glIndexMask +#define qglIndexPointer glIndexPointer +#define qglIndexd glIndexd +#define qglIndexdv glIndexdv +#define qglIndexf glIndexf +#define qglIndexfv glIndexfv +#define qglIndexi glIndexi +#define qglIndexiv glIndexiv +#define qglIndexs glIndexs +#define qglIndexsv glIndexsv +#define qglIndexub glIndexub +#define qglIndexubv glIndexubv +#define qglInitNames glInitNames +#define qglInterleavedArrays glInterleavedArrays +#define qglIsEnabled glIsEnabled +#define qglIsList glIsList +#define qglIsTexture glIsTexture +#define qglLightModelf glLightModelf +#define qglLightModelfv glLightModelfv +#define qglLightModeli glLightModeli +#define qglLightModeliv glLightModeliv +#define qglLightf glLightf +#define qglLightfv glLightfv +#define qglLighti glLighti +#define qglLightiv glLightiv +#define qglLineStipple glLineStipple +#define qglLineWidth glLineWidth +#define qglListBase glListBase +#define qglLoadIdentity glLoadIdentity +#define qglLoadMatrixd glLoadMatrixd +#define qglLoadMatrixf glLoadMatrixf +#define qglLoadName glLoadName +#define qglLogicOp glLogicOp +#define qglMap1d glMap1d +#define qglMap1f glMap1f +#define qglMap2d glMap2d +#define qglMap2f glMap2f +#define qglMapGrid1d glMapGrid1d +#define qglMapGrid1f glMapGrid1f +#define qglMapGrid2d glMapGrid2d +#define qglMapGrid2f glMapGrid2f +#define qglMaterialf glMaterialf +#define qglMaterialfv glMaterialfv +#define qglMateriali glMateriali +#define qglMaterialiv glMaterialiv +#define qglMatrixMode glMatrixMode +#define qglMultMatrixd glMultMatrixd +#define qglMultMatrixf glMultMatrixf +#define qglNewList glNewList +#define qglNormal3b glNormal3b +#define qglNormal3bv glNormal3bv +#define qglNormal3d glNormal3d +#define qglNormal3dv glNormal3dv +#define qglNormal3f glNormal3f +#define qglNormal3fv glNormal3fv +#define qglNormal3i glNormal3i +#define qglNormal3iv glNormal3iv +#define qglNormal3s glNormal3s +#define qglNormal3sv glNormal3sv +#define qglNormalPointer glNormalPointer +#define qglOrtho glOrtho +#define qglPassThrough glPassThrough +#define qglPixelMapfv glPixelMapfv +#define qglPixelMapuiv glPixelMapuiv +#define qglPixelMapusv glPixelMapusv +#define qglPixelStoref glPixelStoref +#define qglPixelStorei glPixelStorei +#define qglPixelTransferf glPixelTransferf +#define qglPixelTransferi glPixelTransferi +#define qglPixelZoom glPixelZoom +#define qglPointSize glPointSize +#define qglPolygonMode glPolygonMode +#define qglPolygonOffset glPolygonOffset +#define qglPolygonStipple glPolygonStipple +#define qglPopAttrib glPopAttrib +#define qglPopClientAttrib glPopClientAttrib +#define qglPopMatrix glPopMatrix +#define qglPopName glPopName +#define qglPrioritizeTextures glPrioritizeTextures +#define qglPushAttrib glPushAttrib +#define qglPushClientAttrib glPushClientAttrib +#define qglPushMatrix glPushMatrix +#define qglPushName glPushName +#define qglRasterPos2d glRasterPos2d +#define qglRasterPos2dv glRasterPos2dv +#define qglRasterPos2f glRasterPos2f +#define qglRasterPos2fv glRasterPos2fv +#define qglRasterPos2i glRasterPos2i +#define qglRasterPos2iv glRasterPos2iv +#define qglRasterPos2s glRasterPos2s +#define qglRasterPos2sv glRasterPos2sv +#define qglRasterPos3d glRasterPos3d +#define qglRasterPos3dv glRasterPos3dv +#define qglRasterPos3f glRasterPos3f +#define qglRasterPos3fv glRasterPos3fv +#define qglRasterPos3i glRasterPos3i +#define qglRasterPos3iv glRasterPos3iv +#define qglRasterPos3s glRasterPos3s +#define qglRasterPos3sv glRasterPos3sv +#define qglRasterPos4d glRasterPos4d +#define qglRasterPos4dv glRasterPos4dv +#define qglRasterPos4f glRasterPos4f +#define qglRasterPos4fv glRasterPos4fv +#define qglRasterPos4i glRasterPos4i +#define qglRasterPos4iv glRasterPos4iv +#define qglRasterPos4s glRasterPos4s +#define qglRasterPos4sv glRasterPos4sv +#define qglReadBuffer glReadBuffer +#define qglReadPixels glReadPixels +#define qglRectd glRectd +#define qglRectdv glRectdv +#define qglRectf glRectf +#define qglRectfv glRectfv +#define qglRecti glRecti +#define qglRectiv glRectiv +#define qglRects glRects +#define qglRectsv glRectsv +#define qglRenderMode glRenderMode +#define qglRotated glRotated +#define qglRotatef glRotatef +#define qglScaled glScaled +#define qglScalef glScalef +#define qglScissor glScissor +#define qglSelectBuffer glSelectBuffer +#define qglShadeModel glShadeModel +#define qglStencilFunc glStencilFunc +#define qglStencilMask glStencilMask +#define qglStencilOp glStencilOp +#define qglTexCoord1d glTexCoord1d +#define qglTexCoord1dv glTexCoord1dv +#define qglTexCoord1f glTexCoord1f +#define qglTexCoord1fv glTexCoord1fv +#define qglTexCoord1i glTexCoord1i +#define qglTexCoord1iv glTexCoord1iv +#define qglTexCoord1s glTexCoord1s +#define qglTexCoord1sv glTexCoord1sv +#define qglTexCoord2d glTexCoord2d +#define qglTexCoord2dv glTexCoord2dv +#define qglTexCoord2f glTexCoord2f +#define qglTexCoord2fv glTexCoord2fv +#define qglTexCoord2i glTexCoord2i +#define qglTexCoord2iv glTexCoord2iv +#define qglTexCoord2s glTexCoord2s +#define qglTexCoord2sv glTexCoord2sv +#define qglTexCoord3d glTexCoord3d +#define qglTexCoord3dv glTexCoord3dv +#define qglTexCoord3f glTexCoord3f +#define qglTexCoord3fv glTexCoord3fv +#define qglTexCoord3i glTexCoord3i +#define qglTexCoord3iv glTexCoord3iv +#define qglTexCoord3s glTexCoord3s +#define qglTexCoord3sv glTexCoord3sv +#define qglTexCoord4d glTexCoord4d +#define qglTexCoord4dv glTexCoord4dv +#define qglTexCoord4f glTexCoord4f +#define qglTexCoord4fv glTexCoord4fv +#define qglTexCoord4i glTexCoord4i +#define qglTexCoord4iv glTexCoord4iv +#define qglTexCoord4s glTexCoord4s +#define qglTexCoord4sv glTexCoord4sv +#define qglTexCoordPointer glTexCoordPointer +#define qglTexEnvf glTexEnvf +#define qglTexEnvfv glTexEnvfv +#define qglTexEnvi glTexEnvi +#define qglTexEnviv glTexEnviv +#define qglTexGend glTexGend +#define qglTexGendv glTexGendv +#define qglTexGenf glTexGenf +#define qglTexGenfv glTexGenfv +#define qglTexGeni glTexGeni +#define qglTexGeniv glTexGeniv +#define qglTexImage1D glTexImage1D +#define qglTexImage2D glTexImage2D +#define qglTexParameterf glTexParameterf +#define qglTexParameterfv glTexParameterfv +#define qglTexParameteri glTexParameteri +#define qglTexParameteriv glTexParameteriv +#define qglTexSubImage1D glTexSubImage1D +#define qglTexSubImage2D glTexSubImage2D +#define qglTranslated glTranslated +#define qglTranslatef glTranslatef +#define qglVertex2d glVertex2d +#define qglVertex2dv glVertex2dv +#define qglVertex2f glVertex2f +#define qglVertex2fv glVertex2fv +#define qglVertex2i glVertex2i +#define qglVertex2iv glVertex2iv +#define qglVertex2s glVertex2s +#define qglVertex2sv glVertex2sv +#define qglVertex3d glVertex3d +#define qglVertex3dv glVertex3dv +#define qglVertex3f glVertex3f +#define qglVertex3fv glVertex3fv +#define qglVertex3i glVertex3i +#define qglVertex3iv glVertex3iv +#define qglVertex3s glVertex3s +#define qglVertex3sv glVertex3sv +#define qglVertex4d glVertex4d +#define qglVertex4dv glVertex4dv +#define qglVertex4f glVertex4f +#define qglVertex4fv glVertex4fv +#define qglVertex4i glVertex4i +#define qglVertex4iv glVertex4iv +#define qglVertex4s glVertex4s +#define qglVertex4sv glVertex4sv +#define qglVertexPointer glVertexPointer +#define qglViewport glViewport + +// Stencil commands +extern PFNGLSTENCILOPSEPARATEPROC qglStencilOpSeparate; + +// Drawing commands +extern PFNGLDRAWRANGEELEMENTSPROC qglDrawRangeElements; +extern PFNGLDRAWARRAYSINSTANCEDPROC qglDrawArraysInstanced; +extern PFNGLDRAWELEMENTSINSTANCEDPROC qglDrawElementsInstanced; +extern PFNGLDRAWELEMENTSBASEVERTEXPROC qglDrawElementsBaseVertex; +extern PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC qglDrawRangeElementsBaseVertex; +extern PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC qglDrawElementsInstancedBaseVertex; +extern PFNGLMULTIDRAWARRAYSPROC qglMultiDrawArrays; +extern PFNGLMULTIDRAWELEMENTSPROC qglMultiDrawElements; +extern PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC qglMultiDrawElementsBaseVertex; + +// Vertex arrays +extern PFNGLVERTEXATTRIBPOINTERPROC qglVertexAttribPointer; +extern PFNGLVERTEXATTRIBIPOINTERPROC qglVertexAttribIPointer; +extern PFNGLVERTEXATTRIBDIVISORPROC qglVertexAttribDivisor; +extern PFNGLENABLEVERTEXATTRIBARRAYPROC qglEnableVertexAttribArray; +extern PFNGLDISABLEVERTEXATTRIBARRAYPROC qglDisableVertexAttribArray; + +extern PFNGLVERTEXATTRIB1FPROC qglVertexAttrib1f; +extern PFNGLVERTEXATTRIB2FPROC qglVertexAttrib2f; +extern PFNGLVERTEXATTRIB3FPROC qglVertexAttrib3f; +extern PFNGLVERTEXATTRIB4FPROC qglVertexAttrib4f; + +// Vertex array objects +extern PFNGLGENVERTEXARRAYSPROC qglGenVertexArrays; +extern PFNGLDELETEVERTEXARRAYSPROC qglDeleteVertexArrays; +extern PFNGLBINDVERTEXARRAYPROC qglBindVertexArray; +extern PFNGLISVERTEXARRAYPROC qglIsVertexArray; + +// Buffer objects +extern PFNGLBINDBUFFERPROC qglBindBuffer; +extern PFNGLDELETEBUFFERSPROC qglDeleteBuffers; +extern PFNGLGENBUFFERSPROC qglGenBuffers; +extern PFNGLISBUFFERPROC qglIsBuffer; +extern PFNGLBUFFERDATAPROC qglBufferData; +extern PFNGLBUFFERSUBDATAPROC qglBufferSubData; +extern PFNGLGETBUFFERSUBDATAPROC qglGetBufferSubData; +extern PFNGLGETBUFFERPARAMETERIVPROC qglGetBufferParameteriv; +extern PFNGLGETBUFFERPARAMETERI64VPROC qglGetBufferParameteri64v; +extern PFNGLGETBUFFERPOINTERVPROC qglGetBufferPointerv; +extern PFNGLBINDBUFFERRANGEPROC qglBindBufferRange; +extern PFNGLBINDBUFFERBASEPROC qglBindBufferBase; +extern PFNGLMAPBUFFERRANGEPROC qglMapBufferRange; +extern PFNGLMAPBUFFERPROC qglMapBuffer; +extern PFNGLFLUSHMAPPEDBUFFERRANGEPROC qglFlushMappedBufferRange; +extern PFNGLUNMAPBUFFERPROC qglUnmapBuffer; +extern PFNGLCOPYBUFFERSUBDATAPROC qglCopyBufferSubData; +extern PFNGLISBUFFERPROC qglIsBuffer; + +// Texturing +extern PFNGLACTIVETEXTUREPROC qglActiveTexture; +extern PFNGLTEXIMAGE3DPROC qglTexImage3D; + +// Shader objects +extern PFNGLCREATESHADERPROC qglCreateShader; +extern PFNGLSHADERSOURCEPROC qglShaderSource; +extern PFNGLCOMPILESHADERPROC qglCompileShader; +extern PFNGLDELETESHADERPROC qglDeleteShader; +extern PFNGLISSHADERPROC qglIsShader; +extern PFNGLGETSHADERIVPROC qglGetShaderiv; +extern PFNGLGETSHADERINFOLOGPROC qglGetShaderInfoLog; +extern PFNGLGETSHADERSOURCEPROC qglGetShaderSource; + +// Program objects +extern PFNGLCREATEPROGRAMPROC qglCreateProgram; +extern PFNGLATTACHSHADERPROC qglAttachShader; +extern PFNGLDETACHSHADERPROC qglDetachShader; +extern PFNGLLINKPROGRAMPROC qglLinkProgram; +extern PFNGLUSEPROGRAMPROC qglUseProgram; +extern PFNGLDELETEPROGRAMPROC qglDeleteProgram; +extern PFNGLVALIDATEPROGRAMPROC qglValidateProgram; +extern PFNGLISPROGRAMPROC qglIsProgram; +extern PFNGLGETPROGRAMIVPROC qglGetProgramiv; +extern PFNGLGETATTACHEDSHADERSPROC qglGetAttachedShaders; +extern PFNGLGETPROGRAMINFOLOGPROC qglGetProgramInfoLog; +extern PFNGLBINDFRAGDATALOCATIONPROC qglBindFragDataLocation; + +// Vertex attributes +extern PFNGLGETACTIVEATTRIBPROC qglGetActiveAttrib; +extern PFNGLGETATTRIBLOCATIONPROC qglGetAttribLocation; +extern PFNGLBINDATTRIBLOCATIONPROC qglBindAttribLocation; +extern PFNGLGETVERTEXATTRIBDVPROC qglGetVertexAttribdv; +extern PFNGLGETVERTEXATTRIBFVPROC qglGetVertexAttribfv; +extern PFNGLGETVERTEXATTRIBIVPROC qglGetVertexAttribiv; +extern PFNGLGETVERTEXATTRIBIIVPROC qglGetVertexAttribIiv; +extern PFNGLGETVERTEXATTRIBIUIVPROC qglGetVertexAttribIuiv; + +// Varying variables +extern PFNGLTRANSFORMFEEDBACKVARYINGSPROC qglTransformFeedbackVaryings; +extern PFNGLGETTRANSFORMFEEDBACKVARYINGPROC qglGetTransformFeedbackVarying; + +// Uniform variables +extern PFNGLGETUNIFORMLOCATIONPROC qglGetUniformLocation; +extern PFNGLGETUNIFORMBLOCKINDEXPROC qglGetUniformBlockIndex; +extern PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC qglGetActiveUniformBlockName; +extern PFNGLGETACTIVEUNIFORMBLOCKIVPROC qglGetActiveUniformBlockiv; +extern PFNGLGETUNIFORMINDICESPROC qglGetUniformIndices; +extern PFNGLGETACTIVEUNIFORMNAMEPROC qglGetActiveUniformName; +extern PFNGLGETACTIVEUNIFORMPROC qglGetActiveUniform; +extern PFNGLGETACTIVEUNIFORMSIVPROC qglGetActiveUniformsiv; +extern PFNGLUNIFORM1IPROC qglUniform1i; +extern PFNGLUNIFORM2IPROC qglUniform2i; +extern PFNGLUNIFORM3IPROC qglUniform3i; +extern PFNGLUNIFORM4IPROC qglUniform4i; +extern PFNGLUNIFORM1FPROC qglUniform1f; +extern PFNGLUNIFORM2FPROC qglUniform2f; +extern PFNGLUNIFORM3FPROC qglUniform3f; +extern PFNGLUNIFORM4FPROC qglUniform4f; +extern PFNGLUNIFORM1IVPROC qglUniform1iv; +extern PFNGLUNIFORM2IVPROC qglUniform2iv; +extern PFNGLUNIFORM3IVPROC qglUniform3iv; +extern PFNGLUNIFORM4IVPROC qglUniform4iv; +extern PFNGLUNIFORM1FVPROC qglUniform1fv; +extern PFNGLUNIFORM2FVPROC qglUniform2fv; +extern PFNGLUNIFORM3FVPROC qglUniform3fv; +extern PFNGLUNIFORM4FVPROC qglUniform4fv; +extern PFNGLUNIFORM1UIPROC qglUniform1ui; +extern PFNGLUNIFORM2UIPROC qglUniform2ui; +extern PFNGLUNIFORM3UIPROC qglUniform3ui; +extern PFNGLUNIFORM4UIPROC qglUniform4ui; +extern PFNGLUNIFORM1UIVPROC qglUniform1uiv; +extern PFNGLUNIFORM2UIVPROC qglUniform2uiv; +extern PFNGLUNIFORM3UIVPROC qglUniform3uiv; +extern PFNGLUNIFORM4UIVPROC qglUniform4uiv; +extern PFNGLUNIFORMMATRIX2FVPROC qglUniformMatrix2fv; +extern PFNGLUNIFORMMATRIX3FVPROC qglUniformMatrix3fv; +extern PFNGLUNIFORMMATRIX4FVPROC qglUniformMatrix4fv; +extern PFNGLUNIFORMMATRIX2X3FVPROC qglUniformMatrix2x3fv; +extern PFNGLUNIFORMMATRIX3X2FVPROC qglUniformMatrix3x2fv; +extern PFNGLUNIFORMMATRIX2X4FVPROC qglUniformMatrix2x4fv; +extern PFNGLUNIFORMMATRIX4X2FVPROC qglUniformMatrix4x2fv; +extern PFNGLUNIFORMMATRIX3X4FVPROC qglUniformMatrix3x4fv; +extern PFNGLUNIFORMMATRIX4X3FVPROC qglUniformMatrix4x3fv; +extern PFNGLUNIFORMBLOCKBINDINGPROC qglUniformBlockBinding; +extern PFNGLGETUNIFORMFVPROC qglGetUniformfv; +extern PFNGLGETUNIFORMIVPROC qglGetUniformiv; +extern PFNGLGETUNIFORMUIVPROC qglGetUniformuiv; + +// Transform feedback +extern PFNGLBEGINTRANSFORMFEEDBACKPROC qglBeginTransformFeedback; +extern PFNGLENDTRANSFORMFEEDBACKPROC qglEndTransformFeedback; + +// Texture compression +extern PFNGLCOMPRESSEDTEXIMAGE3DPROC qglCompressedTexImage3D; +extern PFNGLCOMPRESSEDTEXIMAGE2DPROC qglCompressedTexImage2D; +extern PFNGLCOMPRESSEDTEXIMAGE1DPROC qglCompressedTexImage1D; +extern PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC qglCompressedTexSubImage3D; +extern PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC qglCompressedTexSubImage2D; +extern PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC qglCompressedTexSubImage1D; +extern PFNGLGETCOMPRESSEDTEXIMAGEPROC qglGetCompressedTexImage; + +// GL_NVX_gpu_memory_info +#ifndef GL_NVX_gpu_memory_info +#define GL_NVX_gpu_memory_info +#define GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX 0x9047 +#define GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048 +#define GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049 +#define GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX 0x904A +#define GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX 0x904B +#endif + +// GL_ATI_meminfo +#ifndef GL_ATI_meminfo +#define GL_ATI_meminfo +#define GL_VBO_FREE_MEMORY_ATI 0x87FB +#define GL_TEXTURE_FREE_MEMORY_ATI 0x87FC +#define GL_RENDERBUFFER_FREE_MEMORY_ATI 0x87FD +#endif + +// Framebuffers and renderbuffers +extern PFNGLISRENDERBUFFERPROC qglIsRenderbuffer; +extern PFNGLBINDRENDERBUFFERPROC qglBindRenderbuffer; +extern PFNGLDELETERENDERBUFFERSPROC qglDeleteRenderbuffers; +extern PFNGLGENRENDERBUFFERSPROC qglGenRenderbuffers; +extern PFNGLRENDERBUFFERSTORAGEPROC qglRenderbufferStorage; +extern PFNGLGETRENDERBUFFERPARAMETERIVPROC qglGetRenderbufferParameteriv; +extern PFNGLISFRAMEBUFFERPROC qglIsFramebuffer; +extern PFNGLBINDFRAMEBUFFERPROC qglBindFramebuffer; +extern PFNGLDELETEFRAMEBUFFERSPROC qglDeleteFramebuffers; +extern PFNGLGENFRAMEBUFFERSPROC qglGenFramebuffers; +extern PFNGLCHECKFRAMEBUFFERSTATUSPROC qglCheckFramebufferStatus; +extern PFNGLFRAMEBUFFERTEXTURE1DPROC qglFramebufferTexture1D; +extern PFNGLFRAMEBUFFERTEXTURE2DPROC qglFramebufferTexture2D; +extern PFNGLFRAMEBUFFERTEXTURE3DPROC qglFramebufferTexture3D; +extern PFNGLFRAMEBUFFERTEXTUREPROC qglFramebufferTexture; +extern PFNGLFRAMEBUFFERTEXTURELAYERPROC qglFramebufferTextureLayer; +extern PFNGLFRAMEBUFFERRENDERBUFFERPROC qglFramebufferRenderbuffer; +extern PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC qglGetFramebufferAttachmentParameteriv; +extern PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC qglRenderbufferStorageMultisample; +extern PFNGLBLITFRAMEBUFFERPROC qglBlitFramebuffer; +extern PFNGLGENERATEMIPMAPPROC qglGenerateMipmap; +extern PFNGLDRAWBUFFERSPROC qglDrawBuffers; +extern PFNGLCLEARBUFFERFVPROC qglClearBufferfv; + +// Query objects +extern PFNGLGENQUERIESPROC qglGenQueries; +extern PFNGLDELETEQUERIESPROC qglDeleteQueries; +extern PFNGLISQUERYPROC qglIsQuery; +extern PFNGLBEGINQUERYPROC qglBeginQuery; +extern PFNGLENDQUERYPROC qglEndQuery; +extern PFNGLGETQUERYIVPROC qglGetQueryiv; +extern PFNGLGETQUERYOBJECTIVPROC qglGetQueryObjectiv; +extern PFNGLGETQUERYOBJECTUIVPROC qglGetQueryObjectuiv; + +// GL state +extern PFNGLGETSTRINGIPROC qglGetStringi; + +// Sync objects and fences +extern PFNGLFENCESYNCPROC qglFenceSync; +extern PFNGLDELETESYNCPROC qglDeleteSync; +extern PFNGLCLIENTWAITSYNCPROC qglClientWaitSync; +extern PFNGLWAITSYNCPROC qglWaitSync; + +#ifndef GL_EXT_texture_compression_latc +#define GL_EXT_texture_compression_latc +#define GL_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70 +#define GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71 +#define GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72 +#define GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73 +#endif + +#ifndef GL_ARB_texture_compression_bptc +#define GL_ARB_texture_compression_bptc +#define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C +#define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D +#define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E +#define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F +#endif + +// GL_ARB_texture_storage +extern PFNGLTEXSTORAGE1DPROC qglTexStorage1D; +extern PFNGLTEXSTORAGE2DPROC qglTexStorage2D; +extern PFNGLTEXSTORAGE3DPROC qglTexStorage3D; +#ifndef GL_ARB_texture_storage +#define GL_TEXTURE_IMMUTABLE_FORMAT 0x912F +#endif + +// GL_ARB_buffer_storage +extern PFNGLBUFFERSTORAGEPROC qglBufferStorage; + +// GL_ARB_debug_output +extern PFNGLDEBUGMESSAGECONTROLARBPROC qglDebugMessageControlARB; +extern PFNGLDEBUGMESSAGEINSERTARBPROC qglDebugMessageInsertARB; +extern PFNGLDEBUGMESSAGECALLBACKARBPROC qglDebugMessageCallbackARB; +extern PFNGLGETDEBUGMESSAGELOGARBPROC qglGetDebugMessageLogARB; + +// GL_ARB_timer_query +extern PFNGLQUERYCOUNTERPROC qglQueryCounter; +extern PFNGLGETQUERYOBJECTI64VPROC qglGetQueryObjecti64v; +extern PFNGLGETQUERYOBJECTUI64VPROC qglGetQueryObjectui64v; diff --git a/codemp/rd-rend2/stb_image.h b/codemp/rd-rend2/stb_image.h new file mode 100644 index 0000000000..a184dddb43 --- /dev/null +++ b/codemp/rd-rend2/stb_image.h @@ -0,0 +1,7546 @@ +/* stb_image - v2.19 - public domain image loader - http://nothings.org/stb +no warranty implied; use at your own risk +Do this: +#define STB_IMAGE_IMPLEMENTATION +before you include this file in *one* C or C++ file to create the implementation. +// i.e. it should look like this: +#include ... +#include ... +#include ... +#define STB_IMAGE_IMPLEMENTATION +#include "stb_image.h" +You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. +And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free +QUICK NOTES: +Primarily of interest to game developers and other people who can +avoid problematic images and only need the trivial interface +JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) +PNG 1/2/4/8/16-bit-per-channel +TGA (not sure what subset, if a subset) +BMP non-1bpp, non-RLE +PSD (composited view only, no extra channels, 8/16 bit-per-channel) +GIF (*comp always reports as 4-channel) +HDR (radiance rgbE format) +PIC (Softimage PIC) +PNM (PPM and PGM binary only) +Animated GIF still needs a proper API, but here's one way to do it: +http://gist.github.com/urraka/685d9a6340b26b830d49 +- decode from memory or through FILE (define STBI_NO_STDIO to remove code) +- decode from arbitrary I/O callbacks +- SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) +Full documentation under "DOCUMENTATION" below. +LICENSE +See end of file for license information. +RECENT REVISION HISTORY: +2.19 (2018-02-11) fix warning +2.18 (2018-01-30) fix warnings +2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings +2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes +2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC +2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs +2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes +2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes +2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 +RGB-format JPEG; remove white matting in PSD; +allocate large structures on the stack; +correct channel count for PNG & BMP +2.10 (2016-01-22) avoid warning introduced in 2.09 +2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED +See end of file for full revision history. +============================ Contributors ========================= +Image formats Extensions, features +Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) +Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) +Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) +Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) +Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) +Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) +Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) +github:urraka (animated gif) Junggon Kim (PNM comments) +Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) +socks-the-fox (16-bit PNG) +Jeremy Sawicki (handle all ImageNet JPGs) +Optimizations & bugfixes Mikhail Morozov (1-bit BMP) +Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) +Arseny Kapoulkine +John-Mark Allen +Bug & warning fixes +Marc LeBlanc David Woo Guillaume George Martins Mozeiko +Christpher Lloyd Jerry Jansson Joseph Thomson Phil Jordan +Dave Moore Roy Eltham Hayaki Saito Nathan Reed +Won Chun Luke Graham Johan Duparc Nick Verigakis +the Horde3D community Thomas Ruf Ronny Chevalier github:rlyeh +Janez Zemva John Bartholomew Michal Cichon github:romigrou +Jonathan Blow Ken Hamada Tero Hanninen github:svdijk +Laurent Gomila Cort Stratton Sergio Gonzalez github:snagar +Aruelien Pocheville Thibault Reuille Cass Everitt github:Zelex +Ryamond Barbiero Paul Du Bois Engin Manap github:grim210 +Aldo Culquicondor Philipp Wiesemann Dale Weiler github:sammyhw +Oriol Ferrer Mesia Josh Tobin Matthew Gregan github:phprus +Julian Raschke Gregory Mullen Baldur Karlsson github:poppolopoppo +Christian Floisand Kevin Schmidt github:darealshinji +Blazej Dariusz Roszkowski github:Michaelangel007 +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data) +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy to use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// make more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image now supports loading HDR images in general, and currently +// the Radiance .HDR file format, although the support is provided +// generically. You can still load any file through the existing interface; +// if you attempt to load an HDR file, it will be automatically remapped to +// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// By default we convert iphone-formatted PNGs back to RGB, even though +// they are internally encoded differently. You can disable this conversion +// by by calling stbi_convert_iphone_png_to_rgb(0), in which case +// you will always just get the native iphone "format" through (which +// is BGR stored in RGB). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// + + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif + + ////////////////////////////////////////////////////////////////////////////// + // + // PRIMARY API - works on images of any type + // + + // + // load image by filename, open file, or memory buffer + // + + typedef struct + { + int(*read) (void *user, char *data, int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void(*skip) (void *user, int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int(*eof) (void *user); // returns nonzero if we are at end of file/data + } stbi_io_callbacks; + + //////////////////////////////////// + // + // 8-bits-per-channel interface + // + + STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); +#ifndef STBI_NO_GIF + STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + + +#ifndef STBI_NO_STDIO + STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + // for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + + //////////////////////////////////// + // + // 16-bits-per-channel interface + // + + STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO + STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + + //////////////////////////////////// + // + // float-per-channel interface + // +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + + // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR + STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); + STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO + STBIDEF int stbi_is_hdr(char const *filename); + STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + + // get a VERY brief reason for failure + // NOT THREADSAFE + STBIDEF const char *stbi_failure_reason(void); + + // free the loaded image -- this is just free() + STBIDEF void stbi_image_free(void *retval_from_stbi_load); + + // get image dimensions & components without fully decoding + STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); + STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); + STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); + STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO + STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp); + STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp); + STBIDEF int stbi_is_16_bit(char const *filename); + STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + + // for image formats that explicitly notate that they have premultiplied alpha, + // we just return the colors as stored in the file. set this flag to force + // unpremultiplication. results are undefined if the unpremultiply overflow. + STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + + // indicate whether we should process iphone images back to canonical format, + // or just pass them through "as-is" + STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + + // flip the image vertically, so the first pixel in the output array is the bottom left + STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + + // ZLIB client - used by PNG, available for other purposes + + STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); + STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); + STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); + STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); + STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) +#ifndef STBI_ONLY_JPEG +#define STBI_NO_JPEG +#endif +#ifndef STBI_ONLY_PNG +#define STBI_NO_PNG +#endif +#ifndef STBI_ONLY_BMP +#define STBI_NO_BMP +#endif +#ifndef STBI_ONLY_PSD +#define STBI_NO_PSD +#endif +#ifndef STBI_ONLY_TGA +#define STBI_NO_TGA +#endif +#ifndef STBI_ONLY_GIF +#define STBI_NO_GIF +#endif +#ifndef STBI_ONLY_HDR +#define STBI_NO_HDR +#endif +#ifndef STBI_ONLY_PIC +#define STBI_NO_PIC +#endif +#ifndef STBI_ONLY_PNM +#define STBI_NO_PNM +#endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + + +#ifndef _MSC_VER +#ifdef __cplusplus +#define stbi_inline inline +#else +#define stbi_inline +#endif +#else +#define stbi_inline __forceinline +#endif + + +#ifdef _MSC_VER +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32) == 4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL +#define stbi_lrot(x,y) _lrotl(x,y) +#else +#define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y)))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info, 1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax, 1 + cpuid + mov res, edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +// assume GCC or Clang on ARM targets +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *)buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *)buffer + len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int)fread(data, 1, size, (FILE*)user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + fseek((FILE*)user, n, SEEK_CUR); +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*)user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *)f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +// this is not threadsafe +static const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX / b; +} + +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS +#define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) +#define stbi__err(x,y) stbi__err(y) +#else +#define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load = flag_true_if_should_flip; +} + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + +#ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s, x, y, comp, req_comp, ri, bpc); +#endif +#ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s, x, y, comp, req_comp, ri); +#endif +#ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s, x, y, comp, req_comp, ri); +#endif + +#ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x, y, comp, req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } +#endif + +#ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s, x, y, comp, req_comp, ri); +#endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *)stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *)stbi__malloc(img_len * 2); + if (enlarged == NULL) return (stbi__uint16 *)stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h >> 1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + if (ri.bits_per_channel != 8) { + STBI_ASSERT(ri.bits_per_channel == 16); + result = stbi__convert_16_to_8((stbi__uint16 *)result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *)result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + if (ri.bits_per_channel != 16) { + STBI_ASSERT(ri.bits_per_channel == 8); + result = stbi__convert_8_to_16((stbi_uc *)result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *)result; +} + +#if !defined(STBI_NO_HDR) || !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f = 0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f, x, y, comp, req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s, f); + result = stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s, f); + result = stbi__load_and_postprocess_16bit(&s, x, y, comp, req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, -(int)(s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *)stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f, x, y, comp, req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s, x, y, channels_in_file, desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_8bit(&s, x, y, comp, req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s, buffer, len); + + result = (unsigned char*)stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices(result, *x, *y, *z, *comp); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; +#ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s, x, y, comp, req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data, x, y, comp, req_comp); + return hdr_data; + } +#endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__loadf_main(&s, x, y, comp, req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__loadf_main(&s, x, y, comp, req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f, x, y, comp, req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s, f); + return stbi__loadf_main(&s, x, y, comp, req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ +#ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__hdr_test(&s); +#else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; +#endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result = 0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ +#ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s, f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; +#else + STBI_NOTUSED(f); + return 0; +#endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ +#ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__hdr_test(&s); +#else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; +#endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma = 2.2f, stbi__l2h_scale = 1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i = 1.0f / 2.2f, stbi__h2l_scale_i = 1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1 / gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1 / scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load = 0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data, (char*)s->buffer_start, s->buflen); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + 1; + *s->img_buffer = 0; + } + else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} + +static void stbi__skip(stbi__context *s, int n) +{ + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int)(s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} + +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int)(s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*)buffer + blen, n - blen); + res = (count == (n - blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer + n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } + else + return 0; +} + +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} + +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + return z + (stbi__get16le(s) << 16); +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + + +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc)(((r * 77) + (g * 150) + (29 * b)) >> 8); +} + +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i, j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *)stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j = 0; j < (int)y; ++j) { + unsigned char *src = data + j * x * img_n; + unsigned char *dest = good + j * x * req_comp; + +#define STBI__COMBO(a,b) ((a)*8+(b)) +#define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1, 2) { dest[0] = src[0], dest[1] = 255; } break; + STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; + STBI__CASE(1, 4) { dest[0] = dest[1] = dest[2] = src[0], dest[3] = 255; } break; + STBI__CASE(2, 1) { dest[0] = src[0]; } break; + STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; + STBI__CASE(2, 4) { dest[0] = dest[1] = dest[2] = src[0], dest[3] = src[1]; } break; + STBI__CASE(3, 4) { dest[0] = src[0], dest[1] = src[1], dest[2] = src[2], dest[3] = 255; } break; + STBI__CASE(3, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); } break; + STBI__CASE(3, 2) { dest[0] = stbi__compute_y(src[0], src[1], src[2]), dest[1] = 255; } break; + STBI__CASE(4, 1) { dest[0] = stbi__compute_y(src[0], src[1], src[2]); } break; + STBI__CASE(4, 2) { dest[0] = stbi__compute_y(src[0], src[1], src[2]), dest[1] = src[3]; } break; + STBI__CASE(4, 3) { dest[0] = src[0], dest[1] = src[1], dest[2] = src[2]; } break; + default: STBI_ASSERT(0); + } +#undef STBI__CASE + } + + STBI_FREE(data); + return good; +} + +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16)(((r * 77) + (g * 150) + (29 * b)) >> 8); +} + +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i, j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *)stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *)stbi__errpuc("outofmem", "Out of memory"); + } + + for (j = 0; j < (int)y; ++j) { + stbi__uint16 *src = data + j * x * img_n; + stbi__uint16 *dest = good + j * x * req_comp; + +#define STBI__COMBO(a,b) ((a)*8+(b)) +#define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1, 2) { dest[0] = src[0], dest[1] = 0xffff; } break; + STBI__CASE(1, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; + STBI__CASE(1, 4) { dest[0] = dest[1] = dest[2] = src[0], dest[3] = 0xffff; } break; + STBI__CASE(2, 1) { dest[0] = src[0]; } break; + STBI__CASE(2, 3) { dest[0] = dest[1] = dest[2] = src[0]; } break; + STBI__CASE(2, 4) { dest[0] = dest[1] = dest[2] = src[0], dest[3] = src[1]; } break; + STBI__CASE(3, 4) { dest[0] = src[0], dest[1] = src[1], dest[2] = src[2], dest[3] = 0xffff; } break; + STBI__CASE(3, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); } break; + STBI__CASE(3, 2) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]), dest[1] = 0xffff; } break; + STBI__CASE(4, 1) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]); } break; + STBI__CASE(4, 2) { dest[0] = stbi__compute_y_16(src[0], src[1], src[2]), dest[1] = src[3]; } break; + STBI__CASE(4, 3) { dest[0] = src[0], dest[1] = src[1], dest[2] = src[2]; } break; + default: STBI_ASSERT(0); + } +#undef STBI__CASE + } + + STBI_FREE(data); + return good; +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i, k, n; + float *output; + if (!data) return NULL; + output = (float *)stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp - 1; + for (i = 0; i < x*y; ++i) { + for (k = 0; k < n; ++k) { + output[i*comp + k] = (float)(pow(data[i*comp + k] / 255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + if (k < comp) output[i*comp + k] = data[i*comp + k] / 255.0f; + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i, k, n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *)stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp - 1; + for (i = 0; i < x*y; ++i) { + for (k = 0; k < n; ++k) { + float z = (float)pow(data[i*comp + k] * stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc)stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp + k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc)stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + + // sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + + // definition of jpeg image component + struct + { + int id; + int h, v; + int tq; + int hd, ha; + int dc_pred; + + int x, y, w2, h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + + // kernels + void(*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void(*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i, j, k = 0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i = 0; i < 16; ++i) + for (j = 0; j < count[i]; ++j) + h->size[k++] = (stbi_uc)(i + 1); + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for (j = 1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16)(code++); + if (code - 1 >= (1u << j)) return stbi__err("bad code lengths", "Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16 - j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i = 0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS - s); + int m = 1 << (FAST_BITS - s); + for (j = 0; j < m; ++j) { + h->fast[c + j] = (stbi_uc)i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i = 0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16)((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char)c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17] = { 0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535 }; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c, k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k = FAST_BITS + 1; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + + sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB + k = stbi_lrot(j->code_buffer, n); + STBI_ASSERT(n >= 0 && n < (int)(sizeof(stbi__bmask) / sizeof(*stbi__bmask))); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & ~sgn); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64 + 15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff, dc, k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data, 0, 64 * sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short)(dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c, r, s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)((r >> 8) * dequant[zig]); + } + else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } + else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)(stbi__extend_receive(j, s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff, dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data, 0, 64 * sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + diff = t ? stbi__extend_receive(j, t) : 0; + + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + data[0] = (short)(dc << j->succ_low); + } + else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short)(1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c, r, s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS) - 1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)((r >> 8) << shift); + } + else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } + else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short)(stbi__extend_receive(j, s) << shift); + } + } + } while (k <= j->spec_end); + } + else { + // refinement scan for these AC coefficients + + short bit = (short)(1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit) == 0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } + else { + k = j->spec_start; + do { + int r, s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code", "Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } + else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } + else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit) == 0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + else { + if (r == 0) { + *p = (short)s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int)x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc)x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i, val[64], *v = val; + stbi_uc *o; + short *d = data; + + // columns + for (i = 0; i < 8; ++i, ++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[8] == 0 && d[16] == 0 && d[24] == 0 && d[32] == 0 + && d[40] == 0 && d[48] == 0 && d[56] == 0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0] * 4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } + else { + STBI__IDCT_1D(d[0], d[8], d[16], d[24], d[32], d[40], d[48], d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[0] = (x0 + t3) >> 10; + v[56] = (x0 - t3) >> 10; + v[8] = (x1 + t2) >> 10; + v[48] = (x1 - t2) >> 10; + v[16] = (x2 + t1) >> 10; + v[40] = (x2 - t1) >> 10; + v[24] = (x3 + t0) >> 10; + v[32] = (x3 - t0) >> 10; + } + } + + for (i = 0, v = val, o = out; i < 8; ++i, v += 8, o += out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128 << 17); + x1 += 65536 + (128 << 17); + x2 += 65536 + (128 << 17); + x3 += 65536 + (128 << 17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0 + t3) >> 17); + o[7] = stbi__clamp((x0 - t3) >> 17); + o[1] = stbi__clamp((x1 + t2) >> 17); + o[6] = stbi__clamp((x1 - t2) >> 17); + o[2] = stbi__clamp((x2 + t1) >> 17); + o[5] = stbi__clamp((x2 - t1) >> 17); + o[3] = stbi__clamp((x3 + t0) >> 17); + o[4] = stbi__clamp((x3 - t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y +#define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y +#define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) +#define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add +#define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub +#define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack +#define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) +#define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) +#define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + +#define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f(0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f(0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f(3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f(2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f(1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128 << 17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0 * 8)); + row1 = _mm_load_si128((const __m128i *) (data + 1 * 8)); + row2 = _mm_load_si128((const __m128i *) (data + 2 * 8)); + row3 = _mm_load_si128((const __m128i *) (data + 3 * 8)); + row4 = _mm_load_si128((const __m128i *) (data + 4 * 8)); + row5 = _mm_load_si128((const __m128i *) (data + 5 * 8)); + row6 = _mm_load_si128((const __m128i *) (data + 6 * 8)); + row7 = _mm_load_si128((const __m128i *) (data + 7 * 8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f(0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f(1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f(0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f(2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f(3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f(1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + + // wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + + // wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + + // butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0 * 8); + row1 = vld1q_s16(data + 1 * 8); + row2 = vld1q_s16(data + 2 * 8); + row3 = vld1q_s16(data + 3 * 8); + row4 = vld1q_s16(data + 4 * 8); + row5 = vld1q_s16(data + 5 * 8); + row6 = vld1q_s16(data + 6 * 8); + row7 = vld1q_s16(data + 7 * 8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { + // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. + // whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i, j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2*j * 8 + i * 8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + else { // interleaved + int i, j, k, x, y; + STBI_SIMD_ALIGN(short, data[64]); + for (j = 0; j < z->img_mcu_y; ++j) { + for (i = 0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k = 0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y = 0; y < z->img_comp[n].v; ++y) { + for (x = 0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x) * 8; + int y2 = (j*z->img_comp[n].v + y) * 8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc + z->img_comp[n].hd, z->huff_ac + ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2*y2 + x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } + else { + if (z->scan_n == 1) { + int i, j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + else { // interleaved + int i, j, k, x, y; + for (j = 0; j < z->img_mcu_y; ++j) { + for (i = 0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k = 0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y = 0; y < z->img_comp[n].v; ++y) { + for (x = 0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i = 0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i, j, n; + for (n = 0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x + 7) >> 3; + int h = (z->img_comp[n].y + 7) >> 3; + for (j = 0; j < h; ++j) { + for (i = 0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data + z->img_comp[n].w2*j * 8 + i * 8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker", "Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len", "Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s) - 2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15, i; + if (p != 0 && p != 1) return stbi__err("bad DQT type", "Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table", "Corrupt JPEG"); + + for (i = 0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L == 0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s) - 2; + while (L > 0) { + stbi_uc *v; + int sizes[16], i, n = 0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header", "Corrupt JPEG"); + for (i = 0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc + th, sizes)) return 0; + v = z->huff_dc[th].values; + } + else { + if (!stbi__build_huffman(z->huff_ac + th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i = 0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L == 0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len", "Corrupt JPEG"); + else + return stbi__err("bad APP len", "Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = { 'J','F','I','F','\0' }; + int ok = 1; + int i; + for (i = 0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } + else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = { 'A','d','o','b','e','\0' }; + int ok = 1; + int i; + for (i = 0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker", "Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int)z->s->img_n) return stbi__err("bad SOS component count", "Corrupt JPEG"); + if (Ls != 6 + 2 * z->scan_n) return stbi__err("bad SOS len", "Corrupt JPEG"); + for (i = 0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff", "Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff", "Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } + else { + if (z->spec_start != 0) return stbi__err("bad SOS", "Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS", "Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i = 0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf, p, i, q, h_max = 1, v_max = 1, c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len", "Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit", "JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width", "Corrupt JPEG"); // JPEG requires + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count", "Corrupt JPEG"); + s->img_n = c; + for (i = 0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8 + 3 * s->img_n) return stbi__err("bad SOF len", "Corrupt JPEG"); + + z->rgb = 0; + for (i = 0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H", "Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V", "Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ", "Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i = 0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w - 1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h - 1) / z->img_mcu_h; + + for (i = 0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max - 1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max - 1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i + 1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*)(((size_t)z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i + 1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*)(((size_t)z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI", "Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z, m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none) { + // handle 0s at the end of image data from IP Kamera 9060 + while (!stbi__at_eof(j->s)) { + int x = stbi__get8(j->s); + if (x == 255) { + j->marker = stbi__get8(j->s); + break; + } + } + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + } + else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + } + else { + if (!stbi__process_marker(j, m)) return 0; + } + m = stbi__get_marker(j); + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i = 0; i < w; ++i) + out[i] = stbi__div4(3 * in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0] * 3 + input[1] + 2); + for (i = 1; i < w - 1; ++i) { + int n = 3 * input[i] + 2; + out[i * 2 + 0] = stbi__div4(n + input[i - 1]); + out[i * 2 + 1] = stbi__div4(n + input[i + 1]); + } + out[i * 2 + 0] = stbi__div4(input[w - 2] * 3 + input[w - 1] + 2); + out[i * 2 + 1] = input[w - 1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i, t0, t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3 * in_near[0] + in_far[0]; + out[0] = stbi__div4(t1 + 2); + for (i = 1; i < w; ++i) { + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8); + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); + } + out[w * 2 - 1] = stbi__div4(t1 + 2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i = 0, t0, t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3 * in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3 * in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w - 1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3 * in_near[i + 8] + in_far[i + 8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i * 2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3 * in_near[i + 8] + in_far[i + 8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i * 2, o); +#endif + + // "previous" value for next iter + t1 = 3 * in_near[i + 7] + in_far[i + 7]; + } + + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3 * in_near[i] + in_far[i]; + out[i * 2 - 1] = stbi__div16(3 * t0 + t1 + 8); + out[i * 2] = stbi__div16(3 * t1 + t0 + 8); + } + out[w * 2 - 1] = stbi__div4(t1 + 2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i, j; + STBI_NOTUSED(in_far); + for (i = 0; i < w; ++i) + for (j = 0; j < hs; ++j) + out[i*hs + j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i = 0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1 << 19); // rounding + int r, g, b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned)r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned)g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned)b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16((short)(1.40200f*4096.0f + 0.5f)); + __m128i cr_const1 = _mm_set1_epi16(-(short)(0.71414f*4096.0f + 0.5f)); + __m128i cb_const0 = _mm_set1_epi16(-(short)(0.34414f*4096.0f + 0.5f)); + __m128i cb_const1 = _mm_set1_epi16((short)(1.77200f*4096.0f + 0.5f)); + __m128i y_bias = _mm_set1_epi8((char)(unsigned char)128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i + 7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y + i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr + i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb + i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16((short)(1.40200f*4096.0f + 0.5f)); + int16x8_t cr_const1 = vdupq_n_s16(-(short)(0.71414f*4096.0f + 0.5f)); + int16x8_t cb_const0 = vdupq_n_s16(-(short)(0.34414f*4096.0f + 0.5f)); + int16x8_t cb_const1 = vdupq_n_s16((short)(1.77200f*4096.0f + 0.5f)); + + for (; i + 7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8 * 4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1 << 19); // rounding + int r, g, b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned)r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned)g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned)b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0, *line1; + int hs, vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc)((t + (t >> 8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // resample and color-convert + { + int k; + unsigned int i, j; + stbi_uc *output; + stbi_uc *coutput[4]; + + stbi__resample res_comp[4]; + + for (k = 0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *)stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs - 1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *)stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j = 0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k = 0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i = 0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } + else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } + else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } + else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } + else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } + else + for (i = 0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } + else { + if (is_rgb) { + if (n == 1) + for (i = 0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i = 0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } + else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i = 0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } + else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i = 0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } + else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i = 0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i = 0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255; + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x, y, comp, req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind(j->s); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*)(stbi__malloc(sizeof(stbi__jpeg))); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[288]; + stbi__uint16 value[288]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16 - bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i, k = 0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i = 0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i = 1; i < 16; ++i) + if (sizes[i] >(1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i = 1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16)code; + z->firstsymbol[i] = (stbi__uint16)k; + code = (code + sizes[i]); + if (sizes[i]) + if (code - 1 >= (1 << i)) return stbi__err("bad codelengths", "Corrupt PNG"); + z->maxcode[i] = code << (16 - i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i = 0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16)((s << 9) | i); + z->size[c] = (stbi_uc)s; + z->value[c] = (stbi__uint16)i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s], s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + if (z->zbuffer >= z->zbuffer_end) return 0; + return *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + STBI_ASSERT(z->code_buffer < (1U << z->num_bits)); + z->code_buffer |= (unsigned int)stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b, s, k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s = STBI__ZFAST_BITS + 1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s == 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16 - s)) - z->firstcode[s] + z->firstsymbol[s]; + STBI_ASSERT(z->size[b] == s); + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b, s; + if (a->num_bits < 16) stbi__fill_bits(a); + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit", "Corrupt PNG"); + cur = (int)(z->zout - z->zout_start); + limit = old_limit = (int)(z->zout_end - z->zout_start); + while (cur + n > limit) + limit *= 2; + q = (char *)STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31] = +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0 }; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13 }; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for (;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code", "Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char)z; + } + else { + stbi_uc *p; + int len, dist; + if (z == 256) { + a->zout = zout; + return 1; + } + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0) return stbi__err("bad huffman code", "Corrupt PNG"); + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist", "Corrupt PNG"); + if (zout + len > a->zout_end) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *)(zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } + else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286 + 32 + 137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i, n; + + int hlit = stbi__zreceive(a, 5) + 257; + int hdist = stbi__zreceive(a, 5) + 1; + int hclen = stbi__zreceive(a, 4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i = 0; i < hclen; ++i) { + int s = stbi__zreceive(a, 3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc)s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc)c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a, 2) + 3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n - 1]; + } + else if (c == 17) + c = stbi__zreceive(a, 3) + 3; + else { + STBI_ASSERT(c == 18); + c = stbi__zreceive(a, 7) + 11; + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes + n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths", "Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes + hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len, nlen, k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc)(a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + STBI_ASSERT(a->num_bits == 0); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt", "Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer", "Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if ((cmf * 256 + flg) % 31 != 0) return stbi__err("bad zlib header", "Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict", "Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression", "Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[288] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ +int i; // use <= to match clearly with spec +for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; +for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; +for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; +for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; +for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + do { + final = stbi__zreceive(a, 1); + type = stbi__zreceive(a, 2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } + else if (type == 3) { + return 0; + } + else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length, stbi__zdefault_length, 288)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } + else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *)stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *)buffer; + a.zbuffer_end = (stbi_uc *)buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } + else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *)stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *)buffer; + a.zbuffer_end = (stbi_uc *)buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } + else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *)ibuffer; + a.zbuffer_end = (stbi_uc *)ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int)(a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *)stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *)buffer; + a.zbuffer_end = (stbi_uc *)buffer + len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int)(a.zout - a.zout_start); + return a.zout_start; + } + else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *)ibuffer; + a.zbuffer_end = (stbi_uc *)ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int)(a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i = 0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig", "Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none = 0, + STBI__F_sub = 1, + STBI__F_up = 2, + STBI__F_avg = 3, + STBI__F_paeth = 4, + // synthetic filters used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_paeth_first +}; + +static int stbi__paeth(int a, int b, int c) +{ + int p = a + b - c; + int pa = abs(p - a); + int pb = abs(p - b); + int pc = abs(p - c); + if (pa <= pb && pa <= pc) return a; + if (pb <= pc) return b; + return c; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16 ? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i, j, stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n + 1); + a->out = (stbi_uc *)stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels", "Corrupt PNG"); + + for (j = 0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *prior; + int filter = *raw++; + + if (filter > 4) + return stbi__err("invalid filter", "Corrupt PNG"); + + if (depth < 8) { + STBI_ASSERT(img_width_bytes <= x); + cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place + filter_bytes = 1; + width = img_width_bytes; + } + prior = cur - stride; // bugfix: need to compute this after 'cur +=' computation above + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // handle first byte explicitly + for (k = 0; k < filter_bytes; ++k) { + switch (filter) { + case STBI__F_none: cur[k] = raw[k]; break; + case STBI__F_sub: cur[k] = raw[k]; break; + case STBI__F_up: cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break; + case STBI__F_avg: cur[k] = STBI__BYTECAST(raw[k] + (prior[k] >> 1)); break; + case STBI__F_paeth: cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0, prior[k], 0)); break; + case STBI__F_avg_first: cur[k] = raw[k]; break; + case STBI__F_paeth_first: cur[k] = raw[k]; break; + } + } + + if (depth == 8) { + if (img_n != out_n) + cur[img_n] = 255; // first pixel + raw += img_n; + cur += out_n; + prior += out_n; + } + else if (depth == 16) { + if (img_n != out_n) { + cur[filter_bytes] = 255; // first pixel top byte + cur[filter_bytes + 1] = 255; // first pixel bottom byte + } + raw += filter_bytes; + cur += output_bytes; + prior += output_bytes; + } + else { + raw += 1; + cur += 1; + prior += 1; + } + + // this is a little gross, so that we don't switch per-pixel or per-component + if (depth < 8 || img_n == out_n) { + int nk = (width - 1)*filter_bytes; +#define STBI__CASE(f) \ + case f: \ + for (k=0; k < nk; ++k) + switch (filter) { + // "none" filter turns into a memcpy here; make that explicit. + case STBI__F_none: memcpy(cur, raw, nk); break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k - filter_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k - filter_bytes]) >> 1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - filter_bytes], prior[k], prior[k - filter_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k - filter_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - filter_bytes], 0, 0)); } break; + } +#undef STBI__CASE + raw += nk; + } + else { + STBI_ASSERT(img_n + 1 == out_n); +#define STBI__CASE(f) \ + case f: \ + for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \ + for (k=0; k < filter_bytes; ++k) + switch (filter) { + STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break; + STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k - output_bytes]); } break; + STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break; + STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k - output_bytes]) >> 1)); } break; + STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - output_bytes], prior[k], prior[k - output_bytes])); } break; + STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k - output_bytes] >> 1)); } break; + STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k - output_bytes], 0, 0)); } break; + } +#undef STBI__CASE + + // the loop above sets the high byte of the pixels' alpha, but for + // 16 bit png files we also need the low byte set. we'll do that here. + if (depth == 16) { + cur = a->out + stride*j; // start at the beginning of the row again + for (i = 0; i < x; ++i, cur += output_bytes) { + cur[filter_bytes + 1] = 255; + } + } + } + } + + // we make a separate pass to expand bits to pixels; for performance, + // this could run two scanlines behind the above code, so it won't + // intefere with filtering but will still be in the cache. + if (depth < 8) { + for (j = 0; j < y; ++j) { + stbi_uc *cur = a->out + stride*j; + stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes; + // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit + // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + + // note that the final byte might overshoot and write more data than desired. + // we can allocate enough data that this never writes out of memory, but it + // could also overwrite the next scanline. can it overwrite non-empty data + // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel. + // so we need to explicitly clamp the final ones + + if (depth == 4) { + for (k = x*img_n; k >= 2; k -= 2, ++in) { + *cur++ = scale * ((*in >> 4)); + *cur++ = scale * ((*in) & 0x0f); + } + if (k > 0) *cur++ = scale * ((*in >> 4)); + } + else if (depth == 2) { + for (k = x*img_n; k >= 4; k -= 4, ++in) { + *cur++ = scale * ((*in >> 6)); + *cur++ = scale * ((*in >> 4) & 0x03); + *cur++ = scale * ((*in >> 2) & 0x03); + *cur++ = scale * ((*in) & 0x03); + } + if (k > 0) *cur++ = scale * ((*in >> 6)); + if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03); + if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03); + } + else if (depth == 1) { + for (k = x*img_n; k >= 8; k -= 8, ++in) { + *cur++ = scale * ((*in >> 7)); + *cur++ = scale * ((*in >> 6) & 0x01); + *cur++ = scale * ((*in >> 5) & 0x01); + *cur++ = scale * ((*in >> 4) & 0x01); + *cur++ = scale * ((*in >> 3) & 0x01); + *cur++ = scale * ((*in >> 2) & 0x01); + *cur++ = scale * ((*in >> 1) & 0x01); + *cur++ = scale * ((*in) & 0x01); + } + if (k > 0) *cur++ = scale * ((*in >> 7)); + if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01); + if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01); + if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01); + if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01); + if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01); + if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01); + } + if (img_n != out_n) { + int q; + // insert alpha = 255 + cur = a->out + stride*j; + if (img_n == 1) { + for (q = x - 1; q >= 0; --q) { + cur[q * 2 + 1] = 255; + cur[q * 2 + 0] = cur[q]; + } + } + else { + STBI_ASSERT(img_n == 3); + for (q = x - 1; q >= 0; --q) { + cur[q * 4 + 3] = 255; + cur[q * 4 + 2] = cur[q * 3 + 2]; + cur[q * 4 + 1] = cur[q * 3 + 1]; + cur[q * 4 + 0] = cur[q * 3 + 0]; + } + } + } + } + } + else if (depth == 16) { + // force the image data from big-endian to platform-native. + // this is done in a separate pass due to the decoding relying + // on the data being untouched, but could probably be done + // per-line during decode if care is taken. + stbi_uc *cur = a->out; + stbi__uint16 *cur16 = (stbi__uint16*)cur; + + for (i = 0; i < x*y*out_n; ++i, cur16++, cur += 2) { + *cur16 = (cur[0] << 8) | cur[1]; + } + } + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *)stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + for (p = 0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i, j, x, y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p] - 1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p] - 1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j = 0; j < y; ++j) { + for (i = 0; i < x; ++i) { + int out_y = j*yspc[p] + yorig[p]; + int out_x = i*xspc[p] + xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x + i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } + else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*)z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } + else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *)stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i = 0; i < pixel_count; ++i) { + int n = orig[i] * 4; + p[0] = palette[n]; + p[1] = palette[n + 1]; + p[2] = palette[n + 2]; + p += 3; + } + } + else { + for (i = 0; i < pixel_count; ++i) { + int n = orig[i] * 4; + p[0] = palette[n]; + p[1] = palette[n + 1]; + p[2] = palette[n + 2]; + p[3] = palette[n + 3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load = 0; +static int stbi__de_iphone_flag = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag = flag_true_if_should_convert; +} + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i = 0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } + else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i = 0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = (t * 255 + half) / a; + } + else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } + else { + // convert bgr to rgb + for (i = 0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n = 0; + stbi_uc has_trans = 0, tc[3]; + stbi__uint16 tc16[3]; + stbi__uint32 ioff = 0, idata_limit = 0, i, pal_len = 0; + int first = 1, k, interlace = 0, color = 0, is_iphone = 0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C', 'g', 'B', 'I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I', 'H', 'D', 'R'): { + int comp, filter; + if (!first) return stbi__err("multiple IHDR", "Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len", "Corrupt PNG"); + s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large", "Very large image (corrupt?)"); + s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large", "Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only", "PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype", "Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype", "Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype", "Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method", "Corrupt PNG"); + filter = stbi__get8(s); if (filter) return stbi__err("bad filter method", "Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method", "Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image", "Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + if (scan == STBI__SCAN_header) return 1; + } + else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large", "Corrupt PNG"); + // if SCAN_header, have to scan to see if we have a tRNS + } + break; + } + + case STBI__PNG_TYPE('P', 'L', 'T', 'E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256 * 3) return stbi__err("invalid PLTE", "Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE", "Corrupt PNG"); + for (i = 0; i < pal_len; ++i) { + palette[i * 4 + 0] = stbi__get8(s); + palette[i * 4 + 1] = stbi__get8(s); + palette[i * 4 + 2] = stbi__get8(s); + palette[i * 4 + 3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t', 'R', 'N', 'S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT", "Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE", "Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len", "Corrupt PNG"); + pal_img_n = 4; + for (i = 0; i < c.length; ++i) + palette[i * 4 + 3] = stbi__get8(s); + } + else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha", "Corrupt PNG"); + if (c.length != (stbi__uint32)s->img_n * 2) return stbi__err("bad tRNS len", "Corrupt PNG"); + has_trans = 1; + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } + else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I', 'D', 'A', 'T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE", "Corrupt PNG"); + if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; } + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *)STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata + ioff, c.length)) return stbi__err("outofdata", "Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I', 'E', 'N', 'D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT", "Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *)stbi_zlib_decode_malloc_guesssize_headerflag((char *)z->idata, ioff, raw_len, (int *)&raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n + 1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n + 1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } + else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } + else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { +#ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); +#endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result = NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth < 8) + ri->bits_per_channel = 8; + else + ri->bits_per_channel = p->depth; + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *)result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *)result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x, y, comp, req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind(p->s); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n = 0; + if (z == 0) return -1; + if (z >= 0x10000) n += 16, z >>= 16; + if (z >= 0x00100) n += 8, z >>= 8; + if (z >= 0x00010) n += 4, z >>= 4; + if (z >= 0x00004) n += 2, z >>= 2; + if (z >= 0x00002) n += 1, z >>= 1; + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v >= 0 && v < 256); + v >>= (8 - bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int)((unsigned)v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr, mg, mb, ma, all_a; +} stbi__bmp_data; + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } + else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } + else { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } + } + else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } + else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } + else { + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + stbi__get32le(s); // discard color space + for (i = 0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *)1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr = 0, mg = 0, mb = 0, ma = 0, all_a; + stbi_uc pal[256][4]; + int psize = 0, i, j, width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int)s->img_y) > 0; + s->img_y = abs((int)s->img_y); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - 14 - 24) / 3; + } + else { + if (info.bpp < 16) + psize = (info.offset - 14 - info.hsz) >> 2; + } + + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *)stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z = 0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i = 0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - 14 - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width) & 3; + if (info.bpp == 1) { + for (j = 0; j < (int)s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i = 0; i < (int)s->img_x; ++i) { + int color = (v >> bit_offset) & 0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if ((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } + else { + for (j = 0; j < (int)s->img_y; ++j) { + for (i = 0; i < (int)s->img_x; i += 2) { + int v = stbi__get8(s), v2 = 0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i + 1 == (int)s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } + else { + int rshift = 0, gshift = 0, bshift = 0, ashift = 0, rcount = 0, gcount = 0, bcount = 0, acount = 0; + int z = 0; + int easy = 0; + stbi__skip(s, info.offset - 14 - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2 * s->img_x; + else /* bpp = 32 and pad = 0 */ width = 0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } + else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr) - 7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg) - 7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb) - 7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma) - 7; acount = stbi__bitcount(ma); + } + for (j = 0; j < (int)s->img_y; ++j) { + if (easy) { + for (i = 0; i < (int)s->img_x; ++i) { + unsigned char a; + out[z + 2] = stbi__get8(s); + out[z + 1] = stbi__get8(s); + out[z + 0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } + else { + int bpp = info.bpp; + for (i = 0; i < (int)s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32)stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i = 4 * s->img_x*s->img_y - 1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j = 0; j < (int)s->img_y >> 1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y - 1 - j)*s->img_x*target; + for (i = 0; i < (int)s->img_x*target; ++i) { + t = p1[i], p1[i] = p2[i], p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch (bits_per_pixel) { + case 8: return STBI_grey; + case 16: if (is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if (is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel / 8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if (tga_colormap_type > 1) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if (tga_colormap_type == 1) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 4); // skip image x and y origin + tga_colormap_bpp = sz; + } + else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ((tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11)) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s, 9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if (tga_w < 1) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if (tga_h < 1) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } + else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if (!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if (tga_color_type > 1) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if (tga_color_type == 1) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s, 4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd; + stbi__skip(s, 4); // skip image x and y origin + } + else { // "normal" image w/o colormap + if ((sz != 2) && (sz != 3) && (sz != 10) && (sz != 11)) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s, 9); // skip colormap specification and image x/y origin + } + if (stbi__get16le(s) < 1) goto errorEnd; // test width + if (stbi__get16le(s) < 1) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ((tga_color_type == 1) && (sz != 8) && (sz != 16)) goto errorEnd; // for colormapped images, bpp is size of an index + if ((sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32)) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255) / 31); + out[1] = (stbi_uc)((g * 255) / 31); + out[2] = (stbi_uc)((b * 255) / 31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16 = 0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = { 0 }; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + + // do a tiny bit of precessing + if (tga_image_type >= 8) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if (tga_indexed) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if (!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset); + + if (!tga_indexed && !tga_is_RLE && !tga_rgb16) { + for (i = 0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height - i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } + else { + // do I need to load a palette? + if (tga_indexed) + { + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i = 0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } + else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i = 0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if (tga_is_RLE) + { + if (RLE_count == 0) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } + else if (!RLE_repeating) + { + read_next_pixel = 1; + } + } + else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if (read_next_pixel) + { + // load however much data we did have + if (tga_indexed) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if (pal_idx >= tga_palette_len) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx + j]; + } + } + else if (tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } + else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp + j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if (tga_inverted) + { + for (j = 0; j * 2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if (tga_palette != NULL) + { + STBI_FREE(tga_palette); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i = 0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } + else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } + else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w, h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s, stbi__get32be(s)); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s)); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s)); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *)stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } + else + out = (stbi_uc *)stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out + channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } + else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } + else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *)out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } + else { + stbi_uc *p = out + channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } + else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *)out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16)stbi__get16be(s); + } + else { + stbi_uc *p = out + channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc)(stbi__get16be(s) >> 8); + } + else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i = 0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *)out + 4 * i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16)(pixel[0] * ra + inv_a); + pixel[1] = (stbi__uint16)(pixel[1] * ra + inv_a); + pixel[2] = (stbi__uint16)(pixel[2] * ra + inv_a); + } + } + } + else { + for (i = 0; i < w*h; ++i) { + unsigned char *pixel = out + 4 * i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char)(pixel[0] * ra + inv_a); + pixel[1] = (unsigned char)(pixel[1] * ra + inv_a); + pixel[2] = (unsigned char)(pixel[2] * ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *)stbi__convert_format16((stbi__uint16 *)out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s, const char *str) +{ + int i; + for (i = 0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) + return 0; + + for (i = 0; i<84; ++i) + stbi__get8(s); + + if (!stbi__pic_is4(s, "PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size, type, channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask = 0x80, i; + + for (i = 0; i<4; ++i, mask >>= 1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "PIC file too short"); + dest[i] = stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel, stbi_uc *dest, const stbi_uc *src) +{ + int mask = 0x80, i; + + for (i = 0; i<4; ++i, mask >>= 1) + if (channel&mask) + dest[i] = src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s, int width, int height, int *comp, stbi_uc *result) +{ + int act_comp = 0, num_packets = 0, y, chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets == sizeof(packets) / sizeof(packets[0])) + return stbi__errpuc("bad format", "too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format", "packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for (y = 0; ytype) { + default: + return stbi__errpuc("bad format", "packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for (x = 0; xchannel, dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left = width, i; + + while (left>0) { + stbi_uc count, value[4]; + + count = stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (pure read count)"); + + if (count > left) + count = (stbi_uc)left; + + if (!stbi__readval(s, packet->channel, value)) return 0; + + for (i = 0; ichannel, dest, value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left = width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count == 128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file", "scanline overrun"); + + if (!stbi__readval(s, packet->channel, value)) + return 0; + + for (i = 0; ichannel, dest, value); + } + else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file", "scanline overrun"); + + for (i = 0; ichannel, dest)) + return 0; + } + left -= count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s, int *px, int *py, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x, y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i = 0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file", "file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *)stbi__malloc_mad3(x, y, 4, 0); + memset(result, 0xff, x*y * 4); + + if (!stbi__pic_load_core(s, x, y, comp, result)) { + STBI_FREE(result); + result = 0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result = stbi__convert_format(result, 4, req_comp, x, y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w, h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i = 0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s, g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*)stbi__malloc(sizeof(stbi__gif)); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind(s); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc)init_code; + g->codes[init_code].suffix = (stbi_uc)init_code; + } + + // support no starting clear code + avail = clear + 2; + oldcode = -1; + + len = 0; + for (;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32)stbi__get8(s) << valid_bits; + valid_bits += 8; + } + else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } + else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s, len); + return g->out; + } + else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16)oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } + else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16)code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } + else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp, 0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + g->out = (stbi_uc *)stbi__malloc(4 * g->w * g->h); + g->background = (stbi_uc *)stbi__malloc(4 * g->w * g->h); + g->history = (stbi_uc *)stbi__malloc(g->w * g->h); + if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "tranparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to teh color that was there the previous frame. + memset(g->out, 0x00, 4 * g->w * g->h); + memset(g->background, 0x00, 4 * g->w * g->h); // state of the background (starts transparent) + memset(g->history, 0x00, g->w * g->h); // pixels that were affected previous frame + first_frame = 1; + } + else { + // second frame - how do we dispoase of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy(&g->out[pi * 4], &two_back[pi * 4], 4); + } + } + } + else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy(&g->out[pi * 4], &g->background[pi * 4], 4); + } + } + } + else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy(g->background, g->out, 4 * g->w * g->h); + } + + // clear my history; + memset(g->history, 0x00, g->w * g->h); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } + else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s, g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *)g->lpal; + } + else if (g->flags & 0x80) { + g->color_table = (stbi_uc *)g->pal; + } + else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (o == NULL) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy(&g->out[pi * 4], &g->pal[g->bgindex], 4); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } + else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } + else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *)s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *)s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + out = (stbi_uc*)STBI_REALLOC(out, layers * stride); + if (delays) { + *delays = (int*)STBI_REALLOC(*delays, sizeof(int) * layers); + } + } + else { + out = (stbi_uc*)stbi__malloc(layers * stride); + if (delays) { + *delays = (int*)stbi__malloc(layers * sizeof(int)); + } + } + memcpy(out + ((layers - 1) * stride), u, stride); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } + else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *)s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s, x, y, comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i = 0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if (!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len = 0; + char c = '\0'; + + c = (char)stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN - 1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char)stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if (input[3] != 0) { + float f1; + // Exponent + f1 = (float)ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } + else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1, c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s, buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for (;;) { + token = stbi__hdr_gettoken(s, buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s, buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int)strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int)strtol(token, NULL, 10); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *)stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if (width < 8 || width >= 32768) { + // Read flat data + for (j = 0; j < height; ++j) { + for (i = 0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } + else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc)c1; + rgbe[1] = (stbi_uc)c2; + rgbe[2] = (stbi_uc)len; + rgbe[3] = (stbi_uc)stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *)stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } + else { + // Dump + if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i = 0; i < width; ++i) + stbi__hdr_convert(hdr_data + (j*width + i)*req_comp, scanline + i * 4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind(s); + return 0; + } + + for (;;) { + token = stbi__hdr_gettoken(s, buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind(s); + return 0; + } + token = stbi__hdr_gettoken(s, buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind(s); + return 0; + } + token += 3; + *y = (int)strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind(s); + return 0; + } + token += 3; + *x = (int)strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + stbi__rewind(s); + if (p == NULL) + return 0; + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) *comp = info.ma ? 4 : 3; + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind(s); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind(s); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind(s); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind(s); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind(s); + return 0; + } + (void)stbi__get32be(s); + (void)stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind(s); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp = 0, num_packets = 0, chained, dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s, "\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind(s); + return 0; + } + if ((*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets == sizeof(packets) / sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind(s); + return 0; + } + if (packet->size != 8) { + stbi__rewind(s); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) +// Does not support 16-bit-per-channel + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char)stbi__get8(s); + t = (char)stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n)) + return 0; + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *)stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + stbi__getn(s, out, s->img_n * s->img_x * s->img_y); + + if (req_comp && req_comp != s->img_n) { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char)stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r') + *c = (char)stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value * 10 + (*c - '0'); + *c = (char)stbi__get8(s); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char)stbi__get8(s); + t = (char)stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char)stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + + if (maxv > 255) + return stbi__err("max value > 255", "PPM image not 8-bit"); + else + return 1; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ +#ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; +#endif + +#ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; +#endif + + // test tga last because it's a crappy test! +#ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; +#endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ +#ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; +#endif + +#ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; +#endif + + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s, x, y, comp); + fseek(f, pos, SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f, pos, SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__info_main(&s, x, y, comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)c, user); + return stbi__info_main(&s, x, y, comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s, buffer, len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* +revision history: +2.19 (2018-02-11) fix warning +2.18 (2018-01-30) fix warnings +2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug +1-bit BMP +*_is_16_bit api +avoid warnings +2.16 (2017-07-23) all functions have 16-bit variants; +STBI_NO_STDIO works again; +compilation fixes; +fix rounding in unpremultiply; +optimize vertical flip; +disable raw_len validation; +documentation fixes +2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; +warning fixes; disable run-time SSE detection on gcc; +uniform handling of optional "return" values; +thread-safe initialization of zlib tables +2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs +2.13 (2016-11-29) add 16-bit API, only supported for PNG right now +2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes +2.11 (2016-04-02) allocate large structures on the stack +remove white matting for transparent PSD +fix reported channel count for PNG & BMP +re-enable SSE2 in non-gcc 64-bit +support RGB-formatted JPEG +read 16-bit PNGs (only as 8-bit) +2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED +2.09 (2016-01-16) allow comments in PNM files +16-bit-per-pixel TGA (not bit-per-component) +info() for TGA could break due to .hdr handling +info() for BMP to shares code instead of sloppy parse +can use STBI_REALLOC_SIZED if allocator doesn't support realloc +code cleanup +2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA +2.07 (2015-09-13) fix compiler warnings +partial animated GIF support +limited 16-bpc PSD support +#ifdef unused functions +bug with < 92 byte PIC,PNM,HDR,TGA +2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value +2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning +2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit +2.03 (2015-04-12) extra corruption checking (mmozeiko) +stbi_set_flip_vertically_on_load (nguillemot) +fix NEON support; fix mingw support +2.02 (2015-01-19) fix incorrect assert, fix warning +2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 +2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG +2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) +progressive JPEG (stb) +PGM/PPM support (Ken Miller) +STBI_MALLOC,STBI_REALLOC,STBI_FREE +GIF bugfix -- seemingly never worked +STBI_NO_*, STBI_ONLY_* +1.48 (2014-12-14) fix incorrectly-named assert() +1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) +optimize PNG (ryg) +fix bug in interlaced PNG with user-specified channel count (stb) +1.46 (2014-08-26) +fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG +1.45 (2014-08-16) +fix MSVC-ARM internal compiler error by wrapping malloc +1.44 (2014-08-07) +various warning fixes from Ronny Chevalier +1.43 (2014-07-15) +fix MSVC-only compiler problem in code changed in 1.42 +1.42 (2014-07-09) +don't define _CRT_SECURE_NO_WARNINGS (affects user code) +fixes to stbi__cleanup_jpeg path +added STBI_ASSERT to avoid requiring assert.h +1.41 (2014-06-25) +fix search&replace from 1.36 that messed up comments/error messages +1.40 (2014-06-22) +fix gcc struct-initialization warning +1.39 (2014-06-15) +fix to TGA optimization when req_comp != number of components in TGA; +fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) +add support for BMP version 5 (more ignored fields) +1.38 (2014-06-06) +suppress MSVC warnings on integer casts truncating values +fix accidental rename of 'skip' field of I/O +1.37 (2014-06-04) +remove duplicate typedef +1.36 (2014-06-03) +convert to header file single-file library +if de-iphone isn't set, load iphone images color-swapped instead of returning NULL +1.35 (2014-05-27) +various warnings +fix broken STBI_SIMD path +fix bug where stbi_load_from_file no longer left file pointer in correct place +fix broken non-easy path for 32-bit BMP (possibly never used) +TGA optimization by Arseny Kapoulkine +1.34 (unknown) +use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case +1.33 (2011-07-14) +make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements +1.32 (2011-07-13) +support for "info" function for all supported filetypes (SpartanJ) +1.31 (2011-06-20) +a few more leak fixes, bug in PNG handling (SpartanJ) +1.30 (2011-06-11) +added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) +removed deprecated format-specific test/load functions +removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway +error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) +fix inefficiency in decoding 32-bit BMP (David Woo) +1.29 (2010-08-16) +various warning fixes from Aurelien Pocheville +1.28 (2010-08-01) +fix bug in GIF palette transparency (SpartanJ) +1.27 (2010-08-01) +cast-to-stbi_uc to fix warnings +1.26 (2010-07-24) +fix bug in file buffering for PNG reported by SpartanJ +1.25 (2010-07-17) +refix trans_data warning (Won Chun) +1.24 (2010-07-12) +perf improvements reading from files on platforms with lock-heavy fgetc() +minor perf improvements for jpeg +deprecated type-specific functions so we'll get feedback if they're needed +attempt to fix trans_data warning (Won Chun) +1.23 fixed bug in iPhone support +1.22 (2010-07-10) +removed image *writing* support +stbi_info support from Jetro Lauha +GIF support from Jean-Marc Lienher +iPhone PNG-extensions from James Brown +warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) +1.21 fix use of 'stbi_uc' in header (reported by jon blow) +1.20 added support for Softimage PIC, by Tom Seddon +1.19 bug in interlaced PNG corruption check (found by ryg) +1.18 (2008-08-02) +fix a threading bug (local mutable static) +1.17 support interlaced PNG +1.16 major bugfix - stbi__convert_format converted one too many pixels +1.15 initialize some fields for thread safety +1.14 fix threadsafe conversion bug +header-file-only version (#define STBI_HEADER_FILE_ONLY before including) +1.13 threadsafe +1.12 const qualifiers in the API +1.11 Support installable IDCT, colorspace conversion routines +1.10 Fixes for 64-bit (don't use "unsigned long") +optimized upsampling by Fabian "ryg" Giesen +1.09 Fix format-conversion for PSD code (bad global variables!) +1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz +1.07 attempt to fix C++ warning/errors again +1.06 attempt to fix C++ warning/errors again +1.05 fix TGA loading to return correct *comp and use good luminance calc +1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free +1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR +1.02 support for (subset of) HDR files, float interface for preferred access to them +1.01 fix bug: possible bug in handling right-side up bmps... not sure +fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all +1.00 interface to zlib that skips zlib header +0.99 correct handling of alpha in palette +0.98 TGA loader by lonesock; dynamically add loaders (untested) +0.97 jpeg errors on too large a file; also catch another malloc failure +0.96 fix detection of invalid v value - particleman@mollyrocket forum +0.95 during header scan, seek to markers in case of padding +0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same +0.93 handle jpegtran output; verbose errors +0.92 read 4,8,16,24,32-bit BMP files of several formats +0.91 output 24-bit Windows 3.0 BMP files +0.90 fix a few more warnings; bump version number to approach 1.0 +0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd +0.60 fix compiling as c++ +0.59 fix warnings: merge Dave Moore's -Wall fixes +0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian +0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available +0.56 fix bug: zlib uncompressed mode len vs. nlen +0.55 fix bug: restart_interval not initialized to 0 +0.54 allow NULL for 'int *comp' +0.53 fix bug in png 3->4; speedup png decoding +0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments +0.51 obey req_comp requests, 1-component jpegs return as 1-component, +on 'test' only check type, not whether we support this variant +0.50 (2006-11-19) +first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ \ No newline at end of file diff --git a/codemp/rd-rend2/tr_allocator.cpp b/codemp/rd-rend2/tr_allocator.cpp new file mode 100644 index 0000000000..4da0228c8c --- /dev/null +++ b/codemp/rd-rend2/tr_allocator.cpp @@ -0,0 +1,86 @@ +#include +#include "tr_allocator.h" +#include "tr_local.h" + +Allocator::Allocator( void *memory, size_t memorySize, size_t alignment ) + : alignment(alignment) + , ownMemory(false) + , unalignedBase(memory) + , alignedBase(PADP(unalignedBase, alignment)) + , mark(alignedBase) + , end((char *)unalignedBase + memorySize) +{ + assert(unalignedBase); + assert(memorySize); + assert(alignment); +} + +Allocator::Allocator( size_t memorySize, size_t alignment ) + : alignment(alignment) + , ownMemory(true) +#if defined(GLSL_BUILDTOOL) + , unalignedBase(malloc(memorySize)) +#else + , unalignedBase(Z_Malloc(memorySize, TAG_SHADERTEXT)) +#endif + , alignedBase(PADP(unalignedBase, alignment)) + , mark(alignedBase) + , end((char *)unalignedBase + memorySize) +{ + assert(unalignedBase); + assert(memorySize); + assert(alignment); +} + +Allocator::~Allocator() +{ + if ( ownMemory ) + { +#if defined(GLSL_BUILDTOOL) + free(unalignedBase); +#else + Z_Free(unalignedBase); +#endif + } +} + +void *Allocator::Base() const +{ + return alignedBase; +} + +size_t Allocator::GetSize() const +{ + return (size_t)((char *)end - (char *)alignedBase); +} + +void *Allocator::Alloc( size_t allocSize ) +{ + if ( (size_t)((char *)end - (char *)mark) < allocSize ) + { + assert(!"Allocator is out of memory"); + return nullptr; + } + + void *result = mark; + size_t alignedSize = PAD(allocSize, alignment); + + mark = (char *)mark + alignedSize; + + return result; +} + +void *Allocator::Mark() const +{ + return mark; +} + +void Allocator::Reset() +{ + mark = alignedBase; +} + +void Allocator::ResetTo( void *m ) +{ + mark = m; +} diff --git a/codemp/rd-rend2/tr_allocator.h b/codemp/rd-rend2/tr_allocator.h new file mode 100644 index 0000000000..1b891af62c --- /dev/null +++ b/codemp/rd-rend2/tr_allocator.h @@ -0,0 +1,64 @@ +/* +=========================================================================== +Copyright (C) 2013 - 2016, OpenJK contributors + +This file is part of the OpenJK source code. + +OpenJK is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . +=========================================================================== +*/ + +#pragma once + +class Allocator +{ +public: + Allocator( void *memory, size_t memorySize, size_t alignment = 16 ); + Allocator( size_t memorySize, size_t alignment = 16 ); + ~Allocator(); + + Allocator( const Allocator& ) = delete; + Allocator& operator=( const Allocator& ) = delete; + + size_t GetSize() const; + void *Base() const; + void *Alloc( size_t allocSize ); + void *Mark() const; + void Reset(); + void ResetTo( void *mark ); + +private: + size_t alignment; + bool ownMemory; + void *unalignedBase; + void *alignedBase; + void *mark; + void *end; +}; + +template +T *ojkAllocArray( Allocator& allocator, size_t count ) +{ + return static_cast(allocator.Alloc(sizeof(T) * count)); +} + +inline char *ojkAllocString( Allocator& allocator, size_t stringLength ) +{ + return ojkAllocArray(allocator, stringLength + 1); +} + +template +T *ojkAlloc( Allocator& allocator ) +{ + return ojkAllocArray(allocator, 1); +} diff --git a/codemp/rd-rend2/tr_animation.cpp b/codemp/rd-rend2/tr_animation.cpp new file mode 100644 index 0000000000..b1ca5e95f8 --- /dev/null +++ b/codemp/rd-rend2/tr_animation.cpp @@ -0,0 +1,420 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +#include "tr_local.h" + +/* + +All bones should be an identity orientation to display the mesh exactly +as it is specified. + +For all other frames, the bones represent the transformation from the +orientation of the bone in the base frame to the orientation in this +frame. + +*/ + + +// copied and adapted from tr_mesh.c + +/* +============= +R_MDRCullModel +============= +*/ + +static int R_MDRCullModel( mdrHeader_t *header, trRefEntity_t *ent ) { + vec3_t bounds[2]; + mdrFrame_t *oldFrame, *newFrame; + int i, frameSize; + + frameSize = (size_t)( &((mdrFrame_t *)0)->bones[ header->numBones ] ); + + // compute frame pointers + newFrame = ( mdrFrame_t * ) ( ( byte * ) header + header->ofsFrames + frameSize * ent->e.frame); + oldFrame = ( mdrFrame_t * ) ( ( byte * ) header + header->ofsFrames + frameSize * ent->e.oldframe); + + // cull bounding sphere ONLY if this is not an upscaled entity + if ( !ent->e.nonNormalizedAxes ) + { + if ( ent->e.frame == ent->e.oldframe ) + { + switch ( R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ) ) + { + // Ummm... yeah yeah I know we don't really have an md3 here.. but we pretend + // we do. After all, the purpose of mdrs are not that different, are they? + + case CULL_OUT: + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; + + case CULL_IN: + tr.pc.c_sphere_cull_md3_in++; + return CULL_IN; + + case CULL_CLIP: + tr.pc.c_sphere_cull_md3_clip++; + break; + } + } + else + { + int sphereCull, sphereCullB; + + sphereCull = R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ); + if ( newFrame == oldFrame ) { + sphereCullB = sphereCull; + } else { + sphereCullB = R_CullLocalPointAndRadius( oldFrame->localOrigin, oldFrame->radius ); + } + + if ( sphereCull == sphereCullB ) + { + if ( sphereCull == CULL_OUT ) + { + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; + } + else if ( sphereCull == CULL_IN ) + { + tr.pc.c_sphere_cull_md3_in++; + return CULL_IN; + } + else + { + tr.pc.c_sphere_cull_md3_clip++; + } + } + } + } + + // calculate a bounding box in the current coordinate system + for (i = 0 ; i < 3 ; i++) { + bounds[0][i] = oldFrame->bounds[0][i] < newFrame->bounds[0][i] ? oldFrame->bounds[0][i] : newFrame->bounds[0][i]; + bounds[1][i] = oldFrame->bounds[1][i] > newFrame->bounds[1][i] ? oldFrame->bounds[1][i] : newFrame->bounds[1][i]; + } + + switch ( R_CullLocalBox( bounds ) ) + { + case CULL_IN: + tr.pc.c_box_cull_md3_in++; + return CULL_IN; + case CULL_CLIP: + tr.pc.c_box_cull_md3_clip++; + return CULL_CLIP; + case CULL_OUT: + default: + tr.pc.c_box_cull_md3_out++; + return CULL_OUT; + } +} + +/* +================= +R_MDRComputeFogNum + +================= +*/ + +int R_MDRComputeFogNum( mdrHeader_t *header, trRefEntity_t *ent ) { + int i, j; + fog_t *fog; + mdrFrame_t *mdrFrame; + vec3_t localOrigin; + int frameSize; + + if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + return 0; + } + + frameSize = (size_t)( &((mdrFrame_t *)0)->bones[ header->numBones ] ); + + // FIXME: non-normalized axis issues + mdrFrame = ( mdrFrame_t * ) ( ( byte * ) header + header->ofsFrames + frameSize * ent->e.frame); + VectorAdd( ent->e.origin, mdrFrame->localOrigin, localOrigin ); + for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + fog = &tr.world->fogs[i]; + for ( j = 0 ; j < 3 ; j++ ) { + if ( localOrigin[j] - mdrFrame->radius >= fog->bounds[1][j] ) { + break; + } + if ( localOrigin[j] + mdrFrame->radius <= fog->bounds[0][j] ) { + break; + } + } + if ( j == 3 ) { + return i; + } + } + + return 0; +} + + +/* +============== +R_MDRAddAnimSurfaces +============== +*/ + +// much stuff in there is just copied from R_AddMd3Surfaces in tr_mesh.c + +void R_MDRAddAnimSurfaces( trRefEntity_t *ent, int entityNum ) { + mdrHeader_t *header; + mdrSurface_t *surface; + mdrLOD_t *lod; + shader_t *shader; + skin_t *skin; + int i, j; + int lodnum = 0; + int fogNum = 0; + int cull; + int cubemapIndex; + qboolean personalModel; + + header = (mdrHeader_t *)tr.currentModel->data.mdr; + + personalModel = (qboolean)( + (ent->e.renderfx & RF_THIRD_PERSON) && + !(tr.viewParms.isPortal || + (tr.viewParms.flags & VPF_DEPTHSHADOW))); + + if ( ent->e.renderfx & RF_WRAP_FRAMES ) + { + ent->e.frame %= header->numFrames; + ent->e.oldframe %= header->numFrames; + } + + // + // Validate the frames so there is no chance of a crash. + // This will write directly into the entity structure, so + // when the surfaces are rendered, they don't need to be + // range checked again. + // + if ((ent->e.frame >= header->numFrames) + || (ent->e.frame < 0) + || (ent->e.oldframe >= header->numFrames) + || (ent->e.oldframe < 0) ) + { + ri.Printf( PRINT_DEVELOPER, "R_MDRAddAnimSurfaces: no such frame %d to %d for '%s'\n", + ent->e.oldframe, ent->e.frame, tr.currentModel->name ); + ent->e.frame = 0; + ent->e.oldframe = 0; + } + + // + // cull the entire model if merged bounding box of both frames + // is outside the view frustum. + // + cull = R_MDRCullModel (header, ent); + if ( cull == CULL_OUT ) { + return; + } + + // figure out the current LOD of the model we're rendering, and set the lod pointer respectively. + lodnum = R_ComputeLOD(ent); + // check whether this model has as that many LODs at all. If not, try the closest thing we got. + if(header->numLODs <= 0) + return; + if(header->numLODs <= lodnum) + lodnum = header->numLODs - 1; + + lod = (mdrLOD_t *)( (byte *)header + header->ofsLODs); + for(i = 0; i < lodnum; i++) + { + lod = (mdrLOD_t *) ((byte *) lod + lod->ofsEnd); + } + + // fogNum? + fogNum = R_MDRComputeFogNum( header, ent ); + + cubemapIndex = R_CubemapForPoint(ent->e.origin); + + surface = (mdrSurface_t *)( (byte *)lod + lod->ofsSurfaces ); + + for ( i = 0 ; i < lod->numSurfaces ; i++ ) + { + + if(ent->e.customShader) + shader = R_GetShaderByHandle(ent->e.customShader); + else if(ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) + { + skin = R_GetSkinByHandle(ent->e.customSkin); + shader = tr.defaultShader; + + for(j = 0; j < skin->numSurfaces; j++) + { + if (!strcmp(skin->surfaces[j]->name, surface->name)) + { + shader = (shader_t *)skin->surfaces[j]->shader; + break; + } + } + } + else if(surface->shaderIndex > 0) + shader = R_GetShaderByHandle( surface->shaderIndex ); + else + shader = tr.defaultShader; + + // we will add shadows even if the main object isn't visible in the view + + // stencil shadows can't do personal models unless I polyhedron clip + if ( !personalModel + && r_shadows->integer == 2 + && fogNum == 0 + && !(ent->e.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) ) + && shader->sort == SS_OPAQUE ) + { + R_AddDrawSurf( (surfaceType_t *)surface, entityNum, tr.shadowShader, 0, qfalse, R_IsPostRenderEntity(ent), 0 ); + } + + // projection shadows work fine with personal models + if ( r_shadows->integer == 3 + && fogNum == 0 + && (ent->e.renderfx & RF_SHADOW_PLANE ) + && shader->sort == SS_OPAQUE ) + { + R_AddDrawSurf( (surfaceType_t *)surface, entityNum, tr.projectionShadowShader, 0, qfalse, R_IsPostRenderEntity(ent), 0 ); + } + + if (!personalModel) + R_AddDrawSurf( (surfaceType_t *)surface, entityNum, shader, fogNum, qfalse, R_IsPostRenderEntity(ent), cubemapIndex ); + + surface = (mdrSurface_t *)( (byte *)surface + surface->ofsEnd ); + } +} + +/* +============== +RB_MDRSurfaceAnim +============== +*/ +void RB_MDRSurfaceAnim( mdrSurface_t *surface ) +{ + int i, j, k; + float frontlerp, backlerp; + int *triangles; + int indexes; + int baseIndex, baseVertex; + int numVerts; + mdrVertex_t *v; + mdrHeader_t *header; + mdrFrame_t *frame; + mdrFrame_t *oldFrame; + mdrBone_t bones[MDR_MAX_BONES], *bonePtr, *bone; + + int frameSize; + + // don't lerp if lerping off, or this is the only frame, or the last frame... + // + if (backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame) + { + backlerp = 0; // if backlerp is 0, lerping is off and frontlerp is never used + frontlerp = 1; + } + else + { + backlerp = backEnd.currentEntity->e.backlerp; + frontlerp = 1.0f - backlerp; + } + + header = (mdrHeader_t *)((byte *)surface + surface->ofsHeader); + + frameSize = (size_t)( &((mdrFrame_t *)0)->bones[ header->numBones ] ); + + frame = (mdrFrame_t *)((byte *)header + header->ofsFrames + + backEnd.currentEntity->e.frame * frameSize ); + oldFrame = (mdrFrame_t *)((byte *)header + header->ofsFrames + + backEnd.currentEntity->e.oldframe * frameSize ); + + RB_CheckOverflow( surface->numVerts, surface->numTriangles ); + + triangles = (int *) ((byte *)surface + surface->ofsTriangles); + indexes = surface->numTriangles * 3; + baseIndex = tess.numIndexes; + baseVertex = tess.numVertexes; + + // Set up all triangles. + for (j = 0 ; j < indexes ; j++) + { + tess.indexes[baseIndex + j] = baseVertex + triangles[j]; + } + tess.numIndexes += indexes; + + // + // lerp all the needed bones + // + if ( !backlerp ) + { + // no lerping needed + bonePtr = frame->bones; + } + else + { + bonePtr = bones; + + for ( i = 0 ; i < header->numBones*12 ; i++ ) + { + ((float *)bonePtr)[i] = frontlerp * ((float *)frame->bones)[i] + backlerp * ((float *)oldFrame->bones)[i]; + } + } + + // + // deform the vertexes by the lerped bones + // + numVerts = surface->numVerts; + v = (mdrVertex_t *) ((byte *)surface + surface->ofsVerts); + for ( j = 0; j < numVerts; j++ ) + { + vec3_t tempVert, tempNormal; + mdrWeight_t *w; + + VectorClear( tempVert ); + VectorClear( tempNormal ); + w = v->weights; + for ( k = 0 ; k < v->numWeights ; k++, w++ ) + { + bone = bonePtr + w->boneIndex; + + tempVert[0] += w->boneWeight * ( DotProduct( bone->matrix[0], w->offset ) + bone->matrix[0][3] ); + tempVert[1] += w->boneWeight * ( DotProduct( bone->matrix[1], w->offset ) + bone->matrix[1][3] ); + tempVert[2] += w->boneWeight * ( DotProduct( bone->matrix[2], w->offset ) + bone->matrix[2][3] ); + + tempNormal[0] += w->boneWeight * DotProduct( bone->matrix[0], v->normal ); + tempNormal[1] += w->boneWeight * DotProduct( bone->matrix[1], v->normal ); + tempNormal[2] += w->boneWeight * DotProduct( bone->matrix[2], v->normal ); + } + + tess.xyz[baseVertex + j][0] = tempVert[0]; + tess.xyz[baseVertex + j][1] = tempVert[1]; + tess.xyz[baseVertex + j][2] = tempVert[2]; + + tess.normal[baseVertex + j] = R_VboPackNormal(tempNormal); + + tess.texCoords[baseVertex + j][0][0] = v->texCoords[0]; + tess.texCoords[baseVertex + j][0][1] = v->texCoords[1]; + + v = (mdrVertex_t *)&v->weights[v->numWeights]; + } + + tess.numVertexes += surface->numVerts; +} diff --git a/codemp/rd-rend2/tr_backend.cpp b/codemp/rd-rend2/tr_backend.cpp new file mode 100644 index 0000000000..768c2c4204 --- /dev/null +++ b/codemp/rd-rend2/tr_backend.cpp @@ -0,0 +1,3113 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +#include "tr_local.h" +#include "tr_allocator.h" +#include "glext.h" +#include + +backEndData_t *backEndData; +backEndState_t backEnd; + + +static float s_flipMatrix[16] = { + // convert from our coordinate system (looking down X) + // to OpenGL's coordinate system (looking down -Z) + 0, 0, -1, 0, + -1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 0, 1 +}; + + +/* +** GL_Bind +*/ +void GL_Bind( image_t *image ) { + int texnum; + + if ( !image ) { + ri.Printf( PRINT_WARNING, "GL_Bind: NULL image\n" ); + texnum = tr.defaultImage->texnum; + } else { + texnum = image->texnum; + } + + if ( r_nobind->integer && tr.dlightImage ) { // performance evaluation option + texnum = tr.dlightImage->texnum; + } + + if ( glState.currenttextures[glState.currenttmu] != texnum ) { + if ( image ) { + image->frameUsed = tr.frameCount; + } + glState.currenttextures[glState.currenttmu] = texnum; + if (image && image->flags & IMGFLAG_CUBEMAP) + qglBindTexture( GL_TEXTURE_CUBE_MAP, texnum ); + else if (image->flags & IMGFLAG_3D) + qglBindTexture(GL_TEXTURE_3D, texnum); + else if (image->flags & IMGFLAG_2D_ARRAY) + qglBindTexture(GL_TEXTURE_2D_ARRAY, texnum); + else + qglBindTexture( GL_TEXTURE_2D, texnum ); + } +} + +/* +** GL_SelectTexture +*/ +void GL_SelectTexture( int unit ) +{ + if ( glState.currenttmu == unit ) + { + return; + } + + if (!(unit >= 0 && unit <= 31)) + ri.Error( ERR_DROP, "GL_SelectTexture: unit = %i", unit ); + + qglActiveTexture( GL_TEXTURE0 + unit ); + + glState.currenttmu = unit; +} + +/* +** GL_BindToTMU +*/ +void GL_BindToTMU( image_t *image, int tmu ) +{ + int texnum; + int oldtmu = glState.currenttmu; + + if (!image) + texnum = 0; + else + texnum = image->texnum; + + if ( glState.currenttextures[tmu] != texnum ) { + GL_SelectTexture( tmu ); + if (image) + image->frameUsed = tr.frameCount; + glState.currenttextures[tmu] = texnum; + + if (image && (image->flags & IMGFLAG_CUBEMAP)) + qglBindTexture( GL_TEXTURE_CUBE_MAP, texnum ); + else if (image && (image->flags & IMGFLAG_3D)) + qglBindTexture(GL_TEXTURE_3D, texnum); + else if (image && (image->flags & IMGFLAG_2D_ARRAY)) + qglBindTexture(GL_TEXTURE_2D_ARRAY, texnum); + else + qglBindTexture( GL_TEXTURE_2D, texnum ); + } +} + +/* +** GL_Cull +*/ +void GL_Cull( int cullType ) { + if ( glState.faceCulling == cullType ) { + return; + } + + if ( backEnd.projection2D ) + cullType = CT_TWO_SIDED; + + if ( cullType == CT_TWO_SIDED ) + { + if ( glState.faceCulling != CT_TWO_SIDED ) + qglDisable( GL_CULL_FACE ); + } + else + { + qboolean cullFront = (qboolean)(cullType == CT_FRONT_SIDED); + + if ( glState.faceCulling == CT_TWO_SIDED ) + qglEnable( GL_CULL_FACE ); + + qglCullFace( cullFront ? GL_FRONT : GL_BACK); + } + + glState.faceCulling = cullType; +} + +void GL_DepthRange( float min, float max ) +{ + if ( glState.minDepth == min && glState.maxDepth == max ) + { + return; + } + + qglDepthRange(min, max); + glState.minDepth = min; + glState.maxDepth = max; +} + +/* +** GL_State +** +** This routine is responsible for setting the most commonly changed state +** in Q3. +*/ +void GL_State( uint32_t stateBits ) +{ + uint32_t diff = stateBits ^ glState.glStateBits; + + if ( !diff ) + { + return; + } + + // + // check depthFunc bits + // + if ( diff & GLS_DEPTHFUNC_BITS ) + { + if ( stateBits & GLS_DEPTHFUNC_EQUAL ) + { + qglDepthFunc( GL_EQUAL ); + } + else if ( stateBits & GLS_DEPTHFUNC_GREATER ) + { + qglDepthFunc( GL_GREATER ); + } + else if ( stateBits & GLS_DEPTHFUNC_LESS ) + { + qglDepthFunc( GL_LESS ); + } + else + { + qglDepthFunc( GL_LEQUAL ); + } + } + + // + // check blend bits + // + if ( diff & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) + { + GLenum srcFactor = GL_ONE, dstFactor = GL_ONE; + + if ( stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) + { + switch ( stateBits & GLS_SRCBLEND_BITS ) + { + case GLS_SRCBLEND_ZERO: + srcFactor = GL_ZERO; + break; + case GLS_SRCBLEND_ONE: + srcFactor = GL_ONE; + break; + case GLS_SRCBLEND_DST_COLOR: + srcFactor = GL_DST_COLOR; + break; + case GLS_SRCBLEND_ONE_MINUS_DST_COLOR: + srcFactor = GL_ONE_MINUS_DST_COLOR; + break; + case GLS_SRCBLEND_SRC_ALPHA: + srcFactor = GL_SRC_ALPHA; + break; + case GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA: + srcFactor = GL_ONE_MINUS_SRC_ALPHA; + break; + case GLS_SRCBLEND_DST_ALPHA: + srcFactor = GL_DST_ALPHA; + break; + case GLS_SRCBLEND_ONE_MINUS_DST_ALPHA: + srcFactor = GL_ONE_MINUS_DST_ALPHA; + break; + case GLS_SRCBLEND_ALPHA_SATURATE: + srcFactor = GL_SRC_ALPHA_SATURATE; + break; + default: + ri.Error( ERR_DROP, "GL_State: invalid src blend state bits" ); + break; + } + + switch ( stateBits & GLS_DSTBLEND_BITS ) + { + case GLS_DSTBLEND_ZERO: + dstFactor = GL_ZERO; + break; + case GLS_DSTBLEND_ONE: + dstFactor = GL_ONE; + break; + case GLS_DSTBLEND_SRC_COLOR: + dstFactor = GL_SRC_COLOR; + break; + case GLS_DSTBLEND_ONE_MINUS_SRC_COLOR: + dstFactor = GL_ONE_MINUS_SRC_COLOR; + break; + case GLS_DSTBLEND_SRC_ALPHA: + dstFactor = GL_SRC_ALPHA; + break; + case GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA: + dstFactor = GL_ONE_MINUS_SRC_ALPHA; + break; + case GLS_DSTBLEND_DST_ALPHA: + dstFactor = GL_DST_ALPHA; + break; + case GLS_DSTBLEND_ONE_MINUS_DST_ALPHA: + dstFactor = GL_ONE_MINUS_DST_ALPHA; + break; + default: + ri.Error( ERR_DROP, "GL_State: invalid dst blend state bits" ); + break; + } + + qglEnable( GL_BLEND ); + qglBlendFunc( srcFactor, dstFactor ); + } + else + { + qglDisable( GL_BLEND ); + } + } + + // + // check colormask + // + if ( diff & GLS_COLORMASK_BITS ) + { + if ( stateBits & GLS_COLORMASK_BITS ) + { + qglColorMask( GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE ); + } + else + { + qglColorMask( GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE ); + } + } + + // + // check stenciltest + // + if (diff & GLS_STENCILTEST_ENABLE) + { + if (stateBits & GLS_STENCILTEST_ENABLE) + { + qglEnable(GL_STENCIL_TEST); + } + else + { + qglDisable(GL_STENCIL_TEST); + } + } + + // + // check depthmask + // + if ( diff & GLS_DEPTHMASK_TRUE ) + { + if ( stateBits & GLS_DEPTHMASK_TRUE ) + { + qglDepthMask( GL_TRUE ); + } + else + { + qglDepthMask( GL_FALSE ); + } + } + + // + // fill/line mode + // + if ( diff & GLS_POLYMODE_LINE ) + { + if ( stateBits & GLS_POLYMODE_LINE ) + { + qglPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); + } + else + { + qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); + } + } + + // + // depthtest + // + if ( diff & GLS_DEPTHTEST_DISABLE ) + { + if ( stateBits & GLS_DEPTHTEST_DISABLE ) + { + qglDisable( GL_DEPTH_TEST ); + } + else + { + qglEnable( GL_DEPTH_TEST ); + } + } + + if ( diff & GLS_POLYGON_OFFSET_FILL ) + { + if ( stateBits & GLS_POLYGON_OFFSET_FILL ) + { + qglEnable( GL_POLYGON_OFFSET_FILL ); + } + else + { + qglDisable( GL_POLYGON_OFFSET_FILL ); + } + } + + glState.glStateBits = stateBits; +} + +void GL_VertexAttribPointers( + size_t numAttributes, + vertexAttribute_t *attributes ) +{ + assert(attributes != nullptr || numAttributes == 0); + + uint32_t newAttribs = 0; + for ( int i = 0; i < numAttributes; i++ ) + { + vertexAttribute_t& attrib = attributes[i]; + vertexAttribute_t& currentAttrib = glState.currentVaoAttribs[attrib.index]; + + newAttribs |= (1 << attrib.index); + if (memcmp(¤tAttrib, &attrib, sizeof(currentAttrib)) == 0) + { + // No change + continue; + } + + R_BindVBO(attrib.vbo); + if ( attrib.integerAttribute ) + { + qglVertexAttribIPointer(attrib.index, + attrib.numComponents, + attrib.type, + attrib.stride, + BUFFER_OFFSET(attrib.offset)); + } + else + { + qglVertexAttribPointer(attrib.index, + attrib.numComponents, + attrib.type, + attrib.normalize, + attrib.stride, + BUFFER_OFFSET(attrib.offset)); + } + + if (currentAttrib.stepRate != attrib.stepRate) + qglVertexAttribDivisor(attrib.index, attrib.stepRate); + + currentAttrib = attrib; + } + + uint32_t diff = newAttribs ^ glState.vertexAttribsState; + if ( diff ) + { + for ( int i = 0, j = 1; i < ATTR_INDEX_MAX; i++, j <<= 1 ) + { + // FIXME: Use BitScanForward? + if (diff & j) + { + if(newAttribs & j) + qglEnableVertexAttribArray(i); + else + qglDisableVertexAttribArray(i); + } + } + + glState.vertexAttribsState = newAttribs; + } +} + +void GL_DrawIndexed( + GLenum primitiveType, + int numIndices, + GLenum indexType, + int offset, + int numInstances, + int baseVertex) +{ + assert(numInstances > 0); + qglDrawElementsInstancedBaseVertex( + primitiveType, + numIndices, + indexType, + BUFFER_OFFSET(offset), + numInstances, + baseVertex); +} + +void GL_MultiDrawIndexed( + GLenum primitiveType, + int *numIndices, + glIndex_t **offsets, + int numDraws) +{ + assert(numDraws > 0); + qglMultiDrawElements( + primitiveType, + numIndices, + GL_INDEX_TYPE, + (const GLvoid **)offsets, + numDraws); +} + +void GL_Draw( GLenum primitiveType, int firstVertex, int numVertices, int numInstances ) +{ + assert(numInstances > 0); + qglDrawArraysInstanced(primitiveType, firstVertex, numVertices, numInstances); +} + +void GL_SetProjectionMatrix(matrix_t matrix) +{ + Matrix16Copy(matrix, glState.projection); + Matrix16Multiply(glState.projection, glState.modelview, glState.modelviewProjection); +} + + +void GL_SetModelviewMatrix(matrix_t matrix) +{ + Matrix16Copy(matrix, glState.modelview); + Matrix16Multiply(glState.projection, glState.modelview, glState.modelviewProjection); +} + + +/* +================ +RB_Hyperspace + +A player has predicted a teleport, but hasn't arrived yet +================ +*/ +static void RB_Hyperspace( void ) { + float c = ( backEnd.refdef.time & 255 ) / 255.0f; + vec4_t v = { c, c, c, 1.0f }; + qglClearBufferfv( GL_COLOR, 0, v ); +} + + +static void SetViewportAndScissor( void ) { + GL_SetProjectionMatrix( backEnd.viewParms.projectionMatrix ); + + // set the window clipping + qglViewport( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, + backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + + if ( !backEnd.viewParms.scissorX && !backEnd.viewParms.scissorY && + !backEnd.viewParms.scissorWidth && !backEnd.viewParms.scissorHeight ) + { + qglScissor( backEnd.viewParms.viewportX, backEnd.viewParms.viewportY, + backEnd.viewParms.viewportWidth, backEnd.viewParms.viewportHeight ); + } + else + { + qglScissor( backEnd.viewParms.scissorX, backEnd.viewParms.scissorY, + backEnd.viewParms.scissorWidth, backEnd.viewParms.scissorHeight ); + } +} + +/* +================= +RB_BeginDrawingView + +Any mirrored or portaled views have already been drawn, so prepare +to actually render the visible surfaces for this view +================= +*/ +void RB_BeginDrawingView (void) { + int clearBits = 0; + + // we will need to change the projection matrix before drawing + // 2D images again + backEnd.projection2D = qfalse; + + // FIXME: HUGE HACK: render to the screen fbo if we've already postprocessed the frame and aren't drawing more world + // drawing more world check is in case of double renders, such as skyportals + if (backEnd.viewParms.targetFbo == NULL) + { + if (!tr.renderFbo || (backEnd.framePostProcessed && (backEnd.refdef.rdflags & RDF_NOWORLDMODEL))) + { + FBO_Bind(NULL); + } + else + { + FBO_Bind(tr.renderFbo); + } + } + else + { + FBO_Bind(backEnd.viewParms.targetFbo); + } + + // + // set the modelview matrix for the viewer + // + SetViewportAndScissor(); + + // ensures that depth writes are enabled for the depth clear + GL_State( GLS_DEFAULT ); + // clear relevant buffers + clearBits = GL_DEPTH_BUFFER_BIT; + + if ( r_clear->integer ) + { + clearBits |= GL_COLOR_BUFFER_BIT; + } + + if ( r_measureOverdraw->integer || r_shadows->integer == 2 ) + { + clearBits |= GL_STENCIL_BUFFER_BIT; + } + + if ( r_fastsky->integer && !( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) ) + { + clearBits |= GL_COLOR_BUFFER_BIT; // FIXME: only if sky shaders have been used +#ifdef _DEBUG + qglClearColor( 0.8f, 0.7f, 0.4f, 1.0f ); // FIXME: get color of sky +#else + if (r_fastsky->integer >= 2 && r_fastsky->integer <= 9) { + qglClearColor(g_color_table[r_fastsky->integer][0], g_color_table[r_fastsky->integer][1], g_color_table[r_fastsky->integer][2], 1.0f); + } + else if (r_fastsky->integer == 10) { //10=red special case + qglClearColor(1.0f, 0.0f, 0.0f, 1.0f); + } + else { + qglClearColor(0.0f, 0.0f, 0.0f, 1.0f); // FIXME: get color of sky + } +#endif + } + + if (tr.refdef.rdflags & RDF_AUTOMAP || (!(backEnd.refdef.rdflags & RDF_NOWORLDMODEL))) + { + if (tr.world && tr.world->globalFog) + { + const fog_t *fog = tr.world->globalFog; + + clearBits |= GL_COLOR_BUFFER_BIT; + qglClearColor(fog->parms.color[0], fog->parms.color[1], fog->parms.color[2], 1.0f); + } + } + + // dont clear color if we have a skyportal and it has been rendered + if (tr.world && tr.world->skyboxportal == 1 && !(tr.viewParms.isSkyPortal)) + clearBits &= ~GL_COLOR_BUFFER_BIT; + + if (clearBits > 0 && !(backEnd.viewParms.flags & VPF_NOCLEAR)) + qglClear( clearBits ); + + if (backEnd.viewParms.targetFbo == NULL) + { + // Clear the glow target + float black[] = {0.0f, 0.0f, 0.0f, 1.0f}; + qglClearBufferfv (GL_COLOR, 1, black); + } + + if ( ( backEnd.refdef.rdflags & RDF_HYPERSPACE ) ) + { + RB_Hyperspace(); + return; + } + + // we will only draw a sun if there was sky rendered in this view + backEnd.skyRenderedThisView = qfalse; + + // clip to the plane of the portal + if ( backEnd.viewParms.isPortal ) { +#if 0 + float plane[4]; + double plane2[4]; + + plane[0] = backEnd.viewParms.portalPlane.normal[0]; + plane[1] = backEnd.viewParms.portalPlane.normal[1]; + plane[2] = backEnd.viewParms.portalPlane.normal[2]; + plane[3] = backEnd.viewParms.portalPlane.dist; + + plane2[0] = DotProduct (backEnd.viewParms.ori.axis[0], plane); + plane2[1] = DotProduct (backEnd.viewParms.ori.axis[1], plane); + plane2[2] = DotProduct (backEnd.viewParms.ori.axis[2], plane); + plane2[3] = DotProduct (plane, backEnd.viewParms.ori.origin) - plane[3]; +#endif + GL_SetModelviewMatrix( s_flipMatrix ); + } + + if (backEnd.viewParms.flags & VPF_POINTSHADOW) + qglPolygonOffset(r_shadowOffsetFactor->value, r_shadowOffsetUnits->value); + else + qglPolygonOffset(r_offsetFactor->value, r_offsetUnits->value); +} + + +#define MAC_EVENT_PUMP_MSEC 5 + +void DrawItemSetVertexAttributes( + DrawItem& drawItem, + const vertexAttribute_t *attributes, + uint32_t count, + Allocator& allocator) +{ + drawItem.numAttributes = count; + drawItem.attributes = ojkAllocArray(allocator, count); + memcpy( + drawItem.attributes, attributes, sizeof(*drawItem.attributes) * count); +} + +void DrawItemSetSamplerBindings( + DrawItem& drawItem, + const SamplerBinding *bindings, + uint32_t count, + Allocator& allocator) +{ + drawItem.numSamplerBindings = count; + drawItem.samplerBindings = ojkAllocArray(allocator, count); + memcpy( + drawItem.samplerBindings, + bindings, + sizeof(*drawItem.samplerBindings) * count); +} + +void DrawItemSetUniformBlockBindings( + DrawItem& drawItem, + const UniformBlockBinding *bindings, + uint32_t count, + Allocator& allocator) +{ + drawItem.numUniformBlockBindings = count; + drawItem.uniformBlockBindings = ojkAllocArray( + allocator, count); + memcpy( + drawItem.uniformBlockBindings, + bindings, + sizeof(*drawItem.uniformBlockBindings) * count); +} + +UniformDataWriter::UniformDataWriter() + : failed(false) + , shaderProgram(nullptr) + , scratch(scratchBuffer, sizeof(scratchBuffer), 1) +{ +} + +void UniformDataWriter::Start( shaderProgram_t *sp ) +{ + shaderProgram = sp; +} + +UniformDataWriter& UniformDataWriter::SetUniformInt( uniform_t uniform, int value ) +{ + if ( shaderProgram->uniforms[uniform] == -1 ) + return *this; + + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(int)); + if ( !memory ) + { + failed = true; + return *this; + } + + UniformData *header = static_cast(memory); + header->index = uniform; + header->numElements = 1; + + int *data = reinterpret_cast(header + 1); + *data = value; + + return *this; +} + +UniformDataWriter& UniformDataWriter::SetUniformFloat( uniform_t uniform, float value ) +{ + return SetUniformFloat(uniform, &value, 1); +} + +UniformDataWriter& UniformDataWriter::SetUniformFloat( uniform_t uniform, float *values, size_t count ) +{ + if ( shaderProgram->uniforms[uniform] == -1 ) + return *this; + + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float)*count); + if ( !memory ) + { + failed = true; + return *this; + } + + UniformData *header = static_cast(memory); + header->index = uniform; + header->numElements = count; + memcpy(header + 1, values, sizeof(float) * count); + + return *this; +} + +UniformDataWriter& UniformDataWriter::SetUniformVec2( uniform_t uniform, float x, float y ) +{ + vec2_t values = {x, y}; + return SetUniformVec2(uniform, values); +} + +UniformDataWriter& UniformDataWriter::SetUniformVec2( uniform_t uniform, const float *values, size_t count ) +{ + if ( shaderProgram->uniforms[uniform] == -1 ) + return *this; + + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec2_t)*count); + if ( !memory ) + { + failed = true; + return *this; + } + + UniformData *header = static_cast(memory); + header->index = uniform; + header->numElements = count; + memcpy(header + 1, values, sizeof(vec2_t) * count); + + return *this; +} + +UniformDataWriter& UniformDataWriter::SetUniformVec3( uniform_t uniform, float x, float y, float z ) +{ + vec3_t values = {x, y, z}; + return SetUniformVec3(uniform, values); +} + +UniformDataWriter& UniformDataWriter::SetUniformVec3( uniform_t uniform, const float *values, size_t count ) +{ + if ( shaderProgram->uniforms[uniform] == -1 ) + return *this; + + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec3_t)*count); + if ( !memory ) + { + failed = true; + return *this; + } + + UniformData *header = static_cast(memory); + header->index = uniform; + header->numElements = count; + memcpy(header + 1, values, sizeof(vec3_t) * count); + + return *this; +} + +UniformDataWriter& UniformDataWriter::SetUniformVec4( uniform_t uniform, float x, float y, float z, float w ) +{ + vec4_t values = {x, y, z, w}; + return SetUniformVec4(uniform, values); +} + +UniformDataWriter& UniformDataWriter::SetUniformVec4( uniform_t uniform, const float *values, size_t count ) +{ + if ( shaderProgram->uniforms[uniform] == -1 ) + return *this; + + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(vec4_t)*count); + if ( !memory ) + { + failed = true; + return *this; + } + + UniformData *header = static_cast(memory); + header->index = uniform; + header->numElements = count; + memcpy(header + 1, values, sizeof(vec4_t) * count); + + return *this; +} + +UniformDataWriter& UniformDataWriter::SetUniformMatrix4x3( uniform_t uniform, const float *matrix, size_t count ) +{ + if ( shaderProgram->uniforms[uniform] == -1 ) + return *this; + + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float)*12*count); + if ( !memory ) + { + failed = true; + return *this; + } + + UniformData *header = static_cast(memory); + header->index = uniform; + header->numElements = count; + memcpy(header + 1, matrix, sizeof(float) * 12 * count); + + return *this; +} + +UniformDataWriter& UniformDataWriter::SetUniformMatrix4x4( uniform_t uniform, const float *matrix, size_t count ) +{ + if ( shaderProgram->uniforms[uniform] == -1 ) + return *this; + + void *memory = scratch.Alloc(sizeof(UniformData) + sizeof(float)*16*count); + if ( !memory ) + { + failed = true; + return *this; + } + + UniformData *header = static_cast(memory); + header->index = uniform; + header->numElements = count; + memcpy(header + 1, matrix, sizeof(float) * 16 * count); + + return *this; +} + +UniformData *UniformDataWriter::Finish( Allocator& destHeap ) +{ + UniformData *endSentinel = ojkAlloc(scratch); + if ( failed || !endSentinel ) + { + return nullptr; + } + + endSentinel->index = UNIFORM_COUNT; + + int uniformDataSize = (char *)scratch.Mark() - (char *)scratch.Base(); + + // Copy scratch buffer to per-frame heap + void *finalMemory = destHeap.Alloc(uniformDataSize); + UniformData *result = static_cast(finalMemory); + memcpy(finalMemory, scratch.Base(), uniformDataSize); + scratch.Reset(); + + failed = false; + shaderProgram = nullptr; + + return result; +} + +SamplerBindingsWriter::SamplerBindingsWriter() + : failed(false) + , count(0) +{ +} + +SamplerBindingsWriter& SamplerBindingsWriter::AddStaticImage( image_t *image, int unit ) +{ + SamplerBinding *binding = &scratch[count]; + if ( !binding ) + { + failed = true; + return *this; + } + + binding->image = image; + binding->slot = unit; + binding->videoMapHandle = NULL_HANDLE; + ++count; + + return *this; +} + +SamplerBindingsWriter& SamplerBindingsWriter::AddAnimatedImage( textureBundle_t *bundle, int unit ) +{ + int index; + + if ( bundle->isVideoMap ) + { + SamplerBinding *binding = &scratch[count]; + if ( !binding ) + { + failed = true; + return *this; + } + + binding->image = nullptr; + binding->slot = unit; + binding->videoMapHandle = bundle->videoMapHandle + 1; + ++count; + + return *this; + } + + if ( bundle->numImageAnimations <= 1 ) + { + return AddStaticImage(bundle->image[0], unit); + } + + if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX ) + { + index = backEnd.currentEntity->e.skinNum; + } + else + { + // it is necessary to do this messy calc to make sure animations line up + // exactly with waveforms of the same frequency + index = Q_ftol( tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE ); + index = Q_max(0, index >> FUNCTABLE_SIZE2); + } + + if ( bundle->oneShotAnimMap ) + { + index = Q_min(index, bundle->numImageAnimations - 1); + } + else + { + // loop + index %= bundle->numImageAnimations; + } + + return AddStaticImage(bundle->image[ index ], unit); +} + +SamplerBinding *SamplerBindingsWriter::Finish( Allocator& destHeap, uint32_t* numBindings ) +{ + if ( failed ) + { + return nullptr; + } + + SamplerBinding *result = ojkAllocArray(destHeap, count); + + if ( numBindings ) + { + *numBindings = count; + } + + memcpy(result, scratch, sizeof(SamplerBinding)*count); + failed = false; + count = 0; + return result; +} + +struct Pass +{ + int maxDrawItems; + int numDrawItems; + DrawItem *drawItems; + uint32_t *sortKeys; +}; + +static void RB_BindTextures( size_t numBindings, const SamplerBinding *bindings ) +{ + for ( size_t i = 0; i < numBindings; ++i ) + { + const SamplerBinding& binding = bindings[i]; + if ( binding.videoMapHandle ) + { + int oldtmu = glState.currenttmu; + GL_SelectTexture(binding.slot); + ri.CIN_RunCinematic(binding.videoMapHandle - 1); + ri.CIN_UploadCinematic(binding.videoMapHandle - 1); + GL_SelectTexture(oldtmu); + } + else + { + GL_BindToTMU(binding.image, binding.slot); + } + } +} + +static void RB_BindUniformBlocks( + size_t numBindings, + const UniformBlockBinding *bindings) +{ + for (size_t i = 0; i < numBindings; ++i) + { + const UniformBlockBinding& binding = bindings[i]; + if (binding.offset < 0) + RB_BindUniformBlock(binding.ubo, binding.block, 0); + else + RB_BindUniformBlock(binding.ubo, binding.block, binding.offset); + } +} + +static void RB_SetRenderState(const RenderState& renderState) +{ + GL_Cull(renderState.cullType); + GL_State(renderState.stateBits); + GL_DepthRange( + renderState.depthRange.minDepth, + renderState.depthRange.maxDepth); + + if (renderState.transformFeedback) + { + qglEnable(GL_RASTERIZER_DISCARD); + qglBeginTransformFeedback(GL_POINTS); + } +} + +static void RB_BindTransformFeedbackBuffer(const bufferBinding_t& binding) +{ + if (memcmp(&glState.currentXFBBO, &binding, sizeof(binding)) != 0) + { + if (binding.buffer != 0) + qglBindBufferRange( + GL_TRANSFORM_FEEDBACK_BUFFER, + 0, + binding.buffer, + binding.offset, + binding.size); + else + qglBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0); + + glState.currentXFBBO = binding; + } +} + +static void RB_DrawItems( + int numDrawItems, + const DrawItem *drawItems, + uint32_t *drawOrder) +{ + for ( int i = 0; i < numDrawItems; ++i ) + { + const DrawItem& drawItem = drawItems[drawOrder[i]]; + + if (drawItem.ibo != nullptr) + R_BindIBO(drawItem.ibo); + + GLSL_BindProgram(drawItem.program); + + GL_VertexAttribPointers(drawItem.numAttributes, drawItem.attributes); + RB_BindTextures(drawItem.numSamplerBindings, drawItem.samplerBindings); + RB_BindUniformBlocks( + drawItem.numUniformBlockBindings, + drawItem.uniformBlockBindings); + RB_BindTransformFeedbackBuffer(drawItem.transformFeedbackBuffer); + + GLSL_SetUniforms(drawItem.program, drawItem.uniformData); + + RB_SetRenderState(drawItem.renderState); + + switch ( drawItem.draw.type ) + { + case DRAW_COMMAND_MULTI_INDEXED: + { + GL_MultiDrawIndexed(drawItem.draw.primitiveType, + drawItem.draw.params.multiIndexed.numIndices, + drawItem.draw.params.multiIndexed.firstIndices, + drawItem.draw.params.multiIndexed.numDraws); + break; + } + + case DRAW_COMMAND_INDEXED: + { + GL_DrawIndexed(drawItem.draw.primitiveType, + drawItem.draw.params.indexed.numIndices, + drawItem.draw.params.indexed.indexType, + drawItem.draw.params.indexed.firstIndex, + drawItem.draw.numInstances, + drawItem.draw.params.indexed.baseVertex); + break; + } + + case DRAW_COMMAND_ARRAYS: + { + GL_Draw( + drawItem.draw.primitiveType, + drawItem.draw.params.arrays.firstVertex, + drawItem.draw.params.arrays.numVertices, + drawItem.draw.numInstances); + break; + } + + default: + { + assert(!"Invalid or unhandled draw type"); + break; + } + } + + if (drawItem.renderState.transformFeedback) + { + qglEndTransformFeedback(); + qglDisable(GL_RASTERIZER_DISCARD); + } + } +} + +void RB_AddDrawItem( Pass *pass, uint32_t sortKey, const DrawItem& drawItem ) +{ + // There will be no pass if we are drawing a 2D object. + if ( pass ) + { + if ( pass->numDrawItems >= pass->maxDrawItems ) + { + assert(!"Ran out of space for pass"); + return; + } + + pass->sortKeys[pass->numDrawItems] = sortKey; + pass->drawItems[pass->numDrawItems++] = drawItem; + } + else + { + uint32_t drawOrder[] = {0}; + RB_DrawItems(1, &drawItem, drawOrder); + } +} + +static Pass *RB_CreatePass( Allocator& allocator, int capacity ) +{ + Pass *pass = ojkAlloc(*backEndData->perFrameMemory); + *pass = {}; + pass->maxDrawItems = capacity; + pass->drawItems = ojkAllocArray(allocator, pass->maxDrawItems); + pass->sortKeys = ojkAllocArray(allocator, pass->maxDrawItems); + return pass; +} + +static void RB_PrepareForEntity( int entityNum, float originalTime ) +{ + if ( entityNum != REFENTITYNUM_WORLD ) + { + backEnd.currentEntity = &backEnd.refdef.entities[entityNum]; + + backEnd.refdef.floatTime = originalTime - backEnd.currentEntity->e.shaderTime; + } + else + { + backEnd.currentEntity = &tr.worldEntity; + + backEnd.refdef.floatTime = originalTime; + } + + // we have to reset the shaderTime as well otherwise image animations on + // the world (like water) continue with the wrong frame + tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset; +} + +static void RB_SubmitDrawSurfsForDepthFill( + drawSurf_t *drawSurfs, + int numDrawSurfs, + float originalTime ) +{ + shader_t *oldShader = nullptr; + int oldEntityNum = -1; + int oldSort = -1; + int oldDepthRange = 0; + CBoneCache *oldBoneCache = nullptr; + + drawSurf_t *drawSurf = drawSurfs; + for ( int i = 0; i < numDrawSurfs; i++, drawSurf++ ) + { + shader_t *shader; + int cubemapIndex; + int postRender; + int entityNum; + + R_DecomposeSort(drawSurf->sort, &entityNum, &shader, &cubemapIndex, &postRender); + assert(shader != nullptr); + + if (shader->useSimpleDepthShader == qtrue) + shader = tr.defaultShader; + + if (shader->sort != SS_OPAQUE || shader->useDistortion) + { + // Don't draw yet, let's see what's to come + continue; + } + + if (*drawSurf->surface == SF_MDX) + { + if (((CRenderableSurface*)drawSurf->surface)->boneCache != oldBoneCache) + { + RB_EndSurface(); + RB_BeginSurface(shader, 0, 0); + oldBoneCache = ((CRenderableSurface*)drawSurf->surface)->boneCache; + tr.animationBoneUboOffset = RB_GetBoneUboOffset((CRenderableSurface*)drawSurf->surface); + } + } + + if ( shader == oldShader && entityNum == oldEntityNum ) + { + // fast path, same as previous sort + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); + continue; + } + + // change the tess parameters if needed + // a "entityMergable" shader is a shader that can have surfaces from + // seperate entities merged into a single batch, like smoke and blood + // puff sprites + if ( shader != oldShader || + (entityNum != oldEntityNum && !shader->entityMergable) ) + { + if ( oldShader != nullptr ) + { + RB_EndSurface(); + } + + RB_BeginSurface(shader, 0, 0); + backEnd.pc.c_surfBatches++; + oldShader = shader; + } + + oldSort = drawSurf->sort; + + // change the modelview matrix if needed + if ( entityNum != oldEntityNum ) + { + RB_PrepareForEntity(entityNum, originalTime); + oldEntityNum = entityNum; + } + + // add the triangles for this surface + assert(drawSurf->surface != nullptr); + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); + } + + // draw the contents of the last shader batch + if ( oldShader != nullptr ) + { + RB_EndSurface(); + } +} + +static void RB_SubmitDrawSurfs( + drawSurf_t *drawSurfs, + int numDrawSurfs, + float originalTime ) +{ + shader_t *oldShader = nullptr; + int oldEntityNum = -1; + int oldSort = -1; + int oldFogNum = -1; + int oldDepthRange = 0; + int oldDlighted = 0; + int oldPostRender = 0; + int oldCubemapIndex = -1; + CBoneCache *oldBoneCache = nullptr; + + drawSurf_t *drawSurf = drawSurfs; + for ( int i = 0; i < numDrawSurfs; i++, drawSurf++ ) + { + shader_t *shader; + int cubemapIndex; + int postRender; + int entityNum; + int fogNum; + int dlighted; + + R_DecomposeSort(drawSurf->sort, &entityNum, &shader, &cubemapIndex, &postRender); + assert(shader != nullptr); + fogNum = drawSurf->fogIndex; + dlighted = drawSurf->dlightBits; + + if (*drawSurf->surface == SF_MDX) + { + if (((CRenderableSurface*)drawSurf->surface)->boneCache != oldBoneCache) + { + RB_EndSurface(); + RB_BeginSurface(shader, fogNum, cubemapIndex); + oldBoneCache = ((CRenderableSurface*)drawSurf->surface)->boneCache; + tr.animationBoneUboOffset = RB_GetBoneUboOffset((CRenderableSurface*)drawSurf->surface); + } + } + + if ( shader == oldShader && + fogNum == oldFogNum && + postRender == oldPostRender && + cubemapIndex == oldCubemapIndex && + entityNum == oldEntityNum && + dlighted == oldDlighted && + backEnd.refractionFill == shader->useDistortion ) + { + // fast path, same as previous sort + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); + continue; + } + + oldSort = drawSurf->sort; + + // + // change the tess parameters if needed + // a "entityMergable" shader is a shader that can have surfaces from seperate + // entities merged into a single batch, like smoke and blood puff sprites + if ( (shader != oldShader || + fogNum != oldFogNum || + dlighted != oldDlighted || + postRender != oldPostRender || + cubemapIndex != oldCubemapIndex || + (entityNum != oldEntityNum && !shader->entityMergable)) ) + { + if ( oldShader != nullptr ) + { + RB_EndSurface(); + } + + RB_BeginSurface(shader, fogNum, cubemapIndex); + backEnd.pc.c_surfBatches++; + oldShader = shader; + oldFogNum = fogNum; + oldDlighted = dlighted; + oldPostRender = postRender; + oldCubemapIndex = cubemapIndex; + } + + if ( entityNum != oldEntityNum ) + { + RB_PrepareForEntity(entityNum, originalTime); + oldEntityNum = entityNum; + } + + qboolean isDistortionShader = (qboolean) + ((shader->useDistortion == qtrue) || (backEnd.currentEntity && backEnd.currentEntity->e.renderfx & RF_DISTORTION)); + + if (backEnd.refractionFill != isDistortionShader) + continue; + + // ugly hack for now... + // find better way to pass dlightbits + tess.dlightBits = drawSurf->dlightBits; + + // add the triangles for this surface + rb_surfaceTable[*drawSurf->surface](drawSurf->surface); + } + + // draw the contents of the last shader batch + if ( oldShader != nullptr ) + { + RB_EndSurface(); + } +} + +static void RB_SubmitRenderPass( + Pass& renderPass, + Allocator& allocator ) +{ + uint32_t *drawOrder = ojkAllocArray( + allocator, renderPass.numDrawItems); + + uint32_t numDrawItems = renderPass.numDrawItems; + for ( uint32_t i = 0; i < numDrawItems; ++i ) + drawOrder[i] = i; + + uint32_t *sortKeys = renderPass.sortKeys; + std::sort(drawOrder, drawOrder + numDrawItems, [sortKeys]( uint32_t a, uint32_t b ) + { + return sortKeys[a] < sortKeys[b]; + }); + + RB_DrawItems(renderPass.numDrawItems, renderPass.drawItems, drawOrder); +} + +/* +================== +RB_RenderDrawSurfList +================== +*/ +static void RB_RenderDrawSurfList( drawSurf_t *drawSurfs, int numDrawSurfs ) +{ + /* + merging surfaces together that share the same shader (e.g. polys, patches) + upload per frame data - but this might be the same between render passes? + + how about: + tr.refdef.entities[] + + and .... entityCullInfo_t tr.refdef.entityCullInfo[] + struct visibleEntity_t + { + uint32_t frustumMask; // bitfield of frustums which intersect + EntityId entityId; + }; + + foreach ghoul2 model: + transform bones + + foreach visibleEntity: + upload per frame data + + for polygons: + merge them, create new surface and upload data + + for patch meshes: + merge them, create new surface and upload data + + + each surface corresponds to something which has all of its gpu data uploaded + */ + + int estimatedNumShaderStages = (backEnd.viewParms.flags & VPF_DEPTHSHADOW) ? 1 : 4; + + // Prepare memory for the current render pass + void *allocMark = backEndData->perFrameMemory->Mark(); + assert(backEndData->currentPass == nullptr); + backEndData->currentPass = RB_CreatePass( + *backEndData->perFrameMemory, numDrawSurfs * estimatedNumShaderStages); + + // save original time for entity shader offsets + float originalTime = backEnd.refdef.floatTime; + FBO_t *fbo = glState.currentFBO; + + backEnd.currentEntity = &tr.worldEntity; + backEnd.pc.c_surfaces += numDrawSurfs; + + if ( backEnd.depthFill ) + { + RB_SubmitDrawSurfsForDepthFill(drawSurfs, numDrawSurfs, originalTime); + } + else + { + RB_SubmitDrawSurfs(drawSurfs, numDrawSurfs, originalTime); + } + + // Do the drawing and release memory + RB_SubmitRenderPass( + *backEndData->currentPass, + *backEndData->perFrameMemory); + + backEndData->perFrameMemory->ResetTo(allocMark); + backEndData->currentPass = nullptr; + + // Reset things to how they were + backEnd.refdef.floatTime = originalTime; + FBO_Bind(fbo); + GL_SetModelviewMatrix(backEnd.viewParms.world.modelViewMatrix); +} + + +/* +============================================================================ + +RENDER BACK END FUNCTIONS + +============================================================================ +*/ + +/* +================ +RB_SetGL2D + +================ +*/ +void RB_SetGL2D (void) { + matrix_t matrix; + int width, height; + + if (backEnd.projection2D && backEnd.last2DFBO == glState.currentFBO) + return; + + backEnd.projection2D = qtrue; + backEnd.last2DFBO = glState.currentFBO; + + if (glState.currentFBO) + { + width = glState.currentFBO->width; + height = glState.currentFBO->height; + } + else + { + width = glConfig.vidWidth; + height = glConfig.vidHeight; + } + + // set 2D virtual screen size + qglViewport( 0, 0, width, height ); + qglScissor( 0, 0, width, height ); + + Matrix16Ortho(0, 640, 480, 0, 0, 1, matrix); + GL_SetProjectionMatrix(matrix); + Matrix16Identity(matrix); + GL_SetModelviewMatrix(matrix); + + GL_State( GLS_DEPTHTEST_DISABLE | + GLS_SRCBLEND_SRC_ALPHA | + GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ); + + GL_Cull(CT_TWO_SIDED); + + // set time for 2D shaders + backEnd.refdef.time = ri.Milliseconds(); + backEnd.refdef.floatTime = backEnd.refdef.time * 0.001f; + + // reset color scaling + backEnd.refdef.colorScale = 1.0f; +} + + +/* +============= +RE_StretchRaw + +FIXME: not exactly backend +Stretches a raw 32 bit power of 2 bitmap image over the given screen rectangle. +Used for cinematics. +============= +*/ +void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty) { + int i, j; + int start, end; + vec4_t quadVerts[4]; + vec2_t texCoords[4]; + + if ( !tr.registered ) { + return; + } + R_IssuePendingRenderCommands(); + + if ( tess.numIndexes ) { + RB_EndSurface(); + } + + // we definately want to sync every frame for the cinematics + qglFinish(); + + start = 0; + if ( r_speeds->integer ) { + start = ri.Milliseconds(); + } + + // make sure rows and cols are powers of 2 + for ( i = 0 ; ( 1 << i ) < cols ; i++ ) { + } + for ( j = 0 ; ( 1 << j ) < rows ; j++ ) { + } + if ( ( 1 << i ) != cols || ( 1 << j ) != rows) { + ri.Error (ERR_DROP, "Draw_StretchRaw: size not a power of 2: %i by %i", cols, rows); + } + + RE_UploadCinematic (cols, rows, data, client, dirty); + + if ( r_speeds->integer ) { + end = ri.Milliseconds(); + ri.Printf( PRINT_ALL, "qglTexSubImage2D %i, %i: %i msec\n", cols, rows, end - start ); + } + + // FIXME: HUGE hack + if (!tr.renderFbo || backEnd.framePostProcessed) + { + FBO_Bind(NULL); + } + else + { + FBO_Bind(tr.renderFbo); + } + + RB_SetGL2D(); + + VectorSet4(quadVerts[0], x, y, 0.0f, 1.0f); + VectorSet4(quadVerts[1], x + w, y, 0.0f, 1.0f); + VectorSet4(quadVerts[2], x + w, y + h, 0.0f, 1.0f); + VectorSet4(quadVerts[3], x, y + h, 0.0f, 1.0f); + + VectorSet2(texCoords[0], 0.5f / cols, 0.5f / rows); + VectorSet2(texCoords[1], (cols - 0.5f) / cols, 0.5f / rows); + VectorSet2(texCoords[2], (cols - 0.5f) / cols, (rows - 0.5f) / rows); + VectorSet2(texCoords[3], 0.5f / cols, (rows - 0.5f) / rows); + + GLSL_BindProgram(&tr.textureColorShader); + + GLSL_SetUniformMatrix4x4(&tr.textureColorShader, UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); + GLSL_SetUniformVec4(&tr.textureColorShader, UNIFORM_COLOR, colorWhite); + + RB_InstantQuad2(quadVerts, texCoords); +} + +void RE_UploadCinematic (int cols, int rows, const byte *data, int client, qboolean dirty) { + + GL_Bind( tr.scratchImage[client] ); + + // if the scratchImage isn't in the format we want, specify it as a new texture + if ( cols != tr.scratchImage[client]->width || rows != tr.scratchImage[client]->height ) { + tr.scratchImage[client]->width = tr.scratchImage[client]->uploadWidth = cols; + tr.scratchImage[client]->height = tr.scratchImage[client]->uploadHeight = rows; + qglTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, cols, rows, 0, GL_RGBA, GL_UNSIGNED_BYTE, data ); + qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); + qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); + } else { + if (dirty) { + // otherwise, just subimage upload it so that drivers can tell we are going to be changing + // it and don't try and do a texture compression + qglTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, cols, rows, GL_RGBA, GL_UNSIGNED_BYTE, data ); + } + } +} + + +/* +============= +RB_SetColor + +============= +*/ +static const void *RB_SetColor( const void *data ) { + const setColorCommand_t *cmd; + + cmd = (const setColorCommand_t *)data; + + backEnd.color2D[0] = cmd->color[0]; + backEnd.color2D[1] = cmd->color[1]; + backEnd.color2D[2] = cmd->color[2]; + backEnd.color2D[3] = cmd->color[3]; + + return (const void *)(cmd + 1); +} + +/* +============= +RB_StretchPic +============= +*/ +static const void *RB_StretchPic ( const void *data ) { + const stretchPicCommand_t *cmd; + shader_t *shader; + + cmd = (const stretchPicCommand_t *)data; + + // FIXME: HUGE hack + if (!tr.renderFbo || backEnd.framePostProcessed) + { + FBO_Bind(NULL); + } + else + { + FBO_Bind(tr.renderFbo); + } + + RB_SetGL2D(); + + shader = cmd->shader; + if ( shader != tess.shader ) { + if ( tess.numIndexes ) { + RB_EndSurface(); + } + backEnd.currentEntity = &backEnd.entity2D; + RB_BeginSurface( shader, 0, 0 ); + } + + RB_CHECKOVERFLOW( 4, 6 ); + int numVerts = tess.numVertexes; + int numIndexes = tess.numIndexes; + + tess.numVertexes += 4; + tess.numIndexes += 6; + + tess.indexes[ numIndexes ] = numVerts + 3; + tess.indexes[ numIndexes + 1 ] = numVerts + 0; + tess.indexes[ numIndexes + 2 ] = numVerts + 2; + tess.indexes[ numIndexes + 3 ] = numVerts + 2; + tess.indexes[ numIndexes + 4 ] = numVerts + 0; + tess.indexes[ numIndexes + 5 ] = numVerts + 1; + + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts ]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 1 ]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 2 ]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 3 ]); + + tess.xyz[ numVerts ][0] = cmd->x; + tess.xyz[ numVerts ][1] = cmd->y; + tess.xyz[ numVerts ][2] = 0; + + tess.texCoords[ numVerts ][0][0] = cmd->s1; + tess.texCoords[ numVerts ][0][1] = cmd->t1; + + tess.xyz[ numVerts + 1 ][0] = cmd->x + cmd->w; + tess.xyz[ numVerts + 1 ][1] = cmd->y; + tess.xyz[ numVerts + 1 ][2] = 0; + + tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; + tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + + tess.xyz[ numVerts + 2 ][0] = cmd->x + cmd->w; + tess.xyz[ numVerts + 2 ][1] = cmd->y + cmd->h; + tess.xyz[ numVerts + 2 ][2] = 0; + + tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; + tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + + tess.xyz[ numVerts + 3 ][0] = cmd->x; + tess.xyz[ numVerts + 3 ][1] = cmd->y + cmd->h; + tess.xyz[ numVerts + 3 ][2] = 0; + + tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; + tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + + return (const void *)(cmd + 1); +} + +/* +============= +RB_DrawRotatePic +============= +*/ +static const void *RB_RotatePic ( const void *data ) +{ + const rotatePicCommand_t *cmd; + shader_t *shader; + + cmd = (const rotatePicCommand_t *)data; + + // FIXME: HUGE hack + if (!tr.renderFbo || backEnd.framePostProcessed) + { + FBO_Bind(NULL); + } + else + { + FBO_Bind(tr.renderFbo); + } + + RB_SetGL2D(); + + shader = cmd->shader; + if ( shader != tess.shader ) { + if ( tess.numIndexes ) { + RB_EndSurface(); + } + backEnd.currentEntity = &backEnd.entity2D; + RB_BeginSurface( shader, 0, 0 ); + } + + RB_CHECKOVERFLOW( 4, 6 ); + int numVerts = tess.numVertexes; + int numIndexes = tess.numIndexes; + + float angle = DEG2RAD( cmd->a ); + float s = sinf( angle ); + float c = cosf( angle ); + + matrix3_t m = { + { c, s, 0.0f }, + { -s, c, 0.0f }, + { cmd->x + cmd->w, cmd->y, 1.0f } + }; + + tess.numVertexes += 4; + tess.numIndexes += 6; + + tess.indexes[ numIndexes ] = numVerts + 3; + tess.indexes[ numIndexes + 1 ] = numVerts + 0; + tess.indexes[ numIndexes + 2 ] = numVerts + 2; + tess.indexes[ numIndexes + 3 ] = numVerts + 2; + tess.indexes[ numIndexes + 4 ] = numVerts + 0; + tess.indexes[ numIndexes + 5 ] = numVerts + 1; + + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts ]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 1]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 2]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 3 ]); + + tess.xyz[ numVerts ][0] = m[0][0] * (-cmd->w) + m[2][0]; + tess.xyz[ numVerts ][1] = m[0][1] * (-cmd->w) + m[2][1]; + tess.xyz[ numVerts ][2] = 0; + + tess.texCoords[ numVerts ][0][0] = cmd->s1; + tess.texCoords[ numVerts ][0][1] = cmd->t1; + + tess.xyz[ numVerts + 1 ][0] = m[2][0]; + tess.xyz[ numVerts + 1 ][1] = m[2][1]; + tess.xyz[ numVerts + 1 ][2] = 0; + + tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; + tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + + tess.xyz[ numVerts + 2 ][0] = m[1][0] * (cmd->h) + m[2][0]; + tess.xyz[ numVerts + 2 ][1] = m[1][1] * (cmd->h) + m[2][1]; + tess.xyz[ numVerts + 2 ][2] = 0; + + tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; + tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + + tess.xyz[ numVerts + 3 ][0] = m[0][0] * (-cmd->w) + m[1][0] * (cmd->h) + m[2][0]; + tess.xyz[ numVerts + 3 ][1] = m[0][1] * (-cmd->w) + m[1][1] * (cmd->h) + m[2][1]; + tess.xyz[ numVerts + 3 ][2] = 0; + + tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; + tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + + return (const void *)(cmd + 1); +} + +/* +============= +RB_DrawRotatePic2 +============= +*/ +static const void *RB_RotatePic2 ( const void *data ) +{ + const rotatePicCommand_t *cmd; + shader_t *shader; + + cmd = (const rotatePicCommand_t *)data; + + // FIXME: HUGE hack + if (!tr.renderFbo || backEnd.framePostProcessed) + { + FBO_Bind(NULL); + } + else + { + FBO_Bind(tr.renderFbo); + } + + RB_SetGL2D(); + + shader = cmd->shader; + if ( shader != tess.shader ) { + if ( tess.numIndexes ) { + RB_EndSurface(); + } + backEnd.currentEntity = &backEnd.entity2D; + RB_BeginSurface( shader, 0, 0 ); + } + + RB_CHECKOVERFLOW( 4, 6 ); + int numVerts = tess.numVertexes; + int numIndexes = tess.numIndexes; + + float angle = DEG2RAD( cmd->a ); + float s = sinf( angle ); + float c = cosf( angle ); + + matrix3_t m = { + { c, s, 0.0f }, + { -s, c, 0.0f }, + { cmd->x, cmd->y, 1.0f } + }; + + tess.numVertexes += 4; + tess.numIndexes += 6; + + tess.indexes[ numIndexes ] = numVerts + 3; + tess.indexes[ numIndexes + 1 ] = numVerts + 0; + tess.indexes[ numIndexes + 2 ] = numVerts + 2; + tess.indexes[ numIndexes + 3 ] = numVerts + 2; + tess.indexes[ numIndexes + 4 ] = numVerts + 0; + tess.indexes[ numIndexes + 5 ] = numVerts + 1; + + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts ]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 1]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 2]); + VectorCopy4(backEnd.color2D, tess.vertexColors[ numVerts + 3 ]); + + tess.xyz[ numVerts ][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; + tess.xyz[ numVerts ][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; + tess.xyz[ numVerts ][2] = 0; + + tess.texCoords[ numVerts ][0][0] = cmd->s1; + tess.texCoords[ numVerts ][0][1] = cmd->t1; + + tess.xyz[ numVerts + 1 ][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (-cmd->h * 0.5f) + m[2][0]; + tess.xyz[ numVerts + 1 ][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (-cmd->h * 0.5f) + m[2][1]; + tess.xyz[ numVerts + 1 ][2] = 0; + + tess.texCoords[ numVerts + 1 ][0][0] = cmd->s2; + tess.texCoords[ numVerts + 1 ][0][1] = cmd->t1; + + tess.xyz[ numVerts + 2 ][0] = m[0][0] * (cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; + tess.xyz[ numVerts + 2 ][1] = m[0][1] * (cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; + tess.xyz[ numVerts + 2 ][2] = 0; + + tess.texCoords[ numVerts + 2 ][0][0] = cmd->s2; + tess.texCoords[ numVerts + 2 ][0][1] = cmd->t2; + + tess.xyz[ numVerts + 3 ][0] = m[0][0] * (-cmd->w * 0.5f) + m[1][0] * (cmd->h * 0.5f) + m[2][0]; + tess.xyz[ numVerts + 3 ][1] = m[0][1] * (-cmd->w * 0.5f) + m[1][1] * (cmd->h * 0.5f) + m[2][1]; + tess.xyz[ numVerts + 3 ][2] = 0; + + tess.texCoords[ numVerts + 3 ][0][0] = cmd->s1; + tess.texCoords[ numVerts + 3 ][0][1] = cmd->t2; + + return (const void *)(cmd + 1); +} + +/* +============= +RB_PrefilterEnvMap +============= +*/ + +static const void *RB_PrefilterEnvMap(const void *data) { + + const convolveCubemapCommand_t *cmd = (const convolveCubemapCommand_t *)data; + + // finish any 2D drawing if needed + if (tess.numIndexes) + RB_EndSurface(); + + RB_SetGL2D(); + + qglBindTexture(GL_TEXTURE_CUBE_MAP, tr.renderCubeImage->texnum); + qglGenerateMipmap(GL_TEXTURE_CUBE_MAP); + qglBindTexture(GL_TEXTURE_CUBE_MAP, 0); + + if (!cmd->cubemap->image) + { + GLenum cubemapFormat = GL_RGBA8; + if (r_hdr->integer) + { + cubemapFormat = GL_RGBA16F; + } + // FIX ME: Only allocate needed mip level! + cmd->cubemap->image = R_CreateImage( + va("*cubeMap%d", cmd->cubemapId), + NULL, + CUBE_MAP_SIZE, + CUBE_MAP_SIZE, + IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | + IMGFLAG_CLAMPTOEDGE | + IMGFLAG_MIPMAP | + IMGFLAG_CUBEMAP, + cubemapFormat); + } + assert(cmd->cubemap->image); + + int width = cmd->cubemap->image->width; + int height = cmd->cubemap->image->height; + float roughnessMips = (float)CUBE_MAP_ROUGHNESS_MIPS; + + for (int level = 0; level <= CUBE_MAP_ROUGHNESS_MIPS; level++) + { + FBO_Bind(tr.filterCubeFbo); + qglFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, cmd->cubemap->image->texnum, level); + GL_BindToTMU(tr.renderCubeImage, TB_CUBEMAP); + GLSL_BindProgram(&tr.prefilterEnvMapShader); + + qglViewport(0, 0, width, height); + qglScissor(0, 0, width, height); + + vec4_t viewInfo; + VectorSet4(viewInfo, 0, level, roughnessMips, level / roughnessMips); + GLSL_SetUniformVec4(&tr.prefilterEnvMapShader, UNIFORM_VIEWINFO, viewInfo); + RB_InstantTriangle(); + width = width / 2; + height = height / 2; + } + + return (const void *)(cmd + 1); +} + + +static void RB_RenderSSAO() +{ + const float zmax = backEnd.viewParms.zFar; + const float zmin = r_znear->value; + const vec4_t viewInfo = { zmax / zmin, zmax, 0.0f, 0.0f }; + + FBO_Bind(tr.quarterFbo[0]); + + qglViewport(0, 0, tr.quarterFbo[0]->width, tr.quarterFbo[0]->height); + qglScissor(0, 0, tr.quarterFbo[0]->width, tr.quarterFbo[0]->height); + + GL_State( GLS_DEPTHTEST_DISABLE ); + + GLSL_BindProgram(&tr.ssaoShader); + + GL_BindToTMU(tr.hdrDepthImage, TB_COLORMAP); + GLSL_SetUniformVec4(&tr.ssaoShader, UNIFORM_VIEWINFO, viewInfo); + + RB_InstantTriangle(); + + FBO_Bind(tr.quarterFbo[1]); + + qglViewport(0, 0, tr.quarterFbo[1]->width, tr.quarterFbo[1]->height); + qglScissor(0, 0, tr.quarterFbo[1]->width, tr.quarterFbo[1]->height); + + GLSL_BindProgram(&tr.depthBlurShader[0]); + + GL_BindToTMU(tr.quarterImage[0], TB_COLORMAP); + GL_BindToTMU(tr.hdrDepthImage, TB_LIGHTMAP); + GLSL_SetUniformVec4(&tr.depthBlurShader[0], UNIFORM_VIEWINFO, viewInfo); + + RB_InstantTriangle(); + + FBO_Bind(tr.screenSsaoFbo); + + qglViewport(0, 0, tr.screenSsaoFbo->width, tr.screenSsaoFbo->height); + qglScissor(0, 0, tr.screenSsaoFbo->width, tr.screenSsaoFbo->height); + + GLSL_BindProgram(&tr.depthBlurShader[1]); + + GL_BindToTMU(tr.quarterImage[1], TB_COLORMAP); + GL_BindToTMU(tr.hdrDepthImage, TB_LIGHTMAP); + GLSL_SetUniformVec4(&tr.depthBlurShader[1], UNIFORM_VIEWINFO, viewInfo); + + RB_InstantTriangle(); +} + +static void RB_RenderDepthOnly( drawSurf_t *drawSurfs, int numDrawSurfs ) +{ + backEnd.depthFill = qtrue; + qglColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + RB_RenderDrawSurfList(drawSurfs, numDrawSurfs); + qglColorMask( + !backEnd.colorMask[0], + !backEnd.colorMask[1], + !backEnd.colorMask[2], + !backEnd.colorMask[3]); + backEnd.depthFill = qfalse; + + // Only resolve the main pass depth + if (tr.msaaResolveFbo && backEnd.viewParms.targetFbo == tr.renderFbo) + { + FBO_FastBlit( + tr.renderFbo, NULL, + tr.msaaResolveFbo, NULL, + GL_DEPTH_BUFFER_BIT, + GL_NEAREST); + } + else if (tr.renderFbo == NULL) + { + // If we're rendering directly to the screen, copy the depth to a texture + GL_BindToTMU(tr.renderDepthImage, 0); + qglCopyTexImage2D( + GL_TEXTURE_2D, 0, + GL_DEPTH_COMPONENT24, 0, + 0, glConfig.vidWidth, + glConfig.vidHeight, 0); + } + + if (r_ssao->integer && + !(backEnd.viewParms.flags & VPF_DEPTHSHADOW) && + !(tr.viewParms.isSkyPortal)) + { + // need the depth in a texture we can do GL_LINEAR sampling on, so + // copy it to an HDR image + vec4i_t srcBox; + VectorSet4(srcBox, 0, tr.renderDepthImage->height, tr.renderDepthImage->width, -tr.renderDepthImage->height); + FBO_BlitFromTexture( + tr.renderDepthImage, + srcBox, + nullptr, + tr.hdrDepthFbo, + nullptr, + nullptr, + nullptr, 0); + } +} + +static void RB_RenderMainPass( drawSurf_t *drawSurfs, int numDrawSurfs ) +{ + if ( backEnd.viewParms.flags & VPF_DEPTHSHADOW ) + { + return; + } + + RB_RenderDrawSurfList(drawSurfs, numDrawSurfs); + + if (r_drawSun->integer) + { + RB_DrawSun(0.1, tr.sunShader); + } + + if (r_drawSunRays->integer) + { + FBO_t *oldFbo = glState.currentFBO; + FBO_Bind(tr.sunRaysFbo); + + qglClearColor( 0.0f, 0.0f, 0.0f, 1.0f ); + qglClear( GL_COLOR_BUFFER_BIT ); + + tr.sunFlareQueryActive[tr.sunFlareQueryIndex] = qtrue; + qglBeginQuery(GL_SAMPLES_PASSED, tr.sunFlareQuery[tr.sunFlareQueryIndex]); + + RB_DrawSun(0.3, tr.sunFlareShader); + + qglEndQuery(GL_SAMPLES_PASSED); + + FBO_Bind(oldFbo); + } + + // darken down any stencil shadows + RB_ShadowFinish(); + + RB_RenderFlares(); +} + +static void RB_RenderAllDepthRelatedPasses( drawSurf_t *drawSurfs, int numDrawSurfs ) +{ + if ( backEnd.refdef.rdflags & RDF_NOWORLDMODEL ) + { + return; + } + + if ( !r_depthPrepass->integer && !(backEnd.viewParms.flags & VPF_DEPTHSHADOW) ) + { + return; + } + + FBO_t *oldFbo = glState.currentFBO; + + if (backEnd.viewParms.flags & VPF_DEPTHCLAMP) + { + qglEnable(GL_DEPTH_CLAMP); + } + + RB_RenderDepthOnly(drawSurfs, numDrawSurfs); + + if (r_ssao->integer && + !(backEnd.viewParms.flags & VPF_DEPTHSHADOW) && + !(tr.viewParms.isSkyPortal)) + { + RB_RenderSSAO(); + } + + // reset viewport and scissor + FBO_Bind(oldFbo); + SetViewportAndScissor(); + + if (backEnd.viewParms.flags & VPF_DEPTHCLAMP) + { + qglDisable(GL_DEPTH_CLAMP); + } +} + +static void RB_UpdateCameraConstants(gpuFrame_t *frame) +{ + for (int i = 0; i < tr.numCachedViewParms; i++) + { + backEnd.viewParms = tr.cachedViewParms[i]; + const float zmax = tr.cachedViewParms[i].zFar; + const float zmin = tr.cachedViewParms[i].zNear; + + const float ymax = zmax * tanf(backEnd.viewParms.fovY * M_PI / 360.0f); + const float xmax = zmax * tanf(backEnd.viewParms.fovX * M_PI / 360.0f); + + vec3_t viewBasis[3]; + + VectorNormalize(tr.cachedViewParms[i].ori.axis[0]); + VectorNormalize(tr.cachedViewParms[i].ori.axis[1]); + VectorNormalize(tr.cachedViewParms[i].ori.axis[2]); + + VectorScale(tr.cachedViewParms[i].ori.axis[0], zmax, viewBasis[0]); + VectorScale(tr.cachedViewParms[i].ori.axis[1], xmax, viewBasis[1]); + VectorScale(tr.cachedViewParms[i].ori.axis[2], ymax, viewBasis[2]); + + CameraBlock cameraBlock = {}; + Matrix16Multiply( + tr.cachedViewParms[i].projectionMatrix, + tr.cachedViewParms[i].world.modelViewMatrix, + cameraBlock.viewProjectionMatrix); + VectorSet4(cameraBlock.viewInfo, zmax / zmin, zmax, 0.0f, 0.0f); + VectorCopy(viewBasis[0], cameraBlock.viewForward); + VectorCopy(viewBasis[1], cameraBlock.viewLeft); + VectorCopy(viewBasis[2], cameraBlock.viewUp); + VectorCopy(tr.cachedViewParms[i].ori.origin, cameraBlock.viewOrigin); + + tr.cameraUboOffsets[tr.cachedViewParms[i].currentViewParm] = RB_AppendConstantsData( + frame, &cameraBlock, sizeof(cameraBlock)); + } +} + +static void RB_UpdateSceneConstants(gpuFrame_t *frame, const trRefdef_t *refdef) +{ + SceneBlock sceneBlock = {}; + VectorCopy4(refdef->sunDir, sceneBlock.primaryLightOrigin); + VectorCopy(refdef->sunAmbCol, sceneBlock.primaryLightAmbient); + VectorCopy(refdef->sunCol, sceneBlock.primaryLightColor); + if (tr.world != nullptr) + sceneBlock.globalFogIndex = tr.world->globalFogIndex - 1; + else + sceneBlock.globalFogIndex = -1; + sceneBlock.currentTime = refdef->floatTime; + sceneBlock.frameTime = refdef->frameTime; + + tr.sceneUboOffset = RB_AppendConstantsData( + frame, &sceneBlock, sizeof(sceneBlock)); +} + +static void RB_UpdateLightsConstants(gpuFrame_t *frame, const trRefdef_t *refdef) +{ + LightsBlock lightsBlock = {}; + + memcpy(lightsBlock.shadowVP1, refdef->sunShadowMvp[0], sizeof(matrix_t)); + memcpy(lightsBlock.shadowVP2, refdef->sunShadowMvp[1], sizeof(matrix_t)); + memcpy(lightsBlock.shadowVP3, refdef->sunShadowMvp[2], sizeof(matrix_t)); + + lightsBlock.numLights = MIN(refdef->num_dlights, MAX_DLIGHTS); + for (int i = 0; i < lightsBlock.numLights; ++i) + { + const dlight_t *dlight = refdef->dlights + i; + LightsBlock::Light *lightData = lightsBlock.lights + i; + + VectorSet4( + lightData->origin, + dlight->origin[0], + dlight->origin[1], + dlight->origin[2], + 1.0f); + VectorCopy(dlight->color, lightData->color); + lightData->radius = dlight->radius; + } + // TODO: Add pshadow data + + tr.lightsUboOffset = RB_AppendConstantsData( + frame, &lightsBlock, sizeof(lightsBlock)); +} + +static void RB_UpdateFogsConstants(gpuFrame_t *frame) +{ + FogsBlock fogsBlock = {}; + if (tr.world == nullptr) + { + fogsBlock.numFogs = 0; + } + else + { + fogsBlock.numFogs = tr.world->numfogs - 1; // Don't reserve fog 0 as 'null' + } + + for (int i = 0; i < fogsBlock.numFogs; ++i) + { + const fog_t *fog = tr.world->fogs + i + 1; + FogsBlock::Fog *fogData = fogsBlock.fogs + i; + + VectorCopy4(fog->surface, fogData->plane); + VectorCopy4(fog->color, fogData->color); + fogData->depthToOpaque = sqrtf(-logf(1.0f / 255.0f)) / fog->parms.depthForOpaque; + fogData->hasPlane = fog->hasSurface; + } + + tr.fogsUboOffset = RB_AppendConstantsData( + frame, &fogsBlock, sizeof(fogsBlock)); +} + +static void RB_UpdateEntityLightConstants( + EntityBlock& entityBlock, + const trRefEntity_t *refEntity) +{ + static const float normalizeFactor = 1.0f / 255.0f; + + VectorScale(refEntity->ambientLight, normalizeFactor, entityBlock.ambientLight); + VectorScale(refEntity->directedLight, normalizeFactor, entityBlock.directedLight); + VectorCopy(refEntity->lightDir, entityBlock.lightOrigin); + + vec3_t lightDir; + float lightRadius; + VectorCopy(refEntity->modelLightDir, lightDir); + lightRadius = 300.0f; + if (r_shadows->integer == 2) + { + lightDir[2] = 0.0f; + VectorNormalize(lightDir); + VectorSet(lightDir, lightDir[0] * 0.3f, lightDir[1] * 0.3f, 1.0f); + lightRadius = refEntity->e.lightingOrigin[2] - refEntity->e.shadowPlane + 64.0f; + } + + VectorCopy(lightDir, entityBlock.modelLightDir); + entityBlock.lightOrigin[3] = 0.0f; + entityBlock.lightRadius = lightRadius; +} + +static void RB_UpdateEntityMatrixConstants( + EntityBlock& entityBlock, + const trRefEntity_t *refEntity) +{ + orientationr_t ori; + R_RotateForEntity(refEntity, &backEnd.viewParms, &ori); + Matrix16Copy(ori.modelMatrix, entityBlock.modelMatrix); + VectorCopy(ori.viewOrigin, entityBlock.localViewOrigin); +} + +static void RB_UpdateEntityModelConstants( + EntityBlock& entityBlock, + const trRefEntity_t *refEntity) +{ + static const float normalizeFactor = 1.0f / 255.0f; + + entityBlock.fxVolumetricBase = -1.0f; + if (refEntity->e.renderfx & RF_VOLUMETRIC) + entityBlock.fxVolumetricBase = refEntity->e.shaderRGBA[0] * normalizeFactor; + + entityBlock.vertexLerp = 0.0f; + if (refEntity->e.oldframe || refEntity->e.frame) + if (refEntity->e.oldframe != refEntity->e.frame) + entityBlock.vertexLerp = refEntity->e.backlerp; + + entityBlock.entityTime = 0.0f; + if (refEntity != &tr.worldEntity) + entityBlock.entityTime = -refEntity->e.shaderTime; +} + +static void RB_UpdateSkyEntityConstants(gpuFrame_t *frame, const trRefdef_t *refdef) +{ + EntityBlock skyEntityBlock = {}; + skyEntityBlock.fxVolumetricBase = -1.0f; + + if (tr.world && tr.world->skyboxportal) + Matrix16Translation(tr.skyPortalParms.ori.origin, skyEntityBlock.modelMatrix); + else + Matrix16Translation(refdef->vieworg, skyEntityBlock.modelMatrix); + tr.skyEntityUboOffset = RB_AppendConstantsData( + frame, &skyEntityBlock, sizeof(skyEntityBlock)); +} + +static void ComputeDeformValues( + //const trRefEntity_t *refEntity, + const shader_t *shader, + deform_t *type, + genFunc_t *waveFunc, + vec4_t deformParams0, + vec4_t deformParams1) +{ + // u_DeformGen + *type = DEFORM_NONE; + *waveFunc = GF_NONE; + + // Handled via the CGEN_DISINTEGRATION_2 color gen, as both just happen at the same time + /*if (refEntity->e.renderfx & RF_DISINTEGRATE2) + { + *type = DEFORM_DISINTEGRATION; + return; + }*/ + + if (!ShaderRequiresCPUDeforms(shader)) + { + // only support the first one + const deformStage_t *ds = &shader->deforms[0]; + + switch (ds->deformation) + { + case DEFORM_WAVE: + *type = DEFORM_WAVE; + *waveFunc = ds->deformationWave.func; + + deformParams0[0] = ds->deformationWave.base; + deformParams0[1] = ds->deformationWave.amplitude; + deformParams0[2] = ds->deformationWave.phase; + deformParams0[3] = ds->deformationWave.frequency; + deformParams1[0] = ds->deformationSpread; + deformParams1[1] = 0.0f; + deformParams1[2] = 0.0f; + break; + + case DEFORM_BULGE: + *type = DEFORM_BULGE; + + deformParams0[0] = 0.0f; + deformParams0[1] = ds->bulgeHeight; // amplitude + deformParams0[2] = ds->bulgeWidth; // phase + deformParams0[3] = ds->bulgeSpeed; // frequency + deformParams1[0] = 0.0f; + deformParams1[1] = 0.0f; + deformParams1[2] = 0.0f; + + if (ds->bulgeSpeed == 0.0f && ds->bulgeWidth == 0.0f) + *type = DEFORM_BULGE_UNIFORM; + + break; + + case DEFORM_MOVE: + *type = DEFORM_MOVE; + *waveFunc = ds->deformationWave.func; + + deformParams0[0] = ds->deformationWave.base; + deformParams0[1] = ds->deformationWave.amplitude; + deformParams0[2] = ds->deformationWave.phase; + deformParams0[3] = ds->deformationWave.frequency; + deformParams1[0] = ds->moveVector[0]; + deformParams1[1] = ds->moveVector[1]; + deformParams1[2] = ds->moveVector[2]; + + break; + + case DEFORM_NORMALS: + *type = DEFORM_NORMALS; + + deformParams0[0] = 0.0f; + deformParams0[1] = ds->deformationWave.amplitude; // amplitude + deformParams0[2] = 0.0f; // phase + deformParams0[3] = ds->deformationWave.frequency; // frequency + deformParams1[0] = 0.0f; + deformParams1[1] = 0.0f; + deformParams1[2] = 0.0f; + break; + + case DEFORM_PROJECTION_SHADOW: + *type = DEFORM_PROJECTION_SHADOW; + /* + deformParams0[0] = backEnd.ori.axis[0][2]; + deformParams0[1] = backEnd.ori.axis[1][2]; + deformParams0[2] = backEnd.ori.axis[2][2]; + deformParams0[3] = backEnd.ori.origin[2] - refEntity->e.shadowPlane; + + vec3_t lightDir; + VectorCopy(refEntity->modelLightDir, lightDir); + lightDir[2] = 0.0f; + VectorNormalize(lightDir); + VectorSet(lightDir, lightDir[0] * 0.3f, lightDir[1] * 0.3f, 1.0f); + + deformParams1[0] = lightDir[0]; + deformParams1[1] = lightDir[1]; + deformParams1[2] = lightDir[2];*/ + break; + + default: + break; + } + } +} + +void RB_AddShaderToShaderInstanceUBO(shader_t *shader) +{ + if (shader->numDeforms != 1 && !shader->portalRange) + { + shader->ShaderInstanceUboOffset = -1; + return; + } + + ShaderInstanceBlock shaderInstanceBlock = {}; + ComputeDeformValues( + shader, + (deform_t *)&shaderInstanceBlock.deformType, + (genFunc_t *)&shaderInstanceBlock.deformFunc, + shaderInstanceBlock.deformParams0, + shaderInstanceBlock.deformParams1); + shaderInstanceBlock.portalRange = shader->portalRange; + shaderInstanceBlock.time = -shader->timeOffset; + + shader->ShaderInstanceUboOffset = RB_AddShaderInstanceBlock((void*)&shaderInstanceBlock); +} + +static void RB_UpdateEntityConstants( + gpuFrame_t *frame, const trRefdef_t *refdef) +{ + memset(tr.entityUboOffsets, 0, sizeof(tr.entityUboOffsets)); + for (int i = 0; i < refdef->num_entities; i++) + { + trRefEntity_t *ent = &refdef->entities[i]; + + R_SetupEntityLighting(refdef, ent); + + EntityBlock entityBlock = {}; + RB_UpdateEntityLightConstants(entityBlock, ent); + RB_UpdateEntityMatrixConstants(entityBlock, ent); + RB_UpdateEntityModelConstants(entityBlock, ent); + + tr.entityUboOffsets[i] = RB_AppendConstantsData( + frame, &entityBlock, sizeof(entityBlock)); + } + + const trRefEntity_t *ent = &tr.worldEntity; + EntityBlock entityBlock = {}; + RB_UpdateEntityLightConstants(entityBlock, ent); + RB_UpdateEntityMatrixConstants(entityBlock, ent); + RB_UpdateEntityModelConstants(entityBlock, ent); + + tr.entityUboOffsets[REFENTITYNUM_WORLD] = RB_AppendConstantsData( + frame, &entityBlock, sizeof(entityBlock)); + + RB_UpdateSkyEntityConstants(frame, refdef); +} + +static void RB_UpdateGhoul2Constants(gpuFrame_t *frame, const trRefdef_t *refdef) +{ + for (int i = 0; i < refdef->num_entities; i++) + { + const trRefEntity_t *ent = &refdef->entities[i]; + if (ent->e.reType != RT_MODEL) + continue; + + model_t *model = R_GetModelByHandle(ent->e.hModel); + if (!model) + continue; + + switch (model->type) + { + case MOD_MDXM: + case MOD_BAD: + { + // Transform Bones and upload them + RB_TransformBones(ent, refdef, backEndData->realFrameNumber, frame); + } + break; + + default: + break; + } + } +} + +void RB_UpdateConstants(const trRefdef_t *refdef) +{ + gpuFrame_t *frame = backEndData->currentFrame; + RB_BeginConstantsUpdate(frame); + + RB_UpdateCameraConstants(frame); + RB_UpdateSceneConstants(frame, refdef); + RB_UpdateLightsConstants(frame, refdef); + RB_UpdateFogsConstants(frame); + RB_UpdateGhoul2Constants(frame, refdef); + RB_UpdateEntityConstants(frame, refdef); + + RB_EndConstantsUpdate(frame); +} + +/* +============= +RB_DrawBuffer + +============= +*/ +static const void *RB_DrawBuffer( const void *data ) { + const drawBufferCommand_t *cmd; + + cmd = (const drawBufferCommand_t *)data; + + // finish any 2D drawing if needed + if(tess.numIndexes) + RB_EndSurface(); + + return (const void *)(cmd + 1); +} + +/* +=============== +RB_ShowImages + +Draw all the images to the screen, on top of whatever +was there. This is used to test for texture thrashing. + +Also called by RE_EndRegistration +=============== +*/ +void RB_ShowImages( void ) { + int i; + image_t *image; + float x, y, w, h; + int start, end; + + RB_SetGL2D(); + + qglClear( GL_COLOR_BUFFER_BIT ); + + qglFinish(); + + start = ri.Milliseconds(); + + image = tr.images; + for ( i=0 ; i < tr.numImages; i++, image = image->poolNext ) { + w = glConfig.vidWidth / 20; + h = glConfig.vidHeight / 15; + x = i % 20 * w; + y = i / 20 * h; + + // show in proportional size in mode 2 + if ( r_showImages->integer == 2 ) { + w *= image->uploadWidth / 512.0f; + h *= image->uploadHeight / 512.0f; + } + + { + vec4_t quadVerts[4]; + + GL_Bind(image); + + VectorSet4(quadVerts[0], x, y, 0, 1); + VectorSet4(quadVerts[1], x + w, y, 0, 1); + VectorSet4(quadVerts[2], x + w, y + h, 0, 1); + VectorSet4(quadVerts[3], x, y + h, 0, 1); + + RB_InstantQuad(quadVerts); + } + } + + qglFinish(); + + end = ri.Milliseconds(); + ri.Printf( PRINT_ALL, "%i msec to draw all images\n", end - start ); + +} + +/* +============= +RB_ColorMask + +============= +*/ +static const void *RB_ColorMask(const void *data) +{ + const colorMaskCommand_t *cmd = (colorMaskCommand_t *)data; + + // finish any 2D drawing if needed + RB_EndSurface(); + + // reverse color mask, so 0 0 0 0 is the default + backEnd.colorMask[0] = (qboolean)(!cmd->rgba[0]); + backEnd.colorMask[1] = (qboolean)(!cmd->rgba[1]); + backEnd.colorMask[2] = (qboolean)(!cmd->rgba[2]); + backEnd.colorMask[3] = (qboolean)(!cmd->rgba[3]); + + qglColorMask(cmd->rgba[0], cmd->rgba[1], cmd->rgba[2], cmd->rgba[3]); + + return (const void *)(cmd + 1); +} + +/* +============= +RB_ClearDepth + +============= +*/ +static const void *RB_ClearDepth(const void *data) +{ + const clearDepthCommand_t *cmd = (clearDepthCommand_t *)data; + + // finish any 2D drawing if needed + if(tess.numIndexes) + RB_EndSurface(); + + // texture swapping test + if (r_showImages->integer) + RB_ShowImages(); + + if (!tr.renderFbo || backEnd.framePostProcessed) + { + FBO_Bind(NULL); + } + else + { + FBO_Bind(tr.renderFbo); + } + + qglClear(GL_DEPTH_BUFFER_BIT); + + // if we're doing MSAA, clear the depth texture for the resolve buffer + if (tr.msaaResolveFbo) + { + FBO_Bind(tr.msaaResolveFbo); + qglClear(GL_DEPTH_BUFFER_BIT); + } + + + return (const void *)(cmd + 1); +} + + +/* +============= +RB_SwapBuffers + +============= +*/ +static const void *RB_SwapBuffers( const void *data ) { + const swapBuffersCommand_t *cmd; + + // finish any 2D drawing if needed + if ( tess.numIndexes ) { + RB_EndSurface(); + } + + ResetGhoul2RenderableSurfaceHeap(); + + // texture swapping test + if ( r_showImages->integer ) { + RB_ShowImages(); + } + + cmd = (const swapBuffersCommand_t *)data; + + // we measure overdraw by reading back the stencil buffer and + // counting up the number of increments that have happened + if ( r_measureOverdraw->integer ) { + int i; + long sum = 0; + unsigned char *stencilReadback; + + stencilReadback = (unsigned char *)ri.Hunk_AllocateTempMemory( glConfig.vidWidth * glConfig.vidHeight ); + qglReadPixels( 0, 0, glConfig.vidWidth, glConfig.vidHeight, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, stencilReadback ); + + for ( i = 0; i < glConfig.vidWidth * glConfig.vidHeight; i++ ) { + sum += stencilReadback[i]; + } + + backEnd.pc.c_overDraw += sum; + ri.Hunk_FreeTempMemory( stencilReadback ); + } + + if (!backEnd.framePostProcessed) + { + if (tr.msaaResolveFbo && r_hdr->integer) + { + // Resolving an RGB16F MSAA FBO to the screen messes with the brightness, so resolve to an RGB16F FBO first + FBO_FastBlit(tr.renderFbo, NULL, tr.msaaResolveFbo, NULL, GL_COLOR_BUFFER_BIT, GL_NEAREST); + FBO_FastBlit(tr.msaaResolveFbo, NULL, NULL, NULL, GL_COLOR_BUFFER_BIT, GL_NEAREST); + } + else if (tr.renderFbo) + { + FBO_FastBlit(tr.renderFbo, NULL, NULL, NULL, GL_COLOR_BUFFER_BIT, GL_NEAREST); + } + } + + if ( tr.numFramesToCapture > 0 ) + { + tr.numFramesToCapture--; + if ( !tr.numFramesToCapture ) + { + ri.Printf( PRINT_ALL, "Frames captured\n" ); + ri.FS_FCloseFile(tr.debugFile); + tr.debugFile = 0; + } + } + + R_NewFrameSync(); + + GLimp_LogComment( "***************** RB_SwapBuffers *****************\n\n\n" ); + + ri.WIN_Present( &window ); + + return (const void *)(cmd + 1); +} + +/* +============= +RB_PostProcess + +============= +*/ +const void *RB_PostProcess(const void *data) +{ + const postProcessCommand_t *cmd = (const postProcessCommand_t *)data; + FBO_t *srcFbo; + vec4i_t srcBox, dstBox; + qboolean autoExposure; + + // finish any 2D drawing if needed + if(tess.numIndexes) + RB_EndSurface(); + + if (cmd) + { + backEnd.refdef = cmd->refdef; + backEnd.viewParms = cmd->viewParms; + } + + srcFbo = tr.renderFbo; + if (tr.msaaResolveFbo) + { + // Resolve the MSAA before anything else + // Can't resolve just part of the MSAA FBO, so multiple views will suffer a performance hit here + FBO_FastBlit(tr.renderFbo, NULL, tr.msaaResolveFbo, NULL, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + srcFbo = tr.msaaResolveFbo; + + if ( r_dynamicGlow->integer ) + { + FBO_FastBlitIndexed(tr.renderFbo, tr.msaaResolveFbo, 1, 1, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + } + + dstBox[0] = backEnd.viewParms.viewportX; + dstBox[1] = backEnd.viewParms.viewportY; + dstBox[2] = backEnd.viewParms.viewportWidth; + dstBox[3] = backEnd.viewParms.viewportHeight; + +#if 0 + if (r_ssao->integer) + { + srcBox[0] = backEnd.viewParms.viewportX * tr.screenSsaoImage->width / (float)glConfig.vidWidth; + srcBox[1] = backEnd.viewParms.viewportY * tr.screenSsaoImage->height / (float)glConfig.vidHeight; + srcBox[2] = backEnd.viewParms.viewportWidth * tr.screenSsaoImage->width / (float)glConfig.vidWidth; + srcBox[3] = backEnd.viewParms.viewportHeight * tr.screenSsaoImage->height / (float)glConfig.vidHeight; + + //FBO_BlitFromTexture(tr.screenSsaoImage, srcBox, NULL, srcFbo, dstBox, NULL, NULL, GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO); + srcBox[1] = tr.screenSsaoImage->height - srcBox[1]; + srcBox[3] = -srcBox[3]; + + int blendMode = GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO; + if (r_ssao->integer == 2) + blendMode = GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO; + + FBO_Blit(tr.screenSsaoFbo, srcBox, NULL, srcFbo, dstBox, NULL, NULL, blendMode); + } +#endif + + if (r_dynamicGlow->integer) + { + RB_BloomDownscale(tr.glowImage, tr.glowFboScaled[0]); + int numPasses = Com_Clampi(1, ARRAY_LEN(tr.glowFboScaled), r_dynamicGlowPasses->integer); + for ( int i = 1; i < numPasses; i++ ) + RB_BloomDownscale(tr.glowFboScaled[i - 1], tr.glowFboScaled[i]); + + for ( int i = numPasses - 2; i >= 0; i-- ) + RB_BloomUpscale(tr.glowFboScaled[i + 1], tr.glowFboScaled[i]); + } + srcBox[0] = backEnd.viewParms.viewportX; + srcBox[1] = backEnd.viewParms.viewportY; + srcBox[2] = backEnd.viewParms.viewportWidth; + srcBox[3] = backEnd.viewParms.viewportHeight; + + if (srcFbo) + { + if (r_hdr->integer && (r_toneMap->integer || r_forceToneMap->integer)) + { + autoExposure = (qboolean)(r_autoExposure->integer || r_forceAutoExposure->integer); + RB_ToneMap(srcFbo, srcBox, NULL, dstBox, autoExposure); + } + else if (r_cameraExposure->value == 0.0f) + { + FBO_FastBlit(srcFbo, srcBox, NULL, dstBox, GL_COLOR_BUFFER_BIT, GL_NEAREST); + } + else + { + vec4_t color; + + color[0] = + color[1] = + color[2] = pow(2, r_cameraExposure->value); //exp2(r_cameraExposure->value); + color[3] = 1.0f; + + FBO_Blit(srcFbo, srcBox, NULL, NULL, dstBox, NULL, color, 0); + } + + // Copy depth buffer to the backbuffer for depth culling refractive surfaces + FBO_FastBlit(tr.renderFbo, srcBox, NULL, dstBox, GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_NEAREST); + } + + if (r_drawSunRays->integer) + RB_SunRays(NULL, srcBox, NULL, dstBox); + +#if 0 + if (backEnd.refdef.blurFactor > 0.0f) + RB_BokehBlur(NULL, srcBox, NULL, dstBox, backEnd.refdef.blurFactor); +#endif + + if (r_debugWeather->integer == 2) + { + FBO_BlitFromTexture(tr.weatherDepthImage, NULL, NULL, NULL, nullptr, NULL, NULL, 0); + } + + if (0) + { + vec4i_t dstBox; + VectorSet4(dstBox, 256, glConfig.vidHeight - 256, 256, 256); + FBO_BlitFromTexture(tr.renderDepthImage, NULL, NULL, NULL, dstBox, NULL, NULL, 0); + VectorSet4(dstBox, 512, glConfig.vidHeight - 256, 256, 256); + FBO_BlitFromTexture(tr.screenShadowImage, NULL, NULL, NULL, dstBox, NULL, NULL, 0); + } + + if (0 && r_ssao->integer) + { + vec4i_t dstBox; + VectorSet4(dstBox, 0, glConfig.vidHeight, 512, -512); + FBO_BlitFromTexture(tr.screenSsaoImage, NULL, NULL, NULL, dstBox, NULL, NULL, 0); + VectorSet4(dstBox, 512, glConfig.vidHeight, 512, -512); + FBO_BlitFromTexture(tr.quarterImage[0], NULL, NULL, NULL, dstBox, NULL, NULL, 0); + VectorSet4(dstBox, 1024, glConfig.vidHeight, 512, -512); + FBO_BlitFromTexture(tr.quarterImage[1], NULL, NULL, NULL, dstBox, NULL, NULL, 0); + } + + if (0) + { + vec4i_t dstBox; + VectorSet4(dstBox, 256, glConfig.vidHeight - 256, 256, 256); + FBO_BlitFromTexture(tr.sunRaysImage, NULL, NULL, NULL, dstBox, NULL, NULL, 0); + } + +#if 0 + if (r_cubeMapping->integer && tr.numCubemaps) + { + vec4i_t dstBox; + int cubemapIndex = R_CubemapForPoint( backEnd.viewParms.ori.origin ); + + if (cubemapIndex) + { + VectorSet4(dstBox, 0, glConfig.vidHeight - 256, 256, 256); + //FBO_BlitFromTexture(tr.renderCubeImage, NULL, NULL, NULL, dstBox, &tr.testcubeShader, NULL, 0); + FBO_BlitFromTexture(tr.cubemaps[cubemapIndex - 1], NULL, NULL, NULL, dstBox, &tr.testcubeShader, NULL, 0); + } + } +#endif + + if (r_dynamicGlow->integer != 0) + { + // Composite the glow/bloom texture + int blendFunc = 0; + vec4_t color = { 1.0f, 1.0f, 1.0f, 1.0f }; + + if ( r_dynamicGlow->integer == 2 ) + { + // Debug output + blendFunc = GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO; + } + else if ( r_dynamicGlowSoft->integer ) + { + blendFunc = GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE_MINUS_SRC_COLOR; + color[0] = color[1] = color[2] = r_dynamicGlowIntensity->value; + } + else + { + blendFunc = GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; + color[0] = color[1] = color[2] = r_dynamicGlowIntensity->value; + } + + FBO_BlitFromTexture (tr.glowFboScaled[0]->colorImage[0], NULL, NULL, NULL, NULL, NULL, color, blendFunc); + } + + backEnd.framePostProcessed = qtrue; + FBO_Bind(NULL); + backEnd.refractionFill = qtrue; + RB_RenderDrawSurfList( + backEnd.refdef.drawSurfs + backEnd.refdef.fistDrawSurf, + backEnd.refdef.numDrawSurfs - tr.refdef.fistDrawSurf); + backEnd.refractionFill = qfalse; + + return (const void *)(cmd + 1); +} + +static const void *RB_BeginTimedBlock( const void *data ) +{ + const beginTimedBlockCommand_t *cmd = (const beginTimedBlockCommand_t *)data; + if ( glRefConfig.timerQuery ) + { + gpuFrame_t *currentFrame = &backEndData->frames[backEndData->realFrameNumber % MAX_FRAMES]; + gpuTimer_t *timer = currentFrame->timers + currentFrame->numTimers++; + + if ( cmd->timerHandle >= 0 && currentFrame->numTimers <= MAX_GPU_TIMERS ) + { + gpuTimedBlock_t *timedBlock = currentFrame->timedBlocks + cmd->timerHandle; + timedBlock->beginTimer = timer->queryName; + timedBlock->name = cmd->name; + + currentFrame->numTimedBlocks++; + + qglQueryCounter( timer->queryName, GL_TIMESTAMP ); + } + } + + return (const void *)(cmd + 1); +} + +static const void *RB_EndTimedBlock( const void *data ) +{ + const endTimedBlockCommand_t *cmd = (const endTimedBlockCommand_t *)data; + if ( glRefConfig.timerQuery ) + { + gpuFrame_t *currentFrame = &backEndData->frames[backEndData->realFrameNumber % MAX_FRAMES]; + gpuTimer_t *timer = currentFrame->timers + currentFrame->numTimers++; + + if ( cmd->timerHandle >= 0 && currentFrame->numTimers <= MAX_GPU_TIMERS ) + { + gpuTimedBlock_t *timedBlock = currentFrame->timedBlocks + cmd->timerHandle; + timedBlock->endTimer = timer->queryName; + + qglQueryCounter( timer->queryName, GL_TIMESTAMP ); + } + } + + return (const void *)(cmd + 1); +} + + +/* +============= +RB_DrawSurfs + +============= +*/ +static const void *RB_DrawSurfs(const void *data) { + const drawSurfsCommand_t *cmd; + + // finish any 2D drawing if needed + if (tess.numIndexes) { + RB_EndSurface(); + } + + cmd = (const drawSurfsCommand_t *)data; + + backEnd.refdef = cmd->refdef; + backEnd.viewParms = cmd->viewParms; + + // clear the z buffer, set the modelview, etc + RB_BeginDrawingView(); + + if (cmd->numDrawSurfs > 0) + { + RB_RenderAllDepthRelatedPasses(cmd->drawSurfs, cmd->numDrawSurfs); + + RB_RenderMainPass(cmd->drawSurfs, cmd->numDrawSurfs); + } + + return (const void *)(cmd + 1); +} + + +/* +==================== +RB_ExecuteRenderCommands +==================== +*/ +void RB_ExecuteRenderCommands( const void *data ) { + int t1, t2; + + t1 = ri.Milliseconds (); + + while ( 1 ) { + data = PADP(data, sizeof(void *)); + + switch ( *(const int *)data ) { + case RC_SET_COLOR: + data = RB_SetColor( data ); + break; + case RC_STRETCH_PIC: + data = RB_StretchPic( data ); + break; + case RC_ROTATE_PIC: + data = RB_RotatePic( data ); + break; + case RC_ROTATE_PIC2: + data = RB_RotatePic2( data ); + break; + case RC_DRAW_SURFS: + data = RB_DrawSurfs( data ); + break; + case RC_DRAW_BUFFER: + data = RB_DrawBuffer( data ); + break; + case RC_SWAP_BUFFERS: + data = RB_SwapBuffers( data ); + break; + case RC_SCREENSHOT: + data = RB_TakeScreenshotCmd( data ); + break; + case RC_VIDEOFRAME: + data = RB_TakeVideoFrameCmd( data ); + break; + case RC_COLORMASK: + data = RB_ColorMask(data); + break; + case RC_CLEARDEPTH: + data = RB_ClearDepth(data); + break; + case RC_CONVOLVECUBEMAP: + data = RB_PrefilterEnvMap( data ); + break; + case RC_POSTPROCESS: + data = RB_PostProcess(data); + break; + case RC_BEGIN_TIMED_BLOCK: + data = RB_BeginTimedBlock(data); + break; + case RC_END_TIMED_BLOCK: + data = RB_EndTimedBlock(data); + break; + case RC_END_OF_LIST: + default: + // finish any 2D drawing if needed + if(tess.numIndexes) + RB_EndSurface(); + + // stop rendering + t2 = ri.Milliseconds (); + backEnd.pc.msec = t2 - t1; + return; + } + } + +} + diff --git a/codemp/rd-rend2/tr_bsp.cpp b/codemp/rd-rend2/tr_bsp.cpp new file mode 100644 index 0000000000..0df88ddf5c --- /dev/null +++ b/codemp/rd-rend2/tr_bsp.cpp @@ -0,0 +1,4420 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_map.c + +#include "tr_local.h" + +#define JSON_IMPLEMENTATION +#include "json.h" +#undef JSON_IMPLEMENTATION + +#include "tr_cache.h" +#include "tr_weather.h" +#include + +#include + +/* + +Loads and prepares a map file for scene rendering. + +A single entry point: + +void RE_LoadWorldMap( const char *name ); + +*/ + +static world_t s_worldData; +static byte *fileBase; + +//=============================================================================== + +static void HSVtoRGB( float h, float s, float v, float rgb[3] ) +{ + int i; + float f; + float p, q, t; + + h *= 5; + + i = floor( h ); + f = h - i; + + p = v * ( 1 - s ); + q = v * ( 1 - s * f ); + t = v * ( 1 - s * ( 1 - f ) ); + + switch ( i ) + { + case 0: + rgb[0] = v; + rgb[1] = t; + rgb[2] = p; + break; + case 1: + rgb[0] = q; + rgb[1] = v; + rgb[2] = p; + break; + case 2: + rgb[0] = p; + rgb[1] = v; + rgb[2] = t; + break; + case 3: + rgb[0] = p; + rgb[1] = q; + rgb[2] = v; + break; + case 4: + rgb[0] = t; + rgb[1] = p; + rgb[2] = v; + break; + case 5: + rgb[0] = v; + rgb[1] = p; + rgb[2] = q; + break; + } +} + +/* +=============== +R_ColorShiftLightingBytes + +=============== +*/ +static void R_ColorShiftLightingBytes( byte in[4], byte out[4] ) { + int shift, r, g, b; + + // shift the color data based on overbright range + shift = Q_max( 0, r_mapOverBrightBits->integer - tr.overbrightBits ); + + // shift the data based on overbright range + r = in[0] << shift; + g = in[1] << shift; + b = in[2] << shift; + + // normalize by color instead of saturating to white + if ( ( r | g | b ) > 255 ) { + int max; + + max = r > g ? r : g; + max = max > b ? max : b; + r = r * 255 / max; + g = g * 255 / max; + b = b * 255 / max; + } + + out[0] = r; + out[1] = g; + out[2] = b; + out[3] = in[3]; +} + + +/* +=============== +R_ColorShiftLightingFloats + +=============== +*/ +static void R_ColorShiftLightingFloats(float in[4], float out[4], float scale, bool overbrightBits = true ) +{ + float r, g, b; + + if (overbrightBits) + scale *= pow(2.0f, r_mapOverBrightBits->integer - tr.overbrightBits); + + r = in[0] * scale; + g = in[1] * scale; + b = in[2] * scale; + + if (!glRefConfig.floatLightmap) + { + if (r > 1.0f || g > 1.0f || b > 1.0f) + { + float high = Q_max(Q_max(r, g), b); + + r /= high; + g /= high; + b /= high; + } + } + + out[0] = r; + out[1] = g; + out[2] = b; + out[3] = in[3]; +} + +void ColorToRGBA16F(const vec3_t color, unsigned short rgba16f[4]) +{ + rgba16f[0] = FloatToHalf(color[0]); + rgba16f[1] = FloatToHalf(color[1]); + rgba16f[2] = FloatToHalf(color[2]); + rgba16f[3] = FloatToHalf(1.0f); +} + +/* +=============== +R_LoadLightmaps + +=============== +*/ +#define DEFAULT_LIGHTMAP_SIZE 128 +#define MAX_LIGHTMAP_PAGES 2 +static void R_LoadLightmaps( world_t *worldData, lump_t *l, lump_t *surfs ) { + byte *buf, *buf_p; + dsurface_t *surf; + int len; + byte *image; + int imageSize; + int i, j, numLightmaps = 0, textureInternalFormat = 0; + float maxIntensity = 0; + double sumIntensity = 0; + int numColorComponents = 3; + + bool hdr_capable = glRefConfig.floatLightmap && r_hdr->integer; + + tr.lightmapSize = DEFAULT_LIGHTMAP_SIZE; + tr.hdrLighting = qfalse; + tr.worldInternalLightmapping = qfalse; + + len = l->filelen; + // test for external lightmaps + if (!len) { + for (i = 0, surf = (dsurface_t *)(fileBase + surfs->fileofs); + i < surfs->filelen / sizeof(dsurface_t); + i++, surf++) { + for (int j = 0; j < MAXLIGHTMAPS; j++) + { + numLightmaps = MAX(numLightmaps, LittleLong(surf->lightmapNum[j]) + 1); + } + } + buf = NULL; + } + else + { + numLightmaps = len / (tr.lightmapSize * tr.lightmapSize * 3); + buf = fileBase + l->fileofs; + tr.worldInternalLightmapping = qtrue; + } + + if (numLightmaps == 0) + return; + + // test for hdr lighting + if (hdr_capable && tr.worldInternalLightmapping) + { + char filename[MAX_QPATH]; + byte *externalLightmap = NULL; + int lightmapWidth = tr.lightmapSize; + int lightmapHeight = tr.lightmapSize; + Com_sprintf(filename, sizeof(filename), "maps/%s/lm_%04d.hdr", worldData->baseName, 0); + R_LoadHDRImage(filename, &externalLightmap, &lightmapWidth, &lightmapHeight); + if (externalLightmap != NULL) + { + tr.worldInternalLightmapping = qfalse; + ri.Hunk_FreeTempMemory(externalLightmap); + } + } + + // we are about to upload textures + R_IssuePendingRenderCommands(); + + // check for deluxe mapping + if (numLightmaps <= 1) + { + tr.worldDeluxeMapping = qfalse; + } + else + { + tr.worldDeluxeMapping = qtrue; + tr.worldInternalDeluxeMapping = qtrue; + // Check that none of the deluxe maps are referenced by any of the map surfaces. + for (i = 0, surf = (dsurface_t *)(fileBase + surfs->fileofs); + tr.worldDeluxeMapping && i < surfs->filelen / sizeof(dsurface_t); + i++, surf++) { + for (int j = 0; j < MAXLIGHTMAPS; j++) + { + int lightmapNum = LittleLong(surf->lightmapNum[j]); + + if (lightmapNum >= 0 && (lightmapNum & 1) != 0) { + tr.worldDeluxeMapping = qfalse; + tr.worldInternalDeluxeMapping = qfalse; + break; + } + } + } + if (tr.worldDeluxeMapping == qtrue && (!len)) + numLightmaps++; + } + + imageSize = tr.lightmapSize * tr.lightmapSize * 4 * 2; + image = (byte *)Z_Malloc(imageSize, TAG_BSP, qfalse); + + if (tr.worldDeluxeMapping) + numLightmaps >>= 1; + + if (tr.worldInternalLightmapping) + { + const int targetLightmapsPerX = (int)ceilf(sqrtf(numLightmaps)); + + int lightmapsPerX = 1; + while (lightmapsPerX < targetLightmapsPerX) + lightmapsPerX *= 2; + + tr.lightmapsPerAtlasSide[0] = lightmapsPerX; + tr.lightmapsPerAtlasSide[1] = (int)ceilf((float)numLightmaps / lightmapsPerX); + + tr.lightmapAtlasSize[0] = tr.lightmapsPerAtlasSide[0] * LIGHTMAP_WIDTH; + tr.lightmapAtlasSize[1] = tr.lightmapsPerAtlasSide[1] * LIGHTMAP_HEIGHT; + + // FIXME: What happens if we need more? + tr.numLightmaps = 1; + } + else + { + tr.numLightmaps = numLightmaps; + } + + tr.lightmaps = (image_t **)ri.Hunk_Alloc( tr.numLightmaps * sizeof(image_t *), h_low ); + + if (tr.worldDeluxeMapping) + { + tr.deluxemaps = (image_t **)ri.Hunk_Alloc( tr.numLightmaps * sizeof(image_t *), h_low ); + } + + if (hdr_capable) + textureInternalFormat = GL_RGBA16F; + else + textureInternalFormat = GL_RGBA8; + + if (tr.worldInternalLightmapping) + { + for (i = 0; i < tr.numLightmaps; i++) + { + tr.lightmaps[i] = R_CreateImage( + va("_lightmapatlas%d", i), + NULL, + tr.lightmapAtlasSize[0], + tr.lightmapAtlasSize[1], + IMGTYPE_COLORALPHA, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, + textureInternalFormat); + + if (tr.worldDeluxeMapping) + { + tr.deluxemaps[i] = R_CreateImage( + va("_fatdeluxemap%d", i), + NULL, + tr.lightmapAtlasSize[0], + tr.lightmapAtlasSize[1], + IMGTYPE_DELUXE, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, + 0); + } + } + } + + for (i = 0; i < numLightmaps; i++) + { + int xoff = 0, yoff = 0; + int lightmapnum = i; + // expand the 24 bit on-disk to 32 bit + + if (tr.worldInternalLightmapping) + { + xoff = (i % tr.lightmapsPerAtlasSide[0]) * tr.lightmapSize; + yoff = (i / tr.lightmapsPerAtlasSide[0]) * tr.lightmapSize; + lightmapnum = 0; + } + + // if (tr.worldLightmapping) + { + char filename[MAX_QPATH]; + byte *externalLightmap = NULL; + float *hdrL = NULL; + int lightmapWidth = tr.lightmapSize; + int lightmapHeight = tr.lightmapSize; + int bppc; + bool foundLightmap = true; + + if (!tr.worldInternalLightmapping) + { + if (hdr_capable) + Com_sprintf(filename, sizeof(filename), "maps/%s/lm_%04d.hdr", worldData->baseName, i * (tr.worldDeluxeMapping ? 2 : 1)); + else + Com_sprintf(filename, sizeof(filename), "maps/%s/lm_%04d.tga", worldData->baseName, i * (tr.worldDeluxeMapping ? 2 : 1)); + + bppc = 16; + R_LoadHDRImage(filename, &externalLightmap, &lightmapWidth, &lightmapHeight); + if (!externalLightmap) + { + bppc = 8; + R_LoadImage(filename, &externalLightmap, &lightmapWidth, &lightmapHeight); + } + } + + if (externalLightmap) + { + int newImageSize = lightmapWidth * lightmapHeight * 4 * 2; + if (tr.worldInternalLightmapping && (lightmapWidth != tr.lightmapSize || lightmapHeight != tr.lightmapSize)) + { + ri.Printf(PRINT_ALL, "Error loading %s: non %dx%d lightmaps\n", filename, tr.lightmapSize, tr.lightmapSize); + Z_Free(externalLightmap); + externalLightmap = NULL; + continue; + } + else if (newImageSize > imageSize) + { + Z_Free(image); + imageSize = newImageSize; + image = (byte *)Z_Malloc(imageSize, TAG_BSP, qfalse); + } + numColorComponents = 4; + } + if (!externalLightmap) + { + lightmapWidth = tr.lightmapSize; + lightmapHeight = tr.lightmapSize; + numColorComponents = 3; + } + + foundLightmap = true; + if (externalLightmap) + { + if (bppc > 8) + { + hdrL = (float *)externalLightmap; + tr.hdrLighting = qtrue; + } + else + { + buf_p = externalLightmap; + } + } + else if (buf) + { + if (tr.worldDeluxeMapping) + buf_p = buf + (i * 2) * tr.lightmapSize * tr.lightmapSize * 3; + else + buf_p = buf + i * tr.lightmapSize * tr.lightmapSize * 3; + } + else + { + buf_p = NULL; + foundLightmap = false; + } + + if (foundLightmap) + { + for (j = 0; j < lightmapWidth * lightmapHeight; j++) + { + if (hdrL && hdr_capable) + { + vec4_t color; + int column = (j % lightmapWidth); + int rowIndex = (int)floor(j / lightmapHeight) * lightmapHeight; + + int index = column + rowIndex; + + memcpy(color, &hdrL[index * 3], 12); + + color[3] = 1.0f; + + R_ColorShiftLightingFloats(color, color, 1.0f / M_PI, false); + + ColorToRGBA16F(color, (uint16_t *)(&image[j * 8])); + } + else if (buf_p && hdr_capable) + { + vec4_t color; + + //hack: convert LDR lightmap to HDR one + color[0] = MAX(buf_p[j*numColorComponents + 0], 0.499f); + color[1] = MAX(buf_p[j*numColorComponents + 1], 0.499f); + color[2] = MAX(buf_p[j*numColorComponents + 2], 0.499f); + + // if under an arbitrary value (say 12) grey it out + // this prevents weird splotches in dimly lit areas + if (color[0] + color[1] + color[2] < 12.0f) + { + float avg = (color[0] + color[1] + color[2]) * 0.3333f; + color[0] = avg; + color[1] = avg; + color[2] = avg; + } + color[3] = 1.0f; + + R_ColorShiftLightingFloats(color, color, 1.0f / 255.0f); + + ColorToRGBA16F(color, (unsigned short *)(&image[j * 8])); + } + else if (buf_p) + { + if (r_lightmap->integer == 2) + { // color code by intensity as development tool (FIXME: check range) + float r = buf_p[j*numColorComponents + 0]; + float g = buf_p[j*numColorComponents + 1]; + float b = buf_p[j*numColorComponents + 2]; + float intensity; + float out[3] = { 0.0, 0.0, 0.0 }; + + intensity = 0.33f * r + 0.685f * g + 0.063f * b; + + if (intensity > 255) + intensity = 1.0f; + else + intensity /= 255.0f; + + if (intensity > maxIntensity) + maxIntensity = intensity; + + HSVtoRGB(intensity, 1.00, 0.50, out); + + image[j * 4 + 0] = out[0] * 255; + image[j * 4 + 1] = out[1] * 255; + image[j * 4 + 2] = out[2] * 255; + image[j * 4 + 3] = 255; + + sumIntensity += intensity; + } + else + { + R_ColorShiftLightingBytes(&buf_p[j * numColorComponents], &image[j * 4]); + image[j * 4 + 3] = 255; + } + } + } + + if (tr.worldInternalLightmapping) + R_UpdateSubImage( + tr.lightmaps[lightmapnum], + image, + xoff, + yoff, + lightmapWidth, + lightmapHeight); + else + tr.lightmaps[i] = R_CreateImage( + va("*lightmap%d", i), + image, + lightmapWidth, + lightmapHeight, + IMGTYPE_COLORALPHA, + IMGFLAG_NOLIGHTSCALE | + IMGFLAG_NO_COMPRESSION | + IMGFLAG_CLAMPTOEDGE, + textureInternalFormat); + } + + if (externalLightmap) + Z_Free(externalLightmap); + } + + if (tr.worldDeluxeMapping && buf) + { + buf_p = buf + (i * 2 + 1) * tr.lightmapSize * tr.lightmapSize * 3; + + for (j = 0; j < tr.lightmapSize * tr.lightmapSize; j++) { + image[j * 4 + 0] = buf_p[j * 3 + 0]; + image[j * 4 + 1] = buf_p[j * 3 + 1]; + image[j * 4 + 2] = buf_p[j * 3 + 2]; + + // make 0,0,0 into 127,127,127 + if ((image[j * 4 + 0] == 0) && (image[j * 4 + 1] == 0) && (image[j * 4 + 2] == 0)) + { + image[j*4+0] = + image[j*4+1] = + image[j*4+2] = 127; + } + + image[j * 4 + 3] = 255; + } + + if (tr.worldInternalLightmapping) + { + R_UpdateSubImage( + tr.deluxemaps[lightmapnum], + image, + xoff, + yoff, + tr.lightmapSize, + tr.lightmapSize); + } + else + { + tr.deluxemaps[i] = R_CreateImage( + va("*deluxemap%d", i), + image, + tr.lightmapSize, + tr.lightmapSize, + IMGTYPE_DELUXE, + IMGFLAG_NOLIGHTSCALE | + IMGFLAG_NO_COMPRESSION | + IMGFLAG_CLAMPTOEDGE, + 0); + } + } + else if (r_deluxeMapping->integer) + { + char filename[MAX_QPATH]; + byte *externalLightmap = NULL; + int lightmapWidth = tr.lightmapSize; + int lightmapHeight = tr.lightmapSize; + + // try loading additional deluxemaps + if (tr.worldDeluxeMapping) + Com_sprintf(filename, sizeof(filename), "maps/%s/lm_%04d.tga", worldData->baseName, i * 2 + 1); + else + Com_sprintf(filename, sizeof(filename), "maps/%s/dm_%04d.tga", worldData->baseName, i); + + R_LoadImage(filename, &externalLightmap, &lightmapWidth, &lightmapHeight); + if (!externalLightmap) + continue; + + if (tr.worldInternalLightmapping && (lightmapWidth != tr.lightmapSize || lightmapHeight != tr.lightmapSize)) + { + ri.Printf(PRINT_ALL, "Error loading %s: non %dx%d deluxemaps\n", filename, tr.lightmapSize, tr.lightmapSize); + Z_Free(externalLightmap); + externalLightmap = NULL; + continue; + } + + int newImageSize = lightmapWidth * lightmapHeight * 4 * 2; + if (newImageSize > imageSize) + { + Z_Free(image); + imageSize = newImageSize; + image = (byte *)Z_Malloc(imageSize, TAG_BSP, qfalse); + } + + buf_p = externalLightmap; + + for (j = 0; j < lightmapWidth * lightmapHeight; j++) { + image[j * 4 + 0] = buf_p[j * 4 + 0]; + image[j * 4 + 1] = buf_p[j * 4 + 1]; + image[j * 4 + 2] = buf_p[j * 4 + 2]; + + // make 0,0,0 into 127,127,127 + if ((image[j * 4 + 0] == 0) && (image[j * 4 + 1] == 0) && (image[j * 4 + 2] == 0)) + { + image[j * 4 + 0] = + image[j * 4 + 1] = + image[j * 4 + 2] = 127; + } + + image[j * 4 + 3] = 255; + } + + if (!tr.deluxemaps) + { + tr.deluxemaps = (image_t **)ri.Hunk_Alloc(tr.numLightmaps * sizeof(image_t *), h_low); + if (tr.worldInternalLightmapping) + { + tr.deluxemaps[lightmapnum] = R_CreateImage( + va("_fatdeluxemap%d", i), + NULL, + tr.lightmapAtlasSize[0], + tr.lightmapAtlasSize[1], + IMGTYPE_DELUXE, + IMGFLAG_NOLIGHTSCALE | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, + 0); + } + } + + if (tr.worldInternalLightmapping) + { + R_UpdateSubImage( + tr.deluxemaps[lightmapnum], + image, + xoff, + yoff, + lightmapWidth, + lightmapHeight); + } + else + { + tr.deluxemaps[i] = R_CreateImage( + va("*deluxemap%d", i), + image, + lightmapWidth, + lightmapHeight, + IMGTYPE_DELUXE, + IMGFLAG_NOLIGHTSCALE | + IMGFLAG_NO_COMPRESSION | + IMGFLAG_CLAMPTOEDGE, + 0); + } + + Z_Free(externalLightmap); + externalLightmap = NULL; + } + } + + if ( r_lightmap->integer == 2 ) { + ri.Printf( PRINT_ALL, "Brightest lightmap value: %d\n", ( int ) ( maxIntensity * 255 ) ); + } + + Z_Free(image); + + if (tr.deluxemaps) + tr.worldDeluxeMapping = qtrue; + } + + +static float FatPackU(float input, int lightmapnum) +{ + if (lightmapnum < 0) + return input; + + if (tr.worldInternalDeluxeMapping) + lightmapnum >>= 1; + + if (tr.lightmapAtlasSize[0] > 0) + { + const int lightmapXOffset = lightmapnum % tr.lightmapsPerAtlasSide[0]; + const float invLightmapSide = 1.0f / tr.lightmapsPerAtlasSide[0]; + + return (lightmapXOffset * invLightmapSide) + (input * invLightmapSide); + } + + return input; +} + +static float FatPackV(float input, int lightmapnum) +{ + if (lightmapnum < 0) + return input; + + if (tr.worldInternalDeluxeMapping) + lightmapnum >>= 1; + + if (tr.lightmapAtlasSize[1] > 0) + { + const int lightmapYOffset = lightmapnum / tr.lightmapsPerAtlasSide[0]; + const float invLightmapSide = 1.0f / tr.lightmapsPerAtlasSide[1]; + + return (lightmapYOffset * invLightmapSide) + (input * invLightmapSide); + } + + return input; +} + + +static int FatLightmap(int lightmapnum) +{ + if (lightmapnum < 0) + return lightmapnum; + + if (tr.worldInternalDeluxeMapping) + lightmapnum >>= 1; + + if (tr.lightmapAtlasSize[0] > 0) + return 0; + + return lightmapnum; +} + +/* +================= +RE_SetWorldVisData + +This is called by the clipmodel subsystem so we can share the 1.8 megs of +space in big maps... +================= +*/ +void RE_SetWorldVisData( const byte *vis ) { + tr.externalVisData = vis; +} + + +/* +================= +R_LoadVisibility +================= +*/ +static void R_LoadVisibility( world_t *worldData, lump_t *l ) { + int len; + byte *buf; + + len = (worldData->numClusters + 63) & ~63; + worldData->novis = (byte *)ri.Hunk_Alloc(len, h_low); + Com_Memset(worldData->novis, 0xff, len); + + len = l->filelen; + if ( !len ) { + return; + } + buf = fileBase + l->fileofs; + + worldData->numClusters = LittleLong( ((int *)buf)[0] ); + worldData->clusterBytes = LittleLong( ((int *)buf)[1] ); + + // CM_Load should have given us the vis data to share, so + // we don't need to allocate another copy + if ( tr.externalVisData ) { + worldData->vis = tr.externalVisData; + } else { + byte *dest; + + dest = (byte *)ri.Hunk_Alloc( len - 8, h_low ); + Com_Memcpy( dest, buf + 8, len - 8 ); + worldData->vis = dest; + } +} + +//=============================================================================== + + +/* +=============== +ShaderForShaderNum +=============== +*/ +static shader_t *ShaderForShaderNum( const world_t *worldData, int shaderNum, const int *lightmapNums, const byte *lightmapStyles, const byte *vertexStyles ) { + shader_t *shader; + dshader_t *dsh; + const byte *styles = lightmapStyles; + + int _shaderNum = LittleLong( shaderNum ); + if ( _shaderNum < 0 || _shaderNum >= worldData->numShaders ) { + ri.Error( ERR_DROP, "ShaderForShaderNum: bad num %i", _shaderNum ); + } + dsh = &worldData->shaders[ _shaderNum ]; + + if ( lightmapNums[0] == LIGHTMAP_BY_VERTEX ) { + styles = vertexStyles; + } + + if ( r_vertexLight->integer ) { + lightmapNums = lightmapsVertex; + styles = vertexStyles; + } + + if ( r_fullbright->integer ) { + lightmapNums = lightmapsFullBright; + } + + shader = R_FindShader( dsh->shader, lightmapNums, styles, qtrue ); + + // if the shader had errors, just use default shader + if ( shader->defaultShader ) { + return tr.defaultShader; + } + + return shader; +} + +/* +=============== +ParseFace +=============== +*/ +static void ParseFace( const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, msurface_t *surf, int *indexes ) { + int i, j; + srfBspSurface_t *cv; + glIndex_t *tri; + int numVerts, numIndexes, badTriangles; + int realLightmapNum[MAXLIGHTMAPS]; + + for ( j = 0; j < MAXLIGHTMAPS; j++ ) + { + realLightmapNum[j] = FatLightmap (LittleLong (ds->lightmapNum[j])); + } + + surf->numSurfaceSprites = 0; + surf->surfaceSprites = nullptr; + + // get fog volume + surf->fogIndex = LittleLong( ds->fogNum ) + 1; + if (!surf->fogIndex && worldData->globalFog != nullptr) + { + surf->fogIndex = worldData->globalFogIndex; + } + + // get shader value + surf->shader = ShaderForShaderNum( worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles); + if ( r_singleShader->integer && !surf->shader->isSky ) { + surf->shader = tr.defaultShader; + } + + numVerts = LittleLong(ds->numVerts); + numIndexes = LittleLong(ds->numIndexes); + + //cv = ri.Hunk_Alloc(sizeof(*cv), h_low); + cv = (srfBspSurface_t *)surf->data; + cv->surfaceType = SF_FACE; + + cv->numIndexes = numIndexes; + cv->indexes = (glIndex_t *)ri.Hunk_Alloc(numIndexes * sizeof(cv->indexes[0]), h_low); + + cv->numVerts = numVerts; + cv->verts = (srfVert_t *)ri.Hunk_Alloc(numVerts * sizeof(cv->verts[0]), h_low); + + // copy vertexes + surf->cullinfo.type = CULLINFO_PLANE | CULLINFO_BOX; + ClearBounds(surf->cullinfo.bounds[0], surf->cullinfo.bounds[1]); + verts += LittleLong(ds->firstVert); + if (tangentSpace) + tangentSpace += LittleLong(ds->firstVert); + for(i = 0; i < numVerts; i++) + { + vec4_t color; + + for(j = 0; j < 3; j++) + { + cv->verts[i].xyz[j] = LittleFloat(verts[i].xyz[j]); + cv->verts[i].normal[j] = LittleFloat(verts[i].normal[j]); + } + + if (tangentSpace) + { + for (j = 0; j < 4; j++) + cv->verts[i].tangent[j] = LittleFloat(tangentSpace[i].tangentAndSign[j]); + } + + AddPointToBounds(cv->verts[i].xyz, surf->cullinfo.bounds[0], surf->cullinfo.bounds[1]); + + for(j = 0; j < 2; j++) + { + cv->verts[i].st[j] = LittleFloat(verts[i].st[j]); + } + + for ( j = 0; j < MAXLIGHTMAPS; j++ ) + { + cv->verts[i].lightmap[j][0] = FatPackU( + LittleFloat(verts[i].lightmap[j][0]), ds->lightmapNum[j]); + cv->verts[i].lightmap[j][1] = FatPackV( + LittleFloat(verts[i].lightmap[j][1]), ds->lightmapNum[j]); + + float scale = 1.0f / 255.0f; + if (hdrVertColors) + { + float *hdrColor = hdrVertColors + (ds->firstVert + i) * 3; + color[0] = hdrColor[0] / M_PI; + color[1] = hdrColor[1] / M_PI; + color[2] = hdrColor[2] / M_PI; + scale = 1.0f; + } + else + { + //hack: convert LDR vertex colors to HDR + if (r_hdr->integer) + { + color[0] = MAX(verts[i].color[j][0], 0.499f); + color[1] = MAX(verts[i].color[j][1], 0.499f); + color[2] = MAX(verts[i].color[j][2], 0.499f); + } + else + { + color[0] = verts[i].color[j][0]; + color[1] = verts[i].color[j][1]; + color[2] = verts[i].color[j][2]; + } + } + color[3] = verts[i].color[j][3] / 255.0f; + + R_ColorShiftLightingFloats( color, cv->verts[i].vertexColors[j], scale, hdrVertColors != NULL ); + } + } + + // copy triangles + badTriangles = 0; + indexes += LittleLong(ds->firstIndex); + for(i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3) + { + for(j = 0; j < 3; j++) + { + tri[j] = LittleLong(indexes[i + j]); + + if(tri[j] >= numVerts) + { + ri.Error(ERR_DROP, "Bad index in face surface"); + } + } + + if ((tri[0] == tri[1]) || (tri[1] == tri[2]) || (tri[0] == tri[2])) + { + tri -= 3; + badTriangles++; + } + } + + if (badTriangles) + { + ri.Printf(PRINT_WARNING, "Face has bad triangles, originally shader %s %d tris %d verts, now %d tris\n", surf->shader->name, numIndexes / 3, numVerts, numIndexes / 3 - badTriangles); + cv->numIndexes -= badTriangles * 3; + } + + // take the plane information from the lightmap vector + for ( i = 0 ; i < 3 ; i++ ) { + cv->cullPlane.normal[i] = LittleFloat( ds->lightmapVecs[2][i] ); + } + cv->cullPlane.dist = DotProduct( cv->verts[0].xyz, cv->cullPlane.normal ); + SetPlaneSignbits( &cv->cullPlane ); + cv->cullPlane.type = PlaneTypeForNormal( cv->cullPlane.normal ); + surf->cullinfo.plane = cv->cullPlane; + + surf->data = (surfaceType_t *)cv; +} + + +/* +=============== +ParseMesh +=============== +*/ +static void ParseMesh ( const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, msurface_t *surf ) { + srfBspSurface_t *grid; + int i, j; + int width, height, numPoints; + srfVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE]; + vec3_t bounds[2]; + vec3_t tmpVec; + static surfaceType_t skipData = SF_SKIP; + int realLightmapNum[MAXLIGHTMAPS]; + + for ( j = 0; j < MAXLIGHTMAPS; j++ ) + realLightmapNum[j] = FatLightmap(LittleLong (ds->lightmapNum[j])); + + surf->numSurfaceSprites = 0; + surf->surfaceSprites = nullptr; + + // get fog volume + surf->fogIndex = LittleLong( ds->fogNum ) + 1; + if (!surf->fogIndex && worldData->globalFog != nullptr) + { + surf->fogIndex = worldData->globalFogIndex; + } + + // get shader value + surf->shader = ShaderForShaderNum( worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles ); + if ( r_singleShader->integer && !surf->shader->isSky ) { + surf->shader = tr.defaultShader; + } + + // we may have a nodraw surface, because they might still need to + // be around for movement clipping + if ( worldData->shaders[ LittleLong( ds->shaderNum ) ].surfaceFlags & SURF_NODRAW ) { + surf->data = &skipData; + return; + } + + width = LittleLong( ds->patchWidth ); + height = LittleLong( ds->patchHeight ); + + if(width < 0 || width > MAX_PATCH_SIZE || height < 0 || height > MAX_PATCH_SIZE) + ri.Error(ERR_DROP, "ParseMesh: bad size"); + + verts += LittleLong( ds->firstVert ); + if (tangentSpace) + tangentSpace += LittleLong(ds->firstVert); + numPoints = width * height; + for(i = 0; i < numPoints; i++) + { + vec4_t color; + + for(j = 0; j < 3; j++) + { + points[i].xyz[j] = LittleFloat(verts[i].xyz[j]); + points[i].normal[j] = LittleFloat(verts[i].normal[j]); + } + + if (tangentSpace) + { + for (j = 0; j < 4; j++) + points[i].tangent[j] = LittleFloat(tangentSpace[i].tangentAndSign[j]); + } + + for(j = 0; j < 2; j++) + { + points[i].st[j] = LittleFloat(verts[i].st[j]); + } + + for ( j = 0; j < MAXLIGHTMAPS; j++ ) + { + points[i].lightmap[j][0] = FatPackU(LittleFloat(verts[i].lightmap[j][0]), ds->lightmapNum[j]); + points[i].lightmap[j][1] = FatPackV(LittleFloat(verts[i].lightmap[j][1]), ds->lightmapNum[j]); + + float scale = 1.0f / 255.0f; + if (hdrVertColors) + { + float *hdrColor = hdrVertColors + (ds->firstVert + i)*3; + color[0] = hdrColor[0] / M_PI; + color[1] = hdrColor[1] / M_PI; + color[2] = hdrColor[2] / M_PI; + scale = 1.0f; + } + else + { + //hack: convert LDR vertex colors to HDR + if (r_hdr->integer) + { + color[0] = MAX(verts[i].color[j][0], 0.499f); + color[1] = MAX(verts[i].color[j][1], 0.499f); + color[2] = MAX(verts[i].color[j][2], 0.499f); + } + else + { + color[0] = verts[i].color[j][0]; + color[1] = verts[i].color[j][1]; + color[2] = verts[i].color[j][2]; + } + } + color[3] = verts[i].color[j][3] / 255.0f; + + R_ColorShiftLightingFloats( color, points[i].vertexColors[j], scale, hdrVertColors != NULL ); + } + } + + // pre-tesseleate + grid = R_SubdividePatchToGrid( width, height, points ); + surf->data = (surfaceType_t *)grid; + + // copy the level of detail origin, which is the center + // of the group of all curves that must subdivide the same + // to avoid cracking + for ( i = 0 ; i < 3 ; i++ ) { + bounds[0][i] = LittleFloat( ds->lightmapVecs[0][i] ); + bounds[1][i] = LittleFloat( ds->lightmapVecs[1][i] ); + } + VectorAdd( bounds[0], bounds[1], bounds[1] ); + VectorScale( bounds[1], 0.5f, grid->lodOrigin ); + VectorSubtract( bounds[0], grid->lodOrigin, tmpVec ); + grid->lodRadius = VectorLength( tmpVec ); +} + +/* +=============== +ParseTriSurf +=============== +*/ +static void ParseTriSurf( const world_t *worldData, dsurface_t *ds, drawVert_t *verts, packedTangentSpace_t *tangentSpace, float *hdrVertColors, msurface_t *surf, int *indexes ) { + srfBspSurface_t *cv; + glIndex_t *tri; + int i, j; + int numVerts, numIndexes, badTriangles; + int realLightmapNum[MAXLIGHTMAPS]; + + for ( j = 0; j < MAXLIGHTMAPS; j++ ) + realLightmapNum[j] = FatLightmap(LittleLong (ds->lightmapNum[j])); + + surf->numSurfaceSprites = 0; + surf->surfaceSprites = nullptr; + + // get fog volume + surf->fogIndex = LittleLong( ds->fogNum ) + 1; + if (!surf->fogIndex && worldData->globalFog != nullptr) + { + surf->fogIndex = worldData->globalFogIndex; + } + + // get shader + surf->shader = ShaderForShaderNum( worldData, ds->shaderNum, realLightmapNum, ds->lightmapStyles, ds->vertexStyles ); + if ( r_singleShader->integer && !surf->shader->isSky ) { + surf->shader = tr.defaultShader; + } + + numVerts = LittleLong(ds->numVerts); + numIndexes = LittleLong(ds->numIndexes); + + //cv = ri.Hunk_Alloc(sizeof(*cv), h_low); + cv = (srfBspSurface_t *)surf->data; + cv->surfaceType = SF_TRIANGLES; + + cv->numIndexes = numIndexes; + cv->indexes = (glIndex_t *)ri.Hunk_Alloc(numIndexes * sizeof(cv->indexes[0]), h_low); + + cv->numVerts = numVerts; + cv->verts = (srfVert_t *)ri.Hunk_Alloc(numVerts * sizeof(cv->verts[0]), h_low); + + surf->data = (surfaceType_t *) cv; + + // copy vertexes + surf->cullinfo.type = CULLINFO_BOX; + ClearBounds(surf->cullinfo.bounds[0], surf->cullinfo.bounds[1]); + verts += LittleLong(ds->firstVert); + if (tangentSpace) + tangentSpace += LittleLong(ds->firstVert); + for (i = 0; i < numVerts; i++) + { + vec4_t color; + + for (j = 0; j < 3; j++) + { + cv->verts[i].xyz[j] = LittleFloat(verts[i].xyz[j]); + cv->verts[i].normal[j] = LittleFloat(verts[i].normal[j]); + } + + if (tangentSpace) + { + for (j = 0; j < 4; j++) + cv->verts[i].tangent[j] = LittleFloat(tangentSpace[i].tangentAndSign[j]); + } + + AddPointToBounds( cv->verts[i].xyz, surf->cullinfo.bounds[0], surf->cullinfo.bounds[1] ); + + for(j = 0; j < 2; j++) + { + cv->verts[i].st[j] = LittleFloat(verts[i].st[j]); + } + + for ( j = 0; j < MAXLIGHTMAPS; j++ ) + { + cv->verts[i].lightmap[j][0] = FatPackU( + LittleFloat(verts[i].lightmap[j][0]), ds->lightmapNum[j]); + cv->verts[i].lightmap[j][1] = FatPackV( + LittleFloat(verts[i].lightmap[j][1]), ds->lightmapNum[j]); + + float scale = 1.0f / 255.0f; + if (hdrVertColors) + { + float *hdrColor = hdrVertColors + ((ds->firstVert + i) * 3); + color[0] = hdrColor[0] / M_PI; + color[1] = hdrColor[1] / M_PI; + color[2] = hdrColor[2] / M_PI; + scale = 1.0f; + } + else + { + //hack: convert LDR vertex colors to HDR + if (r_hdr->integer) + { + color[0] = MAX(verts[i].color[j][0], 0.499f); + color[1] = MAX(verts[i].color[j][1], 0.499f); + color[2] = MAX(verts[i].color[j][2], 0.499f); + } + else + { + color[0] = verts[i].color[j][0]; + color[1] = verts[i].color[j][1]; + color[2] = verts[i].color[j][2]; + } + } + color[3] = verts[i].color[j][3] / 255.0f; + + R_ColorShiftLightingFloats( color, cv->verts[i].vertexColors[j], scale, hdrVertColors != NULL ); + } + } + + // copy triangles + badTriangles = 0; + indexes += LittleLong(ds->firstIndex); + for(i = 0, tri = cv->indexes; i < numIndexes; i += 3, tri += 3) + { + for(j = 0; j < 3; j++) + { + tri[j] = LittleLong(indexes[i + j]); + + if(tri[j] >= numVerts) + { + ri.Error(ERR_DROP, "Bad index in face surface"); + } + } + + if ((tri[0] == tri[1]) || (tri[1] == tri[2]) || (tri[0] == tri[2])) + { + tri -= 3; + badTriangles++; + } + } + + if (badTriangles) + { + ri.Printf(PRINT_WARNING, "Trisurf has bad triangles, originally shader %s %d tris %d verts, now %d tris\n", surf->shader->name, numIndexes / 3, numVerts, numIndexes / 3 - badTriangles); + cv->numIndexes -= badTriangles * 3; + } +} + +/* +=============== +ParseFlare +=============== +*/ +static void ParseFlare( const world_t *worldData, dsurface_t *ds, drawVert_t *verts, msurface_t *surf, int *indexes ) { + srfFlare_t *flare; + int i; + + surf->numSurfaceSprites = 0; + surf->surfaceSprites = nullptr; + + // get fog volume + surf->fogIndex = LittleLong( ds->fogNum ) + 1; + if (!surf->fogIndex && worldData->globalFog != nullptr) + { + surf->fogIndex = worldData->globalFogIndex; + } + + // get shader + surf->shader = ShaderForShaderNum( worldData, ds->shaderNum, lightmapsVertex, ds->lightmapStyles, ds->vertexStyles ); + if ( r_singleShader->integer && !surf->shader->isSky ) { + surf->shader = tr.defaultShader; + } + + //flare = ri.Hunk_Alloc( sizeof( *flare ), h_low ); + flare = (srfFlare_t *)surf->data; + flare->surfaceType = SF_FLARE; + + if (surf->shader == tr.defaultShader) + flare->shader = tr.flareShader; + else + flare->shader = surf->shader; + + surf->data = (surfaceType_t *)flare; + + for ( i = 0 ; i < 3 ; i++ ) { + flare->origin[i] = LittleFloat( ds->lightmapOrigin[i] ); + flare->color[i] = LittleFloat( ds->lightmapVecs[0][i] ); + flare->normal[i] = LittleFloat( ds->lightmapVecs[2][i] ); + } +} + + +/* +================= +R_MergedWidthPoints + +returns true if there are grid points merged on a width edge +================= +*/ +int R_MergedWidthPoints(srfBspSurface_t *grid, int offset) { + int i, j; + + for (i = 1; i < grid->width-1; i++) { + for (j = i + 1; j < grid->width-1; j++) { + if ( fabs(grid->verts[i + offset].xyz[0] - grid->verts[j + offset].xyz[0]) > .1) continue; + if ( fabs(grid->verts[i + offset].xyz[1] - grid->verts[j + offset].xyz[1]) > .1) continue; + if ( fabs(grid->verts[i + offset].xyz[2] - grid->verts[j + offset].xyz[2]) > .1) continue; + return qtrue; + } + } + return qfalse; +} + +/* +================= +R_MergedHeightPoints + +returns true if there are grid points merged on a height edge +================= +*/ +int R_MergedHeightPoints(srfBspSurface_t *grid, int offset) { + int i, j; + + for (i = 1; i < grid->height-1; i++) { + for (j = i + 1; j < grid->height-1; j++) { + if ( fabs(grid->verts[grid->width * i + offset].xyz[0] - grid->verts[grid->width * j + offset].xyz[0]) > .1) continue; + if ( fabs(grid->verts[grid->width * i + offset].xyz[1] - grid->verts[grid->width * j + offset].xyz[1]) > .1) continue; + if ( fabs(grid->verts[grid->width * i + offset].xyz[2] - grid->verts[grid->width * j + offset].xyz[2]) > .1) continue; + return qtrue; + } + } + return qfalse; +} + +/* +================= +R_FixSharedVertexLodError_r + +NOTE: never sync LoD through grid edges with merged points! + +FIXME: write generalized version that also avoids cracks between a patch and one that meets half way? +================= +*/ +void R_FixSharedVertexLodError_r( world_t *worldData, int start, srfBspSurface_t *grid1 ) { + int j, k, l, m, n, offset1, offset2, touch; + srfBspSurface_t *grid2; + + for ( j = start; j < worldData->numsurfaces; j++ ) { + // + grid2 = (srfBspSurface_t *) worldData->surfaces[j].data; + // if this surface is not a grid + if ( grid2->surfaceType != SF_GRID ) continue; + // if the LOD errors are already fixed for this patch + if ( grid2->lodFixed == 2 ) continue; + // grids in the same LOD group should have the exact same lod radius + if ( grid1->lodRadius != grid2->lodRadius ) continue; + // grids in the same LOD group should have the exact same lod origin + if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue; + if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue; + if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue; + // + touch = qfalse; + for (n = 0; n < 2; n++) { + // + if (n) offset1 = (grid1->height-1) * grid1->width; + else offset1 = 0; + if (R_MergedWidthPoints(grid1, offset1)) continue; + for (k = 1; k < grid1->width-1; k++) { + for (m = 0; m < 2; m++) { + + if (m) offset2 = (grid2->height-1) * grid2->width; + else offset2 = 0; + if (R_MergedWidthPoints(grid2, offset2)) continue; + for ( l = 1; l < grid2->width-1; l++) { + // + if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue; + if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue; + if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue; + // ok the points are equal and should have the same lod error + grid2->widthLodError[l] = grid1->widthLodError[k]; + touch = qtrue; + } + } + for (m = 0; m < 2; m++) { + + if (m) offset2 = grid2->width-1; + else offset2 = 0; + if (R_MergedHeightPoints(grid2, offset2)) continue; + for ( l = 1; l < grid2->height-1; l++) { + // + if ( fabs(grid1->verts[k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue; + if ( fabs(grid1->verts[k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue; + if ( fabs(grid1->verts[k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue; + // ok the points are equal and should have the same lod error + grid2->heightLodError[l] = grid1->widthLodError[k]; + touch = qtrue; + } + } + } + } + for (n = 0; n < 2; n++) { + // + if (n) offset1 = grid1->width-1; + else offset1 = 0; + if (R_MergedHeightPoints(grid1, offset1)) continue; + for (k = 1; k < grid1->height-1; k++) { + for (m = 0; m < 2; m++) { + + if (m) offset2 = (grid2->height-1) * grid2->width; + else offset2 = 0; + if (R_MergedWidthPoints(grid2, offset2)) continue; + for ( l = 1; l < grid2->width-1; l++) { + // + if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[l + offset2].xyz[0]) > .1) continue; + if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[l + offset2].xyz[1]) > .1) continue; + if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[l + offset2].xyz[2]) > .1) continue; + // ok the points are equal and should have the same lod error + grid2->widthLodError[l] = grid1->heightLodError[k]; + touch = qtrue; + } + } + for (m = 0; m < 2; m++) { + + if (m) offset2 = grid2->width-1; + else offset2 = 0; + if (R_MergedHeightPoints(grid2, offset2)) continue; + for ( l = 1; l < grid2->height-1; l++) { + // + if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[0] - grid2->verts[grid2->width * l + offset2].xyz[0]) > .1) continue; + if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[1] - grid2->verts[grid2->width * l + offset2].xyz[1]) > .1) continue; + if ( fabs(grid1->verts[grid1->width * k + offset1].xyz[2] - grid2->verts[grid2->width * l + offset2].xyz[2]) > .1) continue; + // ok the points are equal and should have the same lod error + grid2->heightLodError[l] = grid1->heightLodError[k]; + touch = qtrue; + } + } + } + } + if (touch) { + grid2->lodFixed = 2; + R_FixSharedVertexLodError_r ( worldData, start, grid2 ); + //NOTE: this would be correct but makes things really slow + //grid2->lodFixed = 1; + } + } +} + +/* +================= +R_FixSharedVertexLodError + +This function assumes that all patches in one group are nicely stitched together for the highest LoD. +If this is not the case this function will still do its job but won't fix the highest LoD cracks. +================= +*/ +void R_FixSharedVertexLodError( world_t *worldData ) { + int i; + srfBspSurface_t *grid1; + + for ( i = 0; i < worldData->numsurfaces; i++ ) { + // + grid1 = (srfBspSurface_t *) worldData->surfaces[i].data; + // if this surface is not a grid + if ( grid1->surfaceType != SF_GRID ) + continue; + // + if ( grid1->lodFixed ) + continue; + // + grid1->lodFixed = 2; + // recursively fix other patches in the same LOD group + R_FixSharedVertexLodError_r( worldData, i + 1, grid1); + } +} + + +/* +=============== +R_StitchPatches +=============== +*/ +int R_StitchPatches( world_t *worldData, int grid1num, int grid2num ) { + float *v1, *v2; + srfBspSurface_t *grid1, *grid2; + int k, l, m, n, offset1, offset2, row, column; + + grid1 = (srfBspSurface_t *) worldData->surfaces[grid1num].data; + grid2 = (srfBspSurface_t *) worldData->surfaces[grid2num].data; + for (n = 0; n < 2; n++) { + // + if (n) offset1 = (grid1->height-1) * grid1->width; + else offset1 = 0; + if (R_MergedWidthPoints(grid1, offset1)) + continue; + for (k = 0; k < grid1->width-2; k += 2) { + + for (m = 0; m < 2; m++) { + + if ( grid2->width >= MAX_GRID_SIZE ) + break; + if (m) offset2 = (grid2->height-1) * grid2->width; + else offset2 = 0; + for ( l = 0; l < grid2->width-1; l++) { + // + v1 = grid1->verts[k + offset1].xyz; + v2 = grid2->verts[l + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + + v1 = grid1->verts[k + 2 + offset1].xyz; + v2 = grid2->verts[l + 1 + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + // + v1 = grid2->verts[l + offset2].xyz; + v2 = grid2->verts[l + 1 + offset2].xyz; + if ( fabs(v1[0] - v2[0]) < .01 && + fabs(v1[1] - v2[1]) < .01 && + fabs(v1[2] - v2[2]) < .01) + continue; + // + //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // insert column into grid2 right after after column l + if (m) row = grid2->height-1; + else row = 0; + grid2 = R_GridInsertColumn( grid2, l+1, row, + grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]); + grid2->lodStitched = qfalse; + worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + return qtrue; + } + } + for (m = 0; m < 2; m++) { + + if (grid2->height >= MAX_GRID_SIZE) + break; + if (m) offset2 = grid2->width-1; + else offset2 = 0; + for ( l = 0; l < grid2->height-1; l++) { + // + v1 = grid1->verts[k + offset1].xyz; + v2 = grid2->verts[grid2->width * l + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + + v1 = grid1->verts[k + 2 + offset1].xyz; + v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + // + v1 = grid2->verts[grid2->width * l + offset2].xyz; + v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) < .01 && + fabs(v1[1] - v2[1]) < .01 && + fabs(v1[2] - v2[2]) < .01) + continue; + // + //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // insert row into grid2 right after after row l + if (m) column = grid2->width-1; + else column = 0; + grid2 = R_GridInsertRow( grid2, l+1, column, + grid1->verts[k + 1 + offset1].xyz, grid1->widthLodError[k+1]); + grid2->lodStitched = qfalse; + worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + return qtrue; + } + } + } + } + for (n = 0; n < 2; n++) { + // + if (n) offset1 = grid1->width-1; + else offset1 = 0; + if (R_MergedHeightPoints(grid1, offset1)) + continue; + for (k = 0; k < grid1->height-2; k += 2) { + for (m = 0; m < 2; m++) { + + if ( grid2->width >= MAX_GRID_SIZE ) + break; + if (m) offset2 = (grid2->height-1) * grid2->width; + else offset2 = 0; + for ( l = 0; l < grid2->width-1; l++) { + // + v1 = grid1->verts[grid1->width * k + offset1].xyz; + v2 = grid2->verts[l + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + + v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz; + v2 = grid2->verts[l + 1 + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + // + v1 = grid2->verts[l + offset2].xyz; + v2 = grid2->verts[(l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) < .01 && + fabs(v1[1] - v2[1]) < .01 && + fabs(v1[2] - v2[2]) < .01) + continue; + // + //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // insert column into grid2 right after after column l + if (m) row = grid2->height-1; + else row = 0; + grid2 = R_GridInsertColumn( grid2, l+1, row, + grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]); + grid2->lodStitched = qfalse; + worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + return qtrue; + } + } + for (m = 0; m < 2; m++) { + + if (grid2->height >= MAX_GRID_SIZE) + break; + if (m) offset2 = grid2->width-1; + else offset2 = 0; + for ( l = 0; l < grid2->height-1; l++) { + // + v1 = grid1->verts[grid1->width * k + offset1].xyz; + v2 = grid2->verts[grid2->width * l + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + + v1 = grid1->verts[grid1->width * (k + 2) + offset1].xyz; + v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + // + v1 = grid2->verts[grid2->width * l + offset2].xyz; + v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) < .01 && + fabs(v1[1] - v2[1]) < .01 && + fabs(v1[2] - v2[2]) < .01) + continue; + // + //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // insert row into grid2 right after after row l + if (m) column = grid2->width-1; + else column = 0; + grid2 = R_GridInsertRow( grid2, l+1, column, + grid1->verts[grid1->width * (k + 1) + offset1].xyz, grid1->heightLodError[k+1]); + grid2->lodStitched = qfalse; + worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + return qtrue; + } + } + } + } + for (n = 0; n < 2; n++) { + // + if (n) offset1 = (grid1->height-1) * grid1->width; + else offset1 = 0; + if (R_MergedWidthPoints(grid1, offset1)) + continue; + for (k = grid1->width-1; k > 1; k -= 2) { + + for (m = 0; m < 2; m++) { + + if ( grid2->width >= MAX_GRID_SIZE ) + break; + if (m) offset2 = (grid2->height-1) * grid2->width; + else offset2 = 0; + for ( l = 0; l < grid2->width-1; l++) { + // + v1 = grid1->verts[k + offset1].xyz; + v2 = grid2->verts[l + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + + v1 = grid1->verts[k - 2 + offset1].xyz; + v2 = grid2->verts[l + 1 + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + // + v1 = grid2->verts[l + offset2].xyz; + v2 = grid2->verts[(l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) < .01 && + fabs(v1[1] - v2[1]) < .01 && + fabs(v1[2] - v2[2]) < .01) + continue; + // + //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // insert column into grid2 right after after column l + if (m) row = grid2->height-1; + else row = 0; + grid2 = R_GridInsertColumn( grid2, l+1, row, + grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]); + grid2->lodStitched = qfalse; + worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + return qtrue; + } + } + for (m = 0; m < 2; m++) { + + if (grid2->height >= MAX_GRID_SIZE) + break; + if (m) offset2 = grid2->width-1; + else offset2 = 0; + for ( l = 0; l < grid2->height-1; l++) { + // + v1 = grid1->verts[k + offset1].xyz; + v2 = grid2->verts[grid2->width * l + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + + v1 = grid1->verts[k - 2 + offset1].xyz; + v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + // + v1 = grid2->verts[grid2->width * l + offset2].xyz; + v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) < .01 && + fabs(v1[1] - v2[1]) < .01 && + fabs(v1[2] - v2[2]) < .01) + continue; + // + //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // insert row into grid2 right after after row l + if (m) column = grid2->width-1; + else column = 0; + grid2 = R_GridInsertRow( grid2, l+1, column, + grid1->verts[k - 1 + offset1].xyz, grid1->widthLodError[k+1]); + if (!grid2) + break; + grid2->lodStitched = qfalse; + worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + return qtrue; + } + } + } + } + for (n = 0; n < 2; n++) { + // + if (n) offset1 = grid1->width-1; + else offset1 = 0; + if (R_MergedHeightPoints(grid1, offset1)) + continue; + for (k = grid1->height-1; k > 1; k -= 2) { + for (m = 0; m < 2; m++) { + + if ( grid2->width >= MAX_GRID_SIZE ) + break; + if (m) offset2 = (grid2->height-1) * grid2->width; + else offset2 = 0; + for ( l = 0; l < grid2->width-1; l++) { + // + v1 = grid1->verts[grid1->width * k + offset1].xyz; + v2 = grid2->verts[l + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + + v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz; + v2 = grid2->verts[l + 1 + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + // + v1 = grid2->verts[l + offset2].xyz; + v2 = grid2->verts[(l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) < .01 && + fabs(v1[1] - v2[1]) < .01 && + fabs(v1[2] - v2[2]) < .01) + continue; + // + //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // insert column into grid2 right after after column l + if (m) row = grid2->height-1; + else row = 0; + grid2 = R_GridInsertColumn( grid2, l+1, row, + grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]); + grid2->lodStitched = qfalse; + worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + return qtrue; + } + } + for (m = 0; m < 2; m++) { + + if (grid2->height >= MAX_GRID_SIZE) + break; + if (m) offset2 = grid2->width-1; + else offset2 = 0; + for ( l = 0; l < grid2->height-1; l++) { + // + v1 = grid1->verts[grid1->width * k + offset1].xyz; + v2 = grid2->verts[grid2->width * l + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + + v1 = grid1->verts[grid1->width * (k - 2) + offset1].xyz; + v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) > .1) + continue; + if ( fabs(v1[1] - v2[1]) > .1) + continue; + if ( fabs(v1[2] - v2[2]) > .1) + continue; + // + v1 = grid2->verts[grid2->width * l + offset2].xyz; + v2 = grid2->verts[grid2->width * (l + 1) + offset2].xyz; + if ( fabs(v1[0] - v2[0]) < .01 && + fabs(v1[1] - v2[1]) < .01 && + fabs(v1[2] - v2[2]) < .01) + continue; + // + //ri.Printf( PRINT_ALL, "found highest LoD crack between two patches\n" ); + // insert row into grid2 right after after row l + if (m) column = grid2->width-1; + else column = 0; + grid2 = R_GridInsertRow( grid2, l+1, column, + grid1->verts[grid1->width * (k - 1) + offset1].xyz, grid1->heightLodError[k+1]); + grid2->lodStitched = qfalse; + worldData->surfaces[grid2num].data = (surfaceType_t *) grid2; + return qtrue; + } + } + } + } + return qfalse; +} + +/* +=============== +R_TryStitchPatch + +This function will try to stitch patches in the same LoD group together for the highest LoD. + +Only single missing vertice cracks will be fixed. + +Vertices will be joined at the patch side a crack is first found, at the other side +of the patch (on the same row or column) the vertices will not be joined and cracks +might still appear at that side. +=============== +*/ +int R_TryStitchingPatch( world_t *worldData, int grid1num ) { + int j, numstitches; + srfBspSurface_t *grid1, *grid2; + + numstitches = 0; + grid1 = (srfBspSurface_t *) worldData->surfaces[grid1num].data; + for ( j = 0; j < worldData->numsurfaces; j++ ) { + // + grid2 = (srfBspSurface_t *) worldData->surfaces[j].data; + // if this surface is not a grid + if ( grid2->surfaceType != SF_GRID ) continue; + // grids in the same LOD group should have the exact same lod radius + if ( grid1->lodRadius != grid2->lodRadius ) continue; + // grids in the same LOD group should have the exact same lod origin + if ( grid1->lodOrigin[0] != grid2->lodOrigin[0] ) continue; + if ( grid1->lodOrigin[1] != grid2->lodOrigin[1] ) continue; + if ( grid1->lodOrigin[2] != grid2->lodOrigin[2] ) continue; + // + while (R_StitchPatches(worldData, grid1num, j)) + { + numstitches++; + } + } + return numstitches; +} + +/* +=============== +R_StitchAllPatches +=============== +*/ +void R_StitchAllPatches( world_t *worldData ) { + int i, stitched, numstitches; + srfBspSurface_t *grid1; + + numstitches = 0; + do + { + stitched = qfalse; + for ( i = 0; i < worldData->numsurfaces; i++ ) { + // + grid1 = (srfBspSurface_t *) worldData->surfaces[i].data; + // if this surface is not a grid + if ( grid1->surfaceType != SF_GRID ) + continue; + // + if ( grid1->lodStitched ) + continue; + // + grid1->lodStitched = qtrue; + stitched = qtrue; + // + numstitches += R_TryStitchingPatch( worldData, i ); + } + } + while (stitched); + ri.Printf( PRINT_ALL, "stitched %d LoD cracks\n", numstitches ); +} + +/* +=============== +R_MovePatchSurfacesToHunk +=============== +*/ +void R_MovePatchSurfacesToHunk( world_t *worldData ) { + int i, size; + srfBspSurface_t *grid, *hunkgrid; + + for ( i = 0; i < worldData->numsurfaces; i++ ) { + // + grid = (srfBspSurface_t *) worldData->surfaces[i].data; + // if this surface is not a grid + if ( grid->surfaceType != SF_GRID ) + continue; + // + size = sizeof(*grid); + hunkgrid = (srfBspSurface_t *)ri.Hunk_Alloc(size, h_low); + Com_Memcpy(hunkgrid, grid, size); + + hunkgrid->widthLodError = (float *)ri.Hunk_Alloc( grid->width * 4, h_low ); + Com_Memcpy( hunkgrid->widthLodError, grid->widthLodError, grid->width * 4 ); + + hunkgrid->heightLodError = (float *)ri.Hunk_Alloc( grid->height * 4, h_low ); + Com_Memcpy( hunkgrid->heightLodError, grid->heightLodError, grid->height * 4 ); + + hunkgrid->numIndexes = grid->numIndexes; + hunkgrid->indexes = (glIndex_t *)ri.Hunk_Alloc(grid->numIndexes * sizeof(glIndex_t), h_low); + Com_Memcpy(hunkgrid->indexes, grid->indexes, grid->numIndexes * sizeof(glIndex_t)); + + hunkgrid->numVerts = grid->numVerts; + hunkgrid->verts = (srfVert_t *)ri.Hunk_Alloc(grid->numVerts * sizeof(srfVert_t), h_low); + Com_Memcpy(hunkgrid->verts, grid->verts, grid->numVerts * sizeof(srfVert_t)); + + R_FreeSurfaceGridMesh( grid ); + + worldData->surfaces[i].data = (surfaceType_t *) hunkgrid; + } +} + + +/* +================= +BSPSurfaceCompare +compare function for qsort() +================= +*/ +static int BSPSurfaceCompare(const void *a, const void *b) +{ + msurface_t *aa, *bb; + + aa = *(msurface_t **) a; + bb = *(msurface_t **) b; + + // shader first + if(aa->shader->sortedIndex < bb->shader->sortedIndex) + return -1; + + else if(aa->shader->sortedIndex > bb->shader->sortedIndex) + return 1; + + // by fogIndex + if(aa->fogIndex < bb->fogIndex) + return -1; + + else if(aa->fogIndex > bb->fogIndex) + return 1; + + // by cubemapIndex + if(aa->cubemapIndex < bb->cubemapIndex) + return -1; + + else if(aa->cubemapIndex > bb->cubemapIndex) + return 1; + + + return 0; +} + +/* +=============== +R_CreateWorldVBOs +=============== +*/ +static void R_CreateWorldVBOs( world_t *worldData ) +{ + int i, j, k; + + int numVerts; + packedVertex_t *verts; + + int numIndexes; + glIndex_t *indexes; + + int numSortedSurfaces, numSurfaces; + msurface_t *surface, **firstSurf, **lastSurf, **currSurf; + msurface_t **surfacesSorted; + + VBO_t *vbo; + IBO_t *ibo; + + int maxVboSize = 64 * 1024 * 1024; + int maxIboSize = 16 * 1024 * 1024; + + int startTime, endTime; + + startTime = ri.Milliseconds(); + + // count surfaces + numSortedSurfaces = 0; + for(surface = &worldData->surfaces[0]; surface < &worldData->surfaces[worldData->numsurfaces]; surface++) + { + srfBspSurface_t *bspSurf; + shader_t *shader = surface->shader; + + if (shader->isPortal) + continue; + + if (shader->isSky) + continue; + + if (ShaderRequiresCPUDeforms(shader)) + continue; + + // check for this now so we can use srfBspSurface_t* universally in the rest of the function + if (!(*surface->data == SF_FACE || *surface->data == SF_GRID || *surface->data == SF_TRIANGLES)) + continue; + + bspSurf = (srfBspSurface_t *) surface->data; + + if (!bspSurf->numIndexes || !bspSurf->numVerts) + continue; + + numSortedSurfaces++; + } + + // presort surfaces + surfacesSorted = (msurface_t **)Z_Malloc(numSortedSurfaces * sizeof(*surfacesSorted), TAG_BSP); + + j = 0; + for(surface = &worldData->surfaces[0]; surface < &worldData->surfaces[worldData->numsurfaces]; surface++) + { + srfBspSurface_t *bspSurf; + shader_t *shader = surface->shader; + + if (shader->isPortal) + continue; + + if (shader->isSky) + continue; + + if (ShaderRequiresCPUDeforms(shader)) + continue; + + // check for this now so we can use srfBspSurface_t* universally in the rest of the function + if (!(*surface->data == SF_FACE || *surface->data == SF_GRID || *surface->data == SF_TRIANGLES)) + continue; + + bspSurf = (srfBspSurface_t *) surface->data; + + if (!bspSurf->numIndexes || !bspSurf->numVerts) + continue; + + surfacesSorted[j++] = surface; + } + + qsort(surfacesSorted, numSortedSurfaces, sizeof(*surfacesSorted), BSPSurfaceCompare); + + k = 0; + for(firstSurf = lastSurf = surfacesSorted; firstSurf < &surfacesSorted[numSortedSurfaces]; firstSurf = lastSurf) + { + int currVboSize, currIboSize; + + // Find range of surfaces to merge by: + // - Collecting a number of surfaces which fit under maxVboSize/maxIboSize, or + // - All the surfaces with a single shader which go over maxVboSize/maxIboSize + currVboSize = currIboSize = 0; + while (currVboSize < maxVboSize && currIboSize < maxIboSize && lastSurf < &surfacesSorted[numSortedSurfaces]) + { + int addVboSize, addIboSize, currShaderIndex; + + addVboSize = addIboSize = 0; + currShaderIndex = (*lastSurf)->shader->sortedIndex; + + for(currSurf = lastSurf; currSurf < &surfacesSorted[numSortedSurfaces] && (*currSurf)->shader->sortedIndex == currShaderIndex; currSurf++) + { + srfBspSurface_t *bspSurf = (srfBspSurface_t *) (*currSurf)->data; + + addVboSize += bspSurf->numVerts * sizeof(srfVert_t); + addIboSize += bspSurf->numIndexes * sizeof(glIndex_t); + } + + if ((currVboSize != 0 && addVboSize + currVboSize > maxVboSize) + || (currIboSize != 0 && addIboSize + currIboSize > maxIboSize)) + break; + + lastSurf = currSurf; + + currVboSize += addVboSize; + currIboSize += addIboSize; + } + + // count verts/indexes/surfaces + numVerts = 0; + numIndexes = 0; + numSurfaces = 0; + for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) + { + srfBspSurface_t *bspSurf = (srfBspSurface_t *) (*currSurf)->data; + + numVerts += bspSurf->numVerts; + numIndexes += bspSurf->numIndexes; + numSurfaces++; + } + + ri.Printf(PRINT_ALL, "...calculating world VBO %d ( %i verts %i tris )\n", k, numVerts, numIndexes / 3); + + // create arrays + verts = (packedVertex_t *)ri.Hunk_AllocateTempMemory(numVerts * sizeof(packedVertex_t)); + indexes = (glIndex_t *)ri.Hunk_AllocateTempMemory(numIndexes * sizeof(glIndex_t)); + + // set up indices and copy vertices + numVerts = 0; + numIndexes = 0; + for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) + { + srfBspSurface_t *bspSurf = (srfBspSurface_t *) (*currSurf)->data; + glIndex_t *surfIndex; + + bspSurf->firstIndex = numIndexes; + bspSurf->minIndex = numVerts + bspSurf->indexes[0]; + bspSurf->maxIndex = numVerts + bspSurf->indexes[0]; + + for(i = 0, surfIndex = bspSurf->indexes; i < bspSurf->numIndexes; i++, surfIndex++) + { + indexes[numIndexes++] = numVerts + *surfIndex; + bspSurf->minIndex = MIN(bspSurf->minIndex, numVerts + *surfIndex); + bspSurf->maxIndex = MAX(bspSurf->maxIndex, numVerts + *surfIndex); + } + + bspSurf->firstVert = numVerts; + + for(i = 0; i < bspSurf->numVerts; i++) + { + packedVertex_t& vert = verts[numVerts++]; + + VectorCopy (bspSurf->verts[i].xyz, vert.position); + vert.normal = R_VboPackNormal (bspSurf->verts[i].normal); + + if (VectorLengthSquared(bspSurf->verts[i].tangent) > 0.001f) + vert.tangent = R_VboPackTangent(bspSurf->verts[i].tangent); + else + vert.tangent = 0u; + + VectorCopy2 (bspSurf->verts[i].st, vert.texcoords[0]); + + for (int j = 0; j < MAXLIGHTMAPS; j++) + { + VectorCopy2 (bspSurf->verts[i].lightmap[j], vert.texcoords[1 + j]); + } + + for (int j = 0; j < MAXLIGHTMAPS; j++) + { + VectorCopy4 (bspSurf->verts[i].vertexColors[j], vert.colors[j]); + } + + vert.lightDirection = R_VboPackNormal (bspSurf->verts[i].lightdir); + } + } + + R_CalcMikkTSpaceBSPSurface(numIndexes/3, verts, indexes); + + vbo = R_CreateVBO((byte *)verts, sizeof (packedVertex_t) * numVerts, VBO_USAGE_STATIC); + ibo = R_CreateIBO((byte *)indexes, numIndexes * sizeof (glIndex_t), VBO_USAGE_STATIC); + + // Setup the offsets and strides + vbo->offsets[ATTR_INDEX_POSITION] = offsetof(packedVertex_t, position); + vbo->offsets[ATTR_INDEX_NORMAL] = offsetof(packedVertex_t, normal); + vbo->offsets[ATTR_INDEX_TANGENT] = offsetof(packedVertex_t, tangent); + vbo->offsets[ATTR_INDEX_TEXCOORD0] = offsetof(packedVertex_t, texcoords[0]); + vbo->offsets[ATTR_INDEX_TEXCOORD1] = offsetof(packedVertex_t, texcoords[1]); + vbo->offsets[ATTR_INDEX_TEXCOORD2] = offsetof(packedVertex_t, texcoords[2]); + vbo->offsets[ATTR_INDEX_TEXCOORD3] = offsetof(packedVertex_t, texcoords[3]); + vbo->offsets[ATTR_INDEX_TEXCOORD4] = offsetof(packedVertex_t, texcoords[4]); + vbo->offsets[ATTR_INDEX_COLOR] = offsetof(packedVertex_t, colors); + vbo->offsets[ATTR_INDEX_LIGHTDIRECTION] = offsetof(packedVertex_t, lightDirection); + + const size_t packedVertexSize = sizeof(packedVertex_t); + vbo->strides[ATTR_INDEX_POSITION] = packedVertexSize; + vbo->strides[ATTR_INDEX_NORMAL] = packedVertexSize; + vbo->strides[ATTR_INDEX_TANGENT] = packedVertexSize; + vbo->strides[ATTR_INDEX_TEXCOORD0] = packedVertexSize; + vbo->strides[ATTR_INDEX_TEXCOORD1] = packedVertexSize; + vbo->strides[ATTR_INDEX_TEXCOORD2] = packedVertexSize; + vbo->strides[ATTR_INDEX_TEXCOORD3] = packedVertexSize; + vbo->strides[ATTR_INDEX_TEXCOORD4] = packedVertexSize; + vbo->strides[ATTR_INDEX_COLOR] = packedVertexSize; + vbo->strides[ATTR_INDEX_LIGHTDIRECTION] = packedVertexSize; + + vbo->sizes[ATTR_INDEX_POSITION] = sizeof(verts->position); + vbo->sizes[ATTR_INDEX_NORMAL] = sizeof(verts->normal); + vbo->sizes[ATTR_INDEX_TEXCOORD0] = sizeof(verts->texcoords[0]); + vbo->sizes[ATTR_INDEX_TEXCOORD1] = sizeof(verts->texcoords[0]); + vbo->sizes[ATTR_INDEX_TEXCOORD2] = sizeof(verts->texcoords[0]); + vbo->sizes[ATTR_INDEX_TEXCOORD3] = sizeof(verts->texcoords[0]); + vbo->sizes[ATTR_INDEX_TEXCOORD4] = sizeof(verts->texcoords[0]); + vbo->sizes[ATTR_INDEX_TANGENT] = sizeof(verts->tangent); + vbo->sizes[ATTR_INDEX_LIGHTDIRECTION] = sizeof(verts->lightDirection); + vbo->sizes[ATTR_INDEX_COLOR] = sizeof(verts->colors); + + // point bsp surfaces to VBO + for (currSurf = firstSurf; currSurf < lastSurf; currSurf++) + { + srfBspSurface_t *bspSurf = (srfBspSurface_t *) (*currSurf)->data; + + bspSurf->vbo = vbo; + bspSurf->ibo = ibo; + } + + ri.Hunk_FreeTempMemory(indexes); + ri.Hunk_FreeTempMemory(verts); + + k++; + } + + Z_Free(surfacesSorted); + + endTime = ri.Milliseconds(); + ri.Printf(PRINT_ALL, "world VBOs calculation time = %5.2f seconds\n", (endTime - startTime) / 1000.0); +} + +/* +=============== +R_LoadSurfaces +=============== +*/ +static void R_LoadSurfaces( world_t *worldData, lump_t *surfs, lump_t *verts, lump_t *indexLump ) { + dsurface_t *in; + msurface_t *out; + drawVert_t *dv; + int *indexes; + int count; + int numFaces, numMeshes, numTriSurfs, numFlares; + int i; + float *hdrVertColors = NULL; + + numFaces = 0; + numMeshes = 0; + numTriSurfs = 0; + numFlares = 0; + + if (surfs->filelen % sizeof(*in)) + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + count = surfs->filelen / sizeof(*in); + + dv = (drawVert_t *)(fileBase + verts->fileofs); + if (verts->filelen % sizeof(*dv)) + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + + indexes = (int *)(fileBase + indexLump->fileofs); + if ( indexLump->filelen % sizeof(*indexes)) + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + + out = (msurface_t *)ri.Hunk_Alloc ( count * sizeof(*out), h_low ); + + worldData->surfaces = out; + worldData->numsurfaces = count; + worldData->surfacesViewCount = (int *)ri.Hunk_Alloc ( count * sizeof(*worldData->surfacesViewCount), h_low ); + worldData->surfacesDlightBits = (int *)ri.Hunk_Alloc ( count * sizeof(*worldData->surfacesDlightBits), h_low ); + worldData->surfacesPshadowBits = (int *)ri.Hunk_Alloc ( count * sizeof(*worldData->surfacesPshadowBits), h_low ); + + // load hdr vertex colors + if (r_hdr->integer) + { + char filename[MAX_QPATH]; + int size; + + Com_sprintf( filename, sizeof( filename ), "maps/%s/vertlight.raw", worldData->baseName); + //ri.Printf(PRINT_ALL, "looking for %s\n", filename); + + size = ri.FS_ReadFile(filename, (void **)&hdrVertColors); + + if (hdrVertColors) + { + //ri.Printf(PRINT_ALL, "Found!\n"); + if (size != sizeof(float) * 3 * verts->filelen / sizeof(*dv)) + ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, (int)((sizeof(float)) * 3 * verts->filelen / sizeof(*dv))); + } + } + + // load vertex tangent space + packedTangentSpace_t *tangentSpace = NULL; + char filename[MAX_QPATH]; + Com_sprintf(filename, sizeof(filename), "maps/%s.tspace", worldData->baseName); + int size = ri.FS_ReadFile(filename, (void **)&tangentSpace); + + if (tangentSpace) + { + assert(size == (verts->filelen / sizeof(*dv)) * sizeof(float) * 4); + + if (size != sizeof(tangentSpace[0]) * verts->filelen / sizeof(*dv)) + ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, (int)(sizeof(float) * 4 * verts->filelen / sizeof(*dv))); + } + + + // Two passes, allocate surfaces first, then load them full of data + // This ensures surfaces are close together to reduce L2 cache misses when using VBOs, + // which don't actually use the verts and indexes + in = (dsurface_t *)(fileBase + surfs->fileofs); + out = worldData->surfaces; + for ( i = 0 ; i < count ; i++, in++, out++ ) { + switch ( LittleLong( in->surfaceType ) ) { + case MST_PATCH: + // FIXME: do this + break; + case MST_TRIANGLE_SOUP: + out->data = (surfaceType_t *)ri.Hunk_Alloc( sizeof(srfBspSurface_t), h_low); + break; + case MST_PLANAR: + out->data = (surfaceType_t *)ri.Hunk_Alloc( sizeof(srfBspSurface_t), h_low); + break; + case MST_FLARE: + out->data = (surfaceType_t *)ri.Hunk_Alloc( sizeof(srfFlare_t), h_low); + break; + default: + break; + } + } + + in = (dsurface_t *)(fileBase + surfs->fileofs); + out = worldData->surfaces; + for ( i = 0 ; i < count ; i++, in++, out++ ) { + switch ( LittleLong( in->surfaceType ) ) { + case MST_PATCH: + ParseMesh ( worldData, in, dv, tangentSpace, hdrVertColors, out ); + { + srfBspSurface_t *surface = (srfBspSurface_t *)out->data; + + out->cullinfo.type = CULLINFO_BOX | CULLINFO_SPHERE; + VectorCopy(surface->cullBounds[0], out->cullinfo.bounds[0]); + VectorCopy(surface->cullBounds[1], out->cullinfo.bounds[1]); + VectorCopy(surface->cullOrigin, out->cullinfo.localOrigin); + out->cullinfo.radius = surface->cullRadius; + } + numMeshes++; + break; + case MST_TRIANGLE_SOUP: + ParseTriSurf( worldData, in, dv, tangentSpace, hdrVertColors, out, indexes ); + numTriSurfs++; + break; + case MST_PLANAR: + ParseFace( worldData, in, dv, tangentSpace, hdrVertColors, out, indexes ); + numFaces++; + break; + case MST_FLARE: + ParseFlare( worldData, in, dv, out, indexes ); + { + out->cullinfo.type = CULLINFO_NONE; + } + numFlares++; + break; + default: + ri.Error( ERR_DROP, "Bad surfaceType" ); + } + } + + if (hdrVertColors) + { + ri.FS_FreeFile(hdrVertColors); + } + +#ifdef PATCH_STITCHING + R_StitchAllPatches(worldData); +#endif + + R_FixSharedVertexLodError(worldData); + +#ifdef PATCH_STITCHING + R_MovePatchSurfacesToHunk(worldData); +#endif + + ri.Printf( PRINT_ALL, "...loaded %d faces, %i meshes, %i trisurfs, %i flares\n", + numFaces, numMeshes, numTriSurfs, numFlares ); +} + + + +/* +================= +R_LoadSubmodels +================= +*/ +static void R_LoadSubmodels( world_t *worldData, int worldIndex, lump_t *l ) { + dmodel_t *in; + bmodel_t *out; + int i, j, count; + + in = (dmodel_t *)(fileBase + l->fileofs); + if (l->filelen % sizeof(*in)) + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + count = l->filelen / sizeof(*in); + + worldData->numBModels = count; + worldData->bmodels = out = (bmodel_t *)ri.Hunk_Alloc( count * sizeof(*out), h_low ); + + for ( i=0 ; itype = MOD_BRUSH; + model->data.bmodel = out; + if (worldIndex >= 0) + { + Com_sprintf( model->name, sizeof( model->name ), "*%d-%d", worldIndex, i ); + } + else + { + Com_sprintf( model->name, sizeof( model->name ), "*%d", i ); + } + + for (j=0 ; j<3 ; j++) { + out->bounds[0][j] = LittleFloat (in->mins[j]); + out->bounds[1][j] = LittleFloat (in->maxs[j]); + } + + CModelCache->InsertModelHandle(model->name, model->index); + + out->worldIndex = worldIndex; + out->firstSurface = LittleLong( in->firstSurface ); + out->numSurfaces = LittleLong( in->numSurfaces ); + + if (i == 0) + { + // Add this for limiting VBO surface creation + worldData->numWorldSurfaces = out->numSurfaces; + } + } +} + + + +//================================================================== + +/* +================= +R_SetParent +================= +*/ +static void R_SetParent (mnode_t *node, mnode_t *parent) +{ + node->parent = parent; + if (node->contents != -1) + return; + R_SetParent (node->children[0], node); + R_SetParent (node->children[1], node); +} + +/* +================= +R_LoadNodesAndLeafs +================= +*/ +static void R_LoadNodesAndLeafs (world_t *worldData, lump_t *nodeLump, lump_t *leafLump) { + int i, j, p; + dnode_t *in; + dleaf_t *inLeaf; + mnode_t *out; + int numNodes, numLeafs; + + in = (dnode_t *)(fileBase + nodeLump->fileofs); + if (nodeLump->filelen % sizeof(dnode_t) || + leafLump->filelen % sizeof(dleaf_t) ) { + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + } + numNodes = nodeLump->filelen / sizeof(dnode_t); + numLeafs = leafLump->filelen / sizeof(dleaf_t); + + out = (mnode_t *)ri.Hunk_Alloc ( (numNodes + numLeafs) * sizeof(*out), h_low); + + worldData->nodes = out; + worldData->numnodes = numNodes + numLeafs; + worldData->numDecisionNodes = numNodes; + + // load nodes + for ( i=0 ; imins[j] = LittleLong (in->mins[j]); + out->maxs[j] = LittleLong (in->maxs[j]); + } + + p = LittleLong(in->planeNum); + out->plane = worldData->planes + p; + + out->contents = CONTENTS_NODE; // differentiate from leafs + + for (j=0 ; j<2 ; j++) + { + p = LittleLong (in->children[j]); + if (p >= 0) + out->children[j] = worldData->nodes + p; + else + out->children[j] = worldData->nodes + numNodes + (-1 - p); + } + } + + // load leafs + inLeaf = (dleaf_t *)(fileBase + leafLump->fileofs); + for ( i=0 ; imins[j] = LittleLong (inLeaf->mins[j]); + out->maxs[j] = LittleLong (inLeaf->maxs[j]); + } + + out->cluster = LittleLong(inLeaf->cluster); + out->area = LittleLong(inLeaf->area); + + if ( out->cluster >= worldData->numClusters ) { + worldData->numClusters = out->cluster + 1; + } + + out->firstmarksurface = LittleLong(inLeaf->firstLeafSurface); + out->nummarksurfaces = LittleLong(inLeaf->numLeafSurfaces); + } + + // chain decendants + R_SetParent (worldData->nodes, NULL); +} + +//============================================================================= + +/* +================= +R_LoadShaders +================= +*/ +static void R_LoadShaders( world_t *worldData, lump_t *l ) { + int i, count; + dshader_t *in, *out; + + in = (dshader_t *)(fileBase + l->fileofs); + if (l->filelen % sizeof(*in)) + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + count = l->filelen / sizeof(*in); + out = (dshader_t *)ri.Hunk_Alloc ( count*sizeof(*out), h_low ); + + worldData->shaders = out; + worldData->numShaders = count; + + Com_Memcpy( out, in, count*sizeof(*out) ); + + for ( i=0 ; ifileofs); + if (l->filelen % sizeof(*in)) + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + count = l->filelen / sizeof(*in); + out = (int *)ri.Hunk_Alloc ( count*sizeof(*out), h_low); + + worldData->marksurfaces = out; + worldData->nummarksurfaces = count; + + for ( i=0 ; ifileofs); + if (l->filelen % sizeof(*in)) + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + count = l->filelen / sizeof(*in); + out = (cplane_t *)ri.Hunk_Alloc ( count*2*sizeof(*out), h_low); + + worldData->planes = out; + worldData->numplanes = count; + + for ( i=0 ; inormal[j] = LittleFloat (in->normal[j]); + if (out->normal[j] < 0) { + bits |= 1<dist = LittleFloat (in->dist); + out->type = PlaneTypeForNormal( out->normal ); + out->signbits = bits; + } +} + +/* +================= +R_LoadFogs + +================= +*/ +static void R_LoadFogs( world_t *worldData, lump_t *l, lump_t *brushesLump, lump_t *sidesLump ) { + int i; + fog_t *out; + dfog_t *fogs; + dbrush_t *brushes, *brush; + dbrushside_t *sides; + int count, brushesCount, sidesCount; + int sideNum; + int planeNum; + shader_t *shader; + float d; + int firstSide; + + fogs = (dfog_t *)(fileBase + l->fileofs); + if (l->filelen % sizeof(*fogs)) { + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + } + count = l->filelen / sizeof(*fogs); + + // create fog strucutres for them + worldData->numfogs = count + 1; + worldData->fogs = (fog_t *)ri.Hunk_Alloc ( worldData->numfogs*sizeof(*out), h_low); + worldData->globalFog = nullptr; + worldData->globalFogIndex = -1; + out = worldData->fogs + 1; + + if ( !count ) { + return; + } + + brushes = (dbrush_t *)(fileBase + brushesLump->fileofs); + if (brushesLump->filelen % sizeof(*brushes)) { + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + } + brushesCount = brushesLump->filelen / sizeof(*brushes); + + sides = (dbrushside_t *)(fileBase + sidesLump->fileofs); + if (sidesLump->filelen % sizeof(*sides)) { + ri.Error (ERR_DROP, "LoadMap: funny lump size in %s",worldData->name); + } + sidesCount = sidesLump->filelen / sizeof(*sides); + + for ( i=0 ; ioriginalBrushNumber = LittleLong( fogs->brushNum ); + + if ( out->originalBrushNumber == -1 ) + { + out->bounds[0][0] = out->bounds[0][1] = out->bounds[0][2] = MIN_WORLD_COORD; + out->bounds[1][0] = out->bounds[1][1] = out->bounds[1][2] = MAX_WORLD_COORD; + firstSide = -1; + + worldData->globalFog = worldData->fogs + i + 1; + worldData->globalFogIndex = i + 1; + } + else + { + if ( (unsigned)out->originalBrushNumber >= brushesCount ) { + ri.Error( ERR_DROP, "fog brushNumber out of range" ); + } + brush = brushes + out->originalBrushNumber; + + firstSide = LittleLong( brush->firstSide ); + + if ( (unsigned)firstSide > sidesCount - 6 ) { + ri.Error( ERR_DROP, "fog brush sideNumber out of range" ); + } + + // brushes are always sorted with the axial sides first + sideNum = firstSide + 0; + planeNum = LittleLong( sides[ sideNum ].planeNum ); + out->bounds[0][0] = -worldData->planes[ planeNum ].dist; + + sideNum = firstSide + 1; + planeNum = LittleLong( sides[ sideNum ].planeNum ); + out->bounds[1][0] = worldData->planes[ planeNum ].dist; + + sideNum = firstSide + 2; + planeNum = LittleLong( sides[ sideNum ].planeNum ); + out->bounds[0][1] = -worldData->planes[ planeNum ].dist; + + sideNum = firstSide + 3; + planeNum = LittleLong( sides[ sideNum ].planeNum ); + out->bounds[1][1] = worldData->planes[ planeNum ].dist; + + sideNum = firstSide + 4; + planeNum = LittleLong( sides[ sideNum ].planeNum ); + out->bounds[0][2] = -worldData->planes[ planeNum ].dist; + + sideNum = firstSide + 5; + planeNum = LittleLong( sides[ sideNum ].planeNum ); + out->bounds[1][2] = worldData->planes[ planeNum ].dist; + } + + // get information from the shader for fog parameters + shader = R_FindShader( fogs->shader, lightmapsNone, stylesDefault, qtrue ); + + if (shader->defaultShader == qtrue || shader->fogParms.depthForOpaque == 0) + { + ri.Printf(PRINT_WARNING, "Couldn't find proper shader for bsp fog %i %s\n", i, fogs->shader); + shader->fogParms.depthForOpaque = 65535.f; + } + + out->parms = shader->fogParms; + + VectorSet4(out->color, + shader->fogParms.color[0] * tr.identityLight, + shader->fogParms.color[1] * tr.identityLight, + shader->fogParms.color[2] * tr.identityLight, + 1.0); + + d = shader->fogParms.depthForOpaque < 1 ? 1 : shader->fogParms.depthForOpaque; + out->tcScale = 1.0f / d; + + // set the gradient vector + sideNum = LittleLong( fogs->visibleSide ); + + out->hasSurface = (out->originalBrushNumber == -1) ? qfalse : qtrue; + if ( sideNum != -1 ) { + planeNum = LittleLong( sides[ firstSide + sideNum ].planeNum ); + VectorSubtract( vec3_origin, worldData->planes[ planeNum ].normal, out->surface ); + out->surface[3] = -worldData->planes[ planeNum ].dist; + } + + out++; + } + +} + + +/* +================ +R_LoadLightGrid + +================ +*/ +void R_LoadLightGrid( world_t *worldData, lump_t *l ) { + int i; + vec3_t maxs; + float *wMins, *wMaxs; + + worldData->lightGridInverseSize[0] = 1.0f / worldData->lightGridSize[0]; + worldData->lightGridInverseSize[1] = 1.0f / worldData->lightGridSize[1]; + worldData->lightGridInverseSize[2] = 1.0f / worldData->lightGridSize[2]; + + wMins = worldData->bmodels[0].bounds[0]; + wMaxs = worldData->bmodels[0].bounds[1]; + + for ( i = 0 ; i < 3 ; i++ ) { + worldData->lightGridOrigin[i] = worldData->lightGridSize[i] * ceil( wMins[i] / worldData->lightGridSize[i] ); + maxs[i] = worldData->lightGridSize[i] * floor( wMaxs[i] / worldData->lightGridSize[i] ); + worldData->lightGridBounds[i] = (maxs[i] - worldData->lightGridOrigin[i])/worldData->lightGridSize[i] + 1; + } + + int numGridDataElements = l->filelen / sizeof(*worldData->lightGridData); + + worldData->lightGridData = (mgrid_t *)ri.Hunk_Alloc( l->filelen, h_low ); + Com_Memcpy( worldData->lightGridData, (void *)(fileBase + l->fileofs), l->filelen ); + + // deal with overbright bits + for ( i = 0 ; i < numGridDataElements ; i++ ) + { + for(int j = 0; j < MAXLIGHTMAPS; j++) + { + R_ColorShiftLightingBytes( + worldData->lightGridData[i].ambientLight[j], + worldData->lightGridData[i].ambientLight[j]); + R_ColorShiftLightingBytes( + worldData->lightGridData[i].directLight[j], + worldData->lightGridData[i].directLight[j]); + } + } + + // load hdr lightgrid + if (r_hdr->integer) + { + char filename[MAX_QPATH]; + float *hdrLightGrid; + int size; + + Com_sprintf( filename, sizeof( filename ), "maps/%s/lightgrid.raw", worldData->baseName); + //ri.Printf(PRINT_ALL, "looking for %s\n", filename); + + size = ri.FS_ReadFile(filename, (void **)&hdrLightGrid); + + if (hdrLightGrid) + { + if (size != sizeof(float) * 6 * worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]) + { + ri.Error(ERR_DROP, "Bad size for %s (%i, expected %i)!", filename, size, (int)(sizeof(float)) * 6 * worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]); + } + + worldData->hdrLightGrid = (float *)ri.Hunk_Alloc(size, h_low); + + for (i = 0; i < worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]; i++) + { + worldData->hdrLightGrid[i * 6 ] = hdrLightGrid[i * 6 ] / M_PI; + worldData->hdrLightGrid[i * 6 + 1] = hdrLightGrid[i * 6 + 1] / M_PI; + worldData->hdrLightGrid[i * 6 + 2] = hdrLightGrid[i * 6 + 2] / M_PI; + worldData->hdrLightGrid[i * 6 + 3] = hdrLightGrid[i * 6 + 3] / M_PI; + worldData->hdrLightGrid[i * 6 + 4] = hdrLightGrid[i * 6 + 4] / M_PI; + worldData->hdrLightGrid[i * 6 + 5] = hdrLightGrid[i * 6 + 5] / M_PI; + } + } + + if (hdrLightGrid) + ri.FS_FreeFile(hdrLightGrid); + } +} + +/* +================ +R_LoadLightGridArray + +================ +*/ +void R_LoadLightGridArray( world_t *worldData, lump_t *l ) { + worldData->numGridArrayElements = worldData->lightGridBounds[0] * worldData->lightGridBounds[1] * worldData->lightGridBounds[2]; + + if ( (unsigned)l->filelen != worldData->numGridArrayElements * sizeof(*worldData->lightGridArray) ) { + Com_Printf (S_COLOR_YELLOW "WARNING: light grid array mismatch\n" ); + worldData->lightGridData = NULL; + return; + } + + worldData->lightGridArray = (unsigned short *)Hunk_Alloc( l->filelen, h_low ); + memcpy( worldData->lightGridArray, (void *)(fileBase + l->fileofs), l->filelen ); +} + +/* +================ +R_LoadEntities +================ +*/ +void R_LoadEntities( world_t *worldData, lump_t *l ) { + const char *p; + char *token, *s; + char vertexRemapShaderText[] = "vertexremapshader"; + char remapShaderText[] = "remapshader"; + char keyname[MAX_TOKEN_CHARS]; + char value[MAX_TOKEN_CHARS]; + world_t *w; + + w = worldData; + w->lightGridSize[0] = 64; + w->lightGridSize[1] = 64; + w->lightGridSize[2] = 128; + + tr.distanceCull = 6000;//DEFAULT_DISTANCE_CULL; + + p = (char *)(fileBase + l->fileofs); + + // store for reference by the cgame + w->entityString = (char *)ri.Hunk_Alloc( l->filelen + 1, h_low ); + strcpy( w->entityString, p ); + w->entityParsePoint = w->entityString; + + token = COM_ParseExt( &p, qtrue ); + if (!*token || *token != '{') { + return; + } + + // only parse the world spawn + while ( 1 ) { + // parse key + token = COM_ParseExt( &p, qtrue ); + + if ( !*token || *token == '}' ) { + break; + } + Q_strncpyz(keyname, token, sizeof(keyname)); + + // parse value + token = COM_ParseExt( &p, qtrue ); + + if ( !*token || *token == '}' ) { + break; + } + Q_strncpyz(value, token, sizeof(value)); + + // check for remapping of shaders for vertex lighting + s = vertexRemapShaderText; + if (!Q_strncmp(keyname, s, strlen(s)) ) { + s = strchr(value, ';'); + if (!s) { + ri.Printf( PRINT_WARNING, "WARNING: no semi colon in vertexshaderremap '%s'\n", value ); + break; + } + *s++ = 0; + if (r_vertexLight->integer) { + R_RemapShader(value, s, "0"); + } + continue; + } + // check for remapping of shaders + s = remapShaderText; + if (!Q_strncmp(keyname, s, strlen(s)) ) { + s = strchr(value, ';'); + if (!s) { + ri.Printf( PRINT_WARNING, "WARNING: no semi colon in shaderremap '%s'\n", value ); + break; + } + *s++ = 0; + R_RemapShader(value, s, "0"); + continue; + } + if (!Q_stricmp(keyname, "distanceCull")) { + sscanf(value, "%f", &tr.distanceCull ); + if (r_distanceCull && r_distanceCull->value) + tr.distanceCull = r_distanceCull->value; + continue; + } + // check for a different grid size + if (!Q_stricmp(keyname, "gridsize")) { + sscanf(value, "%f %f %f", &w->lightGridSize[0], &w->lightGridSize[1], &w->lightGridSize[2] ); + continue; + } + + // check for auto exposure + if (!Q_stricmp(keyname, "autoExposureMinMax")) { + sscanf(value, "%f %f", &tr.autoExposureMinMax[0], &tr.autoExposureMinMax[1]); + continue; + } + } +} + +/* +================= +R_GetEntityToken +================= +*/ +qboolean R_GetEntityToken( char *buffer, int size ) { + char *s; + world_t *worldData = &s_worldData; + + if (size == -1) + { //force reset + worldData->entityParsePoint = worldData->entityString; + return qtrue; + } + + s = COM_Parse( (const char **)&worldData->entityParsePoint ); + Q_strncpyz( buffer, s, size ); + if ( !worldData->entityParsePoint && !s[0] ) { + worldData->entityParsePoint = worldData->entityString; + return qfalse; + } else { + return qtrue; + } +} + +#ifndef MAX_SPAWN_VARS +#define MAX_SPAWN_VARS 64 +#endif + +// derived from G_ParseSpawnVars() in g_spawn.c +static qboolean R_ParseSpawnVars( char *spawnVarChars, int maxSpawnVarChars, int *numSpawnVars, char *spawnVars[MAX_SPAWN_VARS][2] ) +{ + char keyname[MAX_TOKEN_CHARS]; + char com_token[MAX_TOKEN_CHARS]; + int numSpawnVarChars = 0; + + *numSpawnVars = 0; + + // parse the opening brace + if ( !R_GetEntityToken( com_token, sizeof( com_token ) ) ) { + // end of spawn string + return qfalse; + } + if ( com_token[0] != '{' ) { + ri.Printf( PRINT_ALL, "R_ParseSpawnVars: found %s when expecting {\n",com_token ); + return qfalse; + } + + // go through all the key / value pairs + while ( 1 ) { + int keyLength, tokenLength; + + // parse key + if ( !R_GetEntityToken( keyname, sizeof( keyname ) ) ) { + ri.Printf( PRINT_ALL, "R_ParseSpawnVars: EOF without closing brace\n" ); + return qfalse; + } + + if ( keyname[0] == '}' ) { + break; + } + + // parse value + if ( !R_GetEntityToken( com_token, sizeof( com_token ) ) ) { + ri.Printf( PRINT_ALL, "R_ParseSpawnVars: EOF without closing brace\n" ); + return qfalse; + } + + if ( com_token[0] == '}' ) { + ri.Printf( PRINT_ALL, "R_ParseSpawnVars: closing brace without data\n" ); + return qfalse; + } + + if ( *numSpawnVars == MAX_SPAWN_VARS ) { + ri.Printf( PRINT_ALL, "R_ParseSpawnVars: MAX_SPAWN_VARS\n" ); + return qfalse; + } + + keyLength = strlen(keyname) + 1; + tokenLength = strlen(com_token) + 1; + + if (numSpawnVarChars + keyLength + tokenLength > maxSpawnVarChars) + { + ri.Printf( PRINT_ALL, "R_ParseSpawnVars: MAX_SPAWN_VAR_CHARS\n" ); + return qfalse; + } + + strcpy(spawnVarChars + numSpawnVarChars, keyname); + spawnVars[ *numSpawnVars ][0] = spawnVarChars + numSpawnVarChars; + numSpawnVarChars += keyLength; + + strcpy(spawnVarChars + numSpawnVarChars, com_token); + spawnVars[ *numSpawnVars ][1] = spawnVarChars + numSpawnVarChars; + numSpawnVarChars += tokenLength; + + (*numSpawnVars)++; + } + + return qtrue; +} + +void R_LoadEnvironmentJson(const char *baseName) +{ + char filename[MAX_QPATH]; + + union { + char *c; + void *v; + } buffer; + char *bufferEnd; + + const char *environmentArrayJson; + int filelen, i; + + Com_sprintf(filename, sizeof(filename), "cubemaps/%s/env.json", baseName); + + filelen = ri.FS_ReadFile(filename, &buffer.v); + if (!buffer.c) + return; + bufferEnd = buffer.c + filelen; + + ri.Printf(PRINT_ALL, "Loaded Enviroment JSON: %s\n", filename); + + if (JSON_ValueGetType(buffer.c, bufferEnd) != JSONTYPE_OBJECT) + { + ri.Printf(PRINT_ALL, "Bad %s: does not start with a object\n", filename); + ri.FS_FreeFile(buffer.v); + return; + } + //-----------------------------CUBEMAPS------------------------------------ + environmentArrayJson = JSON_ObjectGetNamedValue(buffer.c, bufferEnd, "Cubemaps"); + if (!environmentArrayJson) + { + ri.Printf(PRINT_ALL, "Bad %s: no Cubemaps\n", filename); + ri.FS_FreeFile(buffer.v); + return; + } + + if (JSON_ValueGetType(environmentArrayJson, bufferEnd) != JSONTYPE_ARRAY) + { + ri.Printf(PRINT_ALL, "Bad %s: Cubemaps not an array\n", filename); + ri.FS_FreeFile(buffer.v); + return; + } + + tr.numCubemaps = JSON_ArrayGetIndex(environmentArrayJson, bufferEnd, NULL, 0); + tr.cubemaps = (cubemap_t *)ri.Hunk_Alloc(tr.numCubemaps * sizeof(*tr.cubemaps), h_low); + + for (i = 0; i < tr.numCubemaps; i++) + { + cubemap_t *cubemap = &tr.cubemaps[i]; + const char *cubemapJson, *keyValueJson, *indexes[3]; + int j; + + cubemapJson = JSON_ArrayGetValue(environmentArrayJson, bufferEnd, i); + + keyValueJson = JSON_ObjectGetNamedValue(cubemapJson, bufferEnd, "Name"); + if (!JSON_ValueGetString(keyValueJson, bufferEnd, cubemap->name, MAX_QPATH)) + cubemap->name[0] = '\0'; + + keyValueJson = JSON_ObjectGetNamedValue(cubemapJson, bufferEnd, "Position"); + JSON_ArrayGetIndex(keyValueJson, bufferEnd, indexes, 3); + for (j = 0; j < 3; j++) + cubemap->origin[j] = JSON_ValueGetFloat(indexes[j], bufferEnd); + + cubemap->parallaxRadius = 1000.0f; + keyValueJson = JSON_ObjectGetNamedValue(cubemapJson, bufferEnd, "Radius"); + if (keyValueJson) + cubemap->parallaxRadius = JSON_ValueGetFloat(keyValueJson, bufferEnd); + } + + ri.FS_FreeFile(buffer.v); +} + +void R_LoadCubemapEntities(const char *cubemapEntityName) +{ + char spawnVarChars[2048]; + int numSpawnVars; + char *spawnVars[MAX_SPAWN_VARS][2]; + int numCubemaps = 0; + + // count cubemaps + numCubemaps = 0; + while(R_ParseSpawnVars(spawnVarChars, sizeof(spawnVarChars), &numSpawnVars, spawnVars)) + { + int i; + + for (i = 0; i < numSpawnVars; i++) + { + if (!Q_stricmp(spawnVars[i][0], "classname") && !Q_stricmp(spawnVars[i][1], cubemapEntityName)) + numCubemaps++; + } + } + + if (!numCubemaps) + return; + + tr.numCubemaps = numCubemaps; + tr.cubemaps = (cubemap_t *)ri.Hunk_Alloc(tr.numCubemaps * sizeof(*tr.cubemaps), h_low); + + numCubemaps = 0; + while(R_ParseSpawnVars(spawnVarChars, sizeof(spawnVarChars), &numSpawnVars, spawnVars)) + { + int i; + char name[MAX_QPATH]; + qboolean isCubemap = qfalse; + qboolean originSet = qfalse; + vec3_t origin; + float parallaxRadius = 1000.0f; + + name[0] = '\0'; + for (i = 0; i < numSpawnVars; i++) + { + if (!Q_stricmp(spawnVars[i][0], "classname") && !Q_stricmp(spawnVars[i][1], cubemapEntityName)) + isCubemap = qtrue; + + if (!Q_stricmp(spawnVars[i][0], "name")) + Q_strncpyz(name, spawnVars[i][1], MAX_QPATH); + + if (!Q_stricmp(spawnVars[i][0], "origin")) + { + sscanf(spawnVars[i][1], "%f %f %f", &origin[0], &origin[1], &origin[2]); + originSet = qtrue; + } + else if (!Q_stricmp(spawnVars[i][0], "radius")) + { + sscanf(spawnVars[i][1], "%f", ¶llaxRadius); + } + } + + if (isCubemap && originSet) + { + cubemap_t *cubemap = &tr.cubemaps[numCubemaps]; + Q_strncpyz(cubemap->name, name, MAX_QPATH); + VectorCopy(origin, cubemap->origin); + cubemap->parallaxRadius = parallaxRadius; + cubemap->image = nullptr; + numCubemaps++; + } + } +} + +static void R_AssignCubemapsToWorldSurfaces(world_t *worldData) +{ + world_t *w; + int i; + + w = worldData; + + for (i = 0; i < w->numsurfaces; i++) + { + msurface_t *surf = &w->surfaces[i]; + vec3_t surfOrigin; + + if (surf->cullinfo.type & CULLINFO_SPHERE) + { + VectorCopy(surf->cullinfo.localOrigin, surfOrigin); + } + else if (surf->cullinfo.type & CULLINFO_BOX) + { + surfOrigin[0] = (surf->cullinfo.bounds[0][0] + surf->cullinfo.bounds[1][0]) * 0.5f; + surfOrigin[1] = (surf->cullinfo.bounds[0][1] + surf->cullinfo.bounds[1][1]) * 0.5f; + surfOrigin[2] = (surf->cullinfo.bounds[0][2] + surf->cullinfo.bounds[1][2]) * 0.5f; + } + else + { + //ri.Printf(PRINT_ALL, "surface %d has no cubemap\n", i); + continue; + } + + surf->cubemapIndex = R_CubemapForPoint(surfOrigin); + //ri.Printf(PRINT_ALL, "surface %d has cubemap %d\n", i, surf->cubemapIndex); + } +} + + +static void R_RenderAllCubemaps() +{ + R_IssuePendingRenderCommands(); + R_InitNextFrame(); + + GLenum cubemapFormat = GL_RGBA8; + if (r_hdr->integer) + { + cubemapFormat = GL_RGBA16F; + } + + for (int k = 0; k <= r_cubeMappingBounces->integer; k++) + { + bool bounce = k != 0; + // Limit number of Cubemaps per map + int maxCubemaps = MIN(tr.numCubemaps, 128); + for (int i = 0; i < maxCubemaps; i++) + { + for (int j = 0; j < 6; j++) + { + R_RenderCubemapSide(i, j, bounce); + } + + R_AddConvolveCubemapCmd(&tr.cubemaps[i], i); + R_IssuePendingRenderCommands(); + } + } +} + + +void R_LoadWeatherZones(world_t *worldData, lump_t *brushesLump, lump_t *sidesLump) +{ + dbrush_t *brushes; + dbrushside_t *sides; + int brushesCount, sidesCount; + + brushes = (dbrush_t *)(fileBase + brushesLump->fileofs); + if (brushesLump->filelen % sizeof(*brushes)) { + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); + } + brushesCount = brushesLump->filelen / sizeof(*brushes); + + sides = (dbrushside_t *)(fileBase + sidesLump->fileofs); + if (sidesLump->filelen % sizeof(*sides)) { + ri.Error(ERR_DROP, "LoadMap: funny lump size in %s", worldData->name); + } + sidesCount = sidesLump->filelen / sizeof(*sides); + + tr.weatherSystem->weatherBrushType = WEATHER_BRUSHES_NONE; + + for (int i = 0; i < brushesCount; i++, brushes++) { + dshader_t *currentShader = worldData->shaders + brushes->shaderNum; + int contents = currentShader->contentFlags; + if (!(contents & CONTENTS_INSIDE || contents & CONTENTS_OUTSIDE)) + continue; + + weatherBrushType_t currentBrushType = contents & CONTENTS_OUTSIDE ? WEATHER_BRUSHES_OUTSIDE : WEATHER_BRUSHES_INSIDE; + if (tr.weatherSystem->weatherBrushType == WEATHER_BRUSHES_NONE) + tr.weatherSystem->weatherBrushType = currentBrushType; + + if (tr.weatherSystem->weatherBrushType != currentBrushType) + { + Com_Error(ERR_DROP, "Weather Effect: Both Indoor and Outdoor brushs encountered in map.\n"); + return; + } + + vec4_t planes[64]; + for (int j = 0; j < brushes->numSides; j++) + { + int currentSideIndex = brushes->firstSide + j; + int currentPlaneIndex = sides[currentSideIndex].planeNum; + planes[j][0] = worldData->planes[currentPlaneIndex].normal[0]; + planes[j][1] = worldData->planes[currentPlaneIndex].normal[1]; + planes[j][2] = worldData->planes[currentPlaneIndex].normal[2]; + planes[j][3] = worldData->planes[currentPlaneIndex].dist; + } + + R_AddWeatherBrush((uint8_t)brushes->numSides, planes); + } +} + + +/* +================= +R_MergeLeafSurfaces + +Merges surfaces that share a common leaf +================= +*/ +static void R_MergeLeafSurfaces(world_t *worldData) +{ + int i, j, k; + int numWorldSurfaces; + int mergedSurfIndex; + int numMergedSurfaces; + int numUnmergedSurfaces; + VBO_t *vbo; + IBO_t *ibo; + + msurface_t *mergedSurf; + + glIndex_t *iboIndexes, *outIboIndexes; + int numIboIndexes; + + int startTime, endTime; + + startTime = ri.Milliseconds(); + + numWorldSurfaces = worldData->numWorldSurfaces; + + // use viewcount to keep track of mergers + for (i = 0; i < numWorldSurfaces; i++) + { + worldData->surfacesViewCount[i] = -1; + } + + // mark matching surfaces + for (i = 0; i < worldData->numnodes - worldData->numDecisionNodes; i++) + { + mnode_t *leaf = worldData->nodes + worldData->numDecisionNodes + i; + + for (j = 0; j < leaf->nummarksurfaces; j++) + { + msurface_t *surf1; + shader_t *shader1; + int fogIndex1; + int cubemapIndex1; + int surfNum1; + + surfNum1 = *(worldData->marksurfaces + leaf->firstmarksurface + j); + + if (worldData->surfacesViewCount[surfNum1] != -1) + continue; + + surf1 = worldData->surfaces + surfNum1; + + if ((*surf1->data != SF_GRID) && + (*surf1->data != SF_TRIANGLES) && + (*surf1->data != SF_FACE)) + { + continue; + } + + shader1 = surf1->shader; + + if(shader1->isSky) + continue; + + if(shader1->isPortal) + continue; + + if(ShaderRequiresCPUDeforms(shader1)) + continue; + + fogIndex1 = surf1->fogIndex; + cubemapIndex1 = surf1->cubemapIndex; + + worldData->surfacesViewCount[surfNum1] = surfNum1; + + for (k = j + 1; k < leaf->nummarksurfaces; k++) + { + msurface_t *surf2; + shader_t *shader2; + int fogIndex2; + int cubemapIndex2; + int surfNum2; + + surfNum2 = *(worldData->marksurfaces + leaf->firstmarksurface + k); + + if (worldData->surfacesViewCount[surfNum2] != -1) + continue; + + surf2 = worldData->surfaces + surfNum2; + + if ((*surf2->data != SF_GRID) && + (*surf2->data != SF_TRIANGLES) && + (*surf2->data != SF_FACE)) + continue; + + shader2 = surf2->shader; + + if (shader1 != shader2) + continue; + + fogIndex2 = surf2->fogIndex; + + if (fogIndex1 != fogIndex2) + continue; + + cubemapIndex2 = surf2->cubemapIndex; + + if (cubemapIndex1 != cubemapIndex2) + continue; + + worldData->surfacesViewCount[surfNum2] = surfNum1; + } + } + } + + // don't add surfaces that don't merge to any others to the merged list + for (i = 0; i < numWorldSurfaces; i++) + { + qboolean merges = qfalse; + + if (worldData->surfacesViewCount[i] != i) + continue; + + for (j = 0; j < numWorldSurfaces; j++) + { + if (j == i) + continue; + + if (worldData->surfacesViewCount[j] == i) + { + merges = qtrue; + break; + } + } + + if (!merges) + worldData->surfacesViewCount[i] = -1; + } + + // count merged/unmerged surfaces + numMergedSurfaces = 0; + numUnmergedSurfaces = 0; + for (i = 0; i < numWorldSurfaces; i++) + { + if (worldData->surfacesViewCount[i] == i) + { + numMergedSurfaces++; + } + else if (worldData->surfacesViewCount[i] == -1) + { + numUnmergedSurfaces++; + } + } + + // Allocate merged surfaces + worldData->mergedSurfaces = + (msurface_t *)ri.Hunk_Alloc( + sizeof(*worldData->mergedSurfaces) * numMergedSurfaces, h_low); + worldData->mergedSurfacesViewCount = + (int *)ri.Hunk_Alloc( + sizeof(*worldData->mergedSurfacesViewCount) * numMergedSurfaces, h_low); + worldData->mergedSurfacesDlightBits = + (int *)ri.Hunk_Alloc( + sizeof(*worldData->mergedSurfacesDlightBits) * numMergedSurfaces, h_low); + worldData->mergedSurfacesPshadowBits = + (int *)ri.Hunk_Alloc( + sizeof(*worldData->mergedSurfacesPshadowBits) * numMergedSurfaces, h_low); + worldData->numMergedSurfaces = numMergedSurfaces; + + // view surfaces are like mark surfaces, except negative ones represent merged surfaces + // -1 represents 0, -2 represents 1, and so on + worldData->viewSurfaces = + (int *)ri.Hunk_Alloc( + sizeof(*worldData->viewSurfaces) * worldData->nummarksurfaces, h_low); + + // copy view surfaces into mark surfaces + for (i = 0; i < worldData->nummarksurfaces; i++) + { + worldData->viewSurfaces[i] = worldData->marksurfaces[i]; + } + + // need to be synched here + R_IssuePendingRenderCommands(); + + // actually merge surfaces + numIboIndexes = 0; + mergedSurfIndex = 0; + mergedSurf = worldData->mergedSurfaces; + for (i = 0; i < numWorldSurfaces; i++) + { + msurface_t *surf1; + + vec3_t bounds[2]; + + int numSurfsToMerge; + int numIndexes; + int numVerts; + int firstIndex; + + srfBspSurface_t *vboSurf; + + if (worldData->surfacesViewCount[i] != i) + continue; + + surf1 = worldData->surfaces + i; + + // retrieve vbo + vbo = ((srfBspSurface_t *)(surf1->data))->vbo; + + // count verts, indexes, and surfaces + numSurfsToMerge = 0; + numIndexes = 0; + numVerts = 0; + for (j = i; j < numWorldSurfaces; j++) + { + msurface_t *surf2; + srfBspSurface_t *bspSurf; + + if (worldData->surfacesViewCount[j] != i) + continue; + + surf2 = worldData->surfaces + j; + + bspSurf = (srfBspSurface_t *) surf2->data; + numIndexes += bspSurf->numIndexes; + numVerts += bspSurf->numVerts; + numSurfsToMerge++; + } + + if (numVerts == 0 || numIndexes == 0 || numSurfsToMerge < 2) + { + continue; + } + + // create ibo + ibo = tr.ibos[tr.numIBOs++] = (IBO_t*)ri.Hunk_Alloc(sizeof(*ibo), h_low); + memset(ibo, 0, sizeof(*ibo)); + numIboIndexes = 0; + + // allocate indexes + iboIndexes = outIboIndexes = (glIndex_t*)Z_Malloc(numIndexes * sizeof(*outIboIndexes), TAG_BSP); + + // Merge surfaces (indexes) and calculate bounds + ClearBounds(bounds[0], bounds[1]); + firstIndex = numIboIndexes; + for (j = i; j < numWorldSurfaces; j++) + { + msurface_t *surf2; + srfBspSurface_t *bspSurf; + + if (worldData->surfacesViewCount[j] != i) + continue; + + surf2 = worldData->surfaces + j; + + AddPointToBounds(surf2->cullinfo.bounds[0], bounds[0], bounds[1]); + AddPointToBounds(surf2->cullinfo.bounds[1], bounds[0], bounds[1]); + + bspSurf = (srfBspSurface_t *) surf2->data; + for (k = 0; k < bspSurf->numIndexes; k++) + { + *outIboIndexes++ = bspSurf->indexes[k] + bspSurf->firstVert; + numIboIndexes++; + } + break; + } + + vboSurf = (srfBspSurface_t *)ri.Hunk_Alloc(sizeof(*vboSurf), h_low); + memset(vboSurf, 0, sizeof(*vboSurf)); + vboSurf->surfaceType = SF_VBO_MESH; + + vboSurf->vbo = vbo; + vboSurf->ibo = ibo; + + vboSurf->numIndexes = numIndexes; + vboSurf->numVerts = numVerts; + vboSurf->firstIndex = firstIndex; + + vboSurf->minIndex = *(iboIndexes + firstIndex); + vboSurf->maxIndex = *(iboIndexes + firstIndex); + + for (j = 0; j < numIndexes; j++) + { + vboSurf->minIndex = MIN(vboSurf->minIndex, *(iboIndexes + firstIndex + j)); + vboSurf->maxIndex = MAX(vboSurf->maxIndex, *(iboIndexes + firstIndex + j)); + } + + VectorCopy(bounds[0], vboSurf->cullBounds[0]); + VectorCopy(bounds[1], vboSurf->cullBounds[1]); + + VectorCopy(bounds[0], mergedSurf->cullinfo.bounds[0]); + VectorCopy(bounds[1], mergedSurf->cullinfo.bounds[1]); + + mergedSurf->cullinfo.type = CULLINFO_BOX; + mergedSurf->data = (surfaceType_t *)vboSurf; + mergedSurf->fogIndex = surf1->fogIndex; + mergedSurf->cubemapIndex = surf1->cubemapIndex; + mergedSurf->shader = surf1->shader; + + // finish up the ibo + qglGenBuffers(1, &ibo->indexesVBO); + + R_BindIBO(ibo); + qglBufferData(GL_ELEMENT_ARRAY_BUFFER, numIboIndexes * sizeof(*iboIndexes), iboIndexes, GL_STATIC_DRAW); + R_BindNullIBO(); + + GL_CheckErrors(); + + Z_Free(iboIndexes); + + // redirect view surfaces to this surf + for (j = 0; j < numWorldSurfaces; j++) + { + if (worldData->surfacesViewCount[j] != i) + continue; + + for (k = 0; k < worldData->nummarksurfaces; k++) + { + int *mark = worldData->marksurfaces + k; + int *view = worldData->viewSurfaces + k; + + if (*mark == j) + *view = -(mergedSurfIndex + 1); + } + } + + mergedSurfIndex++; + mergedSurf++; + } + + endTime = ri.Milliseconds(); + + ri.Printf(PRINT_ALL, "Processed %d surfaces into %d merged, %d unmerged in %5.2f seconds\n", + numWorldSurfaces, numMergedSurfaces, numUnmergedSurfaces, (endTime - startTime) / 1000.0f); + + // reset viewcounts + for (i = 0; i < numWorldSurfaces; i++) + { + worldData->surfacesViewCount[i] = -1; + } +} + + +static void R_CalcVertexLightDirs( world_t *worldData ) +{ + int i, k; + msurface_t *surface; + + for(k = 0, surface = &worldData->surfaces[0]; k < worldData->numsurfaces /* worldData->numWorldSurfaces */; k++, surface++) + { + srfBspSurface_t *bspSurf = (srfBspSurface_t *) surface->data; + + switch(bspSurf->surfaceType) + { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + for(i = 0; i < bspSurf->numVerts; i++) + R_LightDirForPoint( + bspSurf->verts[i].xyz, + bspSurf->verts[i].lightdir, + bspSurf->verts[i].normal, + worldData ); + + break; + + default: + break; + } + } +} + +struct sprite_t +{ + vec4_t position; + vec3_t normal; + vec3_t color; + vec2_t widthHeight; + vec2_t skew; +}; + +static uint32_t UpdateHash( const char *text, uint32_t hash ) +{ + for ( int i = 0; text[i]; ++i ) + { + char letter = tolower((unsigned char)text[i]); + if (letter == '.') break; // don't include extension + if (letter == '\\') letter = '/'; // damn path names + if (letter == PATH_SEP) letter = '/'; // damn path names + + hash += (uint32_t)(letter)*(i+119); + } + + return (hash ^ (hash >> 10) ^ (hash >> 20)); +} + +static uint32_t R_CountSurfaceSprites( + const srfBspSurface_t *bspSurf, + float density, + const shaderStage_t *stage) +{ + uint32_t numStageSprites = 0; + + const srfVert_t *verts = bspSurf->verts; + const glIndex_t *indexes = bspSurf->indexes; + + for (int i = 0, numIndexes = bspSurf->numIndexes; i < numIndexes; i += 3) + { + const srfVert_t *v0 = verts + indexes[i + 0]; + const srfVert_t *v1 = verts + indexes[i + 1]; + const srfVert_t *v2 = verts + indexes[i + 2]; + + vec3_t p0, p1, p2; + VectorCopy(v0->xyz, p0); + VectorCopy(v1->xyz, p1); + VectorCopy(v2->xyz, p2); + + const vec2_t p01 = { p1[0] - p0[0], p1[1] - p0[1] }; + const vec2_t p02 = { p2[0] - p0[0], p2[1] - p0[1] }; + + const float zarea = std::fabs(p02[0] * p01[1] - p02[1] * p01[0]); + if (zarea <= 1.0) + { + // Triangle's area is too small to consider. + continue; + } + + const float step = density * Q_rsqrt(zarea); + for (float a = 0.0f; a < 1.0f; a += step) + { + for (float b = 0.0f, bend = (1.0f - a); b < bend; b += step) + { + numStageSprites += 1; + } + } + } + return numStageSprites; +} + +static int R_CreateSurfaceSpritesVertexData( + const srfBspSurface_t *bspSurf, + float density, + const shaderStage_t *stage, + std::vector *sprites) +{ + const srfVert_t *verts = bspSurf->verts; + const glIndex_t *indexes = bspSurf->indexes; + + vec4_t color = { 1.0, 1.0, 1.0, 1.0 }; + if (stage->rgbGen == CGEN_CONST) + { + color[0] = stage->constantColor[0]; + color[1] = stage->constantColor[1]; + color[2] = stage->constantColor[2]; + } + bool vertexLit = ( + stage->rgbGen == CGEN_VERTEX || + stage->rgbGen == CGEN_EXACT_VERTEX || + stage->rgbGen == CGEN_VERTEX_LIT || + stage->rgbGen == CGEN_EXACT_VERTEX_LIT); + + int numSprites = 0; + for ( int i = 0, numIndexes = bspSurf->numIndexes; i < numIndexes; i += 3 ) + { + const srfVert_t *v0 = verts + indexes[i + 0]; + const srfVert_t *v1 = verts + indexes[i + 1]; + const srfVert_t *v2 = verts + indexes[i + 2]; + + vec3_t p0, p1, p2; + VectorCopy(v0->xyz, p0); + VectorCopy(v1->xyz, p1); + VectorCopy(v2->xyz, p2); + + vec3_t n0, n1, n2; + VectorCopy(v0->normal, n0); + VectorCopy(v1->normal, n1); + VectorCopy(v2->normal, n2); + + vec4_t c0, c1, c2; + VectorCopy(v0->vertexColors[0], c0); + VectorCopy(v1->vertexColors[0], c1); + VectorCopy(v2->vertexColors[0], c2); + + const vec2_t p01 = {p1[0] - p0[0], p1[1] - p0[1]}; + const vec2_t p02 = {p2[0] - p0[0], p2[1] - p0[1]}; + + const float zarea = std::fabs(p02[0]*p01[1] - p02[1]*p01[0]); + if ( zarea <= 1.0 ) + { + // Triangle's area is too small to consider. + continue; + } + + // Generate the positions of the surface sprites. + // + // Pick random points inside of each triangle, using barycentric + // coordinates. + const float step = density * Q_rsqrt(zarea); + for ( float a = 0.0f; a < 1.0f; a += step ) + { + for ( float b = 0.0f, bend = (1.0f - a); b < bend; b += step ) + { + float x = flrand(0.0f, 1.0f)*step + a; + float y = flrand(0.0f, 1.0f)*step + b; + float z = 1.0f - x - y; + + // Ensure we're inside the triangle bounds. + if ( x > 1.0f ) continue; + if ( (x + y ) > 1.0f ) continue; + + // Calculate position inside triangle. + // pos = (((p0*x) + p1*y) + p2*z) + sprite_t sprite = {}; + VectorMA(sprite.position, x, p0, sprite.position); + VectorMA(sprite.position, y, p1, sprite.position); + VectorMA(sprite.position, z, p2, sprite.position); + sprite.position[3] = flrand(0.0f, 1.0f); + + if (vertexLit) + { + VectorMA(sprite.color, x, c0, sprite.color); + VectorMA(sprite.color, y, c1, sprite.color); + VectorMA(sprite.color, z, c2, sprite.color); + VectorScale(sprite.color, tr.identityLight, sprite.color); + } + else + VectorCopy(color, sprite.color); + + // x*x + y*y = 1.0 + // => y*y = 1.0 - x*x + // => y = -/+sqrt(1.0 - x*x) + float nx = flrand(-1.0f, 1.0f); + float ny = std::sqrt(1.0f - nx*nx); + ny *= irand(0, 1) ? -1 : 1; + + VectorSet(sprite.normal, nx, ny, 0.0f); + + sprite.widthHeight[0] = stage->ss->width*(1.0f + (stage->ss->variance[0] * flrand(0.0f, 1.0f))); + sprite.widthHeight[1] = stage->ss->height*(1.0f + (stage->ss->variance[1] * flrand(0.0f, 1.0f))); + if (stage->ss->facing == SURFSPRITE_FACING_DOWN) + sprite.widthHeight[1] *= -1.0f; + + sprite.skew[0] = stage->ss->height * stage->ss->vertSkew * flrand(-1.0f, 1.0f); + sprite.skew[1] = stage->ss->height * stage->ss->vertSkew * flrand(-1.0f, 1.0f); + + sprites->push_back(sprite); + sprites->push_back(sprite); + sprites->push_back(sprite); + sprites->push_back(sprite); + ++numSprites; + } + } + } + return numSprites; +} + +static void R_GenerateSurfaceSprites( + const srfBspSurface_t *bspSurf, + const shader_t *shader, + const shaderStage_t *stage, + const int fogIndex, + srfSprites_t *out, + std::vector *sprites) +{ + const surfaceSprite_t *surfaceSprite = stage->ss; + const textureBundle_t *bundle = &stage->bundle[0]; + + uint32_t hash = 0; + for ( int i = 0; bundle->image[i]; ++i ) + hash = UpdateHash(bundle->image[i]->imgName, hash); + + out->baseVertex = sprites->size(); + out->surfaceType = SF_SPRITES; + out->sprite = surfaceSprite; + //R_CreateSurfaceSpritesVertexData(bspSurf, surfaceSprite->density, stage, sprites); + out->numSprites = R_CreateSurfaceSpritesVertexData(bspSurf, surfaceSprite->density, stage, sprites); + out->numIndices = out->numSprites * 6; + out->fogIndex = fogIndex; + + out->vbo = NULL; + out->ibo = NULL; + + // FIXME: Need a better way to handle this. + out->shader = R_CreateShaderFromTextureBundle(va("*ss_%08x\n", hash), + bundle, stage->stateBits); + out->shader->spriteUbo = shader->spriteUbo; + + out->shader->cullType = shader->cullType; + out->shader->stages[0]->glslShaderGroup = tr.spriteShader; + out->alphaTestType = stage->alphaTestType; + + out->numAttributes = 4; + out->attributes = (vertexAttribute_t *)ri.Hunk_Alloc( + sizeof(vertexAttribute_t) * out->numAttributes, h_low); + + out->attributes[0].vbo = out->vbo; + out->attributes[0].index = ATTR_INDEX_POSITION; + out->attributes[0].numComponents = 4; + out->attributes[0].integerAttribute = qfalse; + out->attributes[0].type = GL_FLOAT; + out->attributes[0].normalize = GL_FALSE; + out->attributes[0].stride = sizeof(sprite_t); + out->attributes[0].offset = offsetof(sprite_t, position); + out->attributes[0].stepRate = 0; + + out->attributes[1].vbo = out->vbo; + out->attributes[1].index = ATTR_INDEX_NORMAL; + out->attributes[1].numComponents = 3; + out->attributes[1].integerAttribute = qfalse; + out->attributes[1].type = GL_FLOAT; + out->attributes[1].normalize = GL_FALSE; + out->attributes[1].stride = sizeof(sprite_t); + out->attributes[1].offset = offsetof(sprite_t, normal); + out->attributes[1].stepRate = 0; + + out->attributes[2].vbo = out->vbo; + out->attributes[2].index = ATTR_INDEX_COLOR; + out->attributes[2].numComponents = 3; + out->attributes[2].integerAttribute = qfalse; + out->attributes[2].type = GL_FLOAT; + out->attributes[2].normalize = GL_FALSE; + out->attributes[2].stride = sizeof(sprite_t); + out->attributes[2].offset = offsetof(sprite_t, color); + out->attributes[2].stepRate = 0; + + out->attributes[3].vbo = out->vbo; + out->attributes[3].index = ATTR_INDEX_POSITION2; + out->attributes[3].numComponents = 4; // store width,height and skew + out->attributes[3].integerAttribute = qfalse; + out->attributes[3].type = GL_FLOAT; + out->attributes[3].normalize = GL_FALSE; + out->attributes[3].stride = sizeof(sprite_t); + out->attributes[3].offset = offsetof(sprite_t, widthHeight); + out->attributes[3].stepRate = 0; +} + +static void R_GenerateSurfaceSprites( const world_t *world, int worldIndex ) +{ + int numSpriteStages = 0; + for (int i = 0; i < tr.numShaders; i++) + { + const shader_t *shader = tr.shaders[i]; + if (shader->spriteUbo != NULL) + continue; + + numSpriteStages += shader->numSurfaceSpriteStages; + } + + if (numSpriteStages == 0) + return; + + //TODO: put into backend + const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; + size_t spriteAlignedBlockSize = (sizeof(SurfaceSpriteBlock) + alignment) & ~alignment; + + if (glState.currentGlobalUBO != tr.spriteUbos[worldIndex]) + { + qglBindBuffer(GL_UNIFORM_BUFFER, tr.spriteUbos[worldIndex]); + glState.currentGlobalUBO = tr.spriteUbos[worldIndex]; + } + qglBufferData( + GL_UNIFORM_BUFFER, + numSpriteStages * spriteAlignedBlockSize, + nullptr, + GL_STATIC_DRAW); + + size_t alignedBlockSize = 0; + for (int i = 0; i < tr.numShaders; i++) + { + shader_t *shader = tr.shaders[i]; + if (!shader->numSurfaceSpriteStages) + continue; + + shader->spriteUbo = tr.spriteUbos[worldIndex]; + + for (int j = 0, numStages = shader->numUnfoggedPasses; + j < numStages; ++j) + { + const shaderStage_t *stage = shader->stages[j]; + if (!stage) + break; + + if (!stage->ss || stage->ss->type == SURFSPRITE_NONE) + continue; + + if (j > 0 && (stage->stateBits & GLS_DEPTHFUNC_EQUAL)) + { + continue; + } + + SurfaceSpriteBlock surfaceSpriteBlock = {}; + surfaceSprite_t *ss = stage->ss; + + surfaceSpriteBlock.fxGrow[0] = ss->fxGrow[0]; + surfaceSpriteBlock.fxGrow[1] = ss->fxGrow[1]; + surfaceSpriteBlock.fxDuration = ss->fxDuration; + surfaceSpriteBlock.fadeStartDistance = ss->fadeDist; + surfaceSpriteBlock.fadeEndDistance = MAX(ss->fadeDist + 250.f, ss->fadeMax); + surfaceSpriteBlock.fadeScale = ss->fadeScale; + surfaceSpriteBlock.wind = ss->wind; + surfaceSpriteBlock.windIdle = ss->windIdle; + surfaceSpriteBlock.fxAlphaStart = ss->fxAlphaStart; + surfaceSpriteBlock.fxAlphaEnd = ss->fxAlphaEnd; + + ss->spriteUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, ss->spriteUboOffset, sizeof(SurfaceSpriteBlock), &surfaceSpriteBlock); + alignedBlockSize += spriteAlignedBlockSize; + } + } + + msurface_t *surfaces = world->surfaces; + std::vector sprites_data; + sprites_data.reserve(65535); + IBO_t *ibo; + { + std::vector sprites_index_data; + sprites_index_data.reserve(98298); + for (int i = 0; i < 98299; i++) + { + const uint16_t face_indices[] = { 0, 1, 2, 0, 2, 3 }; + int vert_index = face_indices[i % 6] + (int(i / 6) * 4); + sprites_index_data.push_back(vert_index); + } + ibo = R_CreateIBO((byte *)sprites_index_data.data(), sprites_index_data.size() * sizeof(uint16_t), VBO_USAGE_STATIC); + } + + std::vector currentBatch; + currentBatch.reserve(65535); // worst case, theres at least 65535 surfaces with exactly one sprite + + for ( int i = 0, numSurfaces = world->numsurfaces; i < numSurfaces; ++i ) + { + msurface_t *surf = surfaces + i; + const srfBspSurface_t *bspSurf = (srfBspSurface_t *)surf->data; + switch ( bspSurf->surfaceType ) + { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + { + const shader_t *shader = surf->shader; + if ( !shader->numSurfaceSpriteStages ) + continue; + + surf->numSurfaceSprites = shader->numSurfaceSpriteStages; + surf->surfaceSprites = (srfSprites_t *)ri.Hunk_Alloc( + sizeof(srfSprites_t) * surf->numSurfaceSprites, h_low); + + int surfaceSpriteNum = 0; + for ( int j = 0, numStages = shader->numUnfoggedPasses; + j < numStages; ++j ) + { + const shaderStage_t *stage = shader->stages[j]; + if ( !stage ) + break; + + if ( !stage->ss || stage->ss->type == SURFSPRITE_NONE ) + continue; + + if (j > 0 && (stage->stateBits & GLS_DEPTHFUNC_EQUAL)) + { + ri.Printf(PRINT_WARNING, "depthFunc equal is not supported on surface sprites in rend2. Skipping stage\n"); + surf->numSurfaceSprites -= 1; + continue; + } + + srfSprites_t *sprite = surf->surfaceSprites + surfaceSpriteNum; + int numCurrentSurfaceSprites = R_CountSurfaceSprites(bspSurf, stage->ss->density, stage); + if ((sprites_data.size() + numCurrentSurfaceSprites * 4) > 65535) + { + VBO_t *vbo = R_CreateVBO((byte *)sprites_data.data(), + sizeof(sprite_t) * sprites_data.size(), VBO_USAGE_STATIC); + + for (srfSprites_t *sp : currentBatch) + { + sp->vbo = vbo; + sp->ibo = ibo; + sp->attributes[0].vbo = vbo; + sp->attributes[1].vbo = vbo; + sp->attributes[2].vbo = vbo; + sp->attributes[3].vbo = vbo; + } + + sprites_data.clear(); + currentBatch.clear(); + } + + R_GenerateSurfaceSprites(bspSurf, shader, stage, surf->fogIndex, sprite, &sprites_data); + currentBatch.push_back(sprite); + + ++surfaceSpriteNum; + } + break; + } + + default: + break; + } + } + + if (sprites_data.size() == 0) + return; + + VBO_t *vbo = R_CreateVBO((byte *)sprites_data.data(), + sizeof(sprite_t) * sprites_data.size(), VBO_USAGE_STATIC); + + for (srfSprites_t *sp : currentBatch) + { + sp->vbo = vbo; + sp->ibo = ibo; + sp->attributes[0].vbo = vbo; + sp->attributes[1].vbo = vbo; + sp->attributes[2].vbo = vbo; + sp->attributes[3].vbo = vbo; + } +} + +world_t *R_LoadBSP(const char *name, int *bspIndex) +{ + union { + byte *b; + void *v; + } buffer; + + world_t *worldData; + int worldIndex = -1; + if (bspIndex == nullptr) + { + worldData = &s_worldData; + } + else + { + if (tr.numBspModels >= MAX_SUB_BSP) + { + // too many + return nullptr; + } + + worldIndex = *bspIndex = tr.numBspModels; + + worldData = (world_t *)ri.Hunk_Alloc(sizeof(*worldData), h_low); + tr.bspModels[tr.numBspModels] = worldData; + ++tr.numBspModels; + } + + // load it + ri.FS_ReadFile(name, &buffer.v); + if (!buffer.b) + { + if (bspIndex == nullptr) + { + ri.Error (ERR_DROP, "RE_LoadWorldMap: %s not found", name); + } + + return nullptr; + } + + Com_Memset(worldData, 0, sizeof(*worldData)); + Q_strncpyz(worldData->name, name, sizeof(worldData->name)); + Q_strncpyz(worldData->baseName, COM_SkipPath(worldData->name), sizeof(worldData->name)); + COM_StripExtension(worldData->baseName, worldData->baseName, sizeof(worldData->baseName)); + + Q_strncpyz(tr.worldName, worldData->name, sizeof(worldData->name)); + COM_StripExtension(tr.worldName, tr.worldName, sizeof(tr.worldName)); + + const byte *startMarker = (const byte *)ri.Hunk_Alloc(0, h_low); + dheader_t *header = (dheader_t *)buffer.b; + fileBase = (byte *)header; + + int bspVersion = LittleLong(header->version); + if (bspVersion != BSP_VERSION) + { + ri.Error( + ERR_DROP, + "R_LoadBSP: %s has wrong version number (%i should be %i)", + name, + bspVersion, + BSP_VERSION); + } + + // swap all the lumps + for (int i = 0; i < sizeof(dheader_t) / 4; ++i) + { + ((int *)header)[i] = LittleLong ( ((int *)header)[i]); + } + + // load into heap + R_LoadEntities(worldData, &header->lumps[LUMP_ENTITIES]); + R_LoadShaders(worldData, &header->lumps[LUMP_SHADERS]); + R_LoadLightmaps( + worldData, + &header->lumps[LUMP_LIGHTMAPS], + &header->lumps[LUMP_SURFACES]); + R_LoadPlanes(worldData, &header->lumps[LUMP_PLANES]); + R_LoadFogs( + worldData, + &header->lumps[LUMP_FOGS], + &header->lumps[LUMP_BRUSHES], + &header->lumps[LUMP_BRUSHSIDES]); + R_LoadSurfaces( + worldData, + &header->lumps[LUMP_SURFACES], + &header->lumps[LUMP_DRAWVERTS], + &header->lumps[LUMP_DRAWINDEXES]); + R_LoadMarksurfaces(worldData, &header->lumps[LUMP_LEAFSURFACES]); + R_LoadNodesAndLeafs(worldData, &header->lumps[LUMP_NODES], &header->lumps[LUMP_LEAFS]); + R_LoadSubmodels(worldData, worldIndex, &header->lumps[LUMP_MODELS]); + R_LoadVisibility(worldData, &header->lumps[LUMP_VISIBILITY]); + R_LoadLightGrid(worldData, &header->lumps[LUMP_LIGHTGRID]); + R_LoadLightGridArray(worldData, &header->lumps[LUMP_LIGHTARRAY]); + + // determine vertex light directions + R_CalcVertexLightDirs(worldData); + + if (bspIndex == nullptr) + R_LoadWeatherZones( + worldData, + &header->lumps[LUMP_BRUSHES], + &header->lumps[LUMP_BRUSHSIDES]); + + R_GenerateSurfaceSprites(worldData, worldIndex + 1); + + // load cubemaps + if (r_cubeMapping->integer && bspIndex == nullptr) + { + // Try loading an env.json file first + R_LoadEnvironmentJson(worldData->baseName); + + const int numCubemapEntities = 5; + const char *cubemapEntities[numCubemapEntities] = + { + "misc_cubemap", + "info_player_deathmatch", + "info_player_start", + "info_player_duel", + "info_player_intermission", + }; + + if (!tr.numCubemaps) + { + for (int i = 0; i < numCubemapEntities; i++) + { + R_LoadCubemapEntities(cubemapEntities[i]); + if (tr.numCubemaps) + break; + } + + } + + if (tr.numCubemaps) + { + R_AssignCubemapsToWorldSurfaces(worldData); + } + } + + // create static VBOS from the world + R_CreateWorldVBOs(worldData); + if (r_mergeLeafSurfaces->integer) + { + R_MergeLeafSurfaces(worldData); + } + + worldData->dataSize = (const byte *)ri.Hunk_Alloc(0, h_low) - startMarker; + + // make sure the VBO glState entries are safe + R_BindNullVBO(); + R_BindNullIBO(); + + ri.FS_FreeFile(buffer.v); + + return worldData; +} + +/* +================= +RE_LoadWorldMap + +Called directly from cgame +================= +*/ +void RE_LoadWorldMap( const char *name ) { + if (tr.worldMapLoaded) + { + ri.Error(ERR_DROP, "ERROR: attempted to redundantly load world map"); + } + + // set default map light scale + tr.mapLightScale = 1.0f; + tr.sunShadowScale = 0.5f; + + // set default sun color to be used if it isn't + // overridden by a shader + tr.sunLight[0] = 1.0f; + tr.sunLight[1] = 1.0f; + tr.sunLight[2] = 1.0f; + + // set default sun direction to be used if it isn't + // overridden by a shader + tr.sunDirection[0] = 0.45f; + tr.sunDirection[1] = 0.3f; + tr.sunDirection[2] = 0.9f; + + VectorNormalize(tr.sunDirection); + + // set default autoexposure settings + tr.autoExposureMinMax[0] = -2.0f; + tr.autoExposureMinMax[1] = 2.0f; + + // set default tone mapping settings + tr.toneMinAvgMaxLevel[0] = -8.0f; + tr.toneMinAvgMaxLevel[1] = -2.0f; + tr.toneMinAvgMaxLevel[2] = 0.0f; + tr.explicitToneMap = false; + + world_t *world = R_LoadBSP(name); + if (world == nullptr) + { + // clear tr.world so the next/ try will not look at the partially + // loaded version + tr.world = nullptr; + return; + } + + if (r_hdr->integer && tr.hdrLighting && !tr.explicitToneMap) + { + tr.toneMinAvgMaxLevel[0] = -8.0f; + tr.toneMinAvgMaxLevel[1] = 0.0f; + tr.toneMinAvgMaxLevel[2] = 2.0f; + } + + tr.worldMapLoaded = qtrue; + tr.world = world; + + R_InitWeatherForMap(); + + // Render all cubemaps + if (r_cubeMapping->integer && tr.numCubemaps) + { + R_RenderAllCubemaps(); + } +} diff --git a/codemp/rd-rend2/tr_cache.cpp b/codemp/rd-rend2/tr_cache.cpp new file mode 100644 index 0000000000..4b546f90c9 --- /dev/null +++ b/codemp/rd-rend2/tr_cache.cpp @@ -0,0 +1,343 @@ +// tr_cache.cpp - Cache models, images, and more.. + +#include "tr_local.h" +#include "tr_cache.h" +#include + +namespace +{ + +void NormalizePath( char *out, const char *path, size_t outSize ) +{ + assert(outSize == MAX_QPATH); + Q_strncpyz(out, path, outSize); + Q_strlwr(out); +} + +} + +// This differs significantly from Raven's own caching code. +// For starters, we are allowed to use ri-> whatever because we don't care about running on dedicated (use rd-vanilla!) + +CModelCacheManager *CModelCache = new CModelCacheManager(); + +CachedFile::CachedFile() + : pDiskImage(nullptr) + , iLevelLastUsedOn(0) + , iPAKChecksum(-1) + , iAllocSize(0) +{ +} + +CModelCacheManager::FileCache::iterator CModelCacheManager::FindFile( const char *path ) +{ + return std::find_if( + std::begin(files), std::end(files), [path]( const CachedFile& file ) + { + return strcmp(path, file.path) == 0; + }); +} + +static const byte FakeGLAFile[] = +{ + 0x32, 0x4C, 0x47, 0x41, 0x06, 0x00, 0x00, 0x00, 0x2A, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x01, 0x00, 0x00, 0x00, + 0x14, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x18, 0x01, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, + 0x26, 0x01, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x4D, 0x6F, 0x64, 0x56, 0x69, 0x65, 0x77, 0x20, + 0x69, 0x6E, 0x74, 0x65, 0x72, 0x6E, 0x61, 0x6C, 0x20, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6C, 0x74, + 0x00, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, + 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, + 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0xCD, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, + 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3F, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFD, 0xBF, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, + 0x00, 0x80, 0x00, 0x80, 0x00, 0x80 +}; + +qboolean CModelCacheManager::LoadFile( const char *pFileName, void **ppFileBuffer, qboolean *pbAlreadyCached ) +{ + char path[MAX_QPATH]; + NormalizePath(path, pFileName, sizeof(path)); + + auto cacheEntry = FindFile(path); + if ( cacheEntry != std::end(files) ) + { + *ppFileBuffer = cacheEntry->pDiskImage; + *pbAlreadyCached = qtrue; + + return qtrue; + } + + *pbAlreadyCached = qfalse; + + // special case intercept first... + if (!strcmp (sDEFAULT_GLA_NAME ".gla", path)) + { + // return fake params as though it was found on disk... + void *pvFakeGLAFile = Z_Malloc(sizeof (FakeGLAFile), TAG_FILESYS, qfalse); + + memcpy(pvFakeGLAFile, &FakeGLAFile[0], sizeof (FakeGLAFile)); + *ppFileBuffer = pvFakeGLAFile; + + return qtrue; + } + + int len = ri.FS_ReadFile(path, ppFileBuffer); + if ( len == -1 || *ppFileBuffer == NULL ) + { + return qfalse; + } + + ri.Printf( PRINT_DEVELOPER, "C_LoadFile(): Loaded %s from disk\n", pFileName ); + + return qtrue; +} + + +void* CModelCacheManager::Allocate( int iSize, void *pvDiskBuffer, const char *psModelFileName, qboolean *bAlreadyFound, memtag_t eTag ) +{ + int iChecksum; + char sModelName[MAX_QPATH]; + + /* Standard NULL checking. */ + if( !psModelFileName || !psModelFileName[0] ) + return NULL; + + if( !bAlreadyFound ) + return NULL; + + NormalizePath(sModelName, psModelFileName, sizeof(sModelName)); + + CachedFile *pFile = nullptr; + auto cacheEntry = FindFile(sModelName); + if (cacheEntry == files.end()) + { + /* Create this image. */ + + if( pvDiskBuffer ) + Z_MorphMallocTag( pvDiskBuffer, eTag ); + else + pvDiskBuffer = Z_Malloc(iSize, eTag, qfalse); + + files.emplace_back(); + pFile = &files.back(); + pFile->pDiskImage = pvDiskBuffer; + pFile->iAllocSize = iSize; + Q_strncpyz(pFile->path, sModelName, sizeof(pFile->path)); + + if( ri.FS_FileIsInPAK( sModelName, &iChecksum ) ) + pFile->iPAKChecksum = iChecksum; /* Otherwise, it will be -1. */ + + *bAlreadyFound = qfalse; + } + else + { + /* + * Already found it. + * TODO: shader caching. + */ + *bAlreadyFound = qtrue; + pFile = &(*cacheEntry); + } + + pFile->iLevelLastUsedOn = tr.currentLevel; + + return pFile->pDiskImage; +} + +/* + * Clears out the cache (done on renderer shutdown I suppose) + */ +void CModelCacheManager::DeleteAll( void ) +{ + for ( auto& file : files ) + { + Z_Free(file.pDiskImage); + } + + FileCache().swap(files); + AssetCache().swap(assets); +} + +/* + * Scans the cache for assets which don't match the checksum, and dumps + * those that don't match. + */ +void CModelCacheManager::DumpNonPure( void ) +{ + ri.Printf( PRINT_DEVELOPER, "CCacheManager::DumpNonPure():\n"); + + for ( auto it = files.begin(); it != files.end(); /* empty */ ) + { + int iChecksum; + int iInPak = ri.FS_FileIsInPAK( it->path, &iChecksum ); + + if( iInPak == -1 || iChecksum != it->iPAKChecksum ) + { + /* Erase the file because it doesn't match the checksum */ + ri.Printf( PRINT_DEVELOPER, "Dumping none pure model \"%s\"", it->path ); + + if( it->pDiskImage ) + Z_Free( it->pDiskImage ); + + it = files.erase(it); + } + else + { + ++it; + } + } + + ri.Printf( PRINT_DEVELOPER, "CCacheManager::DumpNonPure(): Ok\n"); +} + +CModelCacheManager::AssetCache::iterator CModelCacheManager::FindAsset( const char *path ) +{ + return std::find_if( + std::begin(assets), std::end(assets), [path]( const Asset& asset ) + { + return strcmp(path, asset.path) == 0; + }); +} + +qhandle_t CModelCacheManager::GetModelHandle( const char *fileName ) +{ + char path[MAX_QPATH]; + NormalizePath(path, fileName, sizeof(path)); + + const auto it = FindAsset(path); + if( it == std::end(assets) ) + return -1; // asset not found + + return it->handle; +} + +void CModelCacheManager::InsertModelHandle( const char *fileName, qhandle_t handle ) +{ + char path[MAX_QPATH]; + NormalizePath(path, fileName, sizeof(path)); + + Asset asset; + asset.handle = handle; + Q_strncpyz(asset.path, path, sizeof(asset.path)); + assets.emplace_back(asset); +} + +qboolean CModelCacheManager::LevelLoadEnd( qboolean deleteUnusedByLevel ) +{ + qboolean bAtLeastOneModelFreed = qfalse; + + ri.Printf( PRINT_DEVELOPER, S_COLOR_GREEN "CModelCacheManager::LevelLoadEnd():\n"); + + for ( auto it = files.begin(); it != files.end(); /* empty */ ) + { + bool bDeleteThis = false; + + if( deleteUnusedByLevel ) + bDeleteThis = (it->iLevelLastUsedOn != tr.currentLevel); + else + bDeleteThis = (it->iLevelLastUsedOn < tr.currentLevel); + + if( bDeleteThis ) + { + ri.Printf( PRINT_DEVELOPER, S_COLOR_GREEN "Dumping \"%s\"", it->path); + if( it->pDiskImage ) + { + Z_Free( it->pDiskImage ); + bAtLeastOneModelFreed = qtrue; // FIXME: is this correct? shouldn't it be in the next lower scope? + } + + it = files.erase(it); + } + else + { + ++it; + } + } + + ri.Printf( PRINT_DEVELOPER, S_COLOR_GREEN "CModelCacheManager::LevelLoadEnd(): Ok\n"); + + return bAtLeastOneModelFreed; +} + +/* + * Wrappers for the above funcs so they export properly. + */ + +qboolean C_Models_LevelLoadEnd( qboolean deleteUnusedByLevel ) +{ + return CModelCache->LevelLoadEnd(deleteUnusedByLevel); +} + +qboolean C_Images_LevelLoadEnd() +{ + return qfalse; +} + +/* + * Shader storage and retrieval, unique to the model caching + */ + +void CModelCacheManager::StoreShaderRequest( const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke ) +{ + char sModelName[MAX_QPATH]; + NormalizePath(sModelName, psModelFileName, sizeof(sModelName)); + + auto file = FindFile(sModelName); + if ( file == files.end() ) + { + return; + } + + if( file->pDiskImage == NULL ) + { + /* Shouldn't even happen. */ + assert(0); + return; + } + + int iNameOffset = psShaderName - (char *)file->pDiskImage; + int iPokeOffset = (char*) piShaderIndexPoke - (char *)file->pDiskImage; + + file->shaderCache.push_back(ShaderCacheEntry(iNameOffset, iPokeOffset)); +} + +void CModelCacheManager::AllocateShaders( const char *psFileName ) +{ + // if we already had this model entry, then re-register all the shaders it wanted... + + char sModelName[MAX_QPATH]; + NormalizePath(sModelName, psFileName, sizeof(sModelName)); + + auto file = FindFile(sModelName); + if ( file == files.end() ) + { + return; + } + + if( file->pDiskImage == NULL ) + { + /* Shouldn't even happen. */ + assert(0); + return; + } + + for( const ShaderCacheEntry& shader : file->shaderCache ) + { + char *psShaderName = ((char*)file->pDiskImage + shader.nameOffset); + int *piShaderPokePtr = (int *)((char*)file->pDiskImage + shader.pokeOffset); + + shader_t *sh = R_FindShader(psShaderName, lightmapsNone, stylesDefault, qtrue); + if ( sh->defaultShader ) + *piShaderPokePtr = 0; + else + *piShaderPokePtr = sh->index; + } +} diff --git a/codemp/rd-rend2/tr_cache.h b/codemp/rd-rend2/tr_cache.h new file mode 100644 index 0000000000..b4fccc188e --- /dev/null +++ b/codemp/rd-rend2/tr_cache.h @@ -0,0 +1,94 @@ +#pragma once + +#include +#include + +/* + * This stores the loaded file information that we need on retrieval + */ +struct Asset +{ + qhandle_t handle; + char path[MAX_QPATH]; +}; + +/* and shaderCache_t is needed for the model cache manager */ +struct ShaderCacheEntry +{ + ShaderCacheEntry( int nameOffset, int pokeOffset ) + : nameOffset(nameOffset) + , pokeOffset(pokeOffset) + { + } + + int nameOffset; + int pokeOffset; +}; +using ShaderCache = std::vector; + +/* + * The actual data stored in the cache + */ +struct CachedFile +{ + void *pDiskImage; // pointer to data loaded from disk + int iLevelLastUsedOn; // level we last used this on + int iPAKChecksum; // -1 = not from PAK + int iAllocSize; // + + ShaderCache shaderCache; + + char path[MAX_QPATH]; + + CachedFile(); +}; + +class CModelCacheManager +{ +public: + using AssetCache = std::vector; + using FileCache = std::vector; + +public: + /* + * Return -1 if asset not currently loaded, return positive qhandle_t if found + */ + qhandle_t GetModelHandle( const char *fileName ); + + /* + * We have a loaded model, let's insert it into the list of loaded models + */ + void InsertModelHandle( const char *fileName, qhandle_t handle ); + + qboolean LevelLoadEnd( qboolean deleteUnusedByLevel ); + void StoreShaderRequest( const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke ); + void AllocateShaders( const char *psFileName ); + + + /* + * Load the file and chuck the contents into ppFileBuffer, OR + * if we're cached already, chuck cached contents into ppFileBuffer + * and set *pbAlreadyCached to qtrue (otherwise, *pbAlreadyCached = false) + */ + qboolean LoadFile( const char *pFileName, void **ppFileBuffer, qboolean *pbAlreadyCached ); + + /* + * Allocate appropriate memory for stuff dealing with cached images + * FIXME: only applies to models? + */ + void *Allocate( int iSize, void *pvDiskBuffer, const char *psModelFileName, qboolean *bAlreadyFound, memtag_t eTag ); + void DeleteAll( void ); + void DumpNonPure(); + +private: + AssetCache::iterator FindAsset( const char *name ); + FileCache::iterator FindFile( const char *name ); + + AssetCache assets; + FileCache files; +}; + +qboolean C_Models_LevelLoadEnd( qboolean deleteUnusedByLevel ); +qboolean C_Images_LevelLoadEnd(); + +extern CModelCacheManager *CModelCache; diff --git a/codemp/rd-rend2/tr_cmds.cpp b/codemp/rd-rend2/tr_cmds.cpp new file mode 100644 index 0000000000..2a0fe463f7 --- /dev/null +++ b/codemp/rd-rend2/tr_cmds.cpp @@ -0,0 +1,827 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +#include "tr_local.h" +#include "tr_allocator.h" + +/* +===================== +R_PerformanceCounters +===================== +*/ +void R_PerformanceCounters( void ) { + gpuFrame_t *currentFrame = backEndData->frames + (backEndData->realFrameNumber % MAX_FRAMES); + + if ( !r_speeds->integer ) { + // clear the counters even if we aren't printing + Com_Memset( &tr.pc, 0, sizeof( tr.pc ) ); + Com_Memset( &backEnd.pc, 0, sizeof( backEnd.pc ) ); + currentFrame->numTimedBlocks = 0; + currentFrame->numTimers = 0; + return; + } + + if (r_speeds->integer == 1) { + ri.Printf (PRINT_ALL, "%i/%i/%i shaders/batches/surfs %i leafs %i verts %i/%i tris %.2f mtex %.2f dc\n", + backEnd.pc.c_shaders, backEnd.pc.c_surfBatches, backEnd.pc.c_surfaces, tr.pc.c_leafs, backEnd.pc.c_vertexes, + backEnd.pc.c_indexes/3, backEnd.pc.c_totalIndexes/3, + R_SumOfUsedImages()/(1000000.0f), backEnd.pc.c_overDraw / (float)(glConfig.vidWidth * glConfig.vidHeight) ); + } else if (r_speeds->integer == 2) { + ri.Printf (PRINT_ALL, "(patch) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", + tr.pc.c_sphere_cull_patch_in, tr.pc.c_sphere_cull_patch_clip, tr.pc.c_sphere_cull_patch_out, + tr.pc.c_box_cull_patch_in, tr.pc.c_box_cull_patch_clip, tr.pc.c_box_cull_patch_out ); + ri.Printf (PRINT_ALL, "(md3) %i sin %i sclip %i sout %i bin %i bclip %i bout\n", + tr.pc.c_sphere_cull_md3_in, tr.pc.c_sphere_cull_md3_clip, tr.pc.c_sphere_cull_md3_out, + tr.pc.c_box_cull_md3_in, tr.pc.c_box_cull_md3_clip, tr.pc.c_box_cull_md3_out ); + } else if (r_speeds->integer == 3) { + ri.Printf (PRINT_ALL, "viewcluster: %i\n", tr.viewCluster ); + } else if (r_speeds->integer == 4) { + if ( backEnd.pc.c_dlightVertexes ) { + ri.Printf (PRINT_ALL, "dlight srf:%i culled:%i verts:%i tris:%i\n", + tr.pc.c_dlightSurfaces, tr.pc.c_dlightSurfacesCulled, + backEnd.pc.c_dlightVertexes, backEnd.pc.c_dlightIndexes / 3 ); + } + } + else if (r_speeds->integer == 5 ) + { + ri.Printf( PRINT_ALL, "zFar: %.0f\n", tr.viewParms.zFar ); + } + else if (r_speeds->integer == 6 ) + { + ri.Printf( PRINT_ALL, "flare adds:%i tests:%i renders:%i\n", + backEnd.pc.c_flareAdds, backEnd.pc.c_flareTests, backEnd.pc.c_flareRenders ); + } + else if (r_speeds->integer == 7 ) + { + ri.Printf( PRINT_ALL, "VBO draws: static %i dynamic %i (%.2fKB)\nMultidraws: %i merged %i\n", + backEnd.pc.c_staticVboDraws, backEnd.pc.c_dynamicVboDraws, backEnd.pc.c_dynamicVboTotalSize / (1024.0f), + backEnd.pc.c_multidraws, backEnd.pc.c_multidrawsMerged ); + ri.Printf( PRINT_ALL, "GLSL binds: %i draws: gen %i light %i fog %i dlight %i\n", + backEnd.pc.c_glslShaderBinds, backEnd.pc.c_genericDraws, backEnd.pc.c_lightallDraws, backEnd.pc.c_fogDraws, backEnd.pc.c_dlightDraws); + } + else if (r_speeds->integer == 8) + { + ri.Printf( PRINT_ALL, "0-19: %d 20-49: %d 50-99: %d 100-299: %d\n", + backEnd.pc.c_triangleCountBins[TRI_BIN_0_19], + backEnd.pc.c_triangleCountBins[TRI_BIN_20_49], + backEnd.pc.c_triangleCountBins[TRI_BIN_50_99], + backEnd.pc.c_triangleCountBins[TRI_BIN_100_299]); + + ri.Printf( PRINT_ALL, "300-599: %d 600-999: %d 1000-1499: %d 1500-1999: %d\n", + backEnd.pc.c_triangleCountBins[TRI_BIN_300_599], + backEnd.pc.c_triangleCountBins[TRI_BIN_600_999], + backEnd.pc.c_triangleCountBins[TRI_BIN_1000_1499], + backEnd.pc.c_triangleCountBins[TRI_BIN_1500_1999]); + ri.Printf( PRINT_ALL, "2000-2999: %d 3000+: %d\n", + backEnd.pc.c_triangleCountBins[TRI_BIN_2000_2999], + backEnd.pc.c_triangleCountBins[TRI_BIN_3000_PLUS]); + } + else if ( r_speeds->integer == 100 ) + { + gpuFrame_t *frame = backEndData->frames + (backEndData->realFrameNumber % MAX_FRAMES); + + // TODO: We want to draw this as text on the screen... + // Print to console for now + + int numTimedBlocks = frame->numTimedBlocks; + for ( int i = 0; i < numTimedBlocks; i++ ) + { + gpuTimedBlock_t *timedBlock = frame->timedBlocks + i; + GLuint64 startTime, endTime, diffInNs; + float diffInMs; + + qglGetQueryObjectui64v( timedBlock->beginTimer, GL_QUERY_RESULT, &startTime); + qglGetQueryObjectui64v( timedBlock->endTimer, GL_QUERY_RESULT, &endTime); + + diffInNs = endTime - startTime; + diffInMs = diffInNs / 1e6f; + + ri.Printf( PRINT_ALL, "%s: %.3fms ", timedBlock->name, diffInMs ); + + if ( (i % 7) == 6 ) + { + ri.Printf( PRINT_ALL, "\n" ); + } + } + + ri.Printf( PRINT_ALL, "\n" ); + } + + Com_Memset( &tr.pc, 0, sizeof( tr.pc ) ); + Com_Memset( &backEnd.pc, 0, sizeof( backEnd.pc ) ); + currentFrame->numTimedBlocks = 0; + currentFrame->numTimers = 0; +} + + +/* +==================== +R_IssueRenderCommands +==================== +*/ +void R_IssueRenderCommands( qboolean runPerformanceCounters ) { + renderCommandList_t *cmdList; + + cmdList = &backEndData->commands; + assert(cmdList); + // add an end-of-list command + *(int *)(cmdList->cmds + cmdList->used) = RC_END_OF_LIST; + + // clear it out, in case this is a sync and not a buffer flip + cmdList->used = 0; + + if ( runPerformanceCounters ) { + R_PerformanceCounters(); + } + + // actually start the commands going + if ( !r_skipBackEnd->integer ) { + // let it start on the new batch + RB_ExecuteRenderCommands( cmdList->cmds ); + } +} + + +/* +==================== +R_IssuePendingRenderCommands + +Issue any pending commands and wait for them to complete. +==================== +*/ +void R_IssuePendingRenderCommands( void ) { + if ( !tr.registered ) { + return; + } + R_IssueRenderCommands( qfalse ); +} + +/* +============ +R_GetCommandBuffer + +make sure there is enough command space +============ +*/ +static void *R_GetCommandBufferReserved( int bytes, int reservedBytes ) { + renderCommandList_t *cmdList; + + cmdList = &backEndData->commands; + bytes = PAD(bytes, sizeof(void *)); + + // always leave room for the end of list command + if ( cmdList->used + bytes + sizeof(int) + reservedBytes > MAX_RENDER_COMMANDS ) { + if ( bytes > MAX_RENDER_COMMANDS - (int)sizeof(int)) { + ri.Error( ERR_FATAL, "R_GetCommandBuffer: bad size %i", bytes ); + } + // if we run out of room, just start dropping commands + return NULL; + } + + cmdList->used += bytes; + + return cmdList->cmds + cmdList->used - bytes; +} + +/* +============ +R_GetCommandBuffer +make sure there is enough command space +============ +*/ +void *R_GetCommandBuffer(int bytes) { + return R_GetCommandBufferReserved(bytes, PAD(sizeof(swapBuffersCommand_t), sizeof(void *))); +} + + +/* +============= +R_AddDrawSurfCmd + +============= +*/ +void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ) { + drawSurfsCommand_t *cmd; + + if (!tr.registered) { + return; + } + cmd = (drawSurfsCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) { + return; + } + cmd->commandId = RC_DRAW_SURFS; + + cmd->drawSurfs = drawSurfs; + cmd->numDrawSurfs = numDrawSurfs; + + cmd->refdef = tr.refdef; + cmd->viewParms = tr.viewParms; +} + +/* +============= +R_AddConvolveCubemapsCmd + +============= +*/ +void R_AddConvolveCubemapCmd( cubemap_t *cubemap , int cubemapId ) { + convolveCubemapCommand_t *cmd; + + if (!tr.registered) { + return; + } + cmd = (convolveCubemapCommand_t *)R_GetCommandBuffer( sizeof( *cmd )); + if ( !cmd ) { + return; + } + cmd->commandId = RC_CONVOLVECUBEMAP; + + cmd->cubemap = cubemap; + cmd->cubemapId = cubemapId; +} + +/* +============= +R_PostProcessingCmd + +============= +*/ +void R_AddPostProcessCmd( ) { + postProcessCommand_t *cmd; + + if (!tr.registered) { + return; + } + cmd = (postProcessCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) { + return; + } + cmd->commandId = RC_POSTPROCESS; + + cmd->refdef = tr.refdef; + cmd->viewParms = tr.viewParms; +} + +qhandle_t R_BeginTimedBlockCmd( const char *name ) +{ + beginTimedBlockCommand_t *cmd; + + if (!tr.registered) { + return (qhandle_t)-1; + } + cmd = (beginTimedBlockCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) + { + return (qhandle_t)-1; + } + + if ( tr.numTimedBlocks >= (MAX_GPU_TIMERS / 2) ) + { + return (qhandle_t)-1; + } + + cmd->commandId = RC_BEGIN_TIMED_BLOCK; + cmd->name = name; + cmd->timerHandle = tr.numTimedBlocks++; + + return (qhandle_t)cmd->timerHandle; +} + +void R_EndTimedBlockCmd( qhandle_t timerHandle ) +{ + endTimedBlockCommand_t *cmd; + + if (!tr.registered) { + return; + } + cmd = (endTimedBlockCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) + { + return; + } + + if ( cmd->timerHandle == -1 ) + { + return; + } + + cmd->commandId = RC_END_TIMED_BLOCK; + cmd->timerHandle = timerHandle; +} + +/* +============= +RE_SetColor + +Passing NULL will set the color to white +============= +*/ +void RE_SetColor( const float *rgba ) { + setColorCommand_t *cmd; + + if ( !tr.registered ) { + return; + } + cmd = (setColorCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) { + return; + } + cmd->commandId = RC_SET_COLOR; + if ( !rgba ) { + static float colorWhite[4] = { 1, 1, 1, 1 }; + + rgba = colorWhite; + } + + cmd->color[0] = rgba[0]; + cmd->color[1] = rgba[1]; + cmd->color[2] = rgba[2]; + cmd->color[3] = rgba[3]; +} + +/* +============= +RE_RotatePic +============= +*/ +void RE_RotatePic ( float x, float y, float w, float h, + float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { + rotatePicCommand_t *cmd; + + if (!tr.registered) { + return; + } + cmd = (rotatePicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) { + return; + } + cmd->commandId = RC_ROTATE_PIC; + cmd->shader = R_GetShaderByHandle( hShader ); + cmd->x = x; + cmd->y = y; + cmd->w = w; + cmd->h = h; + cmd->s1 = s1; + cmd->t1 = t1; + cmd->s2 = s2; + cmd->t2 = t2; + cmd->a = a; +} + +/* +============= +RE_RotatePic2 +============= +*/ +void RE_RotatePic2 ( float x, float y, float w, float h, + float s1, float t1, float s2, float t2,float a, qhandle_t hShader ) { + rotatePicCommand_t *cmd; + + if (!tr.registered) { + return; + } + cmd = (rotatePicCommand_t *) R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) { + return; + } + cmd->commandId = RC_ROTATE_PIC2; + cmd->shader = R_GetShaderByHandle( hShader ); + cmd->x = x; + cmd->y = y; + cmd->w = w; + cmd->h = h; + cmd->s1 = s1; + cmd->t1 = t1; + cmd->s2 = s2; + cmd->t2 = t2; + cmd->a = a; +} + +/* +============= +RE_StretchPic +============= +*/ +void RE_StretchPic ( float x, float y, float w, float h, + float s1, float t1, float s2, float t2, qhandle_t hShader ) { + stretchPicCommand_t *cmd; + + if ( !tr.registered ) { + return; + } + cmd = (stretchPicCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) { + return; + } + cmd->commandId = RC_STRETCH_PIC; + cmd->shader = R_GetShaderByHandle( hShader ); + cmd->x = x; + cmd->y = y; + cmd->w = w; + cmd->h = h; + cmd->s1 = s1; + cmd->t1 = t1; + cmd->s2 = s2; + cmd->t2 = t2; +} + +#define MODE_RED_CYAN 1 +#define MODE_RED_BLUE 2 +#define MODE_RED_GREEN 3 +#define MODE_GREEN_MAGENTA 4 +#define MODE_MAX MODE_GREEN_MAGENTA + +void R_SetColorMode(GLboolean *rgba, stereoFrame_t stereoFrame, int colormode) +{ + rgba[0] = rgba[1] = rgba[2] = rgba[3] = GL_TRUE; + + if(colormode > MODE_MAX) + { + if(stereoFrame == STEREO_LEFT) + stereoFrame = STEREO_RIGHT; + else if(stereoFrame == STEREO_RIGHT) + stereoFrame = STEREO_LEFT; + + colormode -= MODE_MAX; + } + + if(colormode == MODE_GREEN_MAGENTA) + { + if(stereoFrame == STEREO_LEFT) + rgba[0] = rgba[2] = GL_FALSE; + else if(stereoFrame == STEREO_RIGHT) + rgba[1] = GL_FALSE; + } + else + { + if(stereoFrame == STEREO_LEFT) + rgba[1] = rgba[2] = GL_FALSE; + else if(stereoFrame == STEREO_RIGHT) + { + rgba[0] = GL_FALSE; + + if(colormode == MODE_RED_BLUE) + rgba[1] = GL_FALSE; + else if(colormode == MODE_RED_GREEN) + rgba[2] = GL_FALSE; + } + } +} + + +/* +==================== +RE_BeginFrame + +If running in stereo, RE_BeginFrame will be called twice +for each RE_EndFrame +==================== +*/ +void RE_BeginFrame( stereoFrame_t stereoFrame ) { + drawBufferCommand_t *cmd = NULL; + colorMaskCommand_t *colcmd = NULL; + + if ( !tr.registered ) { + return; + } + + int frameNumber = backEndData->realFrameNumber; + gpuFrame_t *thisFrame = &backEndData->frames[frameNumber % MAX_FRAMES]; + backEndData->currentFrame = thisFrame; + if ( thisFrame->sync ) + { + GLsync sync = thisFrame->sync; + GLenum result = qglClientWaitSync( sync, 0, 0 ); + if ( result != GL_ALREADY_SIGNALED ) + { + ri.Printf( PRINT_DEVELOPER, "OpenGL: GPU is more than %d frames behind! Waiting for this frame to finish...\n", MAX_FRAMES ); + + static const GLuint64 HALF_SECOND = 500 * 1000 * 1000; + do + { + result = qglClientWaitSync( sync, GL_SYNC_FLUSH_COMMANDS_BIT, HALF_SECOND); + if ( result == GL_WAIT_FAILED ) + { + // This indicates that opengl context was lost, is there a way to recover? + qglDeleteSync( sync ); + thisFrame->sync = NULL; + + thisFrame->uboWriteOffset = 0; + + thisFrame->dynamicIboCommitOffset = 0; + thisFrame->dynamicIboWriteOffset = 0; + + thisFrame->dynamicVboCommitOffset = 0; + thisFrame->dynamicVboWriteOffset = 0; + + backEndData->perFrameMemory->Reset(); + + ri.Error(ERR_DROP, "OpenGL: Failed to wait for fence. Context lost. (0x%x)\n", qglGetError()); + return; + } + } + while ( result != GL_ALREADY_SIGNALED && result != GL_CONDITION_SATISFIED ); + } + qglDeleteSync( sync ); + thisFrame->sync = NULL; + + // Perform readback operations + if (thisFrame->screenshotReadback.pbo > 0) + R_SaveScreenshot(&thisFrame->screenshotReadback); + + // Resets resources + qglBindBuffer(GL_UNIFORM_BUFFER, thisFrame->ubo); + glState.currentGlobalUBO = thisFrame->ubo; + thisFrame->uboWriteOffset = 0; + + thisFrame->dynamicIboCommitOffset = 0; + thisFrame->dynamicIboWriteOffset = 0; + + thisFrame->dynamicVboCommitOffset = 0; + thisFrame->dynamicVboWriteOffset = 0; + + backEndData->perFrameMemory->Reset(); + } + + tr.frameCount++; + tr.frameSceneNum = 0; + + tr.fogsUboOffset = -1; + tr.lightsUboOffset = -1; + tr.sceneUboOffset = -1; + + // + // do overdraw measurement + // + if ( r_measureOverdraw->integer ) + { + if ( glConfig.stencilBits < 4 ) + { + ri.Printf( PRINT_ALL, "Warning: not enough stencil bits to measure overdraw: %d\n", glConfig.stencilBits ); + ri.Cvar_Set( "r_measureOverdraw", "0" ); + r_measureOverdraw->modified = qfalse; + } + else if ( r_shadows->integer == 2 ) + { + ri.Printf( PRINT_ALL, "Warning: stencil shadows and overdraw measurement are mutually exclusive\n" ); + ri.Cvar_Set( "r_measureOverdraw", "0" ); + r_measureOverdraw->modified = qfalse; + } + else + { + R_IssuePendingRenderCommands(); + qglEnable( GL_STENCIL_TEST ); + qglStencilMask( ~0U ); + qglClearStencil( 0U ); + qglStencilFunc( GL_ALWAYS, 0U, ~0U ); + qglStencilOp( GL_KEEP, GL_INCR, GL_INCR ); + } + r_measureOverdraw->modified = qfalse; + } + else + { + // this is only reached if it was on and is now off + if ( r_measureOverdraw->modified ) { + R_IssuePendingRenderCommands(); + qglDisable( GL_STENCIL_TEST ); + } + r_measureOverdraw->modified = qfalse; + } + + // + // texturemode stuff + // + if ( r_textureMode->modified || r_ext_texture_filter_anisotropic->modified ) { + R_IssuePendingRenderCommands(); + GL_TextureMode( r_textureMode->string ); + r_textureMode->modified = qfalse; + r_ext_texture_filter_anisotropic->modified = qfalse; + } + + // + // gamma stuff + // + if ( r_gamma->modified ) { + r_gamma->modified = qfalse; + + R_IssuePendingRenderCommands(); + R_SetColorMappings(); + } + + if (cl_ratioFix->modified) { + R_Set2DRatio(); + cl_ratioFix->modified = qfalse; + } + + // check for errors + if ( !r_ignoreGLErrors->integer ) + { + R_IssuePendingRenderCommands(); + + GLenum err = qglGetError(); + if ( err != GL_NO_ERROR ) + Com_Error( ERR_FATAL, "RE_BeginFrame() - glGetError() failed (0x%x)!\n", err ); + } + + if (glConfig.stereoEnabled) { + if( !(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd))) ) + return; + + cmd->commandId = RC_DRAW_BUFFER; + + if ( stereoFrame == STEREO_LEFT ) { + cmd->buffer = (int)GL_BACK_LEFT; + } else if ( stereoFrame == STEREO_RIGHT ) { + cmd->buffer = (int)GL_BACK_RIGHT; + } else { + ri.Error( ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame ); + } + } + else + { + if(r_anaglyphMode->integer) + { + if(r_anaglyphMode->modified) + { + // clear both, front and backbuffer. + qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + backEnd.colorMask[0] = qfalse; + backEnd.colorMask[1] = qfalse; + backEnd.colorMask[2] = qfalse; + backEnd.colorMask[3] = qfalse; + qglClearColor(0.0f, 0.0f, 0.0f, 1.0f); + + // clear all framebuffers + if (tr.msaaResolveFbo) + { + FBO_Bind(tr.msaaResolveFbo); + qglClear(GL_COLOR_BUFFER_BIT); + } + + if (tr.renderFbo) + { + FBO_Bind(tr.renderFbo); + qglClear(GL_COLOR_BUFFER_BIT); + } + + FBO_Bind(NULL); + + qglDrawBuffer(GL_FRONT); + qglClear(GL_COLOR_BUFFER_BIT); + qglDrawBuffer(GL_BACK); + qglClear(GL_COLOR_BUFFER_BIT); + + r_anaglyphMode->modified = qfalse; + } + + if(stereoFrame == STEREO_LEFT) + { + if( !(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd))) ) + return; + + if( !(colcmd = (colorMaskCommand_t *)R_GetCommandBuffer(sizeof(*colcmd))) ) + return; + } + else if(stereoFrame == STEREO_RIGHT) + { + clearDepthCommand_t *cldcmd; + + if( !(cldcmd = (clearDepthCommand_t *)R_GetCommandBuffer(sizeof(*cldcmd))) ) + return; + + cldcmd->commandId = RC_CLEARDEPTH; + + if( !(colcmd = (colorMaskCommand_t *)R_GetCommandBuffer(sizeof(*colcmd))) ) + return; + } + else + ri.Error( ERR_FATAL, "RE_BeginFrame: Stereo is enabled, but stereoFrame was %i", stereoFrame ); + + R_SetColorMode(colcmd->rgba, stereoFrame, r_anaglyphMode->integer); + colcmd->commandId = RC_COLORMASK; + } + else + { + if(stereoFrame != STEREO_CENTER) + ri.Error( ERR_FATAL, "RE_BeginFrame: Stereo is disabled, but stereoFrame was %i", stereoFrame ); + + if( !(cmd = (drawBufferCommand_t *)R_GetCommandBuffer(sizeof(*cmd))) ) + return; + } + + if(cmd) + { + cmd->commandId = RC_DRAW_BUFFER; + + if(r_anaglyphMode->modified) + { + qglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + backEnd.colorMask[0] = qfalse; + backEnd.colorMask[1] = qfalse; + backEnd.colorMask[2] = qfalse; + backEnd.colorMask[3] = qfalse; + r_anaglyphMode->modified = qfalse; + } + + if (!Q_stricmp(r_drawBuffer->string, "GL_FRONT")) + cmd->buffer = (int)GL_FRONT; + else + cmd->buffer = (int)GL_BACK; + } + } + + tr.refdef.stereoFrame = stereoFrame; +} + +void R_NewFrameSync() +{ + gpuFrame_t *currentFrame = backEndData->currentFrame; + + assert(!currentFrame->sync); + currentFrame->sync = qglFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + + backEndData->realFrameNumber++; + backEnd.framePostProcessed = qfalse; + backEnd.projection2D = qfalse; +} + + +/* +============= +RE_EndFrame + +Returns the number of msec spent in the back end +============= +*/ +void RE_EndFrame( int *frontEndMsec, int *backEndMsec ) { + swapBuffersCommand_t *cmd; + + if ( !tr.registered ) { + return; + } + cmd = (swapBuffersCommand_t *)R_GetCommandBufferReserved( sizeof( *cmd ), 0 ); + if ( !cmd ) { + return; + } + cmd->commandId = RC_SWAP_BUFFERS; + + R_IssueRenderCommands( qtrue ); + + R_InitNextFrame(); + + if ( frontEndMsec ) { + *frontEndMsec = tr.frontEndMsec; + } + tr.frontEndMsec = 0; + if ( backEndMsec ) { + *backEndMsec = backEnd.pc.msec; + } + backEnd.pc.msec = 0; +} + +/* +============= +RE_TakeVideoFrame +============= +*/ +void RE_TakeVideoFrame( int width, int height, + byte *captureBuffer, byte *encodeBuffer, qboolean motionJpeg ) +{ + videoFrameCommand_t *cmd; + + if( !tr.registered ) { + return; + } + + cmd = (videoFrameCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); + if( !cmd ) { + return; + } + + cmd->commandId = RC_VIDEOFRAME; + + cmd->width = width; + cmd->height = height; + cmd->captureBuffer = captureBuffer; + cmd->encodeBuffer = encodeBuffer; + cmd->motionJpeg = motionJpeg; +} diff --git a/codemp/rd-rend2/tr_curve.cpp b/codemp/rd-rend2/tr_curve.cpp new file mode 100644 index 0000000000..bdb8494242 --- /dev/null +++ b/codemp/rd-rend2/tr_curve.cpp @@ -0,0 +1,763 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +#include "tr_local.h" + +/* + +This file does all of the processing necessary to turn a raw grid of points +read from the map file into a srfBspSurface_t ready for rendering. + +The level of detail solution is direction independent, based only on subdivided +distance from the true curve. + +Only a single entry point: + +srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, + srfVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ) { + +*/ + + +/* +============ +LerpDrawVert +============ +*/ +static void LerpDrawVert( srfVert_t *a, srfVert_t *b, srfVert_t *out ) { + out->xyz[0] = 0.5f * (a->xyz[0] + b->xyz[0]); + out->xyz[1] = 0.5f * (a->xyz[1] + b->xyz[1]); + out->xyz[2] = 0.5f * (a->xyz[2] + b->xyz[2]); + + out->st[0] = 0.5f * (a->st[0] + b->st[0]); + out->st[1] = 0.5f * (a->st[1] + b->st[1]); + + for ( int i = 0; i < MAXLIGHTMAPS; i++ ) + { + out->lightmap[i][0] = 0.5f * (a->lightmap[i][0] + b->lightmap[i][0]); + out->lightmap[i][1] = 0.5f * (a->lightmap[i][1] + b->lightmap[i][1]); + + out->vertexColors[i][0] = 0.5f * (a->vertexColors[i][0] + b->vertexColors[i][0]); + out->vertexColors[i][1] = 0.5f * (a->vertexColors[i][1] + b->vertexColors[i][1]); + out->vertexColors[i][2] = 0.5f * (a->vertexColors[i][2] + b->vertexColors[i][2]); + out->vertexColors[i][3] = 0.5f * (a->vertexColors[i][3] + b->vertexColors[i][3]); + } +} + +/* +============ +Transpose +============ +*/ +static void Transpose( int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { + int i, j; + srfVert_t temp; + + if ( width > height ) { + for ( i = 0 ; i < height ; i++ ) { + for ( j = i + 1 ; j < width ; j++ ) { + if ( j < height ) { + // swap the value + temp = ctrl[j][i]; + ctrl[j][i] = ctrl[i][j]; + ctrl[i][j] = temp; + } else { + // just copy + ctrl[j][i] = ctrl[i][j]; + } + } + } + } else { + for ( i = 0 ; i < width ; i++ ) { + for ( j = i + 1 ; j < height ; j++ ) { + if ( j < width ) { + // swap the value + temp = ctrl[i][j]; + ctrl[i][j] = ctrl[j][i]; + ctrl[j][i] = temp; + } else { + // just copy + ctrl[i][j] = ctrl[j][i]; + } + } + } + } + +} + + +/* +================= +MakeMeshNormals + +Handles all the complicated wrapping and degenerate cases +================= +*/ +static void MakeMeshNormals( int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { + int i, j, k, dist; + vec3_t normal; + vec3_t sum; + int count = 0; + vec3_t base; + vec3_t delta; + int x, y; + srfVert_t *dv; + vec3_t around[8], temp; + qboolean good[8]; + qboolean wrapWidth, wrapHeight; + float len; +static int neighbors[8][2] = { + {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1} + }; + + wrapWidth = qfalse; + for ( i = 0 ; i < height ; i++ ) { + VectorSubtract( ctrl[i][0].xyz, ctrl[i][width-1].xyz, delta ); + len = VectorLengthSquared( delta ); + if ( len > 1.0 ) { + break; + } + } + if ( i == height ) { + wrapWidth = qtrue; + } + + wrapHeight = qfalse; + for ( i = 0 ; i < width ; i++ ) { + VectorSubtract( ctrl[0][i].xyz, ctrl[height-1][i].xyz, delta ); + len = VectorLengthSquared( delta ); + if ( len > 1.0 ) { + break; + } + } + if ( i == width) { + wrapHeight = qtrue; + } + + + for ( i = 0 ; i < width ; i++ ) { + for ( j = 0 ; j < height ; j++ ) { + count = 0; + dv = &ctrl[j][i]; + VectorCopy( dv->xyz, base ); + for ( k = 0 ; k < 8 ; k++ ) { + VectorClear( around[k] ); + good[k] = qfalse; + + for ( dist = 1 ; dist <= 3 ; dist++ ) { + x = i + neighbors[k][0] * dist; + y = j + neighbors[k][1] * dist; + if ( wrapWidth ) { + if ( x < 0 ) { + x = width - 1 + x; + } else if ( x >= width ) { + x = 1 + x - width; + } + } + if ( wrapHeight ) { + if ( y < 0 ) { + y = height - 1 + y; + } else if ( y >= height ) { + y = 1 + y - height; + } + } + + if ( x < 0 || x >= width || y < 0 || y >= height ) { + break; // edge of patch + } + VectorSubtract( ctrl[y][x].xyz, base, temp ); + if ( VectorNormalize2( temp, temp ) == 0 ) { + continue; // degenerate edge, get more dist + } else { + good[k] = qtrue; + VectorCopy( temp, around[k] ); + break; // good edge + } + } + } + + VectorClear( sum ); + for ( k = 0 ; k < 8 ; k++ ) { + if ( !good[k] || !good[(k+1)&7] ) { + continue; // didn't get two points + } + CrossProduct( around[(k+1)&7], around[k], normal ); + if ( VectorNormalize2( normal, normal ) == 0 ) { + continue; + } + VectorAdd( normal, sum, sum ); + count++; + } + //if ( count == 0 ) { + // printf("bad normal\n"); + //} + VectorNormalize2( sum, dv->normal ); + } + } +} + +static void MakeMeshTangentVectors(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], int numIndexes, + glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]) +{ + int i, j; + srfVert_t *dv[3]; + static srfVert_t ctrl2[MAX_GRID_SIZE * MAX_GRID_SIZE]; + glIndex_t *tri; + + // FIXME: use more elegant way + for(i = 0; i < width; i++) + { + for(j = 0; j < height; j++) + { + dv[0] = &ctrl2[j * width + i]; + *dv[0] = ctrl[j][i]; + } + } + + for(i = 0, tri = indexes; i < numIndexes; i += 3, tri += 3) + { + dv[0] = &ctrl2[tri[0]]; + dv[1] = &ctrl2[tri[1]]; + dv[2] = &ctrl2[tri[2]]; + + R_CalcTangentVectors(dv); + } + + for(i = 0; i < width; i++) + { + for(j = 0; j < height; j++) + { + dv[0] = &ctrl2[j * width + i]; + dv[1] = &ctrl[j][i]; + + VectorCopy4(dv[0]->tangent, dv[1]->tangent); + } + } +} + +static int MakeMeshIndexes(int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], + glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]) +{ + int i, j; + int numIndexes; + int w, h; + srfVert_t *dv; + static srfVert_t ctrl2[MAX_GRID_SIZE * MAX_GRID_SIZE]; + + h = height - 1; + w = width - 1; + numIndexes = 0; + for(i = 0; i < h; i++) + { + for(j = 0; j < w; j++) + { + int v1, v2, v3, v4; + + // vertex order to be reckognized as tristrips + v1 = i * width + j + 1; + v2 = v1 - 1; + v3 = v2 + width; + v4 = v3 + 1; + + indexes[numIndexes++] = v2; + indexes[numIndexes++] = v3; + indexes[numIndexes++] = v1; + + indexes[numIndexes++] = v1; + indexes[numIndexes++] = v3; + indexes[numIndexes++] = v4; + } + } + + // FIXME: use more elegant way + for(i = 0; i < width; i++) + { + for(j = 0; j < height; j++) + { + dv = &ctrl2[j * width + i]; + *dv = ctrl[j][i]; + } + } + + return numIndexes; +} + + +/* +============ +InvertCtrl +============ +*/ +static void InvertCtrl( int width, int height, srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE] ) { + int i, j; + srfVert_t temp; + + for ( i = 0 ; i < height ; i++ ) { + for ( j = 0 ; j < width/2 ; j++ ) { + temp = ctrl[i][j]; + ctrl[i][j] = ctrl[i][width-1-j]; + ctrl[i][width-1-j] = temp; + } + } +} + + +/* +================= +InvertErrorTable +================= +*/ +static void InvertErrorTable( float errorTable[2][MAX_GRID_SIZE], int width, int height ) { + int i; + float copy[2][MAX_GRID_SIZE]; + + Com_Memcpy( copy, errorTable, sizeof( copy ) ); + + for ( i = 0 ; i < width ; i++ ) { + errorTable[1][i] = copy[0][i]; //[width-1-i]; + } + + for ( i = 0 ; i < height ; i++ ) { + errorTable[0][i] = copy[1][height-1-i]; + } + +} + +/* +================== +PutPointsOnCurve +================== +*/ +static void PutPointsOnCurve( srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], + int width, int height ) { + int i, j; + srfVert_t prev, next; + + for ( i = 0 ; i < width ; i++ ) { + for ( j = 1 ; j < height ; j += 2 ) { + LerpDrawVert( &ctrl[j][i], &ctrl[j+1][i], &prev ); + LerpDrawVert( &ctrl[j][i], &ctrl[j-1][i], &next ); + LerpDrawVert( &prev, &next, &ctrl[j][i] ); + } + } + + + for ( j = 0 ; j < height ; j++ ) { + for ( i = 1 ; i < width ; i += 2 ) { + LerpDrawVert( &ctrl[j][i], &ctrl[j][i+1], &prev ); + LerpDrawVert( &ctrl[j][i], &ctrl[j][i-1], &next ); + LerpDrawVert( &prev, &next, &ctrl[j][i] ); + } + } +} + +/* +================= +R_CreateSurfaceGridMesh +================= +*/ +srfBspSurface_t *R_CreateSurfaceGridMesh(int width, int height, + srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE], float errorTable[2][MAX_GRID_SIZE], + int numIndexes, glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]) { + int i, j, size; + srfVert_t *vert; + vec3_t tmpVec; + srfBspSurface_t *grid; + + // copy the results out to a grid + size = (width * height - 1) * sizeof( srfVert_t ) + sizeof( *grid ); + +#ifdef PATCH_STITCHING + grid = /*ri.Hunk_Alloc*/ (srfBspSurface_t *)Z_Malloc( size, TAG_GRIDMESH ); + Com_Memset(grid, 0, size); + + grid->widthLodError = /*ri.Hunk_Alloc*/ (float *)Z_Malloc( width * 4, TAG_GRIDMESH ); + Com_Memcpy( grid->widthLodError, errorTable[0], width * 4 ); + + grid->heightLodError = /*ri.Hunk_Alloc*/ (float *)Z_Malloc( height * 4, TAG_GRIDMESH ); + Com_Memcpy( grid->heightLodError, errorTable[1], height * 4 ); + + grid->numIndexes = numIndexes; + grid->indexes = (glIndex_t *)Z_Malloc(grid->numIndexes * sizeof(glIndex_t), TAG_GRIDMESH); + Com_Memcpy(grid->indexes, indexes, numIndexes * sizeof(glIndex_t)); + + grid->numVerts = (width * height); + grid->verts = (srfVert_t *)Z_Malloc(grid->numVerts * sizeof(srfVert_t), TAG_GRIDMESH); +#else + grid = ri.Hunk_Alloc( size ); + Com_Memset(grid, 0, size); + + grid->widthLodError = ri.Hunk_Alloc( width * 4 ); + Com_Memcpy( grid->widthLodError, errorTable[0], width * 4 ); + + grid->heightLodError = ri.Hunk_Alloc( height * 4 ); + Com_Memcpy( grid->heightLodError, errorTable[1], height * 4 ); + + grid->numIndexes = numIndexes; + grid->indexes = (glIndex_t *)ri.Hunk_Alloc(grid->numIndexes * sizeof(glIndex_t), h_low); + Com_Memcpy(grid->indexes, indexes, numIndexes * sizeof(glIndex_t)); + + grid->numVerts = (width * height); + grid->verts = ri.Hunk_Alloc(grid->numVerts * sizeof(srfVert_t), h_low); +#endif + + grid->width = width; + grid->height = height; + grid->surfaceType = SF_GRID; + ClearBounds( grid->cullBounds[0], grid->cullBounds[1] ); + for ( i = 0 ; i < width ; i++ ) { + for ( j = 0 ; j < height ; j++ ) { + vert = &grid->verts[j*width+i]; + *vert = ctrl[j][i]; + AddPointToBounds( vert->xyz, grid->cullBounds[0], grid->cullBounds[1] ); + } + } + + // compute local origin and bounds + VectorAdd( grid->cullBounds[0], grid->cullBounds[1], grid->cullOrigin ); + VectorScale( grid->cullOrigin, 0.5f, grid->cullOrigin ); + VectorSubtract( grid->cullBounds[0], grid->cullOrigin, tmpVec ); + grid->cullRadius = VectorLength( tmpVec ); + + VectorCopy( grid->cullOrigin, grid->lodOrigin ); + grid->lodRadius = grid->cullRadius; + // + return grid; +} + +/* +================= +R_FreeSurfaceGridMesh +================= +*/ +void R_FreeSurfaceGridMesh( srfBspSurface_t *grid ) { + Z_Free(grid->widthLodError); + Z_Free(grid->heightLodError); + Z_Free(grid->indexes); + Z_Free(grid->verts); + Z_Free(grid); +} + +/* +================= +R_SubdividePatchToGrid +================= +*/ +srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, + srfVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ) { + int i, j, k, l; + srfVert_t prev; + srfVert_t next; + srfVert_t mid; + float len, maxLen; + int dir; + int t; + srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; + float errorTable[2][MAX_GRID_SIZE]; + int numIndexes; + static glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]; + int consecutiveComplete; + + Com_Memset (&prev, 0, sizeof (prev)); + Com_Memset (&next, 0, sizeof (next)); + Com_Memset (&mid, 0, sizeof (mid)); + + for ( i = 0 ; i < width ; i++ ) { + for ( j = 0 ; j < height ; j++ ) { + ctrl[j][i] = points[j*width+i]; + } + } + + for ( dir = 0 ; dir < 2 ; dir++ ) { + + for ( j = 0 ; j < MAX_GRID_SIZE ; j++ ) { + errorTable[dir][j] = 0; + } + + consecutiveComplete = 0; + + // horizontal subdivisions + for ( j = 0 ; ; j = (j + 2) % (width - 1) ) { + // check subdivided midpoints against control points + + // FIXME: also check midpoints of adjacent patches against the control points + // this would basically stitch all patches in the same LOD group together. + + maxLen = 0; + for ( i = 0 ; i < height ; i++ ) { + vec3_t midxyz; + vec3_t midxyz2; + vec3_t dir; + vec3_t projected; + float d; + + // calculate the point on the curve + for ( l = 0 ; l < 3 ; l++ ) { + midxyz[l] = (ctrl[i][j].xyz[l] + ctrl[i][j+1].xyz[l] * 2 + + ctrl[i][j+2].xyz[l] ) * 0.25f; + } + + // see how far off the line it is + // using dist-from-line will not account for internal + // texture warping, but it gives a lot less polygons than + // dist-from-midpoint + VectorSubtract( midxyz, ctrl[i][j].xyz, midxyz ); + VectorSubtract( ctrl[i][j+2].xyz, ctrl[i][j].xyz, dir ); + VectorNormalize( dir ); + + d = DotProduct( midxyz, dir ); + VectorScale( dir, d, projected ); + VectorSubtract( midxyz, projected, midxyz2); + len = VectorLengthSquared( midxyz2 ); // we will do the sqrt later + if ( len > maxLen ) { + maxLen = len; + } + } + + maxLen = sqrt(maxLen); + + // if all the points are on the lines, remove the entire columns + if ( maxLen < 0.1f ) { + errorTable[dir][j+1] = 999; + // if we go over the whole grid twice without adding any columns, stop + if (++consecutiveComplete >= width) + break; + continue; + } + + // see if we want to insert subdivided columns + if ( width + 2 > MAX_GRID_SIZE ) { + errorTable[dir][j+1] = 1.0f/maxLen; + break; // can't subdivide any more + } + + if ( maxLen <= r_subdivisions->value ) { + errorTable[dir][j+1] = 1.0f/maxLen; + // if we go over the whole grid twice without adding any columns, stop + if (++consecutiveComplete >= width) + break; + continue; // didn't need subdivision + } + + errorTable[dir][j+2] = 1.0f/maxLen; + + consecutiveComplete = 0; + + // insert two columns and replace the peak + width += 2; + for ( i = 0 ; i < height ; i++ ) { + LerpDrawVert( &ctrl[i][j], &ctrl[i][j+1], &prev ); + LerpDrawVert( &ctrl[i][j+1], &ctrl[i][j+2], &next ); + LerpDrawVert( &prev, &next, &mid ); + + for ( k = width - 1 ; k > j + 3 ; k-- ) { + ctrl[i][k] = ctrl[i][k-2]; + } + ctrl[i][j + 1] = prev; + ctrl[i][j + 2] = mid; + ctrl[i][j + 3] = next; + } + + // skip the new one, we'll get it on the next pass + j += 2; + } + + Transpose( width, height, ctrl ); + t = width; + width = height; + height = t; + } + + + // put all the aproximating points on the curve + PutPointsOnCurve( ctrl, width, height ); + + // cull out any rows or columns that are colinear + for ( i = 1 ; i < width-1 ; i++ ) { + if ( errorTable[0][i] != 999 ) { + continue; + } + for ( j = i+1 ; j < width ; j++ ) { + for ( k = 0 ; k < height ; k++ ) { + ctrl[k][j-1] = ctrl[k][j]; + } + errorTable[0][j-1] = errorTable[0][j]; + } + width--; + } + + for ( i = 1 ; i < height-1 ; i++ ) { + if ( errorTable[1][i] != 999 ) { + continue; + } + for ( j = i+1 ; j < height ; j++ ) { + for ( k = 0 ; k < width ; k++ ) { + ctrl[j-1][k] = ctrl[j][k]; + } + errorTable[1][j-1] = errorTable[1][j]; + } + height--; + } + +#if 1 + // flip for longest tristrips as an optimization + // the results should be visually identical with or + // without this step + if ( height > width ) { + Transpose( width, height, ctrl ); + InvertErrorTable( errorTable, width, height ); + t = width; + width = height; + height = t; + InvertCtrl( width, height, ctrl ); + } +#endif + + // calculate indexes + numIndexes = MakeMeshIndexes(width, height, ctrl, indexes); + + // calculate normals + MakeMeshNormals( width, height, ctrl ); + MakeMeshTangentVectors(width, height, ctrl, numIndexes, indexes); + + return R_CreateSurfaceGridMesh(width, height, ctrl, errorTable, numIndexes, indexes); +} + +/* +=============== +R_GridInsertColumn +=============== +*/ +srfBspSurface_t *R_GridInsertColumn( srfBspSurface_t *grid, int column, int row, vec3_t point, float loderror ) { + int i, j; + int width, height, oldwidth; + srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; + float errorTable[2][MAX_GRID_SIZE]; + float lodRadius; + vec3_t lodOrigin; + int numIndexes; + static glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]; + + oldwidth = 0; + width = grid->width + 1; + if (width > MAX_GRID_SIZE) + return NULL; + height = grid->height; + for (i = 0; i < width; i++) { + if (i == column) { + //insert new column + for (j = 0; j < grid->height; j++) { + LerpDrawVert( &grid->verts[j * grid->width + i-1], &grid->verts[j * grid->width + i], &ctrl[j][i] ); + if (j == row) + VectorCopy(point, ctrl[j][i].xyz); + } + errorTable[0][i] = loderror; + continue; + } + errorTable[0][i] = grid->widthLodError[oldwidth]; + for (j = 0; j < grid->height; j++) { + ctrl[j][i] = grid->verts[j * grid->width + oldwidth]; + } + oldwidth++; + } + for (j = 0; j < grid->height; j++) { + errorTable[1][j] = grid->heightLodError[j]; + } + // put all the aproximating points on the curve + //PutPointsOnCurve( ctrl, width, height ); + + // calculate indexes + numIndexes = MakeMeshIndexes(width, height, ctrl, indexes); + + // calculate normals + MakeMeshNormals( width, height, ctrl ); + + VectorCopy(grid->lodOrigin, lodOrigin); + lodRadius = grid->lodRadius; + // free the old grid + R_FreeSurfaceGridMesh(grid); + // create a new grid + grid = R_CreateSurfaceGridMesh(width, height, ctrl, errorTable, numIndexes, indexes); + grid->lodRadius = lodRadius; + VectorCopy(lodOrigin, grid->lodOrigin); + return grid; +} + +/* +=============== +R_GridInsertRow +=============== +*/ +srfBspSurface_t *R_GridInsertRow( srfBspSurface_t *grid, int row, int column, vec3_t point, float loderror ) { + int i, j; + int width, height, oldheight; + srfVert_t ctrl[MAX_GRID_SIZE][MAX_GRID_SIZE]; + float errorTable[2][MAX_GRID_SIZE]; + float lodRadius; + vec3_t lodOrigin; + int numIndexes; + static glIndex_t indexes[(MAX_GRID_SIZE-1)*(MAX_GRID_SIZE-1)*2*3]; + + oldheight = 0; + width = grid->width; + height = grid->height + 1; + if (height > MAX_GRID_SIZE) + return NULL; + for (i = 0; i < height; i++) { + if (i == row) { + //insert new row + for (j = 0; j < grid->width; j++) { + LerpDrawVert( &grid->verts[(i-1) * grid->width + j], &grid->verts[i * grid->width + j], &ctrl[i][j] ); + if (j == column) + VectorCopy(point, ctrl[i][j].xyz); + } + errorTable[1][i] = loderror; + continue; + } + errorTable[1][i] = grid->heightLodError[oldheight]; + for (j = 0; j < grid->width; j++) { + ctrl[i][j] = grid->verts[oldheight * grid->width + j]; + } + oldheight++; + } + for (j = 0; j < grid->width; j++) { + errorTable[0][j] = grid->widthLodError[j]; + } + // put all the aproximating points on the curve + //PutPointsOnCurve( ctrl, width, height ); + + // calculate indexes + numIndexes = MakeMeshIndexes(width, height, ctrl, indexes); + + // calculate normals + MakeMeshNormals( width, height, ctrl ); + + VectorCopy(grid->lodOrigin, lodOrigin); + lodRadius = grid->lodRadius; + // free the old grid + R_FreeSurfaceGridMesh(grid); + // create a new grid + grid = R_CreateSurfaceGridMesh(width, height, ctrl, errorTable, numIndexes, indexes); + grid->lodRadius = lodRadius; + VectorCopy(lodOrigin, grid->lodOrigin); + return grid; +} diff --git a/codemp/rd-rend2/tr_decals.cpp b/codemp/rd-rend2/tr_decals.cpp new file mode 100644 index 0000000000..6bf4222da7 --- /dev/null +++ b/codemp/rd-rend2/tr_decals.cpp @@ -0,0 +1,299 @@ +#include "tr_local.h" + +#define MAX_VERTS_ON_DECAL_POLY 10 +#define MAX_DECAL_POLYS 500 + +typedef struct decalPoly_s +{ + int time; + int fadetime; + qhandle_t shader; + float color[4]; + poly_t poly; + polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; +} decalPoly_t; + +enum +{ + DECALPOLY_TYPE_NORMAL, + DECALPOLY_TYPE_FADE, + DECALPOLY_TYPE_MAX +}; + +#define DECAL_FADE_TIME 1000 + +decalPoly_t* RE_AllocDecal( int type ); + +static decalPoly_t re_decalPolys[DECALPOLY_TYPE_MAX][MAX_DECAL_POLYS]; + +static int re_decalPolyHead[DECALPOLY_TYPE_MAX]; +static int re_decalPolyTotal[DECALPOLY_TYPE_MAX]; + +/* +=================== +RE_ClearDecals + +This is called to remove all decals from the world +=================== +*/ +void RE_ClearDecals( void ) { + memset( re_decalPolys, 0, sizeof(re_decalPolys) ); + memset( re_decalPolyHead, 0, sizeof(re_decalPolyHead) ); + memset( re_decalPolyTotal, 0, sizeof(re_decalPolyTotal) ); +} + +void R_InitDecals( void ) { + RE_ClearDecals(); +} + +void RE_FreeDecal( int type, int index ) { + if ( !re_decalPolys[type][index].time ) + return; + + if ( type == DECALPOLY_TYPE_NORMAL ) { + decalPoly_t* fade; + + fade = RE_AllocDecal( DECALPOLY_TYPE_FADE ); + + memcpy( fade, &re_decalPolys[type][index], sizeof( decalPoly_t ) ); + + fade->time = tr.refdef.time; + fade->fadetime = tr.refdef.time + DECAL_FADE_TIME; + } + + re_decalPolys[type][index].time = 0; + + re_decalPolyTotal[type]--; +} + +/* +=================== +RE_AllocDecal + +Will allways succeed, even if it requires freeing an old active mark +=================== +*/ +decalPoly_t* RE_AllocDecal( int type ) { + decalPoly_t *le; + + // See if the cvar changed + if ( re_decalPolyTotal[type] > r_markcount->integer ) + RE_ClearDecals(); + + le = &re_decalPolys[type][re_decalPolyHead[type]]; + + // If it has no time its the first occasion its been used + if ( le->time ) { + if ( le->time != tr.refdef.time ) { + int i = re_decalPolyHead[type]; + + // since we are killing one that existed before, make sure we + // kill all the other marks that belong to the group + do { + i++; + if ( i >= r_markcount->integer ) + i = 0; + + // Break out on the first one thats not part of the group + if ( re_decalPolys[type][i].time != le->time ) + break; + + RE_FreeDecal ( type, i ); + } while ( i != re_decalPolyHead[type] ); + + RE_FreeDecal( type, re_decalPolyHead[type] ); + } + else + RE_FreeDecal( type, re_decalPolyHead[type] ); + } + + memset( le, 0, sizeof(decalPoly_t) ); + le->time = tr.refdef.time; + + re_decalPolyTotal[type]++; + + // Move on to the next decal poly and wrap around if need be + re_decalPolyHead[type]++; + if ( re_decalPolyHead[type] >= r_markcount->integer ) + re_decalPolyHead[type] = 0; + + return le; +} + +/* +================= +RE_AddDecalToScene + +origin should be a point within a unit of the plane +dir should be the plane normal + +temporary marks will not be stored or randomly oriented, but immediately +passed to the renderer. +================= +*/ +#define MAX_DECAL_FRAGMENTS 128 +#define MAX_DECAL_POINTS 384 + +void RE_AddDecalToScene( qhandle_t decalShader, const vec3_t origin, const vec3_t dir, float orientation, float red, float green, float blue, float alpha, qboolean alphaFade, float radius, qboolean temporary ) +{ + matrix3_t axis; + float texCoordScale; + vec3_t originalPoints[4]; + byte colors[4]; + int i, j; + int numFragments; + markFragment_t markFragments[MAX_DECAL_FRAGMENTS], *mf; + vec3_t markPoints[MAX_DECAL_POINTS]; + vec3_t projection; + + assert(decalShader); + + if ( r_markcount->integer <= 0 && !temporary ) + return; + + if ( radius <= 0 ) + Com_Error( ERR_FATAL, "RE_AddDecalToScene: called with <= 0 radius" ); + + // create the texture axis + VectorNormalize2( dir, axis[0] ); + PerpendicularVector( axis[1], axis[0] ); + RotatePointAroundVector( axis[2], axis[0], axis[1], orientation ); + CrossProduct( axis[0], axis[2], axis[1] ); + + texCoordScale = 0.5 * 1.0 / radius; + + // create the full polygon + for ( i = 0 ; i < 3 ; i++ ) + { + originalPoints[0][i] = origin[i] - radius * axis[1][i] - radius * axis[2][i]; + originalPoints[1][i] = origin[i] + radius * axis[1][i] - radius * axis[2][i]; + originalPoints[2][i] = origin[i] + radius * axis[1][i] + radius * axis[2][i]; + originalPoints[3][i] = origin[i] - radius * axis[1][i] + radius * axis[2][i]; + } + + // get the fragments + VectorScale( dir, -20, projection ); + numFragments = R_MarkFragments( 4, (const vec3_t*)originalPoints, + projection, MAX_DECAL_POINTS, markPoints[0], + MAX_DECAL_FRAGMENTS, markFragments ); + + colors[0] = red * 255; + colors[1] = green * 255; + colors[2] = blue * 255; + colors[3] = alpha * 255; + + for ( i = 0, mf = markFragments ; i < numFragments ; i++, mf++ ) + { + polyVert_t *v; + polyVert_t verts[MAX_VERTS_ON_DECAL_POLY]; + decalPoly_t *decal; + + // we have an upper limit on the complexity of polygons + // that we store persistantly + if ( mf->numPoints > MAX_VERTS_ON_DECAL_POLY ) + mf->numPoints = MAX_VERTS_ON_DECAL_POLY; + + for ( j = 0, v = verts ; j < mf->numPoints ; j++, v++ ) + { + vec3_t delta; + + VectorCopy( markPoints[mf->firstPoint + j], v->xyz ); + + VectorSubtract( v->xyz, origin, delta ); + v->st[0] = 0.5 + DotProduct( delta, axis[1] ) * texCoordScale; + v->st[1] = 0.5 + DotProduct( delta, axis[2] ) * texCoordScale; + + *(int *)v->modulate = *(int *)colors; + } + + // if it is a temporary (shadow) mark, add it immediately and forget about it + if ( temporary ) + { + RE_AddPolyToScene( decalShader, mf->numPoints, verts, 1 ); + continue; + } + + // otherwise save it persistantly + decal = RE_AllocDecal( DECALPOLY_TYPE_NORMAL ); + decal->time = tr.refdef.time; + decal->shader = decalShader; + decal->poly.numVerts = mf->numPoints; + decal->color[0] = red; + decal->color[1] = green; + decal->color[2] = blue; + decal->color[3] = alpha; + memcpy( decal->verts, verts, mf->numPoints * sizeof( verts[0] ) ); + } +} + +/* +=============== +R_AddDecals +=============== +*/ +void R_AddDecals( void ) +{ + int decalPoly; + int type; + static int lastMarkCount = -1; + + if ( r_markcount->integer != lastMarkCount ) { + if ( lastMarkCount != -1 ) + RE_ClearDecals(); + + lastMarkCount = r_markcount->integer; + } + + if ( r_markcount->integer <= 0 ) + return; + + for ( type = DECALPOLY_TYPE_NORMAL; type < DECALPOLY_TYPE_MAX; type ++ ) + { + decalPoly = re_decalPolyHead[type]; + + do + { + decalPoly_t* p = &re_decalPolys[type][decalPoly]; + + if ( p->time ) + { + if ( p->fadetime ) + { + int t; + + // fade all marks out with time + t = tr.refdef.time - p->time; + if ( t < DECAL_FADE_TIME ) + { + float fade; + int j; + + fade = 255.0f * (1.0f - ((float)t / DECAL_FADE_TIME)); + + for ( j = 0 ; j < p->poly.numVerts ; j++ ) + { + p->verts[j].modulate[3] = fade; + } + + RE_AddPolyToScene( p->shader, p->poly.numVerts, p->verts, 1 ); + } + else + { + RE_FreeDecal ( type, decalPoly ); + } + } + else + { + RE_AddPolyToScene( p->shader, p->poly.numVerts, p->verts, 1 ); + } + } + + decalPoly++; + if ( decalPoly >= r_markcount->integer ) + { + decalPoly = 0; + } + } + while ( decalPoly != re_decalPolyHead[type] ); + } +} diff --git a/codemp/rd-rend2/tr_extensions.cpp b/codemp/rd-rend2/tr_extensions.cpp new file mode 100644 index 0000000000..55bf6c9ffe --- /dev/null +++ b/codemp/rd-rend2/tr_extensions.cpp @@ -0,0 +1,692 @@ +/* +=========================================================================== +Copyright (C) 2011 James Canete (use.less01@gmail.com) + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_extensions.c - extensions needed by the renderer not in sdl_glimp.c + +#include "tr_local.h" + +#define GL_GetProcAddress ri.GL_GetProcAddress + +// Stencil commands +PFNGLSTENCILOPSEPARATEPROC qglStencilOpSeparate; + +// Drawing commands +PFNGLDRAWRANGEELEMENTSPROC qglDrawRangeElements; +PFNGLDRAWARRAYSINSTANCEDPROC qglDrawArraysInstanced; +PFNGLDRAWELEMENTSINSTANCEDPROC qglDrawElementsInstanced; +PFNGLDRAWELEMENTSBASEVERTEXPROC qglDrawElementsBaseVertex; +PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC qglDrawRangeElementsBaseVertex; +PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC qglDrawElementsInstancedBaseVertex; +PFNGLMULTIDRAWARRAYSPROC qglMultiDrawArrays; +PFNGLMULTIDRAWELEMENTSPROC qglMultiDrawElements; +PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC qglMultiDrawElementsBaseVertex; + +// Vertex arrays +PFNGLVERTEXATTRIBPOINTERPROC qglVertexAttribPointer; +PFNGLVERTEXATTRIBIPOINTERPROC qglVertexAttribIPointer; +PFNGLVERTEXATTRIBDIVISORPROC qglVertexAttribDivisor; +PFNGLENABLEVERTEXATTRIBARRAYPROC qglEnableVertexAttribArray; +PFNGLDISABLEVERTEXATTRIBARRAYPROC qglDisableVertexAttribArray; + +// Vertex array objects +PFNGLGENVERTEXARRAYSPROC qglGenVertexArrays; +PFNGLDELETEVERTEXARRAYSPROC qglDeleteVertexArrays; +PFNGLBINDVERTEXARRAYPROC qglBindVertexArray; +PFNGLISVERTEXARRAYPROC qglIsVertexArray; + +// Buffer objects +PFNGLBINDBUFFERPROC qglBindBuffer; +PFNGLDELETEBUFFERSPROC qglDeleteBuffers; +PFNGLGENBUFFERSPROC qglGenBuffers; +PFNGLBUFFERDATAPROC qglBufferData; +PFNGLBUFFERSUBDATAPROC qglBufferSubData; +PFNGLGETBUFFERSUBDATAPROC qglGetBufferSubData; +PFNGLGETBUFFERPARAMETERIVPROC qglGetBufferParameteriv; +PFNGLGETBUFFERPARAMETERI64VPROC qglGetBufferParameteri64v; +PFNGLGETBUFFERPOINTERVPROC qglGetBufferPointerv; +PFNGLBINDBUFFERRANGEPROC qglBindBufferRange; +PFNGLBINDBUFFERBASEPROC qglBindBufferBase; +PFNGLMAPBUFFERRANGEPROC qglMapBufferRange; +PFNGLMAPBUFFERPROC qglMapBuffer; +PFNGLFLUSHMAPPEDBUFFERRANGEPROC qglFlushMappedBufferRange; +PFNGLUNMAPBUFFERPROC qglUnmapBuffer; +PFNGLCOPYBUFFERSUBDATAPROC qglCopyBufferSubData; +PFNGLISBUFFERPROC qglIsBuffer; + +// Texturing +PFNGLACTIVETEXTUREPROC qglActiveTexture; +PFNGLTEXIMAGE3DPROC qglTexImage3D; + +// Shader objects +PFNGLCREATESHADERPROC qglCreateShader; +PFNGLSHADERSOURCEPROC qglShaderSource; +PFNGLCOMPILESHADERPROC qglCompileShader; +PFNGLDELETESHADERPROC qglDeleteShader; +PFNGLISSHADERPROC qglIsShader; +PFNGLGETSHADERIVPROC qglGetShaderiv; +PFNGLGETSHADERINFOLOGPROC qglGetShaderInfoLog; +PFNGLGETSHADERSOURCEPROC qglGetShaderSource; + +// Program objects +PFNGLCREATEPROGRAMPROC qglCreateProgram; +PFNGLATTACHSHADERPROC qglAttachShader; +PFNGLDETACHSHADERPROC qglDetachShader; +PFNGLLINKPROGRAMPROC qglLinkProgram; +PFNGLUSEPROGRAMPROC qglUseProgram; +PFNGLDELETEPROGRAMPROC qglDeleteProgram; +PFNGLVALIDATEPROGRAMPROC qglValidateProgram; +PFNGLISPROGRAMPROC qglIsProgram; +PFNGLGETPROGRAMIVPROC qglGetProgramiv; +PFNGLGETATTACHEDSHADERSPROC qglGetAttachedShaders; +PFNGLGETPROGRAMINFOLOGPROC qglGetProgramInfoLog; +PFNGLBINDFRAGDATALOCATIONPROC qglBindFragDataLocation; + +// Vertex attributes +PFNGLGETACTIVEATTRIBPROC qglGetActiveAttrib; +PFNGLGETATTRIBLOCATIONPROC qglGetAttribLocation; +PFNGLBINDATTRIBLOCATIONPROC qglBindAttribLocation; +PFNGLGETVERTEXATTRIBDVPROC qglGetVertexAttribdv; +PFNGLGETVERTEXATTRIBFVPROC qglGetVertexAttribfv; +PFNGLGETVERTEXATTRIBIVPROC qglGetVertexAttribiv; +PFNGLGETVERTEXATTRIBIIVPROC qglGetVertexAttribIiv; +PFNGLGETVERTEXATTRIBIUIVPROC qglGetVertexAttribIuiv; + +PFNGLVERTEXATTRIB1FPROC qglVertexAttrib1f; +PFNGLVERTEXATTRIB2FPROC qglVertexAttrib2f; +PFNGLVERTEXATTRIB3FPROC qglVertexAttrib3f; +PFNGLVERTEXATTRIB4FPROC qglVertexAttrib4f; + +// Varying variables +PFNGLTRANSFORMFEEDBACKVARYINGSPROC qglTransformFeedbackVaryings; +PFNGLGETTRANSFORMFEEDBACKVARYINGPROC qglGetTransformFeedbackVarying; + +// Uniform variables +PFNGLGETUNIFORMLOCATIONPROC qglGetUniformLocation; +PFNGLGETUNIFORMBLOCKINDEXPROC qglGetUniformBlockIndex; +PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC qglGetActiveUniformBlockName; +PFNGLGETACTIVEUNIFORMBLOCKIVPROC qglGetActiveUniformBlockiv; +PFNGLGETUNIFORMINDICESPROC qglGetUniformIndices; +PFNGLGETACTIVEUNIFORMNAMEPROC qglGetActiveUniformName; +PFNGLGETACTIVEUNIFORMPROC qglGetActiveUniform; +PFNGLGETACTIVEUNIFORMSIVPROC qglGetActiveUniformsiv; +PFNGLUNIFORM1IPROC qglUniform1i; +PFNGLUNIFORM2IPROC qglUniform2i; +PFNGLUNIFORM3IPROC qglUniform3i; +PFNGLUNIFORM4IPROC qglUniform4i; +PFNGLUNIFORM1FPROC qglUniform1f; +PFNGLUNIFORM2FPROC qglUniform2f; +PFNGLUNIFORM3FPROC qglUniform3f; +PFNGLUNIFORM4FPROC qglUniform4f; +PFNGLUNIFORM1IVPROC qglUniform1iv; +PFNGLUNIFORM2IVPROC qglUniform2iv; +PFNGLUNIFORM3IVPROC qglUniform3iv; +PFNGLUNIFORM4IVPROC qglUniform4iv; +PFNGLUNIFORM1FVPROC qglUniform1fv; +PFNGLUNIFORM2FVPROC qglUniform2fv; +PFNGLUNIFORM3FVPROC qglUniform3fv; +PFNGLUNIFORM4FVPROC qglUniform4fv; +PFNGLUNIFORM1UIPROC qglUniform1ui; +PFNGLUNIFORM2UIPROC qglUniform2ui; +PFNGLUNIFORM3UIPROC qglUniform3ui; +PFNGLUNIFORM4UIPROC qglUniform4ui; +PFNGLUNIFORM1UIVPROC qglUniform1uiv; +PFNGLUNIFORM2UIVPROC qglUniform2uiv; +PFNGLUNIFORM3UIVPROC qglUniform3uiv; +PFNGLUNIFORM4UIVPROC qglUniform4uiv; +PFNGLUNIFORMMATRIX2FVPROC qglUniformMatrix2fv; +PFNGLUNIFORMMATRIX3FVPROC qglUniformMatrix3fv; +PFNGLUNIFORMMATRIX4FVPROC qglUniformMatrix4fv; +PFNGLUNIFORMMATRIX2X3FVPROC qglUniformMatrix2x3fv; +PFNGLUNIFORMMATRIX3X2FVPROC qglUniformMatrix3x2fv; +PFNGLUNIFORMMATRIX2X4FVPROC qglUniformMatrix2x4fv; +PFNGLUNIFORMMATRIX4X2FVPROC qglUniformMatrix4x2fv; +PFNGLUNIFORMMATRIX3X4FVPROC qglUniformMatrix3x4fv; +PFNGLUNIFORMMATRIX4X3FVPROC qglUniformMatrix4x3fv; +PFNGLUNIFORMBLOCKBINDINGPROC qglUniformBlockBinding; +PFNGLGETUNIFORMFVPROC qglGetUniformfv; +PFNGLGETUNIFORMIVPROC qglGetUniformiv; +PFNGLGETUNIFORMUIVPROC qglGetUniformuiv; + +// Transform feedback +PFNGLBEGINTRANSFORMFEEDBACKPROC qglBeginTransformFeedback; +PFNGLENDTRANSFORMFEEDBACKPROC qglEndTransformFeedback; + +// Texture compression +PFNGLCOMPRESSEDTEXIMAGE3DPROC qglCompressedTexImage3D; +PFNGLCOMPRESSEDTEXIMAGE2DPROC qglCompressedTexImage2D; +PFNGLCOMPRESSEDTEXIMAGE1DPROC qglCompressedTexImage1D; +PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC qglCompressedTexSubImage3D; +PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC qglCompressedTexSubImage2D; +PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC qglCompressedTexSubImage1D; +PFNGLGETCOMPRESSEDTEXIMAGEPROC qglGetCompressedTexImage; + +// Framebuffers +PFNGLISRENDERBUFFERPROC qglIsRenderbuffer; +PFNGLBINDRENDERBUFFERPROC qglBindRenderbuffer; +PFNGLDELETERENDERBUFFERSPROC qglDeleteRenderbuffers; +PFNGLGENRENDERBUFFERSPROC qglGenRenderbuffers; +PFNGLRENDERBUFFERSTORAGEPROC qglRenderbufferStorage; +PFNGLGETRENDERBUFFERPARAMETERIVPROC qglGetRenderbufferParameteriv; +PFNGLISFRAMEBUFFERPROC qglIsFramebuffer; +PFNGLBINDFRAMEBUFFERPROC qglBindFramebuffer; +PFNGLDELETEFRAMEBUFFERSPROC qglDeleteFramebuffers; +PFNGLGENFRAMEBUFFERSPROC qglGenFramebuffers; +PFNGLCHECKFRAMEBUFFERSTATUSPROC qglCheckFramebufferStatus; +PFNGLFRAMEBUFFERTEXTURE1DPROC qglFramebufferTexture1D; +PFNGLFRAMEBUFFERTEXTURE2DPROC qglFramebufferTexture2D; +PFNGLFRAMEBUFFERTEXTURE3DPROC qglFramebufferTexture3D; +PFNGLFRAMEBUFFERTEXTUREPROC qglFramebufferTexture; +PFNGLFRAMEBUFFERTEXTURELAYERPROC qglFramebufferTextureLayer; +PFNGLFRAMEBUFFERRENDERBUFFERPROC qglFramebufferRenderbuffer; +PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC qglGetFramebufferAttachmentParameteriv; +PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC qglRenderbufferStorageMultisample; +PFNGLBLITFRAMEBUFFERPROC qglBlitFramebuffer; +PFNGLGENERATEMIPMAPPROC qglGenerateMipmap; +PFNGLCLEARBUFFERFVPROC qglClearBufferfv; +PFNGLDRAWBUFFERSPROC qglDrawBuffers; + +// Query objects +PFNGLGENQUERIESPROC qglGenQueries; +PFNGLDELETEQUERIESPROC qglDeleteQueries; +PFNGLISQUERYPROC qglIsQuery; +PFNGLBEGINQUERYPROC qglBeginQuery; +PFNGLENDQUERYPROC qglEndQuery; +PFNGLGETQUERYIVPROC qglGetQueryiv; +PFNGLGETQUERYOBJECTIVPROC qglGetQueryObjectiv; +PFNGLGETQUERYOBJECTUIVPROC qglGetQueryObjectuiv; + +// GL state +PFNGLGETSTRINGIPROC qglGetStringi; + +// Sync objects and fences +PFNGLFENCESYNCPROC qglFenceSync; +PFNGLDELETESYNCPROC qglDeleteSync; +PFNGLCLIENTWAITSYNCPROC qglClientWaitSync; +PFNGLWAITSYNCPROC qglWaitSync; + +// GL_ARB_texture_storage +PFNGLTEXSTORAGE1DPROC qglTexStorage1D; +PFNGLTEXSTORAGE2DPROC qglTexStorage2D; +PFNGLTEXSTORAGE3DPROC qglTexStorage3D; + +// GL_ARB_buffer_storage +PFNGLBUFFERSTORAGEPROC qglBufferStorage; + +// GL_ARB_debug_output +PFNGLDEBUGMESSAGECONTROLARBPROC qglDebugMessageControlARB; +PFNGLDEBUGMESSAGEINSERTARBPROC qglDebugMessageInsertARB; +PFNGLDEBUGMESSAGECALLBACKARBPROC qglDebugMessageCallbackARB; +PFNGLGETDEBUGMESSAGELOGARBPROC qglGetDebugMessageLogARB; + +// GL_ARB_timer_query +PFNGLQUERYCOUNTERPROC qglQueryCounter; +PFNGLGETQUERYOBJECTI64VPROC qglGetQueryObjecti64v; +PFNGLGETQUERYOBJECTUI64VPROC qglGetQueryObjectui64v; + +static qboolean GLimp_HaveExtension(const char *ext) +{ + const char *ptr = Q_stristr( glConfigExt.originalExtensionString, ext ); + if (ptr == NULL) + return qfalse; + ptr += strlen(ext); + return (qboolean)((*ptr == ' ') || (*ptr == '\0')); // verify it's complete string. +} + +template +static qboolean GetGLFunction ( GLFuncType& glFunction, const char *glFunctionString, qboolean errorOnFailure ) +{ + glFunction = (GLFuncType)GL_GetProcAddress (glFunctionString); + if ( glFunction == NULL ) + { + if ( errorOnFailure ) + { + Com_Error (ERR_FATAL, "ERROR: OpenGL function '%s' could not be found.\n", glFunctionString); + } + + return qfalse; + } + + return qtrue; +} + + +static void QCALL GLimp_OnError(GLenum source, GLenum type, GLuint id, GLenum severity, + GLsizei length, const GLchar *message, const void *userParam) +{ + const char *severityText = ""; + const char *typeText = ""; + const char *sourceText = ""; + + switch ( source ) + { + case GL_DEBUG_SOURCE_API_ARB: sourceText = "API"; break; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: sourceText = "WS"; break; + case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: sourceText = "SC"; break; + case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: sourceText = "3rd"; break; + case GL_DEBUG_SOURCE_APPLICATION_ARB: sourceText = "App"; break; + case GL_DEBUG_SOURCE_OTHER_ARB: sourceText = "Oth"; break; + } + + switch ( severity ) + { + case GL_DEBUG_SEVERITY_HIGH_ARB: severityText = "High"; break; + case GL_DEBUG_SEVERITY_MEDIUM_ARB: severityText = "Medium"; break; + case GL_DEBUG_SEVERITY_LOW_ARB: severityText = "Low"; break; + } + + switch ( type ) + { + case GL_DEBUG_TYPE_ERROR_ARB: typeText = "Error"; break; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: typeText = "Deprecated"; break; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: typeText = "Undefined"; break; + case GL_DEBUG_TYPE_PORTABILITY_ARB: typeText = "Portability"; break; + case GL_DEBUG_TYPE_PERFORMANCE_ARB: typeText = "Performance"; break; + case GL_DEBUG_TYPE_OTHER_ARB: typeText = "Other"; break; + } + + Com_Printf( S_COLOR_YELLOW "OpenGL -> [%s][%s][%s] %s\n", sourceText, severityText, typeText, message ); +} + +void GLimp_InitCoreFunctions() +{ + Com_Printf("Initializing OpenGL 3.2 functions\n"); + + // Drawing commands + GetGLFunction (qglDrawRangeElements, "glDrawRangeElements", qtrue); + GetGLFunction (qglDrawArraysInstanced, "glDrawArraysInstanced", qtrue); + GetGLFunction (qglDrawElementsInstanced, "glDrawElementsInstanced", qtrue); + GetGLFunction (qglDrawElementsBaseVertex, "glDrawElementsBaseVertex", qtrue); + GetGLFunction (qglDrawRangeElementsBaseVertex, "glDrawRangeElementsBaseVertex", qtrue); + GetGLFunction (qglDrawElementsInstancedBaseVertex, "glDrawElementsInstancedBaseVertex", qtrue); + GetGLFunction (qglMultiDrawArrays, "glMultiDrawArrays", qtrue); + GetGLFunction (qglMultiDrawElements, "glMultiDrawElements", qtrue); + GetGLFunction (qglMultiDrawElementsBaseVertex, "glMultiDrawElementsBaseVertex", qtrue); + + // Vertex arrays + GetGLFunction (qglVertexAttribPointer, "glVertexAttribPointer", qtrue); + GetGLFunction (qglVertexAttribIPointer, "glVertexAttribIPointer", qtrue); + GetGLFunction (qglVertexAttribDivisor, "glVertexAttribDivisor", qtrue); + GetGLFunction (qglEnableVertexAttribArray, "glEnableVertexAttribArray", qtrue); + GetGLFunction (qglDisableVertexAttribArray, "glDisableVertexAttribArray", qtrue); + + // Vertex array objects + GetGLFunction (qglGenVertexArrays, "glGenVertexArrays", qtrue); + GetGLFunction (qglDeleteVertexArrays, "glDeleteVertexArrays", qtrue); + GetGLFunction (qglBindVertexArray, "glBindVertexArray", qtrue); + GetGLFunction (qglIsVertexArray, "glIsVertexArray", qtrue); + + GetGLFunction (qglVertexAttrib1f, "glVertexAttrib1f", qtrue); + GetGLFunction (qglVertexAttrib2f, "glVertexAttrib2f", qtrue); + GetGLFunction (qglVertexAttrib3f, "glVertexAttrib3f", qtrue); + GetGLFunction (qglVertexAttrib4f, "glVertexAttrib4f", qtrue); + + // Buffer objects + qglGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &glRefConfig.uniformBufferOffsetAlignment); + qglGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &glRefConfig.maxUniformBlockSize); + qglGetIntegerv(GL_MAX_UNIFORM_BUFFER_BINDINGS, &glRefConfig.maxUniformBufferBindings); + GetGLFunction (qglBindBuffer, "glBindBuffer", qtrue); + GetGLFunction (qglDeleteBuffers, "glDeleteBuffers", qtrue); + GetGLFunction (qglGenBuffers, "glGenBuffers", qtrue); + GetGLFunction (qglBufferData, "glBufferData", qtrue); + GetGLFunction (qglBufferSubData, "glBufferSubData", qtrue); + GetGLFunction (qglGetBufferSubData, "glGetBufferSubData", qtrue); + GetGLFunction (qglGetBufferParameteriv, "glGetBufferParameteriv", qtrue); + GetGLFunction (qglGetBufferParameteri64v, "glGetBufferParameteri64v", qtrue); + GetGLFunction (qglGetBufferPointerv, "glGetBufferPointerv", qtrue); + GetGLFunction (qglBindBufferRange, "glBindBufferRange", qtrue); + GetGLFunction (qglBindBufferBase, "glBindBufferBase", qtrue); + GetGLFunction (qglMapBufferRange, "glMapBufferRange", qtrue); + GetGLFunction (qglMapBuffer, "glMapBuffer", qtrue); + GetGLFunction (qglFlushMappedBufferRange, "glFlushMappedBufferRange", qtrue); + GetGLFunction (qglUnmapBuffer, "glUnmapBuffer", qtrue); + GetGLFunction (qglCopyBufferSubData, "glCopyBufferSubData", qtrue); + GetGLFunction (qglIsBuffer, "glIsBuffer", qtrue); + + // Texturing + GetGLFunction (qglActiveTexture, "glActiveTexture", qtrue); + GetGLFunction (qglTexImage3D, "glTexImage3D", qtrue); + + // Shader objects + GetGLFunction (qglCreateShader, "glCreateShader", qtrue); + GetGLFunction (qglShaderSource, "glShaderSource", qtrue); + GetGLFunction (qglCompileShader, "glCompileShader", qtrue); + GetGLFunction (qglDeleteShader, "glDeleteShader", qtrue); + GetGLFunction (qglIsShader, "glIsShader", qtrue); + GetGLFunction (qglGetShaderiv, "glGetShaderiv", qtrue); + GetGLFunction (qglGetShaderInfoLog, "glGetShaderInfoLog", qtrue); + GetGLFunction (qglGetShaderSource, "glGetShaderSource", qtrue); + + // Program objects + GetGLFunction (qglCreateProgram, "glCreateProgram", qtrue); + GetGLFunction (qglAttachShader, "glAttachShader", qtrue); + GetGLFunction (qglDetachShader, "glDetachShader", qtrue); + GetGLFunction (qglLinkProgram, "glLinkProgram", qtrue); + GetGLFunction (qglUseProgram, "glUseProgram", qtrue); + GetGLFunction (qglDeleteProgram, "glDeleteProgram", qtrue); + GetGLFunction (qglValidateProgram, "glValidateProgram", qtrue); + GetGLFunction (qglIsProgram, "glIsProgram", qtrue); + GetGLFunction (qglGetProgramiv, "glGetProgramiv", qtrue); + GetGLFunction (qglGetAttachedShaders, "glGetAttachedShaders", qtrue); + GetGLFunction (qglGetProgramInfoLog, "glGetProgramInfoLog", qtrue); + GetGLFunction (qglBindFragDataLocation, "glBindFragDataLocation", qtrue); + + // Vertex attributes + GetGLFunction (qglGetActiveAttrib, "glGetActiveAttrib", qtrue); + GetGLFunction (qglGetAttribLocation, "glGetAttribLocation", qtrue); + GetGLFunction (qglBindAttribLocation, "glBindAttribLocation", qtrue); + GetGLFunction (qglGetVertexAttribdv, "glGetVertexAttribdv", qtrue); + GetGLFunction (qglGetVertexAttribfv, "glGetVertexAttribfv", qtrue); + GetGLFunction (qglGetVertexAttribiv, "glGetVertexAttribiv", qtrue); + GetGLFunction (qglGetVertexAttribIiv, "glGetVertexAttribIiv", qtrue); + GetGLFunction (qglGetVertexAttribIuiv, "glGetVertexAttribIuiv", qtrue); + + // Varying variables + GetGLFunction (qglTransformFeedbackVaryings, "glTransformFeedbackVaryings", qtrue); + GetGLFunction (qglGetTransformFeedbackVarying, "glGetTransformFeedbackVarying", qtrue); + + // Uniform variables + GetGLFunction (qglGetUniformLocation, "glGetUniformLocation", qtrue); + GetGLFunction (qglGetUniformBlockIndex, "glGetUniformBlockIndex", qtrue); + GetGLFunction (qglGetActiveUniformBlockName, "glGetActiveUniformBlockName", qtrue); + GetGLFunction (qglGetActiveUniformBlockiv, "glGetActiveUniformBlockiv", qtrue); + GetGLFunction (qglGetUniformIndices, "glGetUniformIndices", qtrue); + GetGLFunction (qglGetActiveUniformName, "glGetActiveUniformName", qtrue); + GetGLFunction (qglGetActiveUniform, "glGetActiveUniform", qtrue); + GetGLFunction (qglGetActiveUniformsiv, "glGetActiveUniformsiv", qtrue); + GetGLFunction (qglUniform1i, "glUniform1i", qtrue); + GetGLFunction (qglUniform2i, "glUniform2i", qtrue); + GetGLFunction (qglUniform3i, "glUniform3i", qtrue); + GetGLFunction (qglUniform4i, "glUniform4i", qtrue); + GetGLFunction (qglUniform1f, "glUniform1f", qtrue); + GetGLFunction (qglUniform2f, "glUniform2f", qtrue); + GetGLFunction (qglUniform3f, "glUniform3f", qtrue); + GetGLFunction (qglUniform4f, "glUniform4f", qtrue); + GetGLFunction (qglUniform1iv, "glUniform1iv", qtrue); + GetGLFunction (qglUniform2iv, "glUniform2iv", qtrue); + GetGLFunction (qglUniform3iv, "glUniform3iv", qtrue); + GetGLFunction (qglUniform4iv, "glUniform4iv", qtrue); + GetGLFunction (qglUniform1fv, "glUniform1fv", qtrue); + GetGLFunction (qglUniform2fv, "glUniform2fv", qtrue); + GetGLFunction (qglUniform3fv, "glUniform3fv", qtrue); + GetGLFunction (qglUniform4fv, "glUniform4fv", qtrue); + GetGLFunction (qglUniform1ui, "glUniform1ui", qtrue); + GetGLFunction (qglUniform2ui, "glUniform2ui", qtrue); + GetGLFunction (qglUniform3ui, "glUniform3ui", qtrue); + GetGLFunction (qglUniform4ui, "glUniform4ui", qtrue); + GetGLFunction (qglUniform1uiv, "glUniform1uiv", qtrue); + GetGLFunction (qglUniform2uiv, "glUniform2uiv", qtrue); + GetGLFunction (qglUniform3uiv, "glUniform3uiv", qtrue); + GetGLFunction (qglUniform4uiv, "glUniform4uiv", qtrue); + GetGLFunction (qglUniformMatrix2fv, "glUniformMatrix2fv", qtrue); + GetGLFunction (qglUniformMatrix3fv, "glUniformMatrix3fv", qtrue); + GetGLFunction (qglUniformMatrix4fv, "glUniformMatrix4fv", qtrue); + GetGLFunction (qglUniformMatrix2x3fv, "glUniformMatrix2x3fv", qtrue); + GetGLFunction (qglUniformMatrix3x2fv, "glUniformMatrix3x2fv", qtrue); + GetGLFunction (qglUniformMatrix2x4fv, "glUniformMatrix2x4fv", qtrue); + GetGLFunction (qglUniformMatrix4x2fv, "glUniformMatrix4x2fv", qtrue); + GetGLFunction (qglUniformMatrix3x4fv, "glUniformMatrix3x4fv", qtrue); + GetGLFunction (qglUniformMatrix4x3fv, "glUniformMatrix4x3fv", qtrue); + GetGLFunction (qglUniformBlockBinding, "glUniformBlockBinding", qtrue); + GetGLFunction (qglGetUniformfv, "glGetUniformfv", qtrue); + GetGLFunction (qglGetUniformiv, "glGetUniformiv", qtrue); + GetGLFunction (qglGetUniformuiv, "glGetUniformuiv", qtrue); + + // Transform feedback + GetGLFunction (qglBeginTransformFeedback, "glBeginTransformFeedback", qtrue); + GetGLFunction (qglEndTransformFeedback, "glEndTransformFeedback", qtrue); + + // Texture compression + GetGLFunction (qglCompressedTexImage3D, "glCompressedTexImage3D", qtrue); + GetGLFunction (qglCompressedTexImage2D, "glCompressedTexImage2D", qtrue); + GetGLFunction (qglCompressedTexImage1D, "glCompressedTexImage1D", qtrue); + GetGLFunction (qglCompressedTexSubImage3D, "glCompressedTexSubImage3D", qtrue); + GetGLFunction (qglCompressedTexSubImage2D, "glCompressedTexSubImage2D", qtrue); + GetGLFunction (qglCompressedTexSubImage1D, "glCompressedTexSubImage1D", qtrue); + GetGLFunction (qglGetCompressedTexImage, "glGetCompressedTexImage", qtrue); + + // GLSL + { + char version[256]; + Q_strncpyz( version, (const char *) qglGetString (GL_SHADING_LANGUAGE_VERSION), sizeof( version ) ); + sscanf(version, "%d.%d", &glRefConfig.glslMajorVersion, &glRefConfig.glslMinorVersion); + + ri.Printf(PRINT_ALL, "...using GLSL version %s\n", version); + } + + // Framebuffer and renderbuffers + qglGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &glRefConfig.maxRenderbufferSize); + qglGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &glRefConfig.maxColorAttachments); + + GetGLFunction (qglIsRenderbuffer, "glIsRenderbuffer", qtrue); + GetGLFunction (qglBindRenderbuffer, "glBindRenderbuffer", qtrue); + GetGLFunction (qglDeleteRenderbuffers, "glDeleteRenderbuffers", qtrue); + GetGLFunction (qglGenRenderbuffers, "glGenRenderbuffers", qtrue); + GetGLFunction (qglRenderbufferStorage, "glRenderbufferStorage", qtrue); + GetGLFunction (qglGetRenderbufferParameteriv, "glGetRenderbufferParameteriv", qtrue); + GetGLFunction (qglIsFramebuffer, "glIsFramebuffer", qtrue); + GetGLFunction (qglBindFramebuffer, "glBindFramebuffer", qtrue); + GetGLFunction (qglDeleteFramebuffers, "glDeleteFramebuffers", qtrue); + GetGLFunction (qglGenFramebuffers, "glGenFramebuffers", qtrue); + GetGLFunction (qglCheckFramebufferStatus, "glCheckFramebufferStatus", qtrue); + GetGLFunction (qglFramebufferTexture1D, "glFramebufferTexture1D", qtrue); + GetGLFunction (qglFramebufferTexture2D, "glFramebufferTexture2D", qtrue); + GetGLFunction (qglFramebufferTexture3D, "glFramebufferTexture3D", qtrue); + GetGLFunction (qglFramebufferTexture, "glFramebufferTexture", qtrue); + GetGLFunction (qglFramebufferTextureLayer, "glFramebufferTextureLayer", qtrue); + GetGLFunction (qglFramebufferRenderbuffer, "glFramebufferRenderbuffer", qtrue); + GetGLFunction (qglGetFramebufferAttachmentParameteriv, "glGetFramebufferAttachmentParameteriv", qtrue); + GetGLFunction (qglRenderbufferStorageMultisample, "glRenderbufferStorageMultisample", qtrue); + GetGLFunction (qglBlitFramebuffer, "glBlitFramebuffer", qtrue); + GetGLFunction (qglGenerateMipmap, "glGenerateMipmap", qtrue); + GetGLFunction (qglDrawBuffers, "glDrawBuffers", qtrue); + GetGLFunction (qglClearBufferfv, "glClearBufferfv", qtrue); + GetGLFunction (qglStencilOpSeparate, "glStencilOpSeparate", qtrue); + + // Queries + GetGLFunction (qglGenQueries, "glGenQueries", qtrue); + GetGLFunction (qglDeleteQueries, "glDeleteQueries", qtrue); + GetGLFunction (qglIsQuery, "glIsQuery", qtrue); + GetGLFunction (qglBeginQuery, "glBeginQuery", qtrue); + GetGLFunction (qglEndQuery, "glEndQuery", qtrue); + GetGLFunction (qglGetQueryiv, "glGetQueryiv", qtrue); + GetGLFunction (qglGetQueryObjectiv, "glGetQueryObjectiv", qtrue); + GetGLFunction (qglGetQueryObjectuiv, "glGetQueryObjectuiv", qtrue); + + // GL state + GetGLFunction (qglGetStringi, "glGetStringi", qtrue); + + // Sync objects and fences + GetGLFunction (qglFenceSync, "glFenceSync", qtrue); + GetGLFunction (qglDeleteSync, "glDeleteSync", qtrue); + GetGLFunction (qglClientWaitSync, "glClientWaitSync", qtrue); + GetGLFunction (qglWaitSync, "glWaitSync", qtrue); + +} + +void GLW_InitTextureCompression( void ); +void GLimp_InitExtensions() +{ + const char *extension; + const char* result[3] = { "...ignoring %s\n", "...using %s\n", "...%s not found\n" }; + + Com_Printf ("Initializing OpenGL extensions\n" ); + + // Select our tc scheme + GLW_InitTextureCompression(); + + // GL_EXT_texture_filter_anisotropic + glConfig.maxTextureFilterAnisotropy = 0; + if ( GLimp_HaveExtension( "EXT_texture_filter_anisotropic" ) ) + { + qglGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &glConfig.maxTextureFilterAnisotropy ); + Com_Printf ("...GL_EXT_texture_filter_anisotropic available\n" ); + + if ( r_ext_texture_filter_anisotropic->integer > 1 ) + { + Com_Printf ("...using GL_EXT_texture_filter_anisotropic\n" ); + } + else + { + Com_Printf ("...ignoring GL_EXT_texture_filter_anisotropic\n" ); + } + ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy ); + if ( r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy ) + { + ri.Cvar_SetValue( "r_ext_texture_filter_anisotropic_avail", glConfig.maxTextureFilterAnisotropy ); + } + } + else + { + Com_Printf ("...GL_EXT_texture_filter_anisotropic not found\n" ); + ri.Cvar_Set( "r_ext_texture_filter_anisotropic_avail", "0" ); + } + + // Memory info + glRefConfig.memInfo = MI_NONE; + if( GLimp_HaveExtension( "GL_NVX_gpu_memory_info" ) ) + { + glRefConfig.memInfo = MI_NVX; + } + else if( GLimp_HaveExtension( "GL_ATI_meminfo" ) ) + { + glRefConfig.memInfo = MI_ATI; + } + + glRefConfig.textureCompression = TCR_NONE; + + // GL_EXT_texture_compression_latc + extension = "GL_EXT_texture_compression_latc"; + if (GLimp_HaveExtension(extension)) + { + if (r_ext_compressed_textures->integer) + glRefConfig.textureCompression |= TCR_LATC; + + ri.Printf(PRINT_ALL, result[r_ext_compressed_textures->integer ? 1 : 0], extension); + } + else + { + ri.Printf(PRINT_ALL, result[2], extension); + } + + // GL_ARB_texture_compression_bptc + extension = "GL_ARB_texture_compression_bptc"; + if (GLimp_HaveExtension(extension)) + { + if (r_ext_compressed_textures->integer >= 2) + glRefConfig.textureCompression |= TCR_BPTC; + + ri.Printf(PRINT_ALL, result[(r_ext_compressed_textures->integer >= 2) ? 1 : 0], extension); + } + else + { + ri.Printf(PRINT_ALL, result[2], extension); + } + + // GL_ARB_texture_storage + extension = "GL_ARB_texture_storage"; + glRefConfig.immutableTextures = qfalse; + if( GLimp_HaveExtension( extension ) ) + { + qboolean loaded = qtrue; + + loaded = (qboolean)(loaded && GetGLFunction (qglTexStorage3D, "glTexStorage3D", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction (qglTexStorage1D, "glTexStorage1D", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction (qglTexStorage2D, "glTexStorage2D", qfalse)); + + glRefConfig.immutableTextures = loaded; + + ri.Printf(PRINT_ALL, result[loaded], extension); + } + else + { + ri.Printf(PRINT_ALL, result[2], extension); + } + + // GL_ARB_buffer_storage + extension = "GL_ARB_buffer_storage"; + glRefConfig.immutableBuffers = qfalse; + if( GLimp_HaveExtension( extension ) ) + { + qboolean loaded = qtrue; + + if ( r_arb_buffer_storage->integer ) + { + loaded = (qboolean)(loaded && GetGLFunction (qglBufferStorage, "glBufferStorage", qfalse)); + } + else + { + loaded = qfalse; + } + + glRefConfig.immutableBuffers = loaded; + ri.Printf(PRINT_ALL, result[loaded], extension); + } + else + { + ri.Printf(PRINT_ALL, result[2], extension); + } + + // GL_ARB_debug_output + extension = "GL_ARB_debug_output"; + if ( GLimp_HaveExtension( extension ) ) + { + qboolean loaded = qtrue; + + if ( r_debugContext->integer ) + { + loaded = (qboolean)(loaded && GetGLFunction (qglDebugMessageControlARB, "glDebugMessageControlARB", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction (qglDebugMessageInsertARB, "glDebugMessageInsertARB", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction (qglDebugMessageCallbackARB, "glDebugMessageCallbackARB", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction (qglGetDebugMessageLogARB, "glGetDebugMessageLogARB", qfalse)); + } + else + { + loaded = qfalse; + } + + glRefConfig.debugContext = loaded; + ri.Printf(PRINT_ALL, result[loaded], extension); + } + + // GL_ARB_timer_query + extension = "GL_ARB_timer_query"; + if ( GLimp_HaveExtension( extension ) ) + { + qboolean loaded = qtrue; + + loaded = (qboolean)(loaded && GetGLFunction(qglQueryCounter, "glQueryCounter", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction(qglGetQueryObjecti64v, "glGetQueryObjecti64v", qfalse)); + loaded = (qboolean)(loaded && GetGLFunction(qglGetQueryObjectui64v, "glGetQueryObjectui64v", qfalse)); + + glRefConfig.timerQuery = loaded; + + ri.Printf(PRINT_ALL, result[loaded], extension); + } + + // use float lightmaps? + glRefConfig.floatLightmap = (qboolean)(r_floatLightmap->integer && r_hdr->integer); + + if ( glRefConfig.debugContext ) + { + qglEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB ); + qglDebugMessageCallbackARB(GLimp_OnError, NULL); + } +} diff --git a/codemp/rd-rend2/tr_extramath.cpp b/codemp/rd-rend2/tr_extramath.cpp new file mode 100644 index 0000000000..76cf7c5cb5 --- /dev/null +++ b/codemp/rd-rend2/tr_extramath.cpp @@ -0,0 +1,266 @@ +/* +=========================================================================== +Copyright (C) 2010 James Canete (use.less01@gmail.com) + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_extramath.c - extra math needed by the renderer not in qmath.c + +#include "tr_local.h" + +// Some matrix helper functions +// FIXME: do these already exist in ioq3 and I don't know about them? + +void Matrix16Zero( matrix_t out ) +{ + out[ 0] = 0.0f; out[ 4] = 0.0f; out[ 8] = 0.0f; out[12] = 0.0f; + out[ 1] = 0.0f; out[ 5] = 0.0f; out[ 9] = 0.0f; out[13] = 0.0f; + out[ 2] = 0.0f; out[ 6] = 0.0f; out[10] = 0.0f; out[14] = 0.0f; + out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 0.0f; +} + +void Matrix16Identity( matrix_t out ) +{ + out[ 0] = 1.0f; out[ 4] = 0.0f; out[ 8] = 0.0f; out[12] = 0.0f; + out[ 1] = 0.0f; out[ 5] = 1.0f; out[ 9] = 0.0f; out[13] = 0.0f; + out[ 2] = 0.0f; out[ 6] = 0.0f; out[10] = 1.0f; out[14] = 0.0f; + out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 1.0f; +} + +void Matrix16Copy( const matrix_t in, matrix_t out ) +{ + out[ 0] = in[ 0]; out[ 4] = in[ 4]; out[ 8] = in[ 8]; out[12] = in[12]; + out[ 1] = in[ 1]; out[ 5] = in[ 5]; out[ 9] = in[ 9]; out[13] = in[13]; + out[ 2] = in[ 2]; out[ 6] = in[ 6]; out[10] = in[10]; out[14] = in[14]; + out[ 3] = in[ 3]; out[ 7] = in[ 7]; out[11] = in[11]; out[15] = in[15]; +} + +void Matrix16Multiply( const matrix_t in1, const matrix_t in2, matrix_t out ) +{ + out[ 0] = in1[ 0] * in2[ 0] + in1[ 4] * in2[ 1] + in1[ 8] * in2[ 2] + in1[12] * in2[ 3]; + out[ 1] = in1[ 1] * in2[ 0] + in1[ 5] * in2[ 1] + in1[ 9] * in2[ 2] + in1[13] * in2[ 3]; + out[ 2] = in1[ 2] * in2[ 0] + in1[ 6] * in2[ 1] + in1[10] * in2[ 2] + in1[14] * in2[ 3]; + out[ 3] = in1[ 3] * in2[ 0] + in1[ 7] * in2[ 1] + in1[11] * in2[ 2] + in1[15] * in2[ 3]; + + out[ 4] = in1[ 0] * in2[ 4] + in1[ 4] * in2[ 5] + in1[ 8] * in2[ 6] + in1[12] * in2[ 7]; + out[ 5] = in1[ 1] * in2[ 4] + in1[ 5] * in2[ 5] + in1[ 9] * in2[ 6] + in1[13] * in2[ 7]; + out[ 6] = in1[ 2] * in2[ 4] + in1[ 6] * in2[ 5] + in1[10] * in2[ 6] + in1[14] * in2[ 7]; + out[ 7] = in1[ 3] * in2[ 4] + in1[ 7] * in2[ 5] + in1[11] * in2[ 6] + in1[15] * in2[ 7]; + + out[ 8] = in1[ 0] * in2[ 8] + in1[ 4] * in2[ 9] + in1[ 8] * in2[10] + in1[12] * in2[11]; + out[ 9] = in1[ 1] * in2[ 8] + in1[ 5] * in2[ 9] + in1[ 9] * in2[10] + in1[13] * in2[11]; + out[10] = in1[ 2] * in2[ 8] + in1[ 6] * in2[ 9] + in1[10] * in2[10] + in1[14] * in2[11]; + out[11] = in1[ 3] * in2[ 8] + in1[ 7] * in2[ 9] + in1[11] * in2[10] + in1[15] * in2[11]; + + out[12] = in1[ 0] * in2[12] + in1[ 4] * in2[13] + in1[ 8] * in2[14] + in1[12] * in2[15]; + out[13] = in1[ 1] * in2[12] + in1[ 5] * in2[13] + in1[ 9] * in2[14] + in1[13] * in2[15]; + out[14] = in1[ 2] * in2[12] + in1[ 6] * in2[13] + in1[10] * in2[14] + in1[14] * in2[15]; + out[15] = in1[ 3] * in2[12] + in1[ 7] * in2[13] + in1[11] * in2[14] + in1[15] * in2[15]; +} + +void Matrix16Transform( const matrix_t in1, const vec4_t in2, vec4_t out ) +{ + out[ 0] = in1[ 0] * in2[ 0] + in1[ 4] * in2[ 1] + in1[ 8] * in2[ 2] + in1[12] * in2[ 3]; + out[ 1] = in1[ 1] * in2[ 0] + in1[ 5] * in2[ 1] + in1[ 9] * in2[ 2] + in1[13] * in2[ 3]; + out[ 2] = in1[ 2] * in2[ 0] + in1[ 6] * in2[ 1] + in1[10] * in2[ 2] + in1[14] * in2[ 3]; + out[ 3] = in1[ 3] * in2[ 0] + in1[ 7] * in2[ 1] + in1[11] * in2[ 2] + in1[15] * in2[ 3]; +} + +qboolean Matrix16Compare( const matrix_t a, const matrix_t b ) +{ + return (qboolean)(!(a[ 0] != b[ 0] || a[ 4] != b[ 4] || a[ 8] != b[ 8] || a[12] != b[12] || + a[ 1] != b[ 1] || a[ 5] != b[ 5] || a[ 9] != b[ 9] || a[13] != b[13] || + a[ 2] != b[ 2] || a[ 6] != b[ 6] || a[10] != b[10] || a[14] != b[14] || + a[ 3] != b[ 3] || a[ 7] != b[ 7] || a[11] != b[11] || a[15] != b[15])); +} + +void Matrix16Dump( const matrix_t in ) +{ + ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[ 0], in[ 4], in[ 8], in[12]); + ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[ 1], in[ 5], in[ 9], in[13]); + ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[ 2], in[ 6], in[10], in[14]); + ri.Printf(PRINT_ALL, "%3.5f %3.5f %3.5f %3.5f\n", in[ 3], in[ 7], in[11], in[15]); +} + +void Matrix16Translation(const vec3_t vec, matrix_t out ) +{ + out[ 0] = 1.0f; out[ 4] = 0.0f; out[ 8] = 0.0f; out[12] = vec[0]; + out[ 1] = 0.0f; out[ 5] = 1.0f; out[ 9] = 0.0f; out[13] = vec[1]; + out[ 2] = 0.0f; out[ 6] = 0.0f; out[10] = 1.0f; out[14] = vec[2]; + out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 1.0f; +} + +void Matrix16Ortho( float left, float right, float bottom, float top, float znear, float zfar, matrix_t out ) +{ + out[ 0] = 2.0f / (right - left); out[ 4] = 0.0f; out[ 8] = 0.0f; out[12] = -(right + left) / (right - left); + out[ 1] = 0.0f; out[ 5] = 2.0f / (top - bottom); out[ 9] = 0.0f; out[13] = -(top + bottom) / (top - bottom); + out[ 2] = 0.0f; out[ 6] = 0.0f; out[10] = 2.0f / (zfar - znear); out[14] = -(zfar + znear) / (zfar - znear); + out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 1.0f; +} + +void Matrix16View(vec3_t axes[3], vec3_t origin, matrix_t out) +{ + out[0] = axes[0][0]; + out[1] = axes[1][0]; + out[2] = axes[2][0]; + out[3] = 0; + + out[4] = axes[0][1]; + out[5] = axes[1][1]; + out[6] = axes[2][1]; + out[7] = 0; + + out[8] = axes[0][2]; + out[9] = axes[1][2]; + out[10] = axes[2][2]; + out[11] = 0; + + out[12] = -DotProduct(origin, axes[0]); + out[13] = -DotProduct(origin, axes[1]); + out[14] = -DotProduct(origin, axes[2]); + out[15] = 1; +} + +void Matrix16SimpleInverse( const matrix_t in, matrix_t out) +{ + vec3_t v; + float invSqrLen; + + VectorCopy(in + 0, v); + invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); + out[ 0] = v[0]; out[ 4] = v[1]; out[ 8] = v[2]; out[12] = -DotProduct(v, &in[12]); + + VectorCopy(in + 4, v); + invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); + out[ 1] = v[0]; out[ 5] = v[1]; out[ 9] = v[2]; out[13] = -DotProduct(v, &in[12]); + + VectorCopy(in + 8, v); + invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); + out[ 2] = v[0]; out[ 6] = v[1]; out[10] = v[2]; out[14] = -DotProduct(v, &in[12]); + + out[ 3] = 0.0f; out[ 7] = 0.0f; out[11] = 0.0f; out[15] = 1.0f; +} + +void VectorLerp( vec3_t a, vec3_t b, float lerp, vec3_t c) +{ + c[0] = a[0] * (1.0f - lerp) + b[0] * lerp; + c[1] = a[1] * (1.0f - lerp) + b[1] * lerp; + c[2] = a[2] * (1.0f - lerp) + b[2] * lerp; +} + +qboolean SpheresIntersect(vec3_t origin1, float radius1, vec3_t origin2, float radius2) +{ + float radiusSum = radius1 + radius2; + vec3_t diff; + + VectorSubtract(origin1, origin2, diff); + + if (DotProduct(diff, diff) <= radiusSum * radiusSum) + { + return qtrue; + } + + return qfalse; +} + +void BoundingSphereOfSpheres(vec3_t origin1, float radius1, vec3_t origin2, float radius2, vec3_t origin3, float *radius3) +{ + vec3_t diff; + + VectorScale(origin1, 0.5f, origin3); + VectorMA(origin3, 0.5f, origin2, origin3); + + VectorSubtract(origin1, origin2, diff); + *radius3 = VectorLength(diff) * 0.5f + MAX(radius1, radius2); +} + +int NextPowerOfTwo(int in) +{ + int out; + + for (out = 1; out < in; out <<= 1) + ; + + return out; +} + +unsigned short FloatToHalf(float in) +{ + unsigned short out; + + union + { + float f; + unsigned int i; + } f32; + + int sign, inExponent, inFraction; + int outExponent, outFraction; + + f32.f = in; + + sign = (f32.i & 0x80000000) >> 31; + inExponent = (f32.i & 0x7F800000) >> 23; + inFraction = f32.i & 0x007FFFFF; + + outExponent = CLAMP(inExponent - 127, -15, 16) + 15; + + outFraction = 0; + if (outExponent == 0x1F) + { + if (inExponent == 0xFF && inFraction != 0) + outFraction = 0x3FF; + } + else if (outExponent == 0x00) + { + if (inExponent == 0x00 && inFraction != 0) + outFraction = 0x3FF; + } + else + outFraction = inFraction >> 13; + + out = (sign << 15) | (outExponent << 10) | outFraction; + + return out; +} + +uint32_t ReverseBits(uint32_t v) +{ + v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1); + v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2); + v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4); + v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8); + v = (v >> 16) | (v << 16); + return v; +} + +float GSmithCorrelated(float roughness, float NdotV, float NdotL) +{ + const float m = roughness * roughness; + const float m2 = m * m; + const float visV = NdotL * sqrtf(NdotV * (NdotV - NdotV * m2) + m2); + const float visL = NdotV * sqrtf(NdotL * (NdotL - NdotL * m2) + m2); + + return 0.5f / (visV + visL); +} + +float V_Neubelt(float NdotV, float NdotL) +{ + // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886" + return 1.0 / (4.0 * (NdotL + NdotV - NdotL * NdotV)); +} diff --git a/codemp/rd-rend2/tr_extramath.h b/codemp/rd-rend2/tr_extramath.h new file mode 100644 index 0000000000..55607ab267 --- /dev/null +++ b/codemp/rd-rend2/tr_extramath.h @@ -0,0 +1,109 @@ +/* +=========================================================================== +Copyright (C) 2010 James Canete (use.less01@gmail.com) + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_extramath.h + +#ifndef __TR_EXTRAMATH_H__ +#define __TR_EXTRAMATH_H__ + +typedef float matrix_t[16]; +typedef float mat4x3_t[12]; +typedef float mat3x4_t[12]; +typedef int vec2i_t[2]; +typedef int vec3i_t[3]; +typedef int vec4i_t[4]; + +void Matrix16Zero( matrix_t out ); +void Matrix16Identity( matrix_t out ); +void Matrix16Copy( const matrix_t in, matrix_t out ); +void Matrix16Multiply( const matrix_t in1, const matrix_t in2, matrix_t out ); +void Matrix16Transform( const matrix_t in1, const vec4_t in2, vec4_t out ); +qboolean Matrix16Compare(const matrix_t a, const matrix_t b); +void Matrix16Dump( const matrix_t in ); +void Matrix16Translation( const vec3_t vec, matrix_t out ); +void Matrix16Ortho( float left, float right, float bottom, float top, float znear, float zfar, matrix_t out ); +void Matrix16View(vec3_t axes[3], vec3_t origin, matrix_t out); +void Matrix16SimpleInverse( const matrix_t in, matrix_t out); + +#define VectorCopy2(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1]) +#define VectorSet2(v,x,y) ((v)[0]=(x),(v)[1]=(y)); + +#define VectorCopy4(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3]) +#define VectorSet4(v,x,y,z,w) ((v)[0]=(x),(v)[1]=(y),(v)[2]=(z),(v)[3]=(w)) +#define DotProduct4(a,b) ((a)[0]*(b)[0] + (a)[1]*(b)[1] + (a)[2]*(b)[2] + (a)[3]*(b)[3]) +#define VectorScale4(a,b,c) ((c)[0]=(a)[0]*(b),(c)[1]=(a)[1]*(b),(c)[2]=(a)[2]*(b),(c)[3]=(a)[3]*(b)) + +#define VectorCopy5(a,b) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2],(b)[3]=(a)[3],(b)[4]=(a)[4]) + +#define OffsetByteToFloat(a) ((float)(a) * 1.0f/127.5f - 1.0f) +#define FloatToOffsetByte(a) (byte)(((a) + 1.0f) * 127.5f) +#define ByteToFloat(a) ((float)(a) * 1.0f/255.0f) +#define FloatToByte(a) (byte)((a) * 255.0f) + +#define RGBtosRGB(a) (((a) < 0.0031308f) ? (12.92f * (a)) : (1.055f * pow((a), 0.41666f) - 0.055f)) +#define sRGBtoRGB(a) (((a) <= 0.04045f) ? ((a) / 12.92f) : (pow((((a) + 0.055f) / 1.055f), 2.4)) ) + +QINLINE int VectorCompare4(const vec4_t v1, const vec4_t v2) +{ + if(v1[0] != v2[0] || v1[1] != v2[1] || v1[2] != v2[2] || v1[3] != v2[3]) + { + return 0; + } + return 1; +} + +QINLINE int VectorCompare5(const vec5_t v1, const vec5_t v2) +{ + if(v1[0] != v2[0] || v1[1] != v2[1] || v1[2] != v2[2] || v1[3] != v2[3] || v1[4] != v2[4]) + { + return 0; + } + return 1; +} + +void VectorLerp( vec3_t a, vec3_t b, float lerp, vec3_t c); + + +qboolean SpheresIntersect(vec3_t origin1, float radius1, vec3_t origin2, float radius2); +void BoundingSphereOfSpheres(vec3_t origin1, float radius1, vec3_t origin2, float radius2, vec3_t origin3, float *radius3); + +#ifndef SGN +#define SGN(x) (((x) >= 0) ? !!(x) : -1) +#endif + +#ifndef MAX +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#endif + +#ifndef MIN +#define MIN(a,b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef CLAMP +#define CLAMP(a,b,c) MIN(MAX((a),(b)),(c)) +#endif + +int NextPowerOfTwo(int in); +unsigned short FloatToHalf(float in); +uint32_t ReverseBits(uint32_t v); +float GSmithCorrelated(float roughness, float ndotv, float ndotl); +float V_Neubelt(float NdotV, float NdotL); +#endif diff --git a/codemp/rd-rend2/tr_extratypes.h b/codemp/rd-rend2/tr_extratypes.h new file mode 100644 index 0000000000..b840567cb6 --- /dev/null +++ b/codemp/rd-rend2/tr_extratypes.h @@ -0,0 +1,40 @@ +/* +=========================================================================== +Copyright (C) 2009-2011 Andrei Drexler, Richard Allen, James Canete + +This file is part of Reaction source code. + +Reaction source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Reaction source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Reaction source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +#ifndef __TR_EXTRATYPES_H__ +#define __TR_EXTRATYPES_H__ + +// tr_extratypes.h, for mods that want to extend tr_types.h without losing compatibility with original VMs + +// extra refdef flags start at 0x0008 +//#define RDF_NOFOG 0x0008 // don't apply fog to polys added using RE_AddPolyToScene +#define RDF_EXTRA 256 // Makro - refdefex_t to follow after refdef_t +#define RDF_SUNLIGHT 512 // SmileTheory - render sunlight and shadows + +typedef struct { + float blurFactor; + float sunDir[3]; + float sunCol[3]; + float sunAmbCol[3]; +} refdefex_t; + +#endif diff --git a/codemp/rd-rend2/tr_fbo.cpp b/codemp/rd-rend2/tr_fbo.cpp new file mode 100644 index 0000000000..9a7e4f97a6 --- /dev/null +++ b/codemp/rd-rend2/tr_fbo.cpp @@ -0,0 +1,961 @@ +/* +=========================================================================== +Copyright (C) 2006 Kirk Barnes +Copyright (C) 2006-2008 Robert Beckebans + +This file is part of XreaL source code. + +XreaL source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +XreaL source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with XreaL source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_fbo.c +#include "tr_local.h" + +/* +============= +R_CheckFBO +============= +*/ +qboolean R_CheckFBO(const FBO_t * fbo) +{ + int code; + int id; + + qglGetIntegerv(GL_FRAMEBUFFER_BINDING, &id); + qglBindFramebuffer(GL_FRAMEBUFFER, fbo->frameBuffer); + + code = qglCheckFramebufferStatus(GL_FRAMEBUFFER); + + qglBindFramebuffer(GL_FRAMEBUFFER, id); + + if(code == GL_FRAMEBUFFER_COMPLETE) + { + return qtrue; + } + + // an error occured + switch (code) + { + case GL_FRAMEBUFFER_COMPLETE: + break; + + case GL_FRAMEBUFFER_UNSUPPORTED: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Unsupported framebuffer format\n", fbo->name); + break; + + case GL_FRAMEBUFFER_UNDEFINED: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Default framebuffer was checked, but does not exist\n", fbo->name); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete attachment\n", fbo->name); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, no attachments attached\n", fbo->name); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, mismatched multisampling values\n", fbo->name); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, mismatched layer targets\n", + fbo->name); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, missing draw buffer\n", fbo->name); + break; + + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) Framebuffer incomplete, missing read buffer\n", fbo->name); + break; + + default: + ri.Printf(PRINT_WARNING, "R_CheckFBO: (%s) unknown error 0x%X\n", fbo->name, code); + //ri.Error(ERR_FATAL, "R_CheckFBO: (%s) unknown error 0x%X", fbo->name, code); + //assert(0); + break; + } + + return qfalse; +} + +/* +============ +FBO_Create +============ +*/ +FBO_t *FBO_Create(const char *name, int width, int height) +{ + FBO_t *fbo; + + if(strlen(name) >= MAX_QPATH) + { + ri.Error(ERR_DROP, "FBO_Create: \"%s\" is too long", name); + } + + if(width <= 0 || width > glRefConfig.maxRenderbufferSize) + { + ri.Error(ERR_DROP, "FBO_Create: bad width %i", width); + } + + if(height <= 0 || height > glRefConfig.maxRenderbufferSize) + { + ri.Error(ERR_DROP, "FBO_Create: bad height %i", height); + } + + if(tr.numFBOs == MAX_FBOS) + { + ri.Error(ERR_DROP, "FBO_Create: MAX_FBOS hit"); + } + + fbo = tr.fbos[tr.numFBOs] = (FBO_t *)ri.Hunk_Alloc(sizeof(*fbo), h_low); + Q_strncpyz(fbo->name, name, sizeof(fbo->name)); + fbo->index = tr.numFBOs++; + fbo->width = width; + fbo->height = height; + + qglGenFramebuffers(1, &fbo->frameBuffer); + + return fbo; +} + +void FBO_CreateBuffer(FBO_t *fbo, int format, int index, int multisample) +{ + uint32_t *pRenderBuffer; + GLenum attachment; + qboolean absent; + + switch(format) + { + case GL_RGB: + case GL_RGBA: + case GL_RGB8: + case GL_RGBA8: + case GL_RGB16F: + case GL_RGBA16F: + case GL_RGB32F: + case GL_RGBA32F: + fbo->colorFormat = format; + pRenderBuffer = &fbo->colorBuffers[index]; + attachment = GL_COLOR_ATTACHMENT0 + index; + break; + + case GL_DEPTH_COMPONENT: + case GL_DEPTH_COMPONENT16: + case GL_DEPTH_COMPONENT24: + case GL_DEPTH_COMPONENT32: + fbo->depthFormat = format; + pRenderBuffer = &fbo->depthBuffer; + attachment = GL_DEPTH_ATTACHMENT; + break; + + case GL_STENCIL_INDEX: + case GL_STENCIL_INDEX1: + case GL_STENCIL_INDEX4: + case GL_STENCIL_INDEX8: + case GL_STENCIL_INDEX16: + fbo->stencilFormat = format; + pRenderBuffer = &fbo->stencilBuffer; + attachment = GL_STENCIL_ATTACHMENT; + break; + + case GL_DEPTH_STENCIL: + case GL_DEPTH24_STENCIL8: + fbo->packedDepthStencilFormat = format; + pRenderBuffer = &fbo->packedDepthStencilBuffer; + attachment = 0; // special for stencil and depth + break; + + default: + ri.Printf(PRINT_WARNING, "FBO_CreateBuffer: invalid format %d\n", format); + return; + } + + absent = (qboolean)(*pRenderBuffer == 0); + if (absent) + qglGenRenderbuffers(1, pRenderBuffer); + + qglBindRenderbuffer(GL_RENDERBUFFER, *pRenderBuffer); + if (multisample) + { + qglRenderbufferStorageMultisample(GL_RENDERBUFFER, multisample, format, fbo->width, fbo->height); + } + else + { + qglRenderbufferStorage(GL_RENDERBUFFER, format, fbo->width, fbo->height); + } + + if(absent) + { + if (attachment == 0) + { + qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, *pRenderBuffer); + qglFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, *pRenderBuffer); + } + else + qglFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, *pRenderBuffer); + } +} + + +/* +================= +R_AttachFBOTexture1D +================= +*/ +void R_AttachFBOTexture1D(int texId, int index) +{ + if(index < 0 || index >= glRefConfig.maxColorAttachments) + { + ri.Printf(PRINT_WARNING, "R_AttachFBOTexture1D: invalid attachment index %i\n", index); + return; + } + + qglFramebufferTexture1D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, GL_TEXTURE_1D, texId, 0); +} + +/* +================= +R_AttachFBOTexture2D +================= +*/ +void R_AttachFBOTexture2D(int target, int texId, int index) +{ + if (target != GL_TEXTURE_2D && + (target < GL_TEXTURE_CUBE_MAP_POSITIVE_X || + target > GL_TEXTURE_CUBE_MAP_NEGATIVE_Z)) + { + ri.Printf(PRINT_WARNING, "R_AttachFBOTexture2D: invalid target %i\n", target); + return; + } + + if (index < 0 || index >= glRefConfig.maxColorAttachments) + { + ri.Printf(PRINT_WARNING, "R_AttachFBOTexture2D: invalid attachment index %i\n", index); + return; + } + + qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, target, texId, 0); +} + +/* +================= +R_AttachFBOTexture3D +================= +*/ +void R_AttachFBOTexture3D(int texId, int index, int zOffset) +{ + if(index < 0 || index >= glRefConfig.maxColorAttachments) + { + ri.Printf(PRINT_WARNING, "R_AttachFBOTexture3D: invalid attachment index %i\n", index); + return; + } + + qglFramebufferTexture3D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + index, GL_TEXTURE_3D, texId, 0, zOffset); +} + +/* +================= +R_AttachFBOTextureDepth +================= +*/ +void R_AttachFBOTextureDepth(int texId) +{ + qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texId, 0); +} + +/* +================= +R_AttachFBOTexturePackedDepthStencil +================= +*/ +void R_AttachFBOTexturePackedDepthStencil(int texId) +{ + qglFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texId, 0); +} + +void FBO_AttachTextureImage(image_t *img, int index) +{ + if (!glState.currentFBO) + { + ri.Printf(PRINT_WARNING, "FBO: attempted to attach a texture image with no FBO bound!\n"); + return; + } + + R_AttachFBOTexture2D(GL_TEXTURE_2D, img->texnum, index); + + glState.currentFBO->colorImage[index] = img; + glState.currentFBO->colorBuffers[index] = img->texnum; +} + +static void FBO_SetupDrawBuffers() +{ + if (!glState.currentFBO) + { + ri.Printf(PRINT_WARNING, "FBO: attempted to attach a texture image with no FBO bound!\n"); + return; + } + + FBO_t *currentFBO = glState.currentFBO; + int numBuffers = 0; + GLenum bufs[8]; + + while ( currentFBO->colorBuffers[numBuffers] != 0 ) + { + numBuffers++; + } + + if ( numBuffers == 0 ) + { + qglDrawBuffer (GL_NONE); + } + else + { + for ( int i = 0; i < numBuffers; i++ ) + { + bufs[i] = GL_COLOR_ATTACHMENT0 + i; + } + + qglDrawBuffers (numBuffers, bufs); + } +} + +/* +============ +FBO_Bind +============ +*/ +void FBO_Bind(FBO_t * fbo) +{ + if (glState.currentFBO == fbo) + return; + + if (r_logFile->integer) + { + // don't just call LogComment, or we will get a call to va() every frame! + if (fbo) + GLimp_LogComment(va("--- FBO_Bind( %s ) ---\n", fbo->name)); + else + GLimp_LogComment("--- FBO_Bind ( NULL ) ---\n"); + } + + if (!fbo) + { + qglBindFramebuffer(GL_FRAMEBUFFER, 0); + glState.currentFBO = NULL; + } + else + { + qglBindFramebuffer(GL_FRAMEBUFFER, fbo->frameBuffer); + glState.currentFBO = fbo; + } +} + +/* +============ +FBO_Init +============ +*/ +void FBO_Init(void) +{ + int i; + int hdrFormat, multisample; + + ri.Printf(PRINT_ALL, "------- FBO_Init -------\n"); + + tr.numFBOs = 0; + + GL_CheckErrors(); + + R_IssuePendingRenderCommands(); + +/* if(glRefConfig.textureNonPowerOfTwo) + { + width = glConfig.vidWidth; + height = glConfig.vidHeight; + } + else + { + width = NextPowerOfTwo(glConfig.vidWidth); + height = NextPowerOfTwo(glConfig.vidHeight); + } */ + + hdrFormat = GL_RGBA8; + if (r_hdr->integer) + { + hdrFormat = GL_RGBA16F; + } + + qglGetIntegerv(GL_MAX_SAMPLES, &multisample); + + if (r_ext_framebuffer_multisample->integer < multisample) + { + multisample = r_ext_framebuffer_multisample->integer; + } + + if (multisample < 2) + multisample = 0; + + if (multisample != r_ext_framebuffer_multisample->integer) + { + ri.Cvar_SetValue("r_ext_framebuffer_multisample", (float)multisample); + } + + // only create a render FBO if we need to resolve MSAA or do HDR + // otherwise just render straight to the screen (tr.renderFbo = NULL) + if (multisample) + { + tr.renderFbo = FBO_Create( + "_render", tr.renderDepthImage->width, + tr.renderDepthImage->height); + + FBO_Bind(tr.renderFbo); + FBO_CreateBuffer(tr.renderFbo, hdrFormat, 0, multisample); + FBO_CreateBuffer(tr.renderFbo, hdrFormat, 1, multisample); + FBO_CreateBuffer(tr.renderFbo, GL_DEPTH24_STENCIL8, 0, multisample); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.renderFbo); + + tr.msaaResolveFbo = FBO_Create( + "_msaaResolve", tr.renderDepthImage->width, + tr.renderDepthImage->height); + + FBO_Bind(tr.msaaResolveFbo); + FBO_AttachTextureImage(tr.renderImage, 0); + FBO_AttachTextureImage(tr.glowImage, 1); + R_AttachFBOTexturePackedDepthStencil(tr.renderDepthImage->texnum); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.msaaResolveFbo); + } + else + { + tr.renderFbo = FBO_Create( + "_render", tr.renderDepthImage->width, + tr.renderDepthImage->height); + + FBO_Bind(tr.renderFbo); + FBO_AttachTextureImage(tr.renderImage, 0); + FBO_AttachTextureImage(tr.glowImage, 1); + R_AttachFBOTexturePackedDepthStencil(tr.renderDepthImage->texnum); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.renderFbo); + } + + // clear render buffer + // this fixes the corrupt screen bug with r_hdr 1 on older hardware + FBO_Bind(tr.renderFbo); + qglClearColor( 0.f, 0.f, 0.f, 1 ); + qglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); + + // glow buffers + { + for ( int i = 0; i < ARRAY_LEN(tr.glowImageScaled); i++ ) + { + tr.glowFboScaled[i] = FBO_Create( + va("*glowScaled%d", i), tr.glowImageScaled[i]->width, + tr.glowImageScaled[i]->height); + + FBO_Bind (tr.glowFboScaled[i]); + FBO_AttachTextureImage (tr.glowImageScaled[i], 0); + FBO_SetupDrawBuffers(); + + R_CheckFBO (tr.glowFboScaled[i]); + } + } + + if (r_drawSunRays->integer) + { + tr.sunRaysFbo = FBO_Create( + "_sunRays", tr.renderDepthImage->width, + tr.renderDepthImage->height); + + FBO_Bind(tr.sunRaysFbo); + FBO_AttachTextureImage(tr.sunRaysImage, 0); + R_AttachFBOTextureDepth(tr.renderDepthImage->texnum); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.sunRaysFbo); + } + +#if MAX_DRAWN_PSHADOWS > 0 + if (tr.pshadowArrayImage != NULL) + { + for( i = 0; i < MAX_DRAWN_PSHADOWS; i++) + { + tr.pshadowFbos[i] = FBO_Create( + va("_shadowmap%i", i), tr.pshadowArrayImage->width, + tr.pshadowArrayImage->height); + + FBO_Bind(tr.pshadowFbos[i]); + qglFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tr.pshadowArrayImage->texnum, 0, i); + qglDrawBuffer(GL_NONE); + qglReadBuffer(GL_NONE); + R_CheckFBO(tr.pshadowFbos[i]); + } + + } +#endif + + if (r_dlightMode->integer >= 2) + { + for (i = 0; i < MAX_DLIGHTS * 6; i++) + { + tr.shadowCubeFbo[i] = FBO_Create(va("_shadowCubeFbo_%i", i), PSHADOW_MAP_SIZE, PSHADOW_MAP_SIZE); + FBO_Bind(tr.shadowCubeFbo[i]); + qglFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tr.pointShadowArrayImage->texnum, 0, i); + qglDrawBuffer(GL_NONE); + qglReadBuffer(GL_NONE); + R_CheckFBO(tr.shadowCubeFbo[i]); + } + } + + if (tr.sunShadowArrayImage != NULL) + { + for ( i = 0; i < 3; i++) + { + tr.sunShadowFbo[i] = FBO_Create( + va("_sunshadowmap%i", i), + tr.sunShadowArrayImage->width, + tr.sunShadowArrayImage->height); + + FBO_Bind(tr.sunShadowFbo[i]); + qglFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, tr.sunShadowArrayImage->texnum, 0, i); + qglDrawBuffer(GL_NONE); + qglReadBuffer(GL_NONE); + + R_CheckFBO(tr.sunShadowFbo[i]); + } + + tr.screenShadowFbo = FBO_Create( + "_screenshadow", tr.screenShadowImage->width, + tr.screenShadowImage->height); + + FBO_Bind(tr.screenShadowFbo); + FBO_AttachTextureImage(tr.screenShadowImage, 0); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.screenShadowFbo); + } + + for (i = 0; i < 2; i++) + { + tr.textureScratchFbo[i] = FBO_Create( + va("_texturescratch%d", i), tr.textureScratchImage[i]->width, + tr.textureScratchImage[i]->height); + + FBO_Bind(tr.textureScratchFbo[i]); + FBO_AttachTextureImage(tr.textureScratchImage[i], 0); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.textureScratchFbo[i]); + } + + { + tr.calcLevelsFbo = FBO_Create( + "_calclevels", tr.calcLevelsImage->width, + tr.calcLevelsImage->height); + + FBO_Bind(tr.calcLevelsFbo); + FBO_AttachTextureImage(tr.calcLevelsImage, 0); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.calcLevelsFbo); + } + + { + tr.targetLevelsFbo = FBO_Create( + "_targetlevels", tr.targetLevelsImage->width, + tr.targetLevelsImage->height); + + FBO_Bind(tr.targetLevelsFbo); + FBO_AttachTextureImage(tr.targetLevelsImage, 0); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.targetLevelsFbo); + } + + for (i = 0; i < 2; i++) + { + tr.quarterFbo[i] = FBO_Create( + va("_quarter%d", i), tr.quarterImage[i]->width, + tr.quarterImage[i]->height); + + FBO_Bind(tr.quarterFbo[i]); + FBO_AttachTextureImage(tr.quarterImage[i], 0); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.quarterFbo[i]); + } + + if (r_ssao->integer) + { + tr.hdrDepthFbo = FBO_Create( + "_hdrDepth", tr.hdrDepthImage->width, tr.hdrDepthImage->height); + + FBO_Bind(tr.hdrDepthFbo); + FBO_AttachTextureImage(tr.hdrDepthImage, 0); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.hdrDepthFbo); + + tr.screenSsaoFbo = FBO_Create( + "_screenssao", tr.screenSsaoImage->width, + tr.screenSsaoImage->height); + + FBO_Bind(tr.screenSsaoFbo); + FBO_AttachTextureImage(tr.screenSsaoImage, 0); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.screenSsaoFbo); + } + + if (tr.renderCubeImage != NULL) + { + for (i = 0; i < 6; i++) + { + tr.renderCubeFbo[i] = FBO_Create( + "_renderCubeFbo", tr.renderCubeImage->width, + tr.renderCubeImage->height); + FBO_Bind(tr.renderCubeFbo[i]); + R_AttachFBOTexture2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, tr.renderCubeImage->texnum, 0); + glState.currentFBO->colorImage[0] = tr.renderCubeImage; + glState.currentFBO->colorBuffers[0] = tr.renderCubeImage->texnum; + R_AttachFBOTextureDepth(tr.renderCubeDepthImage->texnum); + + FBO_SetupDrawBuffers(); + R_CheckFBO(tr.renderCubeFbo[i]); + } + + tr.filterCubeFbo = FBO_Create( + "_filterCubeFbo", tr.renderCubeImage->width, + tr.renderCubeImage->height); + FBO_Bind(tr.filterCubeFbo); + qglFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, tr.renderCubeImage->texnum, 0); + glState.currentFBO->colorImage[0] = tr.renderCubeImage; + glState.currentFBO->colorBuffers[0] = tr.renderCubeImage->texnum; + FBO_SetupDrawBuffers(); + R_CheckFBO(tr.filterCubeFbo); + } + + if (tr.weatherDepthImage != nullptr) + { + tr.weatherDepthFbo = FBO_Create( + "_weatherDepthFbo", + tr.weatherDepthImage->width, + tr.weatherDepthImage->height); + + FBO_Bind(tr.weatherDepthFbo); + R_AttachFBOTextureDepth(tr.weatherDepthImage->texnum); + FBO_SetupDrawBuffers(); + + R_CheckFBO(tr.weatherDepthFbo); + } + + GL_CheckErrors(); + + FBO_Bind(NULL); +} + +/* +============ +FBO_Shutdown +============ +*/ +void FBO_Shutdown(void) +{ + int i, j; + FBO_t *fbo; + + ri.Printf(PRINT_ALL, "------- FBO_Shutdown -------\n"); + + FBO_Bind(NULL); + + for(i = 0; i < tr.numFBOs; i++) + { + fbo = tr.fbos[i]; + + for(j = 0; j < glRefConfig.maxColorAttachments; j++) + { + if(fbo->colorBuffers[j]) + qglDeleteRenderbuffers(1, &fbo->colorBuffers[j]); + } + + if(fbo->depthBuffer) + qglDeleteRenderbuffers(1, &fbo->depthBuffer); + + if(fbo->stencilBuffer) + qglDeleteRenderbuffers(1, &fbo->stencilBuffer); + + if(fbo->frameBuffer) + qglDeleteFramebuffers(1, &fbo->frameBuffer); + } +} + +/* +============ +R_FBOList_f +============ +*/ +void R_FBOList_f(void) +{ + int i; + FBO_t *fbo; + + ri.Printf(PRINT_ALL, " size name\n"); + ri.Printf(PRINT_ALL, "----------------------------------------------------------\n"); + + for(i = 0; i < tr.numFBOs; i++) + { + fbo = tr.fbos[i]; + + ri.Printf(PRINT_ALL, " %4i: %4i %4i %s\n", i, fbo->width, fbo->height, fbo->name); + } + + ri.Printf(PRINT_ALL, " %i FBOs\n", tr.numFBOs); +} + +void FBO_BlitFromTexture(struct image_s *src, vec4i_t inSrcBox, vec2_t inSrcTexScale, FBO_t *dst, vec4i_t inDstBox, struct shaderProgram_s *shaderProgram, vec4_t inColor, int blend) +{ + vec4i_t dstBox, srcBox; + vec2_t srcTexScale; + vec4_t color; + vec4_t quadVerts[4]; + vec2_t texCoords[4]; + vec2_t invTexRes; + FBO_t *oldFbo = glState.currentFBO; + matrix_t projection; + int width, height; + + if (!src) + return; + + if (inSrcBox) + { + VectorSet4(srcBox, inSrcBox[0], inSrcBox[1], inSrcBox[0] + inSrcBox[2], inSrcBox[1] + inSrcBox[3]); + } + else + { + VectorSet4(srcBox, 0, 0, src->width, src->height); + } + + // framebuffers are 0 bottom, Y up. + if (inDstBox) + { + if (dst) + { + dstBox[0] = inDstBox[0]; + dstBox[1] = dst->height - inDstBox[1] - inDstBox[3]; + dstBox[2] = inDstBox[0] + inDstBox[2]; + dstBox[3] = dst->height - inDstBox[1]; + } + else + { + dstBox[0] = inDstBox[0]; + dstBox[1] = glConfig.vidHeight - inDstBox[1] - inDstBox[3]; + dstBox[2] = inDstBox[0] + inDstBox[2]; + dstBox[3] = glConfig.vidHeight - inDstBox[1]; + } + } + else if (dst) + { + VectorSet4(dstBox, 0, dst->height, dst->width, 0); + } + else + { + VectorSet4(dstBox, 0, glConfig.vidHeight, glConfig.vidWidth, 0); + } + + if (inSrcTexScale) + { + VectorCopy2(inSrcTexScale, srcTexScale); + } + else + { + srcTexScale[0] = srcTexScale[1] = 1.0f; + } + + if (inColor) + { + VectorCopy4(inColor, color); + } + else + { + VectorCopy4(colorWhite, color); + } + + if (!shaderProgram) + { + shaderProgram = &tr.textureColorShader; + } + + FBO_Bind(dst); + + if (glState.currentFBO) + { + width = glState.currentFBO->width; + height = glState.currentFBO->height; + } + else + { + width = glConfig.vidWidth; + height = glConfig.vidHeight; + } + + qglViewport( 0, 0, width, height ); + qglScissor( 0, 0, width, height ); + + Matrix16Ortho(0, width, height, 0, 0, 1, projection); + + GL_Cull(CT_TWO_SIDED); + + GL_BindToTMU(src, TB_COLORMAP); + + VectorSet4(quadVerts[0], dstBox[0], dstBox[1], 0, 1); + VectorSet4(quadVerts[1], dstBox[2], dstBox[1], 0, 1); + VectorSet4(quadVerts[2], dstBox[2], dstBox[3], 0, 1); + VectorSet4(quadVerts[3], dstBox[0], dstBox[3], 0, 1); + + texCoords[0][0] = srcBox[0] / (float)src->width; texCoords[0][1] = 1.0f - srcBox[1] / (float)src->height; + texCoords[1][0] = srcBox[2] / (float)src->width; texCoords[1][1] = 1.0f - srcBox[1] / (float)src->height; + texCoords[2][0] = srcBox[2] / (float)src->width; texCoords[2][1] = 1.0f - srcBox[3] / (float)src->height; + texCoords[3][0] = srcBox[0] / (float)src->width; texCoords[3][1] = 1.0f - srcBox[3] / (float)src->height; + + invTexRes[0] = 1.0f / src->width * srcTexScale[0]; + invTexRes[1] = 1.0f / src->height * srcTexScale[1]; + + GL_State( blend ); + + GLSL_BindProgram(shaderProgram); + + GLSL_SetUniformMatrix4x4(shaderProgram, UNIFORM_MODELVIEWPROJECTIONMATRIX, projection); + GLSL_SetUniformVec4(shaderProgram, UNIFORM_COLOR, color); + GLSL_SetUniformVec2(shaderProgram, UNIFORM_INVTEXRES, invTexRes); + GLSL_SetUniformVec2(shaderProgram, UNIFORM_AUTOEXPOSUREMINMAX, tr.refdef.autoExposureMinMax); + GLSL_SetUniformVec3(shaderProgram, UNIFORM_TONEMINAVGMAXLINEAR, tr.refdef.toneMinAvgMaxLinear); + + RB_InstantQuad2(quadVerts, texCoords); //, color, shaderProgram, invTexRes); + + FBO_Bind(oldFbo); +} + +void FBO_Blit(FBO_t *src, vec4i_t inSrcBox, vec2_t srcTexScale, FBO_t *dst, vec4i_t dstBox, struct shaderProgram_s *shaderProgram, vec4_t color, int blend) +{ + vec4i_t srcBox; + + if (!src) + { + ri.Printf(PRINT_WARNING, "Tried to blit from a NULL FBO!\n"); + return; + } + + // framebuffers are 0 bottom, Y up. + if (inSrcBox) + { + srcBox[0] = inSrcBox[0]; + srcBox[1] = src->height - inSrcBox[1] - inSrcBox[3]; + srcBox[2] = inSrcBox[2]; + srcBox[3] = inSrcBox[3]; + } + else + { + VectorSet4(srcBox, 0, src->height, src->width, -src->height); + } + + FBO_BlitFromTexture(src->colorImage[0], srcBox, srcTexScale, dst, dstBox, shaderProgram, color, blend | GLS_DEPTHTEST_DISABLE); +} + +void FBO_FastBlit(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, int buffers, int filter) +{ + vec4i_t srcBoxFinal, dstBoxFinal; + GLuint srcFb, dstFb; + + // get to a neutral state first + //FBO_Bind(NULL); + + srcFb = src ? src->frameBuffer : 0; + dstFb = dst ? dst->frameBuffer : 0; + + if (!srcBox) + { + if (src) + { + VectorSet4(srcBoxFinal, 0, 0, src->width, src->height); + } + else + { + VectorSet4(srcBoxFinal, 0, 0, glConfig.vidWidth, glConfig.vidHeight); + } + } + else + { + VectorSet4(srcBoxFinal, srcBox[0], srcBox[1], srcBox[0] + srcBox[2], srcBox[1] + srcBox[3]); + } + + if (!dstBox) + { + if (dst) + { + VectorSet4(dstBoxFinal, 0, 0, dst->width, dst->height); + } + else + { + VectorSet4(dstBoxFinal, 0, 0, glConfig.vidWidth, glConfig.vidHeight); + } + } + else + { + VectorSet4(dstBoxFinal, dstBox[0], dstBox[1], dstBox[0] + dstBox[2], dstBox[1] + dstBox[3]); + } + + qglBindFramebuffer(GL_READ_FRAMEBUFFER, srcFb); + qglBindFramebuffer(GL_DRAW_FRAMEBUFFER, dstFb); + + qglBlitFramebuffer(srcBoxFinal[0], srcBoxFinal[1], srcBoxFinal[2], srcBoxFinal[3], + dstBoxFinal[0], dstBoxFinal[1], dstBoxFinal[2], dstBoxFinal[3], + buffers, filter); + + qglBindFramebuffer(GL_FRAMEBUFFER, 0); + glState.currentFBO = NULL; +} + +void FBO_FastBlitIndexed(FBO_t *src, FBO_t *dst, int srcReadBuffer, int dstDrawBuffer, int buffers, int filter) +{ + assert (src != NULL); + assert (dst != NULL); + + qglBindFramebuffer(GL_READ_FRAMEBUFFER, src->frameBuffer); + qglReadBuffer (GL_COLOR_ATTACHMENT0 + srcReadBuffer); + + qglBindFramebuffer(GL_DRAW_FRAMEBUFFER, dst->frameBuffer); + qglDrawBuffer (GL_COLOR_ATTACHMENT0 + dstDrawBuffer); + + qglBlitFramebuffer(0, 0, src->width, src->height, + 0, 0, dst->width, dst->height, + buffers, filter); + + qglReadBuffer (GL_COLOR_ATTACHMENT0); + + glState.currentFBO = dst; + FBO_SetupDrawBuffers(); + + qglBindFramebuffer(GL_FRAMEBUFFER, 0); + glState.currentFBO = NULL; +} diff --git a/codemp/rd-rend2/tr_fbo.h b/codemp/rd-rend2/tr_fbo.h new file mode 100644 index 0000000000..bea9496a18 --- /dev/null +++ b/codemp/rd-rend2/tr_fbo.h @@ -0,0 +1,66 @@ +/* +=========================================================================== +Copyright (C) 2010 James Canete (use.less01@gmail.com) + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_fbo.h + +#ifndef __TR_FBO_H__ +#define __TR_FBO_H__ + +struct image_s; +struct shaderProgram_s; + +typedef struct FBO_s +{ + char name[MAX_QPATH]; + + int index; + + uint32_t frameBuffer; + + uint32_t colorBuffers[16]; + int colorFormat; + struct image_s *colorImage[16]; + + uint32_t depthBuffer; + int depthFormat; + + uint32_t stencilBuffer; + int stencilFormat; + + uint32_t packedDepthStencilBuffer; + int packedDepthStencilFormat; + + int width; + int height; +} FBO_t; + +void FBO_Bind(FBO_t *fbo); +void FBO_Init(void); +void FBO_Shutdown(void); + +void FBO_BlitFromTexture(struct image_s *src, vec4i_t srcBox, vec2_t srcTexScale, FBO_t *dst, vec4i_t dstBox, struct shaderProgram_s *shaderProgram, vec4_t color, int blend); +void FBO_Blit(FBO_t *src, vec4i_t srcBox, vec2_t srcTexScale, FBO_t *dst, vec4i_t dstBox, struct shaderProgram_s *shaderProgram, vec4_t color, int blend); + +void FBO_FastBlit(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, int buffers, int filter); +void FBO_FastBlitIndexed(FBO_t *src, FBO_t *dst, int srcReadBuffer, int dstDrawBuffer, int buffers, int filter); + + +#endif diff --git a/codemp/rd-rend2/tr_flares.cpp b/codemp/rd-rend2/tr_flares.cpp new file mode 100644 index 0000000000..be6d4120e1 --- /dev/null +++ b/codemp/rd-rend2/tr_flares.cpp @@ -0,0 +1,456 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_flares.c + +#include "tr_local.h" + +/* +============================================================================= + +LIGHT FLARES + +A light flare is an effect that takes place inside the eye when bright light +sources are visible. The size of the flare reletive to the screen is nearly +constant, irrespective of distance, but the intensity should be proportional to the +projected area of the light source. + +A surface that has been flagged as having a light flare will calculate the depth +buffer value that its midpoint should have when the surface is added. + +After all opaque surfaces have been rendered, the depth buffer is read back for +each flare in view. If the point has not been obscured by a closer surface, the +flare should be drawn. + +Surfaces that have a repeated texture should never be flagged as flaring, because +there will only be a single flare added at the midpoint of the polygon. + +To prevent abrupt popping, the intensity of the flare is interpolated up and +down as it changes visibility. This involves scene to scene state, unlike almost +all other aspects of the renderer, and is complicated by the fact that a single +frame may have multiple scenes. + +RB_RenderFlares() will be called once per view (twice in a mirrored scene, potentially +up to five or more times in a frame with 3D status bar icons). + +============================================================================= +*/ + + +// flare states maintain visibility over multiple frames for fading +// layers: view, mirror, menu +typedef struct flare_s { + struct flare_s *next; // for active chain + + int addedFrame; + + qboolean inPortal; // true if in a portal view of the scene + int frameSceneNum; + void *surface; + int fogNum; + + int fadeTime; + + qboolean visible; // state of last test + float drawIntensity; // may be non 0 even if !visible due to fading + + int windowX, windowY; + float eyeZ; + + vec3_t origin; + vec3_t color; + vec3_t normal; +} flare_t; + +#define MAX_FLARES 128 + +flare_t r_flareStructs[MAX_FLARES]; +flare_t *r_activeFlares, *r_inactiveFlares; + +/* +================== +R_ClearFlares +================== +*/ +void R_ClearFlares( void ) { + int i; + + Com_Memset( r_flareStructs, 0, sizeof( r_flareStructs ) ); + r_activeFlares = NULL; + r_inactiveFlares = NULL; + + for ( i = 0 ; i < MAX_FLARES ; i++ ) { + r_flareStructs[i].next = r_inactiveFlares; + r_inactiveFlares = &r_flareStructs[i]; + } +} + + +/* +================== +RB_AddFlare + +This is called at surface tesselation time +================== +*/ +void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t normal ) { + int i; + flare_t *f; + vec3_t local; + float d = 1.0f; + vec4_t eye, clip, normalized, window; + + backEnd.pc.c_flareAdds++; + + if(normal && (normal[0] || normal[1] || normal[2])) + { + VectorSubtract( backEnd.viewParms.ori.origin, point, local ); + VectorNormalizeFast(local); + d = DotProduct(local, normal); + } + + // if the point is off the screen, don't bother adding it + // calculate screen coordinates and depth + R_TransformModelToClip( point, backEnd.ori.modelViewMatrix, + backEnd.viewParms.projectionMatrix, eye, clip ); + + // check to see if the point is completely off screen + for ( i = 0 ; i < 3 ; i++ ) { + if ( clip[i] >= clip[3] || clip[i] <= -clip[3] ) { + return; + } + } + + R_TransformClipToWindow( clip, &backEnd.viewParms, normalized, window ); + + if ( window[0] < 0 || window[0] >= backEnd.viewParms.viewportWidth + || window[1] < 0 || window[1] >= backEnd.viewParms.viewportHeight ) { + return; // shouldn't happen, since we check the clip[] above, except for FP rounding + } + + // see if a flare with a matching surface, scene, and view exists + for ( f = r_activeFlares ; f ; f = f->next ) { + if ( f->surface == surface && f->frameSceneNum == backEnd.viewParms.frameSceneNum + && f->inPortal == backEnd.viewParms.isPortal ) { + break; + } + } + + // allocate a new one + if (!f ) { + if ( !r_inactiveFlares ) { + // the list is completely full + return; + } + f = r_inactiveFlares; + r_inactiveFlares = r_inactiveFlares->next; + f->next = r_activeFlares; + r_activeFlares = f; + + f->surface = surface; + f->frameSceneNum = backEnd.viewParms.frameSceneNum; + f->inPortal = backEnd.viewParms.isPortal; + f->addedFrame = -1; + } + + if ( f->addedFrame != backEnd.viewParms.frameCount - 1 ) { + f->visible = qfalse; + f->fadeTime = backEnd.refdef.time - 2000; + } + + f->addedFrame = backEnd.viewParms.frameCount; + f->fogNum = fogNum; + + VectorCopy(point, f->origin); + VectorCopy( color, f->color ); + VectorCopy( normal, f->normal); + + // fade the intensity of the flare down as the + // light surface turns away from the viewer + VectorScale( f->color, d, f->color ); + + // save info needed to test + f->windowX = backEnd.viewParms.viewportX + window[0]; + f->windowY = backEnd.viewParms.viewportY + window[1]; + + f->eyeZ = eye[2]; +} + +/* +================== +RB_AddDlightFlares +================== +*/ +void RB_AddDlightFlares( void ) { + dlight_t *l; + int i, j, k; + fog_t *fog = NULL; + + if ( !r_flares->integer ) { + return; + } + + l = backEnd.refdef.dlights; + + if(tr.world) + fog = tr.world->fogs; + + for (i=0 ; inumfogs ; j++ ) { + fog = &tr.world->fogs[j]; + for ( k = 0 ; k < 3 ; k++ ) { + if ( l->origin[k] < fog->bounds[0][k] || l->origin[k] > fog->bounds[1][k] ) { + break; + } + } + if ( k == 3 ) { + break; + } + } + if ( j == tr.world->numfogs ) { + j = 0; + } + } + else + j = 0; + + RB_AddFlare( (void *)l, j, l->origin, l->color, NULL ); + } +} + +/* +=============================================================================== + +FLARE BACK END + +=============================================================================== +*/ + +/* +================== +RB_TestFlare +================== +*/ +void RB_TestFlare( flare_t *f ) { + float depth; + qboolean visible; + float fade; + float screenZ; + FBO_t *oldFbo; + + backEnd.pc.c_flareTests++; + + // if we're doing multisample rendering, read from the correct FBO + oldFbo = glState.currentFBO; + if (tr.msaaResolveFbo) + { + FBO_Bind(tr.msaaResolveFbo); + } + + // read back the z buffer contents, which is bad + // TODO: Don't use glReadPixels + qglReadPixels( f->windowX, f->windowY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth ); + + // if we're doing multisample rendering, switch to the old FBO + if (tr.msaaResolveFbo) + { + FBO_Bind(oldFbo); + } + + screenZ = backEnd.viewParms.projectionMatrix[14] / + ( ( 2*depth - 1 ) * backEnd.viewParms.projectionMatrix[11] - backEnd.viewParms.projectionMatrix[10] ); + + visible = (qboolean)(( -f->eyeZ - -screenZ ) < 24); + + if ( visible ) { + if ( !f->visible ) { + f->visible = qtrue; + f->fadeTime = backEnd.refdef.time - 1; + } + fade = ( ( backEnd.refdef.time - f->fadeTime ) / 500.0f ); + } else { + // Dont fade out when flare is occluded. Will result in the ability to see + // flares through surfaces on high movement speeds + /*if ( f->visible ) { + f->visible = qfalse; + f->fadeTime = backEnd.refdef.time - 1; + } + fade = 1.0f - ( ( backEnd.refdef.time - f->fadeTime ) / 1000.0f ) * r_flareFade->value;*/ + fade = 0.0f; + } + + if ( fade < 0 ) { + fade = 0; + } + if ( fade > 1 ) { + fade = 1; + } + + f->drawIntensity = fade; +} + + +/* +================== +RB_RenderFlare +================== +*/ +void RB_RenderFlare( flare_t *f ) { + vec4_t color; + + backEnd.pc.c_flareRenders++; + + srfFlare_t *flare = (srfFlare_t *)f->surface; + + backEnd.currentEntity = &tr.worldEntity; + RB_BeginSurface( flare->shader, f->fogNum, 0 ); + + vec3_t dir; + vec3_t left, up; + vec3_t origin; + float d, dist; + + // calculate the xyz locations for the four corners + VectorMA(f->origin, 3, f->normal, origin); + float* snormal = f->normal; + + VectorSubtract(origin, backEnd.viewParms.ori.origin, dir); + dist = VectorNormalize(dir); + + d = -DotProduct(dir, snormal); + if (d < 0) { + d = -d; + } + + // fade the intensity of the flare down as the + // light surface turns away from the viewer + color[0] = d; + color[1] = d; + color[2] = d; + color[3] = 1.0f; //only gets used if the shader has cgen exact_vertex! + + float radius = tess.shader->portalRange ? tess.shader->portalRange : 30; + if (dist < 512.0f) + { + radius = radius * dist / 512.0f; + } + if (radius < 5.0f) + { + radius = 5.0f; + } + VectorScale(backEnd.viewParms.ori.axis[1], radius, left); + VectorScale(backEnd.viewParms.ori.axis[2], radius, up); + if (backEnd.viewParms.isMirror) { + VectorSubtract(vec3_origin, left, left); + } + + RB_AddQuadStamp(origin, left, up, color); + + RB_EndSurface(); +} + +/* +================== +RB_RenderFlares + +Because flares are simulating an occular effect, they should be drawn after +everything (all views) in the entire frame has been drawn. + +Because of the way portals use the depth buffer to mark off areas, the +needed information would be lost after each view, so we are forced to draw +flares after each view. + +The resulting artifact is that flares in mirrors or portals don't dim properly +when occluded by something in the main view, and portal flares that should +extend past the portal edge will be overwritten. +================== +*/ +void RB_RenderFlares (void) { + flare_t *f; + flare_t **prev; + qboolean draw; + + if ( !r_flares->integer ) { + return; + } + + if (backEnd.viewParms.flags & VPF_DEPTHSHADOW) + return; + + // Reset currentEntity to world so that any previously referenced entities + // don't have influence on the rendering of these flares (i.e. RF_ renderer flags). + backEnd.currentEntity = &tr.worldEntity; + backEnd.ori = backEnd.viewParms.world; + +// RB_AddDlightFlares(); + + // perform z buffer readback on each flare in this view + draw = qfalse; + prev = &r_activeFlares; + while ( ( f = *prev ) != NULL ) { + // throw out any flares that weren't added last frame + if ( f->addedFrame < backEnd.viewParms.frameCount - 1 ) { + *prev = f->next; + f->next = r_inactiveFlares; + r_inactiveFlares = f; + continue; + } + + // don't draw any here that aren't from this scene / portal + f->drawIntensity = 0; + if ( f->frameSceneNum == backEnd.viewParms.frameSceneNum + && f->inPortal == backEnd.viewParms.isPortal ) { + RB_TestFlare( f ); + if ( f->drawIntensity ) { + draw = qtrue; + } else { + // this flare has completely faded out, so remove it from the chain + *prev = f->next; + f->next = r_inactiveFlares; + r_inactiveFlares = f; + continue; + } + } + + prev = &f->next; + } + + if ( !draw ) { + return; // none visible + } + + for ( f = r_activeFlares ; f ; f = f->next ) { + if ( f->frameSceneNum == backEnd.viewParms.frameSceneNum + && f->inPortal == backEnd.viewParms.isPortal + && f->drawIntensity ) { + RB_RenderFlare( f ); + } + } +} + + + + + diff --git a/codemp/rd-rend2/tr_ghoul2.cpp b/codemp/rd-rend2/tr_ghoul2.cpp new file mode 100644 index 0000000000..0705bee8d5 --- /dev/null +++ b/codemp/rd-rend2/tr_ghoul2.cpp @@ -0,0 +1,4942 @@ +#include "client/client.h" //FIXME!! EVIL - just include the definitions needed +#include "tr_local.h" +#include "qcommon/matcomp.h" +#include "qcommon/qcommon.h" +#include "ghoul2/G2.h" +#include "ghoul2/g2_local.h" +#ifdef _G2_GORE +#include "G2_gore_r2.h" +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4512) //default assignment operator could not be gened +#endif +#include "qcommon/disablewarnings.h" +#include "tr_cache.h" + +#define LL(x) x=LittleLong(x) + +#ifdef G2_PERFORMANCE_ANALYSIS +#include "qcommon/timing.h" + +timing_c G2PerformanceTimer_RenderSurfaces; +timing_c G2PerformanceTimer_R_AddGHOULSurfaces; +timing_c G2PerformanceTimer_G2_TransformGhoulBones; +timing_c G2PerformanceTimer_G2_ProcessGeneratedSurfaceBolts; +timing_c G2PerformanceTimer_ProcessModelBoltSurfaces; +timing_c G2PerformanceTimer_G2_ConstructGhoulSkeleton; +timing_c G2PerformanceTimer_RB_SurfaceGhoul; +timing_c G2PerformanceTimer_G2_SetupModelPointers; +timing_c G2PerformanceTimer_PreciseFrame; + +int G2PerformanceCounter_G2_TransformGhoulBones = 0; + +int G2Time_RenderSurfaces = 0; +int G2Time_R_AddGHOULSurfaces = 0; +int G2Time_G2_TransformGhoulBones = 0; +int G2Time_G2_ProcessGeneratedSurfaceBolts = 0; +int G2Time_ProcessModelBoltSurfaces = 0; +int G2Time_G2_ConstructGhoulSkeleton = 0; +int G2Time_RB_SurfaceGhoul = 0; +int G2Time_G2_SetupModelPointers = 0; +int G2Time_PreciseFrame = 0; + +void G2Time_ResetTimers(void) +{ + G2Time_RenderSurfaces = 0; + G2Time_R_AddGHOULSurfaces = 0; + G2Time_G2_TransformGhoulBones = 0; + G2Time_G2_ProcessGeneratedSurfaceBolts = 0; + G2Time_ProcessModelBoltSurfaces = 0; + G2Time_G2_ConstructGhoulSkeleton = 0; + G2Time_RB_SurfaceGhoul = 0; + G2Time_G2_SetupModelPointers = 0; + G2Time_PreciseFrame = 0; + G2PerformanceCounter_G2_TransformGhoulBones = 0; +} + +void G2Time_ReportTimers(void) +{ + Com_Printf("\n---------------------------------\nRenderSurfaces: %i\nR_AddGhoulSurfaces: %i\nG2_TransformGhoulBones: %i\nG2_ProcessGeneratedSurfaceBolts: %i\nProcessModelBoltSurfaces: %i\nG2_ConstructGhoulSkeleton: %i\nRB_SurfaceGhoul: %i\nG2_SetupModelPointers: %i\n\nPrecise frame time: %i\nTransformGhoulBones calls: %i\n---------------------------------\n\n", + G2Time_RenderSurfaces, + G2Time_R_AddGHOULSurfaces, + G2Time_G2_TransformGhoulBones, + G2Time_G2_ProcessGeneratedSurfaceBolts, + G2Time_ProcessModelBoltSurfaces, + G2Time_G2_ConstructGhoulSkeleton, + G2Time_RB_SurfaceGhoul, + G2Time_G2_SetupModelPointers, + G2Time_PreciseFrame, + G2PerformanceCounter_G2_TransformGhoulBones + ); +} +#endif + +//rww - RAGDOLL_BEGIN +#ifdef __linux__ +#include +#else +#include +#endif + +//rww - RAGDOLL_END + +static const int MAX_RENDERABLE_SURFACES = 2048; +static CRenderableSurface renderSurfHeap[MAX_RENDERABLE_SURFACES]; +static int currentRenderSurfIndex = 0; + +static CRenderableSurface *AllocGhoul2RenderableSurface() +{ + if ( currentRenderSurfIndex >= MAX_RENDERABLE_SURFACES - 1) + { + ResetGhoul2RenderableSurfaceHeap(); + ri.Printf( PRINT_DEVELOPER, "AllocRenderableSurface: Reached maximum number of Ghoul2 renderable surfaces (%d)\n", MAX_RENDERABLE_SURFACES ); + } + + CRenderableSurface *rs = &renderSurfHeap[currentRenderSurfIndex++]; + + rs->Init(); + + return rs; +} + +void ResetGhoul2RenderableSurfaceHeap() +{ + currentRenderSurfIndex = 0; +} + +bool HackadelicOnClient = false; // means this is a render traversal + +qboolean G2_SetupModelPointers(CGhoul2Info *ghlInfo); +qboolean G2_SetupModelPointers(CGhoul2Info_v &ghoul2); + +extern cvar_t *r_Ghoul2AnimSmooth; +extern cvar_t *r_Ghoul2UnSqashAfterSmooth; + +static const mdxaBone_t identityMatrix = +{ + { + { 0.0f, -1.0f, 0.0f, 0.0f }, + { 1.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f, 0.0f } + } +}; + +// I hate doing this, but this is the simplest way to get this into the routines it needs to be +mdxaBone_t worldMatrix; +mdxaBone_t worldMatrixInv; +#ifdef _G2_GORE +qhandle_t goreShader=-1; +#endif + +// nasty little matrix multiply going on here.. +void Mat3x4_Multiply(mdxaBone_t *out, const mdxaBone_t *in2, const mdxaBone_t *in) +{ + assert(out != nullptr); + assert(in2 != nullptr); + assert(in != nullptr); + + // Let's say we are doing R = N * M + const float n00 = in2->matrix[0][0]; + const float n01 = in2->matrix[0][1]; + const float n02 = in2->matrix[0][2]; + const float n03 = in2->matrix[0][3]; + const float n10 = in2->matrix[1][0]; + const float n11 = in2->matrix[1][1]; + const float n12 = in2->matrix[1][2]; + const float n13 = in2->matrix[1][3]; + const float n20 = in2->matrix[2][0]; + const float n21 = in2->matrix[2][1]; + const float n22 = in2->matrix[2][2]; + const float n23 = in2->matrix[2][3]; + + const float m00 = in->matrix[0][0]; + const float m01 = in->matrix[0][1]; + const float m02 = in->matrix[0][2]; + const float m03 = in->matrix[0][3]; + const float m10 = in->matrix[1][0]; + const float m11 = in->matrix[1][1]; + const float m12 = in->matrix[1][2]; + const float m13 = in->matrix[1][3]; + const float m20 = in->matrix[2][0]; + const float m21 = in->matrix[2][1]; + const float m22 = in->matrix[2][2]; + const float m23 = in->matrix[2][3]; + + // first row of out + out->matrix[0][0] = (n00 * m00) + (n01 * m10) + (n02 * m20); + out->matrix[0][1] = (n00 * m01) + (n01 * m11) + (n02 * m21); + out->matrix[0][2] = (n00 * m02) + (n01 * m12) + (n02 * m22); + out->matrix[0][3] = (n00 * m03) + (n01 * m13) + (n02 * m23) + n03; + + // second row of outf out + out->matrix[1][0] = (n10 * m00) + (n11 * m10) + (n12 * m20); + out->matrix[1][1] = (n10 * m01) + (n11 * m11) + (n12 * m21); + out->matrix[1][2] = (n10 * m02) + (n11 * m12) + (n12 * m22); + out->matrix[1][3] = (n10 * m03) + (n11 * m13) + (n12 * m23) + n13; + + // third row of out out + out->matrix[2][0] = (n20 * m00) + (n21 * m10) + (n22 * m20); + out->matrix[2][1] = (n20 * m01) + (n21 * m11) + (n22 * m21); + out->matrix[2][2] = (n20 * m02) + (n21 * m12) + (n22 * m22); + out->matrix[2][3] = (n20 * m03) + (n21 * m13) + (n22 * m23) + n23; +} + +void Mat3x4_Scale( mdxaBone_t *result, const mdxaBone_t *lhs, const float scale ) +{ + for ( int i = 0; i < 3; ++i ) + { + for ( int j = 0; j < 3; ++j ) + { + result->matrix[i][j] = lhs->matrix[i][j] * scale; + } + } +} + +void Mat3x4_Lerp( + mdxaBone_t *result, + const mdxaBone_t *lhs, + const mdxaBone_t *rhs, + const float t ) +{ + for ( int i = 0; i < 3; ++i ) + { + for ( int j = 0; j < 4; ++j ) + { + result->matrix[i][j] = lhs->matrix[i][j] * t + rhs->matrix[i][j] * (1.0f - t); + } + } +} + +const mdxaBone_t operator +( const mdxaBone_t& lhs, const mdxaBone_t& rhs ) +{ + mdxaBone_t result; + for ( int i = 0; i < 3; ++i ) + { + for ( int j = 0; j < 4; ++j ) + { + result.matrix[i][j] = lhs.matrix[i][j] + rhs.matrix[i][j]; + } + } + return result; +} + +const mdxaBone_t operator -( const mdxaBone_t& lhs, const mdxaBone_t& rhs ) +{ + mdxaBone_t result; + for ( int i = 0; i < 3; ++i ) + { + for ( int j = 0; j < 4; ++j ) + { + result.matrix[i][j] = lhs.matrix[i][j] - rhs.matrix[i][j]; + } + } + return result; +} + +const mdxaBone_t operator *( const mdxaBone_t& lhs, const mdxaBone_t& rhs ) +{ + mdxaBone_t result; + Mat3x4_Multiply(&result, &lhs, &rhs); + return result; +} + +const mdxaBone_t operator *( const mdxaBone_t& lhs, const float scale ) +{ + mdxaBone_t result; + for ( int i = 0; i < 3; ++i ) + { + for ( int j = 0; j < 4; ++j ) + { + result.matrix[i][j] = lhs.matrix[i][j] * scale; + } + } + return result; +} + +const mdxaBone_t operator *( const float scale, const mdxaBone_t& rhs ) +{ + return rhs * scale; +} + + +class CConstructBoneList +{ +public: + int surfaceNum; + int *boneUsedList; + surfaceInfo_v &rootSList; + model_t *currentModel; + boneInfo_v &boneList; + + CConstructBoneList( + int initsurfaceNum, + int *initboneUsedList, + surfaceInfo_v& initrootSList, + model_t *initcurrentModel, + boneInfo_v& initboneList) + : surfaceNum(initsurfaceNum) + , boneUsedList(initboneUsedList) + , rootSList(initrootSList) + , currentModel(initcurrentModel) + , boneList(initboneList) + { + } +}; + +class CTransformBone +{ +public: + int touch; // for minimal recalculation + int touchRender; + mdxaBone_t boneMatrix; //final matrix + int parent; // only set once + + CTransformBone() + : touch(0) + , touchRender(0) + { + } + +}; + +struct SBoneCalc +{ + int newFrame; + int currentFrame; + float backlerp; + float blendFrame; + int blendOldFrame; + bool blendMode; + float blendLerp; +}; + +class CBoneCache; +static void G2_TransformBone( int index, CBoneCache &CB ); + +class CBoneCache +{ + void EvalLow( int index ) + { + assert(index >= 0 && index < (int)mBones.size()); + + if ( mFinalBones[index].touch != mCurrentTouch ) + { + // need to evaluate the bone + assert((mFinalBones[index].parent >= 0 + && mFinalBones[index].parent < (int)mFinalBones.size()) || + (index == 0 && mFinalBones[index].parent == -1)); + + if ( mFinalBones[index].parent >= 0 ) + { + EvalLow(mFinalBones[index].parent); // make sure parent is evaluated + + const SBoneCalc &par = mBones[mFinalBones[index].parent]; + SBoneCalc &bone = mBones[index]; + bone.newFrame = par.newFrame; + bone.currentFrame = par.currentFrame; + bone.backlerp = par.backlerp; + bone.blendFrame = par.blendFrame; + bone.blendOldFrame = par.blendOldFrame; + bone.blendMode = par.blendMode; + bone.blendLerp = par.blendLerp; + } + + G2_TransformBone(index, *this); + + mFinalBones[index].touch = mCurrentTouch; + } + } + + void SmoothLow( int index ) + { + if ( mSmoothBones[index].touch == mLastTouch ) + { + const mdxaBone_t& newM = mFinalBones[index].boneMatrix; + mdxaBone_t& oldM = mSmoothBones[index].boneMatrix; + + oldM = mSmoothFactor * (oldM - newM) + newM; + } + else + { + mSmoothBones[index].boneMatrix = mFinalBones[index].boneMatrix; + } + + const mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); + const mdxaSkel_t *skel = + (mdxaSkel_t *)((byte *)offsets + offsets->offsets[index]); + + mdxaBone_t tempMatrix = + mSmoothBones[index].boneMatrix * skel->BasePoseMat; + const float maxl = VectorLength(&skel->BasePoseMat.matrix[0][0]); + VectorNormalize(&tempMatrix.matrix[0][0]); + VectorNormalize(&tempMatrix.matrix[1][0]); + VectorNormalize(&tempMatrix.matrix[2][0]); + Mat3x4_Scale(&tempMatrix, &tempMatrix, maxl); + + mSmoothBones[index].boneMatrix = tempMatrix * skel->BasePoseMatInv; + mSmoothBones[index].touch = mCurrentTouch; + +#ifdef _DEBUG + for ( int i = 0; i < 3; i++ ) + { + for ( int j = 0; j < 4; j++ ) + { + assert(!Q_isnan(mSmoothBones[index].boneMatrix.matrix[i][j])); + } + } +#endif// _DEBUG + } + +public: + int frameSize; + const mdxaHeader_t *header; + const model_t *mod; + + // these are split for better cpu cache behavior + std::vector mBones; + std::vector mFinalBones; + std::vector mSmoothBones; // for render smoothing + + boneInfo_v *rootBoneList; + mdxaBone_t rootMatrix; + int incomingTime; + + int mCurrentTouch; + int mCurrentTouchRender; + int mLastTouch; + int mLastLastTouch; + + // for render smoothing + bool mSmoothingActive; + bool mUnsquash; + float mSmoothFactor; + + // GPU Data + mat3x4_t boneMatrices[MAX_G2_BONES]; + int uboOffset; + int uboGPUFrame; + + CBoneCache( const model_t *amod, const mdxaHeader_t *aheader ) + : header(aheader) + , mod(amod) + , mBones(header->numBones) + , mFinalBones(header->numBones) + , mSmoothBones(header->numBones) + , mCurrentTouch(3) + , mLastTouch(2) + , mLastLastTouch(1) + , mSmoothingActive(false) + , mUnsquash(false) + , mSmoothFactor(0.0f) + , uboOffset(-1) + , uboGPUFrame(-1) + { + assert(amod); + assert(aheader); + + Com_Memset(boneMatrices, 0, sizeof(boneMatrices)); + + int numBones = header->numBones; + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); + + for ( int i = 0; i < numBones; ++i ) + { + mdxaSkel_t *skel = + (mdxaSkel_t *)((byte *)offsets + offsets->offsets[i]); + mFinalBones[i].parent = skel->parent; + } + } + + SBoneCalc &Root() + { + assert(mBones.size()); + return mBones[0]; + } + + const mdxaBone_t &EvalUnsmooth( int index ) + { + EvalLow(index); + if ( mSmoothingActive && mSmoothBones[index].touch ) + { + return mSmoothBones[index].boneMatrix; + } + + return mFinalBones[index].boneMatrix; + } + + const mdxaBone_t &Eval( int index ) + { + //Hey, this is what sof2 does. Let's try it out. + assert(index >= 0 && index <( int)mBones.size()); + if ( mFinalBones[index].touch != mCurrentTouch ) + { + EvalLow(index); + } + + return mFinalBones[index].boneMatrix; + } + + const mdxaBone_t &EvalRender( int index ) + { + assert(index >= 0 && index < (int)mBones.size()); + if ( mFinalBones[index].touch != mCurrentTouch ) + { + mFinalBones[index].touchRender = mCurrentTouchRender; + EvalLow(index); + } + + if ( mSmoothingActive ) + { + if ( mSmoothBones[index].touch != mCurrentTouch ) + { + SmoothLow(index); + } + + return mSmoothBones[index].boneMatrix; + } + + return mFinalBones[index].boneMatrix; + } + + bool WasRendered( int index ) + { + assert(index >= 0 && index < (int)mBones.size()); + return mFinalBones[index].touchRender == mCurrentTouchRender; + } + + int GetParent( int index ) + { + if ( index == 0 ) + { + return -1; + } + + assert( index > 0 && index < (int)mBones.size()); + return mFinalBones[index].parent; + } +}; + +void RemoveBoneCache(CBoneCache *boneCache) +{ +#ifdef _FULL_G2_LEAK_CHECKING + g_Ghoul2Allocations -= sizeof(*boneCache); +#endif + + delete boneCache; +} + +#ifdef _G2_LISTEN_SERVER_OPT +void CopyBoneCache(CBoneCache *to, CBoneCache *from) +{ + memcpy(to, from, sizeof(CBoneCache)); +} +#endif + +const mdxaBone_t &EvalBoneCache(int index,CBoneCache *boneCache) +{ + assert(boneCache); + return boneCache->Eval(index); +} + +// rww - RAGDOLL_BEGIN +const mdxaHeader_t *G2_GetModA(CGhoul2Info &ghoul2) +{ + if (!ghoul2.mBoneCache) + { + return 0; + } + + CBoneCache &boneCache=*ghoul2.mBoneCache; + return boneCache.header; +} + +int G2_GetBoneDependents(CGhoul2Info &ghoul2,int boneNum,int *tempDependents,int maxDep) +{ + // fixme, these should be precomputed + if (!ghoul2.mBoneCache || !maxDep) + { + return 0; + } + + CBoneCache &boneCache = *ghoul2.mBoneCache; + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = + (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); + + int numDependencies = 0; + for (int i = 0; i < skel->numChildren; i++) + { + if (!maxDep) + { + return i; // number added + } + + *tempDependents = skel->children[i]; + assert(*tempDependents > 0 && *tempDependents < boneCache.header->numBones); + maxDep--; + tempDependents++; + numDependencies++; + } + + for (int i = 0; i < skel->numChildren; i++) + { + int num = G2_GetBoneDependents(ghoul2, skel->children[i], tempDependents, maxDep); + tempDependents += num; + numDependencies += num; + maxDep -= num; + assert(maxDep >= 0); + if (!maxDep) + { + break; + } + } + + return numDependencies; +} + +bool G2_WasBoneRendered(CGhoul2Info &ghoul2,int boneNum) +{ + if (!ghoul2.mBoneCache) + { + return false; + } + + CBoneCache &boneCache = *ghoul2.mBoneCache; + return boneCache.WasRendered(boneNum); +} + +void G2_GetBoneBasepose( + CGhoul2Info &ghoul2, + int boneNum, + mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv) +{ + if (!ghoul2.mBoneCache) + { + // yikes + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); + return; + } + + assert(ghoul2.mBoneCache); + CBoneCache &boneCache = *ghoul2.mBoneCache; + assert(boneCache.mod); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); + + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); + + retBasepose = &skel->BasePoseMat; + retBaseposeInv = &skel->BasePoseMatInv; +} + +char *G2_GetBoneNameFromSkel(CGhoul2Info &ghoul2, int boneNum) +{ + if (!ghoul2.mBoneCache) + { + return NULL; + } + + CBoneCache &boneCache = *ghoul2.mBoneCache; + assert(boneCache.mod); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); + + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); + + return skel->name; +} + +void G2_RagGetBoneBasePoseMatrixLow( + CGhoul2Info &ghoul2, + int boneNum, + mdxaBone_t &boneMatrix, + mdxaBone_t &retMatrix, + vec3_t scale) +{ + assert(ghoul2.mBoneCache); + CBoneCache &boneCache = *ghoul2.mBoneCache; + assert(boneCache.mod); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); + + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); + + Mat3x4_Multiply(&retMatrix, &boneMatrix, &skel->BasePoseMat); + + if (scale[0]) + { + retMatrix.matrix[0][3] *= scale[0]; + } + + if (scale[1]) + { + retMatrix.matrix[1][3] *= scale[1]; + } + + if (scale[2]) + { + retMatrix.matrix[2][3] *= scale[2]; + } + + VectorNormalize((float *)&retMatrix.matrix[0]); + VectorNormalize((float *)&retMatrix.matrix[1]); + VectorNormalize((float *)&retMatrix.matrix[2]); +} + +void G2_GetBoneMatrixLow( + CGhoul2Info &ghoul2, + int boneNum, + const vec3_t scale, + mdxaBone_t &retMatrix, + mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv) +{ + if ( !ghoul2.mBoneCache ) + { + retMatrix = identityMatrix; + // yikes + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); + return; + } + + mdxaBone_t bolt; + assert(ghoul2.mBoneCache); + CBoneCache &boneCache = *ghoul2.mBoneCache; + assert(boneCache.mod); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); + + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); + + Mat3x4_Multiply( + &bolt, + &boneCache.Eval(boneNum), + &skel->BasePoseMat); + retBasepose = &skel->BasePoseMat; + retBaseposeInv = &skel->BasePoseMatInv; + + if (scale[0]) + { + bolt.matrix[0][3] *= scale[0]; + } + + if (scale[1]) + { + bolt.matrix[1][3] *= scale[1]; + } + + if (scale[2]) + { + bolt.matrix[2][3] *= scale[2]; + } + + VectorNormalize((float *)&bolt.matrix[0]); + VectorNormalize((float *)&bolt.matrix[1]); + VectorNormalize((float *)&bolt.matrix[2]); + + Mat3x4_Multiply(&retMatrix, &worldMatrix, &bolt); + +#ifdef _DEBUG + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 4; j++) + { + assert(!Q_isnan(retMatrix.matrix[i][j])); + } + } +#endif // _DEBUG +} + +int G2_GetParentBoneMatrixLow( + CGhoul2Info &ghoul2, + int boneNum, + const vec3_t scale, + mdxaBone_t &retMatrix, + mdxaBone_t *&retBasepose, + mdxaBone_t *&retBaseposeInv) +{ + int parent = -1; + if ( ghoul2.mBoneCache ) + { + CBoneCache &boneCache = *ghoul2.mBoneCache; + assert(boneCache.mod); + assert(boneNum >= 0 && boneNum < boneCache.header->numBones); + + parent = boneCache.GetParent(boneNum); + if ( parent < 0 || parent >= boneCache.header->numBones ) + { + parent = -1; + retMatrix = identityMatrix; + + // yikes + retBasepose = const_cast(&identityMatrix); + retBaseposeInv = const_cast(&identityMatrix); + } + else + { + G2_GetBoneMatrixLow( + ghoul2, + parent, + scale, + retMatrix, + retBasepose, + retBaseposeInv); + } + } + return parent; +} +//rww - RAGDOLL_END + +class CRenderSurface +{ +public: + int surfaceNum; + surfaceInfo_v &rootSList; + shader_t *cust_shader; + int fogNum; + qboolean personalModel; + CBoneCache *boneCache; + int renderfx; + skin_t *skin; + model_t *currentModel; + int lod; + boltInfo_v &boltList; +#ifdef _G2_GORE + shader_t *gore_shader; + CGoreSet *gore_set; +#endif + + CRenderSurface( + int initsurfaceNum, + surfaceInfo_v &initrootSList, + shader_t *initcust_shader, + int initfogNum, + qboolean initpersonalModel, + CBoneCache *initboneCache, + int initrenderfx, + skin_t *initskin, + model_t *initcurrentModel, + int initlod, +#ifdef _G2_GORE + boltInfo_v &initboltList, + shader_t *initgore_shader, + CGoreSet *initgore_set +#else + boltInfo_v &initboltList +#endif + ) + : surfaceNum(initsurfaceNum) + , rootSList(initrootSList) + , cust_shader(initcust_shader) + , fogNum(initfogNum) + , personalModel(initpersonalModel) + , boneCache(initboneCache) + , renderfx(initrenderfx) + , skin(initskin) + , currentModel(initcurrentModel) + , lod(initlod) + , boltList(initboltList) +#ifdef _G2_GORE + , gore_shader(initgore_shader) + , gore_set(initgore_set) +#endif + { + } +}; + +/* + +All bones should be an identity orientation to display the mesh exactly +as it is specified. + +For all other frames, the bones represent the transformation from the +orientation of the bone in the base frame to the orientation in this +frame. + +*/ + + +/* +============= +R_ACullModel +============= +*/ +static int R_GCullModel( trRefEntity_t *ent ) { + + // scale the radius if need be + float largestScale = ent->e.modelScale[0]; + + if (ent->e.modelScale[1] > largestScale) + { + largestScale = ent->e.modelScale[1]; + } + if (ent->e.modelScale[2] > largestScale) + { + largestScale = ent->e.modelScale[2]; + } + if (!largestScale) + { + largestScale = 1; + } + + // cull bounding sphere + switch ( R_CullLocalPointAndRadius( vec3_origin, ent->e.radius * largestScale) ) + { + case CULL_OUT: + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; + + case CULL_IN: + tr.pc.c_sphere_cull_md3_in++; + return CULL_IN; + + case CULL_CLIP: + tr.pc.c_sphere_cull_md3_clip++; + return CULL_IN; + } + return CULL_IN; +} + + +/* +================= +R_AComputeFogNum + +================= +*/ +static int R_GComputeFogNum( trRefEntity_t *ent ) { + + int i, j; + fog_t *fog; + + if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + return 0; + } + + for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + fog = &tr.world->fogs[i]; + for ( j = 0 ; j < 3 ; j++ ) { + if ( ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j] ) { + break; + } + if ( ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j] ) { + break; + } + } + if ( j == 3 ) { + return i; + } + } + + return 0; +} + +// work out lod for this entity. +static int G2_ComputeLOD( trRefEntity_t *ent, const model_t *currentModel, int lodBias ) +{ + float flod, lodscale; + float projectedRadius; + int lod; + + if ( currentModel->numLods < 2 || ent->e.renderfx & RF_NOLOD ) + { // model has only 1 LOD level, skip computations and bias + return(0); + } + + if ( r_lodbias->integer > lodBias ) + { + lodBias = r_lodbias->integer; + } + + // scale the radius if need be + float largestScale = ent->e.modelScale[0]; + + if (ent->e.modelScale[1] > largestScale) + { + largestScale = ent->e.modelScale[1]; + } + if (ent->e.modelScale[2] > largestScale) + { + largestScale = ent->e.modelScale[2]; + } + if (!largestScale) + { + largestScale = 1; + } + + projectedRadius = ProjectRadius( 0.75*largestScale*ent->e.radius, ent->e.origin ); + + // we reduce the radius to make the LOD match other model types which use + // the actual bound box size + if ( projectedRadius != 0 ) + { + lodscale = (r_lodscale->value+r_autolodscalevalue->value); + if ( lodscale > 20 ) + { + lodscale = 20; + } + else if ( lodscale < 0 ) + { + lodscale = 0; + } + flod = 1.0f - projectedRadius * lodscale; + } + else + { + // object intersects near view plane, e.g. view weapon + flod = 0; + } + flod *= currentModel->numLods; + lod = Q_ftol( flod ); + + if ( lod < 0 ) + { + lod = 0; + } + else if ( lod >= currentModel->numLods ) + { + lod = currentModel->numLods - 1; + } + + + lod += lodBias; + + if ( lod >= currentModel->numLods ) + lod = currentModel->numLods - 1; + if ( lod < 0 ) + lod = 0; + + return lod; +} + +//====================================================================== +// +// Bone Manipulation code + + +void G2_CreateQuaterion(mdxaBone_t *mat, vec4_t quat) +{ + // this is revised for the 3x4 matrix we use in G2. + float t = 1 + mat->matrix[0][0] + mat->matrix[1][1] + mat->matrix[2][2]; + float s; + + // If the trace of the matrix is greater than zero, then + // perform an "instant" calculation. + // Important note wrt. rouning errors: + // Test if ( T > 0.00000001 ) to avoid large distortions! + if (t > 0.00000001) + { + s = sqrt(t) * 2; + quat[0] = ( mat->matrix[1][2] - mat->matrix[2][1] ) / s; + quat[1] = ( mat->matrix[2][0] - mat->matrix[0][2] ) / s; + quat[2] = ( mat->matrix[0][1] - mat->matrix[1][0] ) / s; + quat[3] = 0.25 * s; + } + else + { + // If the trace of the matrix is equal to zero then identify + // which major diagonal element has the greatest value. + + // Depending on this, calculate the following: + if ( mat->matrix[0][0] > mat->matrix[1][1] && mat->matrix[0][0] > mat->matrix[2][2] ) { + // Column 0: + s = sqrt( 1.0 + mat->matrix[0][0] - mat->matrix[1][1] - mat->matrix[2][2])* 2; + quat[0] = 0.25 * s; + quat[1] = (mat->matrix[0][1] + mat->matrix[1][0] ) / s; + quat[2] = (mat->matrix[2][0] + mat->matrix[0][2] ) / s; + quat[3] = (mat->matrix[1][2] - mat->matrix[2][1] ) / s; + + } else if ( mat->matrix[1][1] > mat->matrix[2][2] ) { + // Column 1: + s = sqrt( 1.0 + mat->matrix[1][1] - mat->matrix[0][0] - mat->matrix[2][2] ) * 2; + quat[0] = (mat->matrix[0][1] + mat->matrix[1][0] ) / s; + quat[1] = 0.25 * s; + quat[2] = (mat->matrix[1][2] + mat->matrix[2][1] ) / s; + quat[3] = (mat->matrix[2][0] - mat->matrix[0][2] ) / s; + + } else { + // Column 2: + s = sqrt( 1.0 + mat->matrix[2][2] - mat->matrix[0][0] - mat->matrix[1][1] ) * 2; + quat[0] = (mat->matrix[2][0]+ mat->matrix[0][2] ) / s; + quat[1] = (mat->matrix[1][2] + mat->matrix[2][1] ) / s; + quat[2] = 0.25 * s; + quat[3] = (mat->matrix[0][1] - mat->matrix[1][0] ) / s; + } + } +} + +void G2_CreateMatrixFromQuaterion(mdxaBone_t *mat, vec4_t quat) +{ + const float xx = quat[0] * quat[0]; + const float xy = quat[0] * quat[1]; + const float xz = quat[0] * quat[2]; + const float xw = quat[0] * quat[3]; + + const float yy = quat[1] * quat[1]; + const float yz = quat[1] * quat[2]; + const float yw = quat[1] * quat[3]; + + const float zz = quat[2] * quat[2]; + const float zw = quat[2] * quat[3]; + + mat->matrix[0][0] = 1 - 2 * ( yy + zz ); + mat->matrix[1][0] = 2 * ( xy - zw ); + mat->matrix[2][0] = 2 * ( xz + yw ); + + mat->matrix[0][1] = 2 * ( xy + zw ); + mat->matrix[1][1] = 1 - 2 * ( xx + zz ); + mat->matrix[2][1] = 2 * ( yz - xw ); + + mat->matrix[0][2] = 2 * ( xz - yw ); + mat->matrix[1][2] = 2 * ( yz + xw ); + mat->matrix[2][2] = 1 - 2 * ( xx + yy ); + + mat->matrix[0][3] = mat->matrix[1][3] = mat->matrix[2][3] = 0; +} + +static int G2_GetBonePoolIndex( const mdxaHeader_t *pMDXAHeader, int iFrame, int iBone) +{ + const int iOffsetToIndex = (iFrame * pMDXAHeader->numBones * 3) + (iBone * 3); + mdxaIndex_t *pIndex = (mdxaIndex_t *)((byte*)pMDXAHeader + pMDXAHeader->ofsFrames + iOffsetToIndex); + + return (pIndex->iIndex[2] << 16) + (pIndex->iIndex[1] << 8) + (pIndex->iIndex[0]); +} + +/*static inline*/ void UnCompressBone( + float mat[3][4], + int iBoneIndex, + const mdxaHeader_t *pMDXAHeader, + int iFrame) +{ + mdxaCompQuatBone_t *pCompBonePool = + (mdxaCompQuatBone_t *)((byte *)pMDXAHeader + pMDXAHeader->ofsCompBonePool); + MC_UnCompressQuat( + mat, + pCompBonePool[G2_GetBonePoolIndex(pMDXAHeader, iFrame, iBoneIndex)].Comp); +} + +#define DEBUG_G2_TIMING (0) +#define DEBUG_G2_TIMING_RENDER_ONLY (1) + +void G2_TimingModel( + boneInfo_t &bone, + int currentTime, + int numFramesInFile, + int ¤tFrame, + int &newFrame, + float& lerp) +{ + assert(bone.startFrame >= 0); + assert(bone.startFrame <= numFramesInFile); + assert(bone.endFrame >= 0); + assert(bone.endFrame <= numFramesInFile); + + // yes - add in animation speed to current frame + const float animSpeed = bone.animSpeed; + float time; + if (bone.pauseTime) + { + time = (bone.pauseTime - bone.startTime) / 50.0f; + } + else + { + time = (currentTime - bone.startTime) / 50.0f; + } + + time = Q_max(0.0f, time); + float newLerpFrame = bone.startFrame + (time * animSpeed); + + const int numFramesInAnim = bone.endFrame - bone.startFrame; + const float endFrame = (float)bone.endFrame; + + // we are supposed to be animating right? + if ( numFramesInAnim != 0 ) + { + // did we run off the end? + if ( (animSpeed > 0.0f && newLerpFrame > (endFrame - 1)) || + (animSpeed < 0.0f && newLerpFrame < (endFrame + 1)) ) + { + // yep - decide what to do + if ( bone.flags & BONE_ANIM_OVERRIDE_LOOP ) + { + // get our new animation frame back within the bounds of the animation set + if ( animSpeed < 0.0f ) + { + // we don't use this case, or so I am told + // if we do, let me know, I need to insure the mod works + + // should we be creating a virtual frame? + if ( (newLerpFrame < (endFrame + 1)) && (newLerpFrame >= endFrame) ) + { + // now figure out what we are lerping between delta is + // the fraction between this frame and the next, since + // the new anim is always at a .0f; + lerp = endFrame + 1 - newLerpFrame; + + // frames are easy to calculate + currentFrame = endFrame; + newFrame = bone.startFrame; + } + else + { + if ( newLerpFrame <= (endFrame + 1) ) + { + newLerpFrame = + endFrame + fmod(newLerpFrame - endFrame, numFramesInAnim) - + numFramesInAnim; + } + + // now figure out what we are lerping between delta is + // the fraction between this frame and the next, since + // the new anim is always at a .0f; + lerp = ceil(newLerpFrame) - newLerpFrame; + + // frames are easy to calculate + currentFrame = ceil(newLerpFrame); + + // should we be creating a virtual frame? + if ( currentFrame <= (endFrame + 1) ) + { + newFrame = bone.startFrame; + } + else + { + newFrame = currentFrame - 1; + } + } + } + else + { + // should we be creating a virtual frame? + if ( (newLerpFrame > (endFrame - 1)) && (newLerpFrame < endFrame)) + { + // now figure out what we are lerping between delta is + // the fraction between this frame and the next, since + // the new anim is always at a .0f; + lerp = newLerpFrame - (int)newLerpFrame; + + // frames are easy to calculate + currentFrame = (int)newLerpFrame; + newFrame = bone.startFrame; + } + else + { + if ( newLerpFrame >= endFrame ) + { + newLerpFrame = + endFrame + fmod(newLerpFrame - endFrame, numFramesInAnim) - + numFramesInAnim; + } + + // now figure out what we are lerping between delta is + // the fraction between this frame and the next, since + // the new anim is always at a .0f; + lerp = newLerpFrame - (int)newLerpFrame; + + // frames are easy to calculate + currentFrame = (int)newLerpFrame; + + // should we be creating a virtual frame? + if ( newLerpFrame >= (endFrame - 1) ) + { + newFrame = bone.startFrame; + } + else + { + newFrame = currentFrame + 1; + } + } + } + } + else + { + if ( ((bone.flags & BONE_ANIM_OVERRIDE_FREEZE) == BONE_ANIM_OVERRIDE_FREEZE) ) + { + // if we are supposed to reset the default anim, then do so + if ( animSpeed > 0.0f ) + { + currentFrame = bone.endFrame - 1; + } + else + { + currentFrame = bone.endFrame + 1; + } + + newFrame = currentFrame; + lerp = 0.0f; + } + else + { + bone.flags &= ~BONE_ANIM_TOTAL; + } + } + } + else + { + if (animSpeed> 0.0) + { + // frames are easy to calculate + currentFrame = (int)newLerpFrame; + + // figure out the difference between the two frames - we have + // to decide what frame and what percentage of that frame we + // want to display + lerp = (newLerpFrame - currentFrame); + + assert(currentFrame>=0&¤tFrame= (int)endFrame) + { + // we only want to lerp with the first frame of the anim if + // we are looping + if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) + { + newFrame = bone.startFrame; + } + else + { + // if we intend to end this anim or freeze after this, then + // just keep on the last frame + newFrame = bone.endFrame-1; + } + } + } + else + { + lerp = (ceil(newLerpFrame)-newLerpFrame); + + // frames are easy to calculate + currentFrame = ceil(newLerpFrame); + if (currentFrame>bone.startFrame) + { + currentFrame=bone.startFrame; + newFrame = currentFrame; + lerp = 0.0f; + } + else + { + newFrame = currentFrame-1; + + // are we now on the end frame? + if (newFrame < endFrame+1) + { + // we only want to lerp with the first frame of the + // anim if we are looping + if (bone.flags & BONE_ANIM_OVERRIDE_LOOP) + { + newFrame = bone.startFrame; + } + // if we intend to end this anim or freeze after this, + // then just keep on the last frame + else + { + newFrame = bone.endFrame+1; + } + } + } + } + } + } + else + { + if ( animSpeed < 0.0 ) + { + currentFrame = bone.endFrame + 1; + } + else + { + currentFrame = bone.endFrame - 1; + } + + currentFrame = Q_max(0, currentFrame); + newFrame = currentFrame; + + lerp = 0.0f; + } + + assert(currentFrame >= 0 && currentFrame < numFramesInFile); + assert(newFrame >= 0 && newFrame < numFramesInFile); + assert(lerp >= 0.0f && lerp <= 1.0f); +} + +#ifdef _RAG_PRINT_TEST +void G2_RagPrintMatrix(mdxaBone_t *mat); +#endif +// basically construct a seperate skeleton with full hierarchy to store a matrix +// off which will give us the desired settling position given the frame in the skeleton +// that should be used -rww +int G2_Add_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName); +int G2_Find_Bone(const model_t *mod, boneInfo_v &blist, const char *boneName); + +void G2_RagGetAnimMatrix( + CGhoul2Info &ghoul2, + const int boneNum, + mdxaBone_t &matrix, + const int frame) +{ + mdxaBone_t animMatrix; + mdxaSkel_t *skel; + mdxaSkel_t *pskel; + mdxaSkelOffsets_t *offsets; + int parent; + int bListIndex; + int parentBlistIndex; +#ifdef _RAG_PRINT_TEST + bool actuallySet = false; +#endif + + assert(ghoul2.mBoneCache); + assert(ghoul2.animModel); + + offsets = (mdxaSkelOffsets_t *)((byte *)ghoul2.mBoneCache->header + sizeof(mdxaHeader_t)); + skel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boneNum]); + + //find/add the bone in the list + if (!skel->name[0]) + { + bListIndex = -1; + } + else + { + bListIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, skel->name); + if (bListIndex == -1) + { +#ifdef _RAG_PRINT_TEST + Com_Printf("Attempting to add %s\n", skel->name); +#endif + bListIndex = G2_Add_Bone(ghoul2.animModel, ghoul2.mBlist, skel->name); + } + } + + assert(bListIndex != -1); + + boneInfo_t &bone = ghoul2.mBlist[bListIndex]; + + if (bone.hasAnimFrameMatrix == frame) + { //already calculated so just grab it + matrix = bone.animFrameMatrix; + return; + } + + //get the base matrix for the specified frame + UnCompressBone(animMatrix.matrix, boneNum, ghoul2.mBoneCache->header, frame); + + parent = skel->parent; + if (boneNum > 0 && parent > -1) + { + // recursively call to assure all parent matrices are set up + G2_RagGetAnimMatrix(ghoul2, parent, matrix, frame); + + // assign the new skel ptr for our parent + pskel = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[parent]); + + // taking bone matrix for the skeleton frame and parent's + // animFrameMatrix into account, determine our final animFrameMatrix + if (!pskel->name[0]) + { + parentBlistIndex = -1; + } + else + { + parentBlistIndex = G2_Find_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); + if (parentBlistIndex == -1) + { + parentBlistIndex = G2_Add_Bone(ghoul2.animModel, ghoul2.mBlist, pskel->name); + } + } + + assert(parentBlistIndex != -1); + + boneInfo_t &pbone = ghoul2.mBlist[parentBlistIndex]; + + // this should have been calc'd in the recursive call + assert(pbone.hasAnimFrameMatrix == frame); + + Mat3x4_Multiply(&bone.animFrameMatrix, &pbone.animFrameMatrix, &animMatrix); + +#ifdef _RAG_PRINT_TEST + if (parentBlistIndex != -1 && bListIndex != -1) + { + actuallySet = true; + } + else + { + Com_Printf("BAD LIST INDEX: %s, %s [%i]\n", skel->name, pskel->name, parent); + } +#endif + } + else + { + // root + Mat3x4_Multiply(&bone.animFrameMatrix, &ghoul2.mBoneCache->rootMatrix, &animMatrix); +#ifdef _RAG_PRINT_TEST + if (bListIndex != -1) + { + actuallySet = true; + } + else + { + Com_Printf("BAD LIST INDEX: %s\n", skel->name); + } +#endif + } + + //never need to figure it out again + bone.hasAnimFrameMatrix = frame; + +#ifdef _RAG_PRINT_TEST + if (!actuallySet) + { + Com_Printf("SET FAILURE\n"); + G2_RagPrintMatrix(&bone.animFrameMatrix); + } +#endif + + matrix = bone.animFrameMatrix; +} + +static void G2_TransformBone( int child, CBoneCache& BC ) +{ + SBoneCalc &TB = BC.mBones[child]; + mdxaBone_t currentBone; + boneInfo_v& boneList = *BC.rootBoneList; + int angleOverride = 0; + +#if DEBUG_G2_TIMING + bool printTiming=false; +#endif + // should this bone be overridden by a bone in the bone list? + int boneListIndex = G2_Find_Bone_In_List(boneList, child); + if (boneListIndex != -1) + { + // we found a bone in the list - we need to override something here. + boneInfo_t& bone = boneList[boneListIndex]; + int boneFlags = bone.flags; + + // do we override the rotational angles? + if ( boneFlags & BONE_ANGLES_TOTAL ) + { + angleOverride = boneFlags & BONE_ANGLES_TOTAL; + } + + // set blending stuff if we need to + if ( boneFlags & BONE_ANIM_BLEND ) + { + const float blendTime = BC.incomingTime - bone.blendStart; + + // only set up the blend anim if we actually have some blend time + // left on this bone anim - otherwise we might corrupt some blend + // higher up the hiearchy + if ( blendTime >= 0.0f && blendTime < bone.blendTime ) + { + TB.blendFrame = bone.blendFrame; + TB.blendOldFrame = bone.blendLerpFrame; + TB.blendLerp = (blendTime / bone.blendTime); + TB.blendMode = true; + } + else + { + TB.blendMode = false; + } + } + else if ( boneFlags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE) ) + { + // turn off blending if we are just doing a straing animation + // override + TB.blendMode = false; + } + + // should this animation be overridden by an animation in the bone + // list? + if (boneFlags & (BONE_ANIM_OVERRIDE_LOOP | BONE_ANIM_OVERRIDE)) + { + G2_TimingModel( + bone, + BC.incomingTime, + BC.header->numFrames, + TB.currentFrame, + TB.newFrame, + TB.backlerp); + } + +#if DEBUG_G2_TIMING + printTiming=true; +#endif + } + + // figure out where the location of the bone animation data is + if ( !(TB.newFrame >= 0 && TB.newFrame < BC.header->numFrames) ) + { + TB.newFrame = 0; + } + + if ( !(TB.currentFrame >= 0 && TB.currentFrame < BC.header->numFrames) ) + { + TB.currentFrame = 0; + } + + // figure out where the location of the blended animation data is + if ( TB.blendFrame < 0.0 || TB.blendFrame >= (BC.header->numFrames + 1) ) + { + TB.blendFrame = 0.0; + } + + if ( !(TB.blendOldFrame >= 0 && TB.blendOldFrame < BC.header->numFrames) ) + { + TB.blendOldFrame = 0; + } + +#if DEBUG_G2_TIMING + +#if DEBUG_G2_TIMING_RENDER_ONLY + if (!HackadelicOnClient) + { + printTiming = false; + } +#endif + + if (printTiming) + { + char mess[1000]; + if (TB.blendMode) + { + sprintf( + mess, + "b %2d %5d %4d %4d %4d %4d %f %f\n", + boneListIndex, + BC.incomingTime, + (int)TB.newFrame, + (int)TB.currentFrame, + (int)TB.blendFrame, + (int)TB.blendOldFrame, + TB.backlerp, + TB.blendLerp); + } + else + { + sprintf( + mess, + "a %2d %5d %4d %4d %f\n", + boneListIndex, + BC.incomingTime, + TB.newFrame, + TB.currentFrame, + TB.backlerp); + } + + Com_OPrintf("%s",mess); + + const boneInfo_t &bone=boneList[boneListIndex]; + if (bone.flags&BONE_ANIM_BLEND) + { + sprintf( + mess, + " bfb[%2d] %5d %5d (%5d-%5d) %4.2f %4x bt(%5d-%5d) %7.2f %5d\n", + boneListIndex, + BC.incomingTime, + bone.startTime, + bone.startFrame, + bone.endFrame, + bone.animSpeed, + bone.flags, + bone.blendStart, + bone.blendStart+bone.blendTime, + bone.blendFrame, + bone.blendLerpFrame); + } + else + { + sprintf(mess," bfa[%2d] %5d %5d (%5d-%5d) %4.2f %4x\n", + boneListIndex, + BC.incomingTime, + bone.startTime, + bone.startFrame, + bone.endFrame, + bone.animSpeed, + bone.flags); + } + } +#endif + + assert(child >=0 && child < BC.header->numBones); + + // decide where the transformed bone is going + + // lerp this bone - use the temp space on the ref entity to put the bone + // transforms into + if ( !TB.backlerp ) + { + UnCompressBone(currentBone.matrix, child, BC.header, TB.currentFrame); + } + else + { + mdxaBone_t newFrameBone; + mdxaBone_t currentFrameBone; + UnCompressBone(newFrameBone.matrix, child, BC.header, TB.newFrame); + UnCompressBone(currentFrameBone.matrix, child, BC.header, TB.currentFrame); + Mat3x4_Lerp(¤tBone, &newFrameBone, ¤tFrameBone, TB.backlerp); + } + + // are we blending with another frame of anim? + // blend in the other frame if we need to + if ( TB.blendMode ) + { + mdxaBone_t blendFrameBone; + mdxaBone_t blendOldFrameBone; + UnCompressBone(blendFrameBone.matrix, child, BC.header, TB.blendFrame); + UnCompressBone(blendOldFrameBone.matrix, child, BC.header, TB.blendOldFrame); + + const float backlerp = TB.blendFrame - (int)TB.blendFrame; + mdxaBone_t lerpFrameBone; + Mat3x4_Lerp(&lerpFrameBone, &blendFrameBone, &blendOldFrameBone, backlerp); + Mat3x4_Lerp(¤tBone, ¤tBone, &lerpFrameBone, TB.blendLerp); + } + + if ( !child ) + { + // now multiply by the root matrix, so we can offset this model + // should we need to + BC.mFinalBones[child].boneMatrix = BC.rootMatrix * currentBone; + } + + // figure out where the bone hirearchy info is + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)BC.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = + (mdxaSkel_t *)((byte *)offsets + offsets->offsets[child]); + + int parent = BC.mFinalBones[child].parent; + assert((parent == -1 && child == 0) || (parent >= 0 && parent < (int)BC.mBones.size())); + + if ( angleOverride & BONE_ANGLES_REPLACE ) + { + const bool isRag = + ((angleOverride & (BONE_ANGLES_RAGDOLL | BONE_ANGLES_IK)) != 0); + + mdxaBone_t& bone = BC.mFinalBones[child].boneMatrix; + const boneInfo_t& boneOverride = boneList[boneListIndex]; + + // give us the matrix the animation thinks we should have, so we + // can get the correct X&Y coors + const mdxaBone_t firstPass = BC.mFinalBones[parent].boneMatrix * currentBone; + if (isRag) + { + // this is crazy, we are gonna drive the animation to ID while we + // are doing post mults to compensate. + mdxaBone_t temp = firstPass * skel->BasePoseMat; + const float matrixScale = VectorLength((float*)&temp); + mdxaBone_t toMatrix = + { + { + { 1.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 1.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 1.0f, 0.0f } + } + }; + toMatrix.matrix[0][0] = matrixScale; + toMatrix.matrix[1][1] = matrixScale; + toMatrix.matrix[2][2] = matrixScale; + toMatrix.matrix[0][3] = temp.matrix[0][3]; + toMatrix.matrix[1][3] = temp.matrix[1][3]; + toMatrix.matrix[2][3] = temp.matrix[2][3]; + + temp = toMatrix * skel->BasePoseMatInv; + + float blendTime = BC.incomingTime - boneOverride.boneBlendStart; + float blendLerp = (blendTime / boneOverride.boneBlendTime); + if (blendLerp > 0.0f) + { + // has started + if (blendLerp > 1.0f) + { + bone = temp; + } + else + { + Mat3x4_Lerp(&bone, &temp, ¤tBone, blendLerp); + } + } + } + else + { + // are we attempting to blend with the base animation? and still + // within blend time? + if (boneOverride.boneBlendTime > 0.0f && + (((boneOverride.boneBlendStart + boneOverride.boneBlendTime) < BC.incomingTime))) + { + // ok, we are supposed to be blending. Work out lerp + const float blendTime = BC.incomingTime - boneOverride.boneBlendStart; + const float blendLerp = (blendTime / boneOverride.boneBlendTime); + + if (blendLerp <= 1) + { + if (blendLerp < 0) + { + assert(0); + } + + // now work out the matrix we want to get *to* - firstPass + // is where we are coming *from* + mdxaBone_t temp = firstPass * skel->BasePoseMat; + const float matrixScale = VectorLength((const float*)&temp); + + const mdxaBone_t& m = + HackadelicOnClient ? boneOverride.newMatrix : boneOverride.matrix; + + mdxaBone_t newMatrixTemp; + Mat3x4_Scale(&newMatrixTemp, &m, matrixScale); + newMatrixTemp.matrix[0][3] = temp.matrix[0][3]; + newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; + newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; + + temp = newMatrixTemp * skel->BasePoseMatInv; + Mat3x4_Lerp(&bone, &temp, &firstPass, blendLerp); + } + else + { + bone = firstPass; + } + } + else + { + // no, so just override it directly + const mdxaBone_t temp = firstPass * skel->BasePoseMat; + const float matrixScale = VectorLength((const float*)&temp); + + const mdxaBone_t& m = + HackadelicOnClient ? boneOverride.newMatrix : boneOverride.matrix; + + mdxaBone_t newMatrixTemp; + Mat3x4_Scale(&newMatrixTemp, &m, matrixScale); + newMatrixTemp.matrix[0][3] = temp.matrix[0][3]; + newMatrixTemp.matrix[1][3] = temp.matrix[1][3]; + newMatrixTemp.matrix[2][3] = temp.matrix[2][3]; + + bone = newMatrixTemp * skel->BasePoseMatInv; + } + } + } + else if (angleOverride & BONE_ANGLES_PREMULT) + { + const mdxaBone_t& boneA = + child ? BC.mFinalBones[parent].boneMatrix : BC.rootMatrix; + + const mdxaBone_t& boneB = + HackadelicOnClient ? + boneList[boneListIndex].newMatrix : + boneList[boneListIndex].matrix; + + BC.mFinalBones[child].boneMatrix = boneA * boneB; + + if ((angleOverride & (BONE_ANGLES_RAGDOLL | BONE_ANGLES_IK)) == 0) + { + BC.mFinalBones[child].boneMatrix = + BC.mFinalBones[child].boneMatrix * currentBone; + } + } + else if (child) + { + // now transform the matrix by it's parent, asumming we have a parent, and + // we aren't overriding the angles absolutely + BC.mFinalBones[child].boneMatrix = + BC.mFinalBones[parent].boneMatrix * currentBone; + } + + // now multiply our resulting bone by an override matrix should we need to + if (angleOverride & BONE_ANGLES_POSTMULT) + { + const mdxaBone_t& postMultMatrix = + HackadelicOnClient ? + boneList[boneListIndex].newMatrix : + boneList[boneListIndex].matrix; + + BC.mFinalBones[child].boneMatrix = + BC.mFinalBones[child].boneMatrix * postMultMatrix; + } +} + +void G2_SetUpBolts( + mdxaHeader_t *header, + CGhoul2Info &ghoul2, + mdxaBone_v &bonePtr, + boltInfo_v &boltList) +{ + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)header + sizeof(mdxaHeader_t)); + + for ( size_t i = 0; i < boltList.size(); ++i ) + { + if ( boltList[i].boneNumber == -1 ) + { + continue; + } + + // figure out where the bone hirearchy info is + mdxaSkel_t *skel = + (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boltList[i].boneNumber]); + boltList[i].position = bonePtr[boltList[i].boneNumber].second * skel->BasePoseMat; + } +} + +#define GHOUL2_RAG_STARTED 0x0010 +//rwwFIXMEFIXME: Move this into the stupid header or something. + +static void G2_TransformGhoulBones( + boneInfo_v &rootBoneList, + mdxaBone_t &rootMatrix, + CGhoul2Info &ghoul2, + int time, + bool smooth = true) +{ +#ifdef G2_PERFORMANCE_ANALYSIS + G2PerformanceTimer_G2_TransformGhoulBones.Start(); + G2PerformanceCounter_G2_TransformGhoulBones++; +#endif + + model_t *currentModel = (model_t *)ghoul2.currentModel; + mdxaHeader_t *aHeader = (mdxaHeader_t *)ghoul2.aHeader; + + assert(ghoul2.aHeader); + assert(ghoul2.currentModel); + assert(ghoul2.currentModel->data.glm && ghoul2.currentModel->data.glm->header); + if (!aHeader->numBones) + { + assert(0); // this would be strange + return; + } + if (!ghoul2.mBoneCache) + { + ghoul2.mBoneCache=new CBoneCache(currentModel,aHeader); + +#ifdef _FULL_G2_LEAK_CHECKING + g_Ghoul2Allocations += sizeof(*ghoul2.mBoneCache); +#endif + } + ghoul2.mBoneCache->mod=currentModel; + ghoul2.mBoneCache->header=aHeader; + assert(ghoul2.mBoneCache->mBones.size()==(unsigned)aHeader->numBones); + + ghoul2.mBoneCache->mSmoothingActive=false; + ghoul2.mBoneCache->mUnsquash=false; + + // master smoothing control + if (HackadelicOnClient && smooth && !ri.Cvar_VariableIntegerValue("dedicated")) + { + ghoul2.mBoneCache->mLastTouch = ghoul2.mBoneCache->mLastLastTouch; + + // master smoothing control + float val = r_Ghoul2AnimSmooth->value; + if (val > 0.0f && val < 1.0f) + { + if (ghoul2.mFlags & GHOUL2_CRAZY_SMOOTH) + { + val = 0.9f; + } + else if (ghoul2.mFlags & GHOUL2_RAG_STARTED) + { + for (size_t k = 0; k < rootBoneList.size(); k++) + { + boneInfo_t &bone = rootBoneList[k]; + if (bone.flags & BONE_ANGLES_RAGDOLL) + { + if (bone.firstCollisionTime && + bone.firstCollisionTime > (time - 250) && + bone.firstCollisionTime < time) + { + val = 0.9f; + } + else if (bone.airTime > time) + { + val = 0.2f; + } + else + { + val = 0.8f; + } + break; + } + } + } + + ghoul2.mBoneCache->mSmoothFactor = val; // meaningless formula + ghoul2.mBoneCache->mSmoothingActive = true; + + if (r_Ghoul2UnSqashAfterSmooth->integer) + { + ghoul2.mBoneCache->mUnsquash = true; + } + } + } + else + { + ghoul2.mBoneCache->mSmoothFactor = 1.0f; + } + + ghoul2.mBoneCache->mCurrentTouch++; + + if (HackadelicOnClient) + { + ghoul2.mBoneCache->mLastLastTouch = ghoul2.mBoneCache->mCurrentTouch; + ghoul2.mBoneCache->mCurrentTouchRender = ghoul2.mBoneCache->mCurrentTouch; + } + else + { + ghoul2.mBoneCache->mCurrentTouchRender = 0; + } + + ghoul2.mBoneCache->frameSize = 0; + + ghoul2.mBoneCache->rootBoneList = &rootBoneList; + ghoul2.mBoneCache->rootMatrix = rootMatrix; + ghoul2.mBoneCache->incomingTime = time; + + SBoneCalc &TB = ghoul2.mBoneCache->Root(); + TB.newFrame = 0; + TB.currentFrame = 0; + TB.backlerp = 0.0f; + TB.blendFrame = 0; + TB.blendOldFrame = 0; + TB.blendMode = false; + TB.blendLerp = 0; + +#ifdef G2_PERFORMANCE_ANALYSIS + G2Time_G2_TransformGhoulBones += G2PerformanceTimer_G2_TransformGhoulBones.End(); +#endif +} + + +#define MDX_TAG_ORIGIN 2 + +//====================================================================== +// +// Surface Manipulation code + + +// We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place +void G2_ProcessSurfaceBolt( + mdxaBone_v &bonePtr, + mdxmSurface_t *surface, + int boltNum, + boltInfo_v &boltList, + surfaceInfo_t *surfInfo, + model_t *mod) +{ + mdxmVertex_t *v, *vert0, *vert1, *vert2; + vec3_t axes[3], sides[3]; + float pTri[3][3], d; + int j, k; + + // now there are two types of tag surface - model ones and procedural + // generated types - lets decide which one we have here. + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) + { + int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; + int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; + + // find original surface our original poly was in. + mdxmSurface_t *originalSurf = + (mdxmSurface_t *)G2_FindSurface((void *)mod, surfNumber, surfInfo->genLod); + mdxmTriangle_t *originalTriangleIndexes = + (mdxmTriangle_t *)((byte *)originalSurf + originalSurf->ofsTriangles); + + // get the original polys indexes + int index0 = originalTriangleIndexes[polyNumber].indexes[0]; + int index1 = originalTriangleIndexes[polyNumber].indexes[1]; + int index2 = originalTriangleIndexes[polyNumber].indexes[2]; + + // decide where the original verts are + + vert0 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert0 += index0; + + vert1 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert1 += index1; + + vert2 = (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + vert2 += index2; + + // clear out the triangle verts to be + VectorClear(pTri[0]); + VectorClear(pTri[1]); + VectorClear(pTri[2]); + + int *piBoneRefs = (int *)((byte *)originalSurf + originalSurf->ofsBoneReferences); + + // now go and transform just the points we need from the surface that + // was hit originally + // w = vert0->weights; + float fTotalWeight = 0.0f; + int iNumWeights = G2_GetVertWeights(vert0); + for (k = 0; k < iNumWeights; k++) + { + int iBoneIndex = G2_GetVertBoneIndex(vert0, k); + float fBoneWeight = G2_GetVertBoneWeight(vert0, k, fTotalWeight, iNumWeights); + + pTri[0][0] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[0][1] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[0][2] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert0->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + } + + fTotalWeight = 0.0f; + iNumWeights = G2_GetVertWeights(vert1); + for (k = 0; k < iNumWeights; k++) + { + int iBoneIndex = G2_GetVertBoneIndex(vert1, k); + float fBoneWeight = G2_GetVertBoneWeight(vert1, k, fTotalWeight, iNumWeights); + + pTri[1][0] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[1][1] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[1][2] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert1->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + } + + fTotalWeight = 0.0f; + iNumWeights = G2_GetVertWeights(vert2); + for (k = 0; k < iNumWeights; k++) + { + int iBoneIndex = G2_GetVertBoneIndex(vert2, k); + float fBoneWeight = G2_GetVertBoneWeight(vert2, k, fTotalWeight, iNumWeights); + + pTri[2][0] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[2][1] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[2][2] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], vert2->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + } + + vec3_t normal; + vec3_t up; + vec3_t right; + vec3_t vec0, vec1; + // work out baryCentricK + float baryCentricK = 1.0 - (surfInfo->genBarycentricI + surfInfo->genBarycentricJ); + + // now we have the model transformed into model space, now generate an origin. + boltList[boltNum].position.matrix[0][3] = (pTri[0][0] * surfInfo->genBarycentricI) + + (pTri[1][0] * surfInfo->genBarycentricJ) + + (pTri[2][0] * baryCentricK); + boltList[boltNum].position.matrix[1][3] = (pTri[0][1] * surfInfo->genBarycentricI) + + (pTri[1][1] * surfInfo->genBarycentricJ) + + (pTri[2][1] * baryCentricK); + boltList[boltNum].position.matrix[2][3] = (pTri[0][2] * surfInfo->genBarycentricI) + + (pTri[1][2] * surfInfo->genBarycentricJ) + + (pTri[2][2] * baryCentricK); + + // generate a normal to this new triangle + VectorSubtract(pTri[0], pTri[1], vec0); + VectorSubtract(pTri[2], pTri[1], vec1); + + CrossProduct(vec0, vec1, normal); + VectorNormalize(normal); + + // forward vector + boltList[boltNum].position.matrix[0][0] = normal[0]; + boltList[boltNum].position.matrix[1][0] = normal[1]; + boltList[boltNum].position.matrix[2][0] = normal[2]; + + // up will be towards point 0 of the original triangle. + // so lets work it out. Vector is hit point - point 0 + up[0] = boltList[boltNum].position.matrix[0][3] - pTri[0][0]; + up[1] = boltList[boltNum].position.matrix[1][3] - pTri[0][1]; + up[2] = boltList[boltNum].position.matrix[2][3] - pTri[0][2]; + + // normalise it + VectorNormalize(up); + + // that's the up vector + boltList[boltNum].position.matrix[0][1] = up[0]; + boltList[boltNum].position.matrix[1][1] = up[1]; + boltList[boltNum].position.matrix[2][1] = up[2]; + + // right is always straight + + CrossProduct(normal, up, right); + // that's the up vector + boltList[boltNum].position.matrix[0][2] = right[0]; + boltList[boltNum].position.matrix[1][2] = right[1]; + boltList[boltNum].position.matrix[2][2] = right[2]; + } + // no, we are looking at a normal model tag + else + { + int *piBoneRefs = (int *)((byte *)surface + surface->ofsBoneReferences); + + // whip through and actually transform each vertex + v = (mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + for (j = 0; j < 3; j++) + { + // mdxmWeight_t *w; + + VectorClear(pTri[j]); + // w = v->weights; + + const int iNumWeights = G2_GetVertWeights(v); + float fTotalWeight = 0.0f; + for (k = 0; k < iNumWeights; k++) + { + int iBoneIndex = G2_GetVertBoneIndex(v, k); + float fBoneWeight = G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); + + // bone = bonePtr + piBoneRefs[w->boneIndex]; + pTri[j][0] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[0][3]); + pTri[j][1] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[1][3]); + pTri[j][2] += + fBoneWeight * + (DotProduct(bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2], v->vertCoords) + + bonePtr[piBoneRefs[iBoneIndex]].second.matrix[2][3]); + } + + v++; + } + + // clear out used arrays + memset(axes, 0, sizeof(axes)); + memset(sides, 0, sizeof(sides)); + + // work out actual sides of the tag triangle + for (j = 0; j < 3; j++) + { + sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; + sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; + sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; + } + + // do math trig to work out what the matrix will be from this + // triangle's translated position + VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); + VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); + + // project shortest side so that it is exactly 90 degrees to the longer + // side + d = DotProduct(axes[0], axes[1]); + VectorMA(axes[0], -d, axes[1], axes[0]); + VectorNormalize2(axes[0], axes[0]); + + CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); + VectorNormalize2(axes[2], axes[2]); + + // set up location in world space of the origin point in out going + // matrix + boltList[boltNum].position.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; + boltList[boltNum].position.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; + boltList[boltNum].position.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; + + // copy axis to matrix - do some magic to orient minus Y to positive X + // and so on so bolt on stuff is oriented correctly + boltList[boltNum].position.matrix[0][0] = axes[1][0]; + boltList[boltNum].position.matrix[0][1] = axes[0][0]; + boltList[boltNum].position.matrix[0][2] = -axes[2][0]; + + boltList[boltNum].position.matrix[1][0] = axes[1][1]; + boltList[boltNum].position.matrix[1][1] = axes[0][1]; + boltList[boltNum].position.matrix[1][2] = -axes[2][1]; + + boltList[boltNum].position.matrix[2][0] = axes[1][2]; + boltList[boltNum].position.matrix[2][1] = axes[0][2]; + boltList[boltNum].position.matrix[2][2] = -axes[2][2]; + } +} + +// now go through all the generated surfaces that aren't included in the model +// surface hierarchy and create the correct bolt info for them +void G2_ProcessGeneratedSurfaceBolts(CGhoul2Info &ghoul2, mdxaBone_v &bonePtr, model_t *mod_t) +{ +#ifdef G2_PERFORMANCE_ANALYSIS + G2PerformanceTimer_G2_ProcessGeneratedSurfaceBolts.Start(); +#endif + + // look through the surfaces off the end of the pre-defined model surfaces + for ( size_t i = 0, numSurfaces = ghoul2.mSlist.size(); i < numSurfaces; i++ ) + { + // only look for bolts if we are actually a generated surface, and not + // just an overriden one + if (ghoul2.mSlist[i].offFlags & G2SURFACEFLAG_GENERATED) + { + // well alrighty then. Lets see if there is a bolt that is + // attempting to use it + int boltNum = G2_Find_Bolt_Surface_Num( + ghoul2.mBltlist, i, G2SURFACEFLAG_GENERATED); + + if (boltNum != -1) + { + G2_ProcessSurfaceBolt( + bonePtr, + nullptr, + boltNum, + ghoul2.mBltlist, + &ghoul2.mSlist[i], mod_t); + } + } + } + +#ifdef G2_PERFORMANCE_ANALYSIS + G2Time_G2_ProcessGeneratedSurfaceBolts += + G2PerformanceTimer_G2_ProcessGeneratedSurfaceBolts.End(); +#endif +} + +void RenderSurfaces( CRenderSurface &RS, const trRefEntity_t *ent, int entityNum ) +{ +#ifdef G2_PERFORMANCE_ANALYSIS + G2PerformanceTimer_RenderSurfaces.Start(); +#endif + + int i; + const shader_t *shader = 0; + int offFlags = 0; +#ifdef _G2_GORE + bool drawGore = true; +#endif + + assert(RS.currentModel); + assert(RS.currentModel->data.glm && RS.currentModel->data.glm->header); + // back track and get the surfinfo struct for this surface + mdxmSurface_t *surface = + (mdxmSurface_t *)G2_FindSurface(RS.currentModel, RS.surfaceNum, RS.lod); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *) + ((byte *)RS.currentModel->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *) + ((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + + // see if we have an override surface in the surface list + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(RS.surfaceNum, RS.rootSList); + + // really, we should use the default flags for this surface unless it's been overriden + offFlags = surfInfo->flags; + + // set the off flags if we have some + if (surfOverride) + { + offFlags = surfOverride->offFlags; + } + + // if this surface is not off, add it to the shader render list + if (!offFlags) + { + if ( RS.cust_shader ) + { + shader = RS.cust_shader; + } + else if ( RS.skin ) + { + int j; + + // match the surface name to something in the skin file + shader = tr.defaultShader; + for ( j = 0 ; j < RS.skin->numSurfaces ; j++ ) + { + // the names have both been lowercased + if ( !strcmp( RS.skin->surfaces[j]->name, surfInfo->name ) ) + { + shader = (shader_t*)RS.skin->surfaces[j]->shader; + break; + } + } + } + else + { + shader = R_GetShaderByHandle( surfInfo->shaderIndex ); + } + + // Get dlightBits and Cubemap + float radius; + // scale the radius if needed + float largestScale = MAX(ent->e.modelScale[0], MAX(ent->e.modelScale[1], ent->e.modelScale[2])); + radius = ent->e.radius * largestScale; + int dlightBits = R_DLightsForPoint(ent->e.origin, radius); + int cubemapIndex = R_CubemapForPoint(ent->e.origin); + + // don't add third_person objects if not viewing through a portal + if ( !RS.personalModel ) + { + // set the surface info to point at the where the transformed bone + // list is going to be for when the surface gets rendered out + CRenderableSurface *newSurf = AllocGhoul2RenderableSurface(); + newSurf->vboMesh = &RS.currentModel->data.glm->vboModels[RS.lod].vboMeshes[RS.surfaceNum]; + assert (newSurf->vboMesh != NULL && RS.surfaceNum == surface->thisSurfaceIndex); + newSurf->surfaceData = surface; + newSurf->boneCache = RS.boneCache; + newSurf->dlightBits = dlightBits; + + // render shadows? + if (r_shadows->integer == 2 + && (RS.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) + && shader->sort == SS_OPAQUE) + newSurf->genShadows = qtrue; + + R_AddDrawSurf( + (surfaceType_t *)newSurf, + entityNum, + (shader_t *)shader, + RS.fogNum, + qfalse, + R_IsPostRenderEntity(ent), + cubemapIndex); + +#ifdef _G2_GORE + if ( RS.gore_set && drawGore ) + { + int curTime = G2API_GetTime(tr.refdef.time); + + auto range = RS.gore_set->mGoreRecords.equal_range(RS.surfaceNum); + CRenderableSurface *last = newSurf; + for ( auto k = range.first; k != range.second; /* blank */ ) + { + auto kcur = k; + k++; + + R2GoreTextureCoordinates *tex = FindR2GoreRecord(kcur->second.mGoreTag); + if (!tex || // it is gone, lets get rid of it + (kcur->second.mDeleteTime && + curTime >= kcur->second.mDeleteTime)) // out of time + { + RS.gore_set->mGoreRecords.erase(kcur); + } + else if (tex->tex[RS.lod]) + { + CRenderableSurface *newSurf2 = AllocGhoul2RenderableSurface(); + *newSurf2 = *newSurf; + newSurf2->goreChain = 0; + newSurf2->alternateTex = tex->tex[RS.lod]; + newSurf2->scale = 1.0f; + newSurf2->fade = 1.0f; + newSurf2->impactTime = 1.0f; // done with + int magicFactor42 = 500; // ms, impact time + if (curTime > kcur->second.mGoreGrowStartTime && + curTime < (kcur->second.mGoreGrowStartTime + magicFactor42) ) + { + newSurf2->impactTime = + float(curTime - kcur->second.mGoreGrowStartTime) / + float(magicFactor42); // linear + } +#ifdef REND2_SP_MAYBE + if (curTime < kcur->second.mGoreGrowEndTime) + { + newSurf2->scale = Q_max( + 1.0f, + 1.0f / + ((curTime - kcur->second.mGoreGrowStartTime) * + kcur->second.mGoreGrowFactor + + kcur->second.mGoreGrowOffset)); + } +#endif + shader_t *gshader; + if (kcur->second.shader) + { + gshader = R_GetShaderByHandle(kcur->second.shader); + } + else + { + gshader = R_GetShaderByHandle(goreShader); + } +#ifdef REND2_SP_MAYBE + // Set fade on surf. + // Only if we have a fade time set, and let us fade on + // rgb if we want -rww + if (kcur->second.mDeleteTime && kcur->second.mFadeTime) + { + if ( (kcur->second.mDeleteTime - curTime) < kcur->second.mFadeTime ) + { + newSurf2->fade = + (float)(kcur->second.mDeleteTime - curTime) / + kcur->second.mFadeTime; + if (kcur->second.mFadeRGB) + { + // RGB fades are scaled from 2.0f to 3.0f + // (simply to differentiate) + newSurf2->fade = Q_max(2.01f, newSurf2->fade + 2.0f); + } + } + } +#endif + last->goreChain = newSurf2; + last = newSurf2; + R_AddDrawSurf( + (surfaceType_t *)newSurf2, + entityNum, + gshader, + RS.fogNum, + qfalse, + R_IsPostRenderEntity(ent), + cubemapIndex); + } + } + } +#endif + } + + // projection shadows work fine with personal models + if (r_shadows->integer == 3 + && RS.fogNum == 0 + && (RS.renderfx & (RF_NOSHADOW | RF_DEPTHHACK)) + && shader->sort == SS_OPAQUE) { + + CRenderableSurface *newSurf = AllocGhoul2RenderableSurface(); + newSurf->vboMesh = &RS.currentModel->data.glm->vboModels[RS.lod].vboMeshes[RS.surfaceNum]; + assert(newSurf->vboMesh != NULL && RS.surfaceNum == surface->thisSurfaceIndex); + newSurf->surfaceData = surface; + newSurf->boneCache = RS.boneCache; + R_AddDrawSurf((surfaceType_t *)newSurf, entityNum, tr.projectionShadowShader, 0, qfalse, qfalse, 0); + } + } + + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) + { + return; + } + + // now recursively call for the children + for (i=0; i< surfInfo->numChildren; i++) + { + RS.surfaceNum = surfInfo->childIndexes[i]; + RenderSurfaces(RS, ent, entityNum); + } + +#ifdef G2_PERFORMANCE_ANALYSIS + G2Time_RenderSurfaces += G2PerformanceTimer_RenderSurfaces.End(); +#endif +} + +// Go through the model and deal with just the surfaces that are tagged as bolt +// on points - this is for the server side skeleton construction +void ProcessModelBoltSurfaces( + int surfaceNum, + surfaceInfo_v &rootSList, + mdxaBone_v &bonePtr, + model_t *currentModel, + int lod, + boltInfo_v &boltList) +{ +#ifdef G2_PERFORMANCE_ANALYSIS + G2PerformanceTimer_ProcessModelBoltSurfaces.Start(); +#endif + int i; + int offFlags = 0; + + // back track and get the surfinfo struct for this surface + mdxmSurface_t *surface = (mdxmSurface_t *) + G2_FindSurface((void *)currentModel, surfaceNum, 0); + mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *) + ((byte *)currentModel->data.glm->header + sizeof(mdxmHeader_t)); + mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *) + ((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + + // see if we have an override surface in the surface list + surfaceInfo_t *surfOverride = G2_FindOverrideSurface(surfaceNum, rootSList); + + // really, we should use the default flags for this surface unless it's been overriden + offFlags = surfInfo->flags; + + // set the off flags if we have some + if (surfOverride) + { + offFlags = surfOverride->offFlags; + } + + // is this surface considered a bolt surface? + if (surfInfo->flags & G2SURFACEFLAG_ISBOLT) + { + // well alrighty then. Lets see if there is a bolt that is attempting to use it + int boltNum = G2_Find_Bolt_Surface_Num(boltList, surfaceNum, 0); + // yes - ok, processing time. + if (boltNum != -1) + { + G2_ProcessSurfaceBolt(bonePtr, surface, boltNum, boltList, surfOverride, currentModel); + } + } + + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) + { + return; + } + + // now recursively call for the children + for (i=0; i< surfInfo->numChildren; i++) + { + ProcessModelBoltSurfaces( + surfInfo->childIndexes[i], rootSList, bonePtr, currentModel, lod, boltList); + } + +#ifdef G2_PERFORMANCE_ANALYSIS + G2Time_ProcessModelBoltSurfaces += G2PerformanceTimer_ProcessModelBoltSurfaces.End(); +#endif +} + + +// build the used bone list so when doing bone transforms we can determine if we need to do it or not +void G2_ConstructUsedBoneList(CConstructBoneList &CBL) +{ + int i, j; + int offFlags = 0; + mdxmHeader_t *mdxm = CBL.currentModel->data.glm->header; + + // back track and get the surfinfo struct for this surface + const mdxmSurface_t *surface = (mdxmSurface_t *)G2_FindSurface((void *)CBL.currentModel, CBL.surfaceNum, 0); + const mdxmHierarchyOffsets_t *surfIndexes = (mdxmHierarchyOffsets_t *)((byte *)mdxm + sizeof(mdxmHeader_t)); + const mdxmSurfHierarchy_t *surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfIndexes + surfIndexes->offsets[surface->thisSurfaceIndex]); + const model_t *mod_a = R_GetModelByHandle(mdxm->animIndex); + mdxaHeader_t *mdxa = mod_a->data.gla; + const mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + const mdxaSkel_t *skel, *childSkel; + + // see if we have an override surface in the surface list + const surfaceInfo_t *surfOverride = G2_FindOverrideSurface(CBL.surfaceNum, CBL.rootSList); + + // really, we should use the default flags for this surface unless it's been overriden + offFlags = surfInfo->flags; + + // set the off flags if we have some + if (surfOverride) + { + offFlags = surfOverride->offFlags; + } + + // if this surface is not off, add it to the shader render list + if (!(offFlags & G2SURFACEFLAG_OFF)) + { + int *bonesReferenced = (int *)((byte*)surface + surface->ofsBoneReferences); + // now whip through the bones this surface uses + for (i=0; inumBoneReferences;i++) + { + int iBoneIndex = bonesReferenced[i]; + CBL.boneUsedList[iBoneIndex] = 1; + + // now go and check all the descendant bones attached to this bone and see if any have the always flag on them. If so, activate them + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iBoneIndex]); + + // for every child bone... + for (j=0; j< skel->numChildren; j++) + { + // get the skel data struct for each child bone of the referenced bone + childSkel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[skel->children[j]]); + + // does it have the always on flag on? + if (childSkel->flags & G2BONEFLAG_ALWAYSXFORM) + { + // yes, make sure it's in the list of bones to be transformed. + CBL.boneUsedList[skel->children[j]] = 1; + } + } + + // now we need to ensure that the parents of this bone are actually active... + // + int iParentBone = skel->parent; + while (iParentBone != -1) + { + if (CBL.boneUsedList[iParentBone]) // no need to go higher + break; + CBL.boneUsedList[iParentBone] = 1; + skel = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[iParentBone]); + iParentBone = skel->parent; + } + } + } + else + // if we are turning off all descendants, then stop this recursion now + if (offFlags & G2SURFACEFLAG_NODESCENDANTS) + { + return; + } + + // now recursively call for the children + for (i=0; i< surfInfo->numChildren; i++) + { + CBL.surfaceNum = surfInfo->childIndexes[i]; + G2_ConstructUsedBoneList(CBL); + } +} + + +// sort all the ghoul models in this list so if they go in reference order. +// This will ensure the bolt on's are attached to the right place on the +// previous model, since it ensures the model being attached to is built and +// rendered first. +// NOTE!! This assumes at least one model will NOT have a parent. If it does - +// we are screwed +static void G2_Sort_Models( + CGhoul2Info_v& ghoul2, + int *const modelList, + int modelListCapacity, + int *const modelCount ) +{ + *modelCount = 0; + + if ( modelListCapacity < ghoul2.size() ) + { + return; + } + + // first walk all the possible ghoul2 models, and stuff the out array with + // those with no parents + for ( int i = 0, numModels = ghoul2.size(); i < numModels; ++i ) + { + CGhoul2Info& g2Info = ghoul2[i]; + + // have a ghoul model here? + if ( g2Info.mModelindex == -1 ) + { + continue; + } + + if ( !g2Info.mValid ) + { + continue; + } + + // are we attached to anything? + if ( g2Info.mModelBoltLink == -1 ) + { + // no, insert us first + modelList[(*modelCount)++] = i; + } + } + + int startPoint = 0; + int endPoint = *modelCount; + + // now, using that list of parentless models, walk the descendant tree for + // each of them, inserting the descendents in the list + while ( startPoint != endPoint ) + { + for ( int i = 0, numModels = ghoul2.size(); i < numModels; ++i ) + { + CGhoul2Info& g2Info = ghoul2[i]; + + // have a ghoul model here? + if ( g2Info.mModelindex == -1 ) + { + continue; + } + + if ( !g2Info.mValid ) + { + continue; + } + + // what does this model think it's attached to? + if ( g2Info.mModelBoltLink == -1 ) + { + continue; + } + + int boltTo = (g2Info.mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + + // is it any of the models we just added to the list? + for ( int j = startPoint; j < endPoint; ++j ) + { + // is this my parent model? + if ( boltTo == modelList[j] ) + { + // yes, insert into list and exit now + modelList[(*modelCount)++] = i; + break; + } + } + } + + // update start and end points + startPoint = endPoint; + endPoint = *modelCount; + } +} + +void *G2_FindSurface_BC(const model_s *mod, int index, int lod) +{ + mdxmHeader_t *mdxm = mod->data.glm->header; + assert(mod); + assert(mdxm); + + // point at first lod list + byte *current = (byte*)((intptr_t)mdxm + (intptr_t)mdxm->ofsLODs); + int i; + + //walk the lods + assert(lod>=0&&lodnumLODs); + for (i=0; iofsEnd; + } + + // avoid the lod pointer data structure + current += sizeof(mdxmLOD_t); + + mdxmLODSurfOffset_t *indexes = (mdxmLODSurfOffset_t *)current; + // we are now looking at the offset array + assert(index>=0&&indexnumSurfaces); + current += indexes->offsets[index]; + + return (void *)current; +} + +// We've come across a surface that's designated as a bolt surface, process it and put it in the appropriate bolt place +void G2_ProcessSurfaceBolt2( + CBoneCache &boneCache, + const mdxmSurface_t *surface, + int boltNum, + boltInfo_v &boltList, + const surfaceInfo_t *surfInfo, + const model_t *mod, + mdxaBone_t &retMatrix) +{ + float pTri[3][3]; + + // now there are two types of tag surface - model ones and procedural + // generated types - lets decide which one we have here. + if (surfInfo && surfInfo->offFlags == G2SURFACEFLAG_GENERATED) + { + const int surfNumber = surfInfo->genPolySurfaceIndex & 0x0ffff; + const int polyNumber = (surfInfo->genPolySurfaceIndex >> 16) & 0x0ffff; + + // find original surface our original poly was in. + const mdxmSurface_t *originalSurf = + (mdxmSurface_t *)G2_FindSurface_BC(mod, surfNumber, surfInfo->genLod); + const mdxmTriangle_t *originalTriangleIndexes = + (mdxmTriangle_t *)((byte*)originalSurf + originalSurf->ofsTriangles); + + // get the original polys indexes + const int index0 = originalTriangleIndexes[polyNumber].indexes[0]; + const int index1 = originalTriangleIndexes[polyNumber].indexes[1]; + const int index2 = originalTriangleIndexes[polyNumber].indexes[2]; + + // decide where the original verts are + const mdxmVertex_t *surfVerts = + (mdxmVertex_t *)((byte *)originalSurf + originalSurf->ofsVerts); + const mdxmVertex_t *verts[3] = { + surfVerts + index0, + surfVerts + index1, + surfVerts + index2 + }; + + // clear out the triangle verts to be + VectorClear(pTri[0]); + VectorClear(pTri[1]); + VectorClear(pTri[2]); + const int *piBoneReferences = + (int *)((byte*)originalSurf + originalSurf->ofsBoneReferences); + + for ( int i = 0; i < 3; ++i ) + { + // now go and transform just the points we need from the surface that + // was hit originally + const int iNumWeights = G2_GetVertWeights(verts[i]); + float fTotalWeight = 0.0f; + for ( int k = 0 ; k < iNumWeights ; k++ ) + { + const int iBoneIndex = G2_GetVertBoneIndex(verts[i], k); + const float fBoneWeight = G2_GetVertBoneWeight( + verts[i], k, fTotalWeight, iNumWeights); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); + + pTri[i][0] += fBoneWeight * + (DotProduct(bone.matrix[0], verts[i]->vertCoords) + bone.matrix[0][3]); + pTri[i][1] += fBoneWeight * + (DotProduct(bone.matrix[1], verts[i]->vertCoords) + bone.matrix[1][3]); + pTri[i][2] += fBoneWeight * + (DotProduct(bone.matrix[2], verts[i]->vertCoords) + bone.matrix[2][3]); + } + } + + const float baryCentricK = + 1.0f - (surfInfo->genBarycentricI + surfInfo->genBarycentricJ); + + // now we have the model transformed into model space, now generate an origin. + for ( int i = 0; i < 3; ++i ) + { + retMatrix.matrix[i][3] = + (pTri[0][i] * surfInfo->genBarycentricI) + + (pTri[1][i] * surfInfo->genBarycentricJ) + + (pTri[2][i] * baryCentricK); + } + + // generate a normal to this new triangle + vec3_t vec0, vec1; + VectorSubtract(pTri[0], pTri[1], vec0); + VectorSubtract(pTri[2], pTri[1], vec1); + + vec3_t normal; + CrossProduct(vec0, vec1, normal); + VectorNormalize(normal); + + // forward vector + retMatrix.matrix[0][0] = normal[0]; + retMatrix.matrix[1][0] = normal[1]; + retMatrix.matrix[2][0] = normal[2]; + + // up will be towards point 0 of the original triangle. + // so lets work it out. Vector is hit point - point 0 + vec3_t up; + up[0] = retMatrix.matrix[0][3] - pTri[0][0]; + up[1] = retMatrix.matrix[1][3] - pTri[0][1]; + up[2] = retMatrix.matrix[2][3] - pTri[0][2]; + + // normalise it + VectorNormalize(up); + + // that's the up vector + retMatrix.matrix[0][1] = up[0]; + retMatrix.matrix[1][1] = up[1]; + retMatrix.matrix[2][1] = up[2]; + + // right is always straight + vec3_t right; + CrossProduct( normal, up, right ); + + // that's the up vector + retMatrix.matrix[0][2] = right[0]; + retMatrix.matrix[1][2] = right[1]; + retMatrix.matrix[2][2] = right[2]; + + } + // no, we are looking at a normal model tag + else + { + // whip through and actually transform each vertex + const mdxmVertex_t *v = + (const mdxmVertex_t *)((byte *)surface + surface->ofsVerts); + const int *piBoneReferences = + (const int*)((byte *)surface + surface->ofsBoneReferences); + for ( int j = 0; j < 3; j++ ) + { + VectorClear(pTri[j]); + + const int iNumWeights = G2_GetVertWeights( v ); + float fTotalWeight = 0.0f; + for ( int k = 0 ; k < iNumWeights ; k++) + { + const int iBoneIndex = G2_GetVertBoneIndex(v, k); + const float fBoneWeight = + G2_GetVertBoneWeight(v, k, fTotalWeight, iNumWeights); + const mdxaBone_t &bone = boneCache.Eval(piBoneReferences[iBoneIndex]); + + pTri[j][0] += fBoneWeight * + (DotProduct(bone.matrix[0], v->vertCoords) + bone.matrix[0][3]); + pTri[j][1] += fBoneWeight * + (DotProduct(bone.matrix[1], v->vertCoords) + bone.matrix[1][3]); + pTri[j][2] += fBoneWeight * + (DotProduct(bone.matrix[2], v->vertCoords) + bone.matrix[2][3]); + } + + v++; + } + + // clear out used arrays + vec3_t axes[3] = {}; + vec3_t sides[3] = {}; + + // work out actual sides of the tag triangle + for ( int j = 0; j < 3; j++ ) + { + sides[j][0] = pTri[(j + 1) % 3][0] - pTri[j][0]; + sides[j][1] = pTri[(j + 1) % 3][1] - pTri[j][1]; + sides[j][2] = pTri[(j + 1) % 3][2] - pTri[j][2]; + } + + // do math trig to work out what the matrix will be from this + // triangle's translated position + VectorNormalize2(sides[iG2_TRISIDE_LONGEST], axes[0]); + VectorNormalize2(sides[iG2_TRISIDE_SHORTEST], axes[1]); + + // project shortest side so that it is exactly 90 degrees to the longer + // side + float d = DotProduct(axes[0], axes[1]); + VectorMA(axes[0], -d, axes[1], axes[0]); + VectorNormalize2(axes[0], axes[0]); + + CrossProduct(sides[iG2_TRISIDE_LONGEST], sides[iG2_TRISIDE_SHORTEST], axes[2]); + VectorNormalize2(axes[2], axes[2]); + + // set up location in world space of the origin point in out going + // matrix + retMatrix.matrix[0][3] = pTri[MDX_TAG_ORIGIN][0]; + retMatrix.matrix[1][3] = pTri[MDX_TAG_ORIGIN][1]; + retMatrix.matrix[2][3] = pTri[MDX_TAG_ORIGIN][2]; + + // copy axis to matrix - do some magic to orient minus Y to positive X + // and so on so bolt on stuff is oriented correctly + retMatrix.matrix[0][0] = axes[1][0]; + retMatrix.matrix[0][1] = axes[0][0]; + retMatrix.matrix[0][2] = -axes[2][0]; + + retMatrix.matrix[1][0] = axes[1][1]; + retMatrix.matrix[1][1] = axes[0][1]; + retMatrix.matrix[1][2] = -axes[2][1]; + + retMatrix.matrix[2][0] = axes[1][2]; + retMatrix.matrix[2][1] = axes[0][2]; + retMatrix.matrix[2][2] = -axes[2][2]; + } +} + +void G2_GetBoltMatrixLow( + CGhoul2Info& ghoul2, + int boltNum, + const vec3_t scale, + mdxaBone_t& retMatrix) +{ + if ( !ghoul2.mBoneCache ) + { + retMatrix = identityMatrix; + return; + } + + CBoneCache& boneCache = *ghoul2.mBoneCache; + assert(boneCache.mod); + + boltInfo_v& boltList = ghoul2.mBltlist; + if ( boltList.empty() || boltNum >= boltList.size() ) + { + retMatrix = identityMatrix; + return; + } + + boltInfo_t& bolt = boltList[boltNum]; + int boltBone = bolt.boneNumber; + int boltSurface = bolt.surfaceNumber; + + if ( boltBone >= 0 ) + { + mdxaSkelOffsets_t *offsets = + (mdxaSkelOffsets_t *)((byte *)boneCache.header + sizeof(mdxaHeader_t)); + mdxaSkel_t *skel = + (mdxaSkel_t *)((byte *)offsets + offsets->offsets[boltBone]); + + Mat3x4_Multiply( + &retMatrix, + (mdxaBone_t *)&boneCache.EvalUnsmooth(boltBone), + &skel->BasePoseMat); + } + else if ( boltSurface >= 0 ) + { + const surfaceInfo_t *surfInfo = nullptr; + for ( const surfaceInfo_t& t : ghoul2.mSlist ) + { + if ( t.surface == boltSurface ) + { + surfInfo = &t; + } + } + + mdxmSurface_t *surface = nullptr; + if ( !surfInfo ) + { + surface = (mdxmSurface_t *)G2_FindSurface_BC( + boneCache.mod, boltSurface, 0); + } + + if ( !surface && surfInfo && surfInfo->surface < 10000 ) + { + surface = (mdxmSurface_t *)G2_FindSurface_BC( + boneCache.mod, surfInfo->surface, 0); + } + + G2_ProcessSurfaceBolt2( + boneCache, + surface, + boltNum, + boltList, + surfInfo, + (model_t *)boneCache.mod, + retMatrix); + } + else + { + // we have a bolt without a bone or surface, not a huge problem but we + // ought to at least clear the bolt matrix + retMatrix = identityMatrix; + } +} + +static void RootMatrix( + CGhoul2Info_v &ghoul2, + int time, + const vec3_t scale, + mdxaBone_t &retMatrix) +{ + for ( int i = 0, numModels = ghoul2.size(); i < numModels; ++i ) + { + if ( ghoul2[i].mModelindex == -1 || !ghoul2[i].mValid ) + { + continue; + } + + if ( ghoul2[i].mFlags & GHOUL2_NEWORIGIN ) + { + mdxaBone_t bolt; + mdxaBone_t tempMatrix; + + G2_ConstructGhoulSkeleton(ghoul2, time, false, scale); + G2_GetBoltMatrixLow(ghoul2[i], ghoul2[i].mNewOrigin, scale, bolt); + + tempMatrix.matrix[0][0] = 1.0f; + tempMatrix.matrix[0][1] = 0.0f; + tempMatrix.matrix[0][2] = 0.0f; + tempMatrix.matrix[0][3] = -bolt.matrix[0][3]; + + tempMatrix.matrix[1][0] = 0.0f; + tempMatrix.matrix[1][1] = 1.0f; + tempMatrix.matrix[1][2] = 0.0f; + tempMatrix.matrix[1][3] = -bolt.matrix[1][3]; + + tempMatrix.matrix[2][0] = 0.0f; + tempMatrix.matrix[2][1] = 0.0f; + tempMatrix.matrix[2][2] = 1.0f; + tempMatrix.matrix[2][3] = -bolt.matrix[2][3]; + + retMatrix = tempMatrix * identityMatrix; + return; + } + } + + retMatrix = identityMatrix; +} + +/* +============== +R_AddGHOULSurfaces +============== +*/ + +void R_AddGhoulSurfaces( trRefEntity_t *ent, int entityNum ) +{ +#ifdef G2_PERFORMANCE_ANALYSIS + G2PerformanceTimer_R_AddGHOULSurfaces.Start(); +#endif + + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)ent->e.ghoul2); + + if ( !ghoul2.IsValid() ) + { + return; + } + + // if we don't want server ghoul2 models and this is one, or we just don't + // want ghoul2 models at all, then return + if (r_noServerGhoul2->integer) + { + return; + } + + if (!G2_SetupModelPointers(ghoul2)) + { + return; + } + + int currentTime = G2API_GetTime(tr.refdef.time); + + // cull the entire model if merged bounding box of both frames is outside + // the view frustum. + int cull = R_GCullModel(ent); + if ( cull == CULL_OUT ) + { + return; + } + + HackadelicOnClient = true; + + // don't add third_person objects if not in a portal + qboolean personalModel = (qboolean)( + (ent->e.renderfx & RF_THIRD_PERSON) && + !(tr.viewParms.isPortal || + (tr.viewParms.flags & VPF_DEPTHSHADOW))); + + int modelList[256]; + assert(ghoul2.size() < ARRAY_LEN(modelList)); + modelList[255] = 548; + + // see if we are in a fog volume + int fogNum = R_GComputeFogNum(ent); + + // order sort the ghoul 2 models so bolt ons get bolted to the right model + int modelCount; + G2_Sort_Models(ghoul2, modelList, ARRAY_LEN(modelList), &modelCount); + assert(modelList[255] == 548); + +#ifdef _G2_GORE + if ( goreShader == -1 ) + { + goreShader = RE_RegisterShader("gfx/damage/burnmark1"); + } +#endif + + // walk each possible model for this entity and try rendering it out + for (int j = 0; j < modelCount; ++j ) + { + CGhoul2Info& g2Info = ghoul2[modelList[j]]; + + if ( !g2Info.mValid ) + { + continue; + } + + if ( (g2Info.mFlags & (GHOUL2_NOMODEL | GHOUL2_NORENDER)) != 0 ) + { + continue; + } + + // figure out whether we should be using a custom shader for this model + skin_t *skin = nullptr; + shader_t *cust_shader = nullptr; + + if (ent->e.customShader) + { + cust_shader = R_GetShaderByHandle(ent->e.customShader ); + } + else + { + cust_shader = nullptr; + // figure out the custom skin thing + if (g2Info.mCustomSkin) + { + skin = R_GetSkinByHandle(g2Info.mCustomSkin ); + } + else if (ent->e.customSkin) + { + skin = R_GetSkinByHandle(ent->e.customSkin ); + } + else if ( g2Info.mSkin > 0 && g2Info.mSkin < tr.numSkins ) + { + skin = R_GetSkinByHandle( g2Info.mSkin ); + } + } + + int whichLod = G2_ComputeLOD( ent, g2Info.currentModel, g2Info.mLodBias ); + G2_FindOverrideSurface(-1, g2Info.mSlist); //reset the quick surface override lookup; + +#ifdef _G2_GORE + CGoreSet *gore = nullptr; + if ( g2Info.mGoreSetTag ) + { + gore = FindGoreSet(g2Info.mGoreSetTag); + if ( !gore ) // my gore is gone, so remove it + { + g2Info.mGoreSetTag = 0; + } + } + + CRenderSurface RS(g2Info.mSurfaceRoot, + g2Info.mSlist, + cust_shader, + fogNum, + personalModel, + g2Info.mBoneCache, + ent->e.renderfx, + skin, + (model_t *)g2Info.currentModel, + whichLod, + g2Info.mBltlist, + nullptr, + gore); +#else + CRenderSurface RS(g2Info.mSurfaceRoot, + g2Info.mSlist, + cust_shader, + fogNum, + personalModel, + g2Info.mBoneCache, + ent->e.renderfx, + skin, + (model_t *)g2Info.currentModel, + whichLod, + g2Info.mBltlist); +#endif + if ( !personalModel && (RS.renderfx & RF_SHADOW_PLANE) ) + { + RS.renderfx |= RF_NOSHADOW; + } + + RenderSurfaces(RS, ent, entityNum); + } + + HackadelicOnClient = false; + +#ifdef G2_PERFORMANCE_ANALYSIS + G2Time_R_AddGHOULSurfaces += G2PerformanceTimer_R_AddGHOULSurfaces.End(); +#endif +} + +#ifdef _G2_LISTEN_SERVER_OPT +qboolean G2API_OverrideServerWithClientData(CGhoul2Info *serverInstance); +#endif + +bool G2_NeedsRecalc(CGhoul2Info *ghlInfo,int frameNum) +{ + G2_SetupModelPointers(ghlInfo); + // not sure if I still need this test, probably + if (ghlInfo->mSkelFrameNum!=frameNum|| + !ghlInfo->mBoneCache|| + ghlInfo->mBoneCache->mod!=ghlInfo->currentModel) + { +#ifdef _G2_LISTEN_SERVER_OPT + if (ghlInfo->entityNum != ENTITYNUM_NONE && + G2API_OverrideServerWithClientData(ghlInfo)) + { //if we can manage this, then we don't have to reconstruct + return false; + } +#endif + ghlInfo->mSkelFrameNum=frameNum; + return true; + } + return false; +} + +/* +============== +G2_ConstructGhoulSkeleton +builds a complete skeleton for all ghoul models in a CGhoul2Info_v class +using LOD 0 +============== +*/ +void G2_ConstructGhoulSkeleton( + CGhoul2Info_v &ghoul2, + const int frameNum, + bool checkForNewOrigin, + const vec3_t scale) +{ +#ifdef G2_PERFORMANCE_ANALYSIS + G2PerformanceTimer_G2_ConstructGhoulSkeleton.Start(); +#endif + int modelCount; + mdxaBone_t rootMatrix; + int modelList[256]; + + assert(ghoul2.size() <= ARRAY_LEN(modelList)); + modelList[255] = 548; + + if ( checkForNewOrigin ) + { + RootMatrix(ghoul2, frameNum, scale, rootMatrix); + } + else + { + rootMatrix = identityMatrix; + } + + G2_Sort_Models(ghoul2, modelList, ARRAY_LEN(modelList), &modelCount); + assert(modelList[255] == 548); + + for ( int j = 0; j < modelCount; j++ ) + { + int i = modelList[j]; + CGhoul2Info& g2Info = ghoul2[i]; + + if ( !g2Info.mValid ) + { + continue; + } + + if ( j && g2Info.mModelBoltLink != -1 ) + { + int boltMod = (g2Info.mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (g2Info.mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + + mdxaBone_t bolt; + G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, scale, bolt); + G2_TransformGhoulBones( + g2Info.mBlist, + bolt, + g2Info, + frameNum, + checkForNewOrigin); + } + else +#ifdef _G2_LISTEN_SERVER_OPT + if (g2Info.entityNum == ENTITYNUM_NONE || g2Info.mSkelFrameNum != frameNum) +#endif + { + G2_TransformGhoulBones( + g2Info.mBlist, + rootMatrix, + g2Info, + frameNum, + checkForNewOrigin); + } + } + +#ifdef G2_PERFORMANCE_ANALYSIS + G2Time_G2_ConstructGhoulSkeleton += G2PerformanceTimer_G2_ConstructGhoulSkeleton.End(); +#endif +} + +static inline float G2_GetVertBoneWeightNotSlow( const mdxmVertex_t *pVert, const int iWeightNum) +{ + float fBoneWeight; + + int iTemp = pVert->BoneWeightings[iWeightNum]; + + iTemp|= (pVert->uiNmWeightsAndBoneIndexes >> (iG2_BONEWEIGHT_TOPBITS_SHIFT+(iWeightNum*2)) ) & iG2_BONEWEIGHT_TOPBITS_AND; + + fBoneWeight = fG2_BONEWEIGHT_RECIPROCAL_MULT * iTemp; + + return fBoneWeight; +} + +void RB_TransformBones(const trRefEntity_t *ent, const trRefdef_t *refdef, int currentFrameNum, gpuFrame_t *frame) +{ + if (!ent->e.ghoul2 || !G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) + return; + + CGhoul2Info_v &ghoul2 = *((CGhoul2Info_v *)ent->e.ghoul2); + + if (!ghoul2.IsValid()) + return; + + // if we don't want server ghoul2 models and this is one, or we just don't + // want ghoul2 models at all, then return + if (r_noServerGhoul2->integer) + { + return; + } + + if (!G2_SetupModelPointers(ghoul2)) + { + return; + } + + int currentTime = G2API_GetTime(refdef->time); + + HackadelicOnClient = true; + + mdxaBone_t rootMatrix; + RootMatrix(ghoul2, currentTime, ent->e.modelScale, rootMatrix); + + int modelList[256]; + assert(ghoul2.size() < ARRAY_LEN(modelList)); + modelList[255] = 548; + + // order sort the ghoul 2 models so bolt ons get bolted to the right model + int modelCount; + G2_Sort_Models(ghoul2, modelList, ARRAY_LEN(modelList), &modelCount); + assert(modelList[255] == 548); + + // construct a world matrix for this entity + G2_GenerateWorldMatrix(ent->e.angles, ent->e.origin); + + // walk each possible model for this entity and try transforming all bones + for (int j = 0; j < modelCount; ++j) + { + CGhoul2Info& g2Info = ghoul2[modelList[j]]; + + if (!g2Info.mValid) + { + continue; + } + + if ((g2Info.mFlags & (GHOUL2_NOMODEL | GHOUL2_NORENDER)) != 0) + { + continue; + } + + if (j && g2Info.mModelBoltLink != -1) + { + int boltMod = (g2Info.mModelBoltLink >> MODEL_SHIFT) & MODEL_AND; + int boltNum = (g2Info.mModelBoltLink >> BOLT_SHIFT) & BOLT_AND; + + mdxaBone_t bolt; + G2_GetBoltMatrixLow(ghoul2[boltMod], boltNum, ent->e.modelScale, bolt); + G2_TransformGhoulBones(g2Info.mBlist, bolt, g2Info, currentTime); + } + else + { + G2_TransformGhoulBones(g2Info.mBlist, rootMatrix, g2Info, currentTime); + } + + CBoneCache *bc = g2Info.mBoneCache; + if (bc->uboGPUFrame == currentFrameNum) + return; + + for (int bone = 0; bone < (int)bc->mBones.size(); bone++) + { + const mdxaBone_t& b = bc->EvalRender(bone); + Com_Memcpy( + bc->boneMatrices + bone, + &b.matrix[0][0], + sizeof(mat3x4_t)); + } + bc->uboOffset = -1; + + SkeletonBoneMatricesBlock bonesBlock = {}; + Com_Memcpy( + bonesBlock.matrices, + bc->boneMatrices, + sizeof(mat3x4_t) * bc->mBones.size()); + + int uboOffset = RB_AppendConstantsData( + frame, &bonesBlock, sizeof(mat3x4_t) * bc->mBones.size()); + + bc->uboOffset = uboOffset; + bc->uboGPUFrame = currentFrameNum; + } +} + +int RB_GetBoneUboOffset(CRenderableSurface *surf) +{ + if (surf->boneCache) + return surf->boneCache->uboOffset; + else + return -1; +} + +void RB_SetBoneUboOffset(CRenderableSurface *surf, int offset, int currentFrameNum) +{ + surf->boneCache->uboOffset = offset; + surf->boneCache->uboGPUFrame = currentFrameNum; +} + +void RB_FillBoneBlock(CRenderableSurface *surf, mat3x4_t *outMatrices) +{ + Com_Memcpy( + outMatrices, + surf->boneCache->boneMatrices, + sizeof(surf->boneCache->boneMatrices)); +} + +void RB_SurfaceGhoul( CRenderableSurface *surf ) +{ + mdxmVBOMesh_t *surface = surf->vboMesh; + + if ( surface->vbo == NULL || surface->ibo == NULL ) + { + return; + } + + int numIndexes = surface->numIndexes; + int numVertexes = surface->numVertexes; + int minIndex = surface->minIndex; + int maxIndex = surface->maxIndex; + int indexOffset = surface->indexOffset; + +#ifdef _G2_GORE + if (surf->alternateTex) + { + R_BindVBO(tr.goreVBO); + R_BindIBO(tr.goreIBO); + tess.externalIBO = tr.goreIBO; + + numIndexes = surf->alternateTex->numIndexes; + numVertexes = surf->alternateTex->numVerts; + minIndex = surf->alternateTex->firstVert; + maxIndex = surf->alternateTex->firstVert + surf->alternateTex->numVerts; + indexOffset = surf->alternateTex->firstIndex; + +#ifdef REND2_SP_MAYBE + // UNTESTED CODE + if (surf->scale > 1.0f) + { + tess.scale = true; + tess.texCoords[tess.firstIndex][0][0] = surf->scale; + } + + //now check for fade overrides -rww + if (surf->fade) + { + static int lFade; + if (surf->fade < 1.0) + { + tess.fade = true; + lFade = Q_ftol(254.4f*surf->fade); + tess.svars.colors[tess.firstIndex][0] = + tess.svars.colors[tess.firstIndex][1] = + tess.svars.colors[tess.firstIndex][2] = Q_ftol(1.0f); + tess.svars.colors[tess.firstIndex][3] = lFade; + } + else if (surf->fade > 2.0f && surf->fade < 3.0f) + { //hack to fade out on RGB if desired (don't want to add more to CRenderableSurface) -rww + tess.fade = true; + lFade = Q_ftol(254.4f*(surf->fade - 2.0f)); + if (lFade < tess.svars.colors[tess.firstIndex][0]) + { //don't set it unless the fade is less than the current r value (to avoid brightening suddenly before we start fading) + tess.svars.colors[tess.firstIndex][0] = + tess.svars.colors[tess.firstIndex][1] = + tess.svars.colors[tess.firstIndex][2] = lFade; + } + tess.svars.colors[tess.firstIndex][3] = lFade; + } + } + tess.scale = false; + tess.fade = false; +#endif + } else { +#endif + + R_BindVBO(surface->vbo); + R_BindIBO(surface->ibo); + tess.externalIBO = surface->ibo; + + glState.genShadows = surf->genShadows; +#ifdef _G2_GORE + } +#endif + int i, mergeForward, mergeBack; + GLvoid *firstIndexOffset, *lastIndexOffset; + + // merge this into any existing multidraw primitives + mergeForward = -1; + mergeBack = -1; + firstIndexOffset = BUFFER_OFFSET(indexOffset * sizeof(glIndex_t)); + lastIndexOffset = BUFFER_OFFSET((indexOffset + numIndexes) * sizeof(glIndex_t)); + + if (r_mergeMultidraws->integer) + { + i = 0; + + if (r_mergeMultidraws->integer == 1) + { + // lazy merge, only check the last primitive + if (tess.multiDrawPrimitives) + { + i = tess.multiDrawPrimitives - 1; + } + } + + for (; i < tess.multiDrawPrimitives; i++) + { + if (tess.multiDrawLastIndex[i] == firstIndexOffset) + { + mergeBack = i; + } + + if (lastIndexOffset == tess.multiDrawFirstIndex[i]) + { + mergeForward = i; + } + } + } + + if (mergeBack != -1 && mergeForward == -1) + { + tess.multiDrawNumIndexes[mergeBack] += numIndexes; + tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; + tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], minIndex); + tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], maxIndex); + backEnd.pc.c_multidrawsMerged++; + } + else if (mergeBack == -1 && mergeForward != -1) + { + tess.multiDrawNumIndexes[mergeForward] += numIndexes; + tess.multiDrawFirstIndex[mergeForward] = (glIndex_t *)firstIndexOffset; + tess.multiDrawLastIndex[mergeForward] = tess.multiDrawFirstIndex[mergeForward] + tess.multiDrawNumIndexes[mergeForward]; + tess.multiDrawMinIndex[mergeForward] = MIN(tess.multiDrawMinIndex[mergeForward], minIndex); + tess.multiDrawMaxIndex[mergeForward] = MAX(tess.multiDrawMaxIndex[mergeForward], maxIndex); + backEnd.pc.c_multidrawsMerged++; + } + else if (mergeBack != -1 && mergeForward != -1) + { + tess.multiDrawNumIndexes[mergeBack] += numIndexes + tess.multiDrawNumIndexes[mergeForward]; + tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; + tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], MIN(tess.multiDrawMinIndex[mergeForward], minIndex)); + tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], MAX(tess.multiDrawMaxIndex[mergeForward], maxIndex)); + tess.multiDrawPrimitives--; + + if (mergeForward != tess.multiDrawPrimitives) + { + tess.multiDrawNumIndexes[mergeForward] = tess.multiDrawNumIndexes[tess.multiDrawPrimitives]; + tess.multiDrawFirstIndex[mergeForward] = tess.multiDrawFirstIndex[tess.multiDrawPrimitives]; + } + backEnd.pc.c_multidrawsMerged += 2; + } + else if (mergeBack == -1 && mergeForward == -1) + { + tess.multiDrawNumIndexes[tess.multiDrawPrimitives] = numIndexes; + tess.multiDrawFirstIndex[tess.multiDrawPrimitives] = (glIndex_t *)firstIndexOffset; + tess.multiDrawLastIndex[tess.multiDrawPrimitives] = (glIndex_t *)lastIndexOffset; + tess.multiDrawMinIndex[tess.multiDrawPrimitives] = minIndex; + tess.multiDrawMaxIndex[tess.multiDrawPrimitives] = maxIndex; + tess.multiDrawPrimitives++; + } + + backEnd.pc.c_multidraws++; + + tess.numIndexes += numIndexes; + tess.numVertexes += numVertexes; + tess.useInternalVBO = qfalse; + tess.dlightBits |= surf->dlightBits; + + glState.skeletalAnimation = qtrue; +} + +/* +================= +R_LoadMDXM - load a Ghoul 2 Mesh file +================= +*/ + +/* + +Some information used in the creation of the JK2 - JKA bone remap table + +These are the old bones: +Complete list of all 72 bones: + +*/ + +int OldToNewRemapTable[72] = { +0,// Bone 0: "model_root": Parent: "" (index -1) +1,// Bone 1: "pelvis": Parent: "model_root" (index 0) +2,// Bone 2: "Motion": Parent: "pelvis" (index 1) +3,// Bone 3: "lfemurYZ": Parent: "pelvis" (index 1) +4,// Bone 4: "lfemurX": Parent: "pelvis" (index 1) +5,// Bone 5: "ltibia": Parent: "pelvis" (index 1) +6,// Bone 6: "ltalus": Parent: "pelvis" (index 1) +6,// Bone 7: "ltarsal": Parent: "pelvis" (index 1) +7,// Bone 8: "rfemurYZ": Parent: "pelvis" (index 1) +8,// Bone 9: "rfemurX": Parent: "pelvis" (index 1) +9,// Bone10: "rtibia": Parent: "pelvis" (index 1) +10,// Bone11: "rtalus": Parent: "pelvis" (index 1) +10,// Bone12: "rtarsal": Parent: "pelvis" (index 1) +11,// Bone13: "lower_lumbar": Parent: "pelvis" (index 1) +12,// Bone14: "upper_lumbar": Parent: "lower_lumbar" (index 13) +13,// Bone15: "thoracic": Parent: "upper_lumbar" (index 14) +14,// Bone16: "cervical": Parent: "thoracic" (index 15) +15,// Bone17: "cranium": Parent: "cervical" (index 16) +16,// Bone18: "ceyebrow": Parent: "face_always_" (index 71) +17,// Bone19: "jaw": Parent: "face_always_" (index 71) +18,// Bone20: "lblip2": Parent: "face_always_" (index 71) +19,// Bone21: "leye": Parent: "face_always_" (index 71) +20,// Bone22: "rblip2": Parent: "face_always_" (index 71) +21,// Bone23: "ltlip2": Parent: "face_always_" (index 71) +22,// Bone24: "rtlip2": Parent: "face_always_" (index 71) +23,// Bone25: "reye": Parent: "face_always_" (index 71) +24,// Bone26: "rclavical": Parent: "thoracic" (index 15) +25,// Bone27: "rhumerus": Parent: "thoracic" (index 15) +26,// Bone28: "rhumerusX": Parent: "thoracic" (index 15) +27,// Bone29: "rradius": Parent: "thoracic" (index 15) +28,// Bone30: "rradiusX": Parent: "thoracic" (index 15) +29,// Bone31: "rhand": Parent: "thoracic" (index 15) +29,// Bone32: "mc7": Parent: "thoracic" (index 15) +34,// Bone33: "r_d5_j1": Parent: "thoracic" (index 15) +35,// Bone34: "r_d5_j2": Parent: "thoracic" (index 15) +35,// Bone35: "r_d5_j3": Parent: "thoracic" (index 15) +30,// Bone36: "r_d1_j1": Parent: "thoracic" (index 15) +31,// Bone37: "r_d1_j2": Parent: "thoracic" (index 15) +31,// Bone38: "r_d1_j3": Parent: "thoracic" (index 15) +32,// Bone39: "r_d2_j1": Parent: "thoracic" (index 15) +33,// Bone40: "r_d2_j2": Parent: "thoracic" (index 15) +33,// Bone41: "r_d2_j3": Parent: "thoracic" (index 15) +32,// Bone42: "r_d3_j1": Parent: "thoracic" (index 15) +33,// Bone43: "r_d3_j2": Parent: "thoracic" (index 15) +33,// Bone44: "r_d3_j3": Parent: "thoracic" (index 15) +34,// Bone45: "r_d4_j1": Parent: "thoracic" (index 15) +35,// Bone46: "r_d4_j2": Parent: "thoracic" (index 15) +35,// Bone47: "r_d4_j3": Parent: "thoracic" (index 15) +36,// Bone48: "rhang_tag_bone": Parent: "thoracic" (index 15) +37,// Bone49: "lclavical": Parent: "thoracic" (index 15) +38,// Bone50: "lhumerus": Parent: "thoracic" (index 15) +39,// Bone51: "lhumerusX": Parent: "thoracic" (index 15) +40,// Bone52: "lradius": Parent: "thoracic" (index 15) +41,// Bone53: "lradiusX": Parent: "thoracic" (index 15) +42,// Bone54: "lhand": Parent: "thoracic" (index 15) +42,// Bone55: "mc5": Parent: "thoracic" (index 15) +43,// Bone56: "l_d5_j1": Parent: "thoracic" (index 15) +44,// Bone57: "l_d5_j2": Parent: "thoracic" (index 15) +44,// Bone58: "l_d5_j3": Parent: "thoracic" (index 15) +43,// Bone59: "l_d4_j1": Parent: "thoracic" (index 15) +44,// Bone60: "l_d4_j2": Parent: "thoracic" (index 15) +44,// Bone61: "l_d4_j3": Parent: "thoracic" (index 15) +45,// Bone62: "l_d3_j1": Parent: "thoracic" (index 15) +46,// Bone63: "l_d3_j2": Parent: "thoracic" (index 15) +46,// Bone64: "l_d3_j3": Parent: "thoracic" (index 15) +45,// Bone65: "l_d2_j1": Parent: "thoracic" (index 15) +46,// Bone66: "l_d2_j2": Parent: "thoracic" (index 15) +46,// Bone67: "l_d2_j3": Parent: "thoracic" (index 15) +47,// Bone68: "l_d1_j1": Parent: "thoracic" (index 15) +48,// Bone69: "l_d1_j2": Parent: "thoracic" (index 15) +48,// Bone70: "l_d1_j3": Parent: "thoracic" (index 15) +52// Bone71: "face_always_": Parent: "cranium" (index 17) +}; + + +/* + +Bone 0: "model_root": + Parent: "" (index -1) + #Kids: 1 + Child 0: (index 1), name "pelvis" + +Bone 1: "pelvis": + Parent: "model_root" (index 0) + #Kids: 4 + Child 0: (index 2), name "Motion" + Child 1: (index 3), name "lfemurYZ" + Child 2: (index 7), name "rfemurYZ" + Child 3: (index 11), name "lower_lumbar" + +Bone 2: "Motion": + Parent: "pelvis" (index 1) + #Kids: 0 + +Bone 3: "lfemurYZ": + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 4), name "lfemurX" + Child 1: (index 5), name "ltibia" + Child 2: (index 49), name "ltail" + +Bone 4: "lfemurX": + Parent: "lfemurYZ" (index 3) + #Kids: 0 + +Bone 5: "ltibia": + Parent: "lfemurYZ" (index 3) + #Kids: 1 + Child 0: (index 6), name "ltalus" + +Bone 6: "ltalus": + Parent: "ltibia" (index 5) + #Kids: 0 + +Bone 7: "rfemurYZ": + Parent: "pelvis" (index 1) + #Kids: 3 + Child 0: (index 8), name "rfemurX" + Child 1: (index 9), name "rtibia" + Child 2: (index 50), name "rtail" + +Bone 8: "rfemurX": + Parent: "rfemurYZ" (index 7) + #Kids: 0 + +Bone 9: "rtibia": + Parent: "rfemurYZ" (index 7) + #Kids: 1 + Child 0: (index 10), name "rtalus" + +Bone 10: "rtalus": + Parent: "rtibia" (index 9) + #Kids: 0 + +Bone 11: "lower_lumbar": + Parent: "pelvis" (index 1) + #Kids: 1 + Child 0: (index 12), name "upper_lumbar" + +Bone 12: "upper_lumbar": + Parent: "lower_lumbar" (index 11) + #Kids: 1 + Child 0: (index 13), name "thoracic" + +Bone 13: "thoracic": + Parent: "upper_lumbar" (index 12) + #Kids: 5 + Child 0: (index 14), name "cervical" + Child 1: (index 24), name "rclavical" + Child 2: (index 25), name "rhumerus" + Child 3: (index 37), name "lclavical" + Child 4: (index 38), name "lhumerus" + +Bone 14: "cervical": + Parent: "thoracic" (index 13) + #Kids: 1 + Child 0: (index 15), name "cranium" + +Bone 15: "cranium": + Parent: "cervical" (index 14) + #Kids: 1 + Child 0: (index 52), name "face_always_" + +Bone 16: "ceyebrow": + Parent: "face_always_" (index 52) + #Kids: 0 + +Bone 17: "jaw": + Parent: "face_always_" (index 52) + #Kids: 0 + +Bone 18: "lblip2": + Parent: "face_always_" (index 52) + #Kids: 0 + +Bone 19: "leye": + Parent: "face_always_" (index 52) + #Kids: 0 + +Bone 20: "rblip2": + Parent: "face_always_" (index 52) + #Kids: 0 + +Bone 21: "ltlip2": + Parent: "face_always_" (index 52) + #Kids: 0 + +Bone 22: "rtlip2": + Parent: "face_always_" (index 52) + #Kids: 0 + +Bone 23: "reye": + Parent: "face_always_" (index 52) + #Kids: 0 + +Bone 24: "rclavical": + Parent: "thoracic" (index 13) + #Kids: 0 + +Bone 25: "rhumerus": + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 26), name "rhumerusX" + Child 1: (index 27), name "rradius" + +Bone 26: "rhumerusX": + Parent: "rhumerus" (index 25) + #Kids: 0 + +Bone 27: "rradius": + Parent: "rhumerus" (index 25) + #Kids: 9 + Child 0: (index 28), name "rradiusX" + Child 1: (index 29), name "rhand" + Child 2: (index 30), name "r_d1_j1" + Child 3: (index 31), name "r_d1_j2" + Child 4: (index 32), name "r_d2_j1" + Child 5: (index 33), name "r_d2_j2" + Child 6: (index 34), name "r_d4_j1" + Child 7: (index 35), name "r_d4_j2" + Child 8: (index 36), name "rhang_tag_bone" + +Bone 28: "rradiusX": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 29: "rhand": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 30: "r_d1_j1": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 31: "r_d1_j2": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 32: "r_d2_j1": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 33: "r_d2_j2": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 34: "r_d4_j1": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 35: "r_d4_j2": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 36: "rhang_tag_bone": + Parent: "rradius" (index 27) + #Kids: 0 + +Bone 37: "lclavical": + Parent: "thoracic" (index 13) + #Kids: 0 + +Bone 38: "lhumerus": + Parent: "thoracic" (index 13) + #Kids: 2 + Child 0: (index 39), name "lhumerusX" + Child 1: (index 40), name "lradius" + +Bone 39: "lhumerusX": + Parent: "lhumerus" (index 38) + #Kids: 0 + +Bone 40: "lradius": + Parent: "lhumerus" (index 38) + #Kids: 9 + Child 0: (index 41), name "lradiusX" + Child 1: (index 42), name "lhand" + Child 2: (index 43), name "l_d4_j1" + Child 3: (index 44), name "l_d4_j2" + Child 4: (index 45), name "l_d2_j1" + Child 5: (index 46), name "l_d2_j2" + Child 6: (index 47), name "l_d1_j1" + Child 7: (index 48), name "l_d1_j2" + Child 8: (index 51), name "lhang_tag_bone" + +Bone 41: "lradiusX": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 42: "lhand": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 43: "l_d4_j1": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 44: "l_d4_j2": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 45: "l_d2_j1": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 46: "l_d2_j2": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 47: "l_d1_j1": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 48: "l_d1_j2": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 49: "ltail": + Parent: "lfemurYZ" (index 3) + #Kids: 0 + +Bone 50: "rtail": + Parent: "rfemurYZ" (index 7) + #Kids: 0 + +Bone 51: "lhang_tag_bone": + Parent: "lradius" (index 40) + #Kids: 0 + +Bone 52: "face_always_": + Parent: "cranium" (index 15) + #Kids: 8 + Child 0: (index 16), name "ceyebrow" + Child 1: (index 17), name "jaw" + Child 2: (index 18), name "lblip2" + Child 3: (index 19), name "leye" + Child 4: (index 20), name "rblip2" + Child 5: (index 21), name "ltlip2" + Child 6: (index 22), name "rtlip2" + Child 7: (index 23), name "reye" + + + +*/ + +qboolean R_LoadMDXM(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) +{ + int i,l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + mdxmSurfHierarchy_t *surfInfo; + + pinmodel= (mdxmHeader_t *)buffer; + // + // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... + // + version = (pinmodel->version); + size = (pinmodel->ofsEnd); + + if (!bAlreadyCached) + { + LL(version); + LL(size); + } + + if (version != MDXM_VERSION) { + Com_Printf (S_COLOR_YELLOW "R_LoadMDXM: %s has wrong version (%i should be %i)\n", + mod_name, version, MDXM_VERSION); + return qfalse; + } + + mod->type = MOD_MDXM; + mod->dataSize += size; + + qboolean bAlreadyFound = qfalse; + mdxm = (mdxmHeader_t*)CModelCache->Allocate(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + mod->data.glm = (mdxmData_t *)ri.Hunk_Alloc (sizeof (mdxmData_t), h_low); + mod->data.glm->header = mdxm; + + //RE_RegisterModels_Malloc(size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM); + + assert(bAlreadyCached == bAlreadyFound); + + if (!bAlreadyFound) + { + // horrible new hackery, if !bAlreadyFound then we've just done a + // tag-morph, so we need to set the bool reference passed into this + // function to true, to tell the caller NOT to do an ri.FS_Freefile + // since we've hijacked that memory block... + // + // Aaaargh. Kill me now... + // + bAlreadyCached = qtrue; + assert( mdxm == buffer ); + + LL(mdxm->ident); + LL(mdxm->version); + LL(mdxm->numLODs); + LL(mdxm->ofsLODs); + LL(mdxm->numSurfaces); + LL(mdxm->ofsSurfHierarchy); + LL(mdxm->ofsEnd); + } + + // first up, go load in the animation file we need that has the skeletal + // animation info for this model + mdxm->animIndex = RE_RegisterModel(va ("%s.gla",mdxm->animName)); + + if (!mdxm->animIndex) + { + Com_Printf (S_COLOR_YELLOW "R_LoadMDXM: missing animation file %s for mesh %s\n", mdxm->animName, mdxm->name); + return qfalse; + } + + mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + + if (bAlreadyFound) + { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + } + + bool isAnOldModelFile = false; + if (mdxm->numBones == 72 && strstr(mdxm->animName,"_humanoid") ) + { + isAnOldModelFile = true; + } + + surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); + for ( i = 0 ; i < mdxm->numSurfaces ; i++) + { + LL(surfInfo->numChildren); + LL(surfInfo->parentIndex); + + Q_strlwr(surfInfo->name); //just in case + if ( !strcmp( &surfInfo->name[strlen(surfInfo->name)-4],"_off") ) + { + surfInfo->name[strlen(surfInfo->name)-4]=0; //remove "_off" from name + } + + // do all the children indexs + for (j=0; jnumChildren; j++) + { + LL(surfInfo->childIndexes[j]); + } + + shader_t *sh; + // get the shader name + sh = R_FindShader( surfInfo->shader, lightmapsNone, stylesDefault, qtrue ); + // insert it in the surface list + if ( sh->defaultShader ) + { + surfInfo->shaderIndex = 0; + } + else + { + surfInfo->shaderIndex = sh->index; + } + + CModelCache->StoreShaderRequest(mod_name, &surfInfo->shader[0], &surfInfo->shaderIndex); + + // find the next surface + surfInfo = (mdxmSurfHierarchy_t *)((byte *)surfInfo + offsetof(mdxmSurfHierarchy_t, childIndexes) + sizeof(int) * surfInfo->numChildren); + } + + // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) + lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); + for ( l = 0 ; l < mdxm->numLODs ; l++) + { + int triCount = 0; + + LL(lod->ofsEnd); + // swap all the surfaces + surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); + for ( i = 0 ; i < mdxm->numSurfaces ; i++) + { + LL(surf->numTriangles); + LL(surf->ofsTriangles); + LL(surf->numVerts); + LL(surf->ofsVerts); + LL(surf->ofsEnd); + LL(surf->ofsHeader); + LL(surf->numBoneReferences); + LL(surf->ofsBoneReferences); +// LL(surf->maxVertBoneWeights); + + triCount += surf->numTriangles; + + if ( surf->numVerts > SHADER_MAX_VERTEXES ) { + Com_Error( + ERR_DROP, + "R_LoadMDXM: %s has more than %i verts on a surface (%i)", + mod_name, + SHADER_MAX_VERTEXES, + surf->numVerts); + } + if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { + Com_Error( + ERR_DROP, + "R_LoadMDXM: %s has more than %i triangles on a surface (%i)", + mod_name, + SHADER_MAX_INDEXES / 3, + surf->numTriangles); + } + + // change to surface identifier + surf->ident = SF_MDX; + // register the shaders + + if (isAnOldModelFile) + { + int *boneRef = (int *) ( (byte *)surf + surf->ofsBoneReferences ); + for ( j = 0 ; j < surf->numBoneReferences ; j++ ) + { + if (boneRef[j] >= 0 && boneRef[j] < 72) + { + boneRef[j]=OldToNewRemapTable[boneRef[j]]; + } + else + { + boneRef[j]=0; + } + } + } + // find the next surface + surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + } + // find the next LOD + lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + } + + // Make a copy on the GPU + lod = (mdxmLOD_t *)((byte *)mdxm + mdxm->ofsLODs); + + mod->data.glm->vboModels = (mdxmVBOModel_t *)ri.Hunk_Alloc (sizeof (mdxmVBOModel_t) * mdxm->numLODs, h_low); + for ( l = 0; l < mdxm->numLODs; l++ ) + { + mdxmVBOModel_t *vboModel = &mod->data.glm->vboModels[l]; + mdxmVBOMesh_t *vboMeshes; + + vec3_t *verts; + uint32_t *normals; + vec2_t *texcoords; + byte *bonerefs; + byte *weights; + uint32_t *tangents; + + byte *data; + int dataSize = 0; + int ofsPosition, ofsNormals, ofsTexcoords, ofsBoneRefs, ofsWeights, ofsTangents; + int stride = 0; + int numVerts = 0; + int numTriangles = 0; + + // +1 to add total vertex count + int *baseVertexes = (int *)ri.Hunk_AllocateTempMemory (sizeof (int) * (mdxm->numSurfaces + 1)); + int *indexOffsets = (int *)ri.Hunk_AllocateTempMemory (sizeof (int) * mdxm->numSurfaces); + + vboModel->numVBOMeshes = mdxm->numSurfaces; + vboModel->vboMeshes = (mdxmVBOMesh_t *)ri.Hunk_Alloc (sizeof (mdxmVBOMesh_t) * mdxm->numSurfaces, h_low); + vboMeshes = vboModel->vboMeshes; + + surf = (mdxmSurface_t *)((byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof (mdxmLODSurfOffset_t))); + + // Calculate the required size of the vertex buffer. + for ( int n = 0; n < mdxm->numSurfaces; n++ ) + { + baseVertexes[n] = numVerts; + indexOffsets[n] = numTriangles * 3; + + numVerts += surf->numVerts; + numTriangles += surf->numTriangles; + + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); + } + + baseVertexes[mdxm->numSurfaces] = numVerts; + + dataSize += numVerts * sizeof (*verts); + dataSize += numVerts * sizeof (*normals); + dataSize += numVerts * sizeof (*texcoords); + dataSize += numVerts * sizeof (*weights) * 4; + dataSize += numVerts * sizeof (*bonerefs) * 4; + dataSize += numVerts * sizeof (*tangents); + + // Allocate and write to memory + data = (byte *)ri.Hunk_AllocateTempMemory (dataSize); + + ofsPosition = stride; + verts = (vec3_t *)(data + ofsPosition); + stride += sizeof (*verts); + + ofsNormals = stride; + normals = (uint32_t *)(data + ofsNormals); + stride += sizeof (*normals); + + ofsTexcoords = stride; + texcoords = (vec2_t *)(data + ofsTexcoords); + stride += sizeof (*texcoords); + + ofsBoneRefs = stride; + bonerefs = data + ofsBoneRefs; + stride += sizeof (*bonerefs) * 4; + + ofsWeights = stride; + weights = data + ofsWeights; + stride += sizeof (*weights) * 4; + + ofsTangents = stride; + tangents = (uint32_t *)(data + ofsTangents); + stride += sizeof (*tangents); + + // Fill in the index buffer and compute tangents + glIndex_t *indices = (glIndex_t *)ri.Hunk_AllocateTempMemory(sizeof(glIndex_t) * numTriangles * 3); + glIndex_t *index = indices; + uint32_t *tangentsf = (uint32_t *)ri.Hunk_AllocateTempMemory(sizeof(uint32_t) * numVerts); + + surf = (mdxmSurface_t *)((byte *)lod + sizeof(mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t))); + + for (int n = 0; n < mdxm->numSurfaces; n++) + { + mdxmTriangle_t *t = (mdxmTriangle_t *)((byte *)surf + surf->ofsTriangles); + glIndex_t *surf_indices = (glIndex_t *)ri.Hunk_AllocateTempMemory(sizeof(glIndex_t) * surf->numTriangles * 3); + glIndex_t *surf_index = surf_indices; + + for (int k = 0; k < surf->numTriangles; k++, index += 3, surf_index += 3) + { + index[0] = t[k].indexes[0] + baseVertexes[n]; + assert(index[0] >= 0 && index[0] < numVerts); + + index[1] = t[k].indexes[1] + baseVertexes[n]; + assert(index[1] >= 0 && index[1] < numVerts); + + index[2] = t[k].indexes[2] + baseVertexes[n]; + assert(index[2] >= 0 && index[2] < numVerts); + + surf_index[0] = t[k].indexes[0]; + surf_index[1] = t[k].indexes[1]; + surf_index[2] = t[k].indexes[2]; + } + + // Build tangent space + mdxmVertex_t *vertices = (mdxmVertex_t *)((byte *)surf + surf->ofsVerts); + mdxmVertexTexCoord_t *textureCoordinates = (mdxmVertexTexCoord_t *)(vertices + surf->numVerts); + + R_CalcMikkTSpaceGlmSurface( + surf->numTriangles, + vertices, + textureCoordinates, + tangentsf + baseVertexes[n], + surf_indices + ); + + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); + } + + assert(index == (indices + numTriangles * 3)); + + surf = (mdxmSurface_t *)((byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof (mdxmLODSurfOffset_t))); + + for (int n = 0; n < mdxm->numSurfaces; n++) + { + // Positions and normals + mdxmVertex_t *v = (mdxmVertex_t *)((byte *)surf + surf->ofsVerts); + int *boneRef = (int *)((byte *)surf + surf->ofsBoneReferences); + + for (int k = 0; k < surf->numVerts; k++) + { + VectorCopy(v[k].vertCoords, *verts); + *normals = R_VboPackNormal(v[k].normal); + + verts = (vec3_t *)((byte *)verts + stride); + normals = (uint32_t *)((byte *)normals + stride); + } + + // Weights + for (int k = 0; k < surf->numVerts; k++) + { + int numWeights = G2_GetVertWeights(&v[k]); + int lastWeight = 255; + int lastInfluence = numWeights - 1; + for (int w = 0; w < lastInfluence; w++) + { + float weight = G2_GetVertBoneWeightNotSlow(&v[k], w); + weights[w] = (byte)(weight * 255.0f); + int packedIndex = G2_GetVertBoneIndex(&v[k], w); + bonerefs[w] = boneRef[packedIndex]; + + lastWeight -= weights[w]; + } + + assert(lastWeight > 0); + + // Ensure that all the weights add up to 1.0 + weights[lastInfluence] = lastWeight; + int packedIndex = G2_GetVertBoneIndex(&v[k], lastInfluence); + bonerefs[lastInfluence] = boneRef[packedIndex]; + + // Fill in the rest of the info with zeroes. + for (int w = numWeights; w < 4; w++) + { + weights[w] = 0; + bonerefs[w] = 0; + } + + weights += stride; + bonerefs += stride; + } + + // Texture coordinates + mdxmVertexTexCoord_t *tc = (mdxmVertexTexCoord_t *)(v + surf->numVerts); + for (int k = 0; k < surf->numVerts; k++) + { + (*texcoords)[0] = tc[k].texCoords[0]; + (*texcoords)[1] = tc[k].texCoords[1]; + + texcoords = (vec2_t *)((byte *)texcoords + stride); + } + + for (int k = 0; k < surf->numVerts; k++) + { + *tangents = *(tangentsf + baseVertexes[n] + k); + tangents = (uint32_t *)((byte *)tangents + stride); + } + + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); + } + + assert ((byte *)verts == (data + dataSize)); + + const char *modelName = strrchr (mdxm->name, '/'); + if (modelName == NULL) + { + modelName = mdxm->name; + } + VBO_t *vbo = R_CreateVBO (data, dataSize, VBO_USAGE_STATIC); + IBO_t *ibo = R_CreateIBO((byte *)indices, sizeof(glIndex_t) * numTriangles * 3, VBO_USAGE_STATIC); + + ri.Hunk_FreeTempMemory (data); + ri.Hunk_FreeTempMemory (tangentsf); + ri.Hunk_FreeTempMemory (indices); + + vbo->offsets[ATTR_INDEX_POSITION] = ofsPosition; + vbo->offsets[ATTR_INDEX_NORMAL] = ofsNormals; + vbo->offsets[ATTR_INDEX_TEXCOORD0] = ofsTexcoords; + vbo->offsets[ATTR_INDEX_BONE_INDEXES] = ofsBoneRefs; + vbo->offsets[ATTR_INDEX_BONE_WEIGHTS] = ofsWeights; + vbo->offsets[ATTR_INDEX_TANGENT] = ofsTangents; + + vbo->strides[ATTR_INDEX_POSITION] = stride; + vbo->strides[ATTR_INDEX_NORMAL] = stride; + vbo->strides[ATTR_INDEX_TEXCOORD0] = stride; + vbo->strides[ATTR_INDEX_BONE_INDEXES] = stride; + vbo->strides[ATTR_INDEX_BONE_WEIGHTS] = stride; + vbo->strides[ATTR_INDEX_TANGENT] = stride; + + vbo->sizes[ATTR_INDEX_POSITION] = sizeof(*verts); + vbo->sizes[ATTR_INDEX_NORMAL] = sizeof(*normals); + vbo->sizes[ATTR_INDEX_TEXCOORD0] = sizeof(*texcoords); + vbo->sizes[ATTR_INDEX_BONE_WEIGHTS] = sizeof(*weights); + vbo->sizes[ATTR_INDEX_BONE_INDEXES] = sizeof(*bonerefs); + vbo->sizes[ATTR_INDEX_TANGENT] = sizeof(*tangents); + + surf = (mdxmSurface_t *)((byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof (mdxmLODSurfOffset_t))); + + for ( int n = 0; n < mdxm->numSurfaces; n++ ) + { + vboMeshes[n].vbo = vbo; + vboMeshes[n].ibo = ibo; + + vboMeshes[n].indexOffset = indexOffsets[n]; + vboMeshes[n].minIndex = baseVertexes[n]; + vboMeshes[n].maxIndex = baseVertexes[n + 1] - 1; + vboMeshes[n].numVertexes = surf->numVerts; + vboMeshes[n].numIndexes = surf->numTriangles * 3; + + surf = (mdxmSurface_t *)((byte *)surf + surf->ofsEnd); + } + + vboModel->vbo = vbo; + vboModel->ibo = ibo; + + ri.Hunk_FreeTempMemory (indexOffsets); + ri.Hunk_FreeTempMemory (baseVertexes); + + lod = (mdxmLOD_t *)((byte *)lod + lod->ofsEnd); + } + + return qtrue; +} + +//#define CREATE_LIMB_HIERARCHY + +#ifdef CREATE_LIMB_HIERARCHY + +#define NUM_ROOTPARENTS 4 +#define NUM_OTHERPARENTS 12 +#define NUM_BOTTOMBONES 4 + +#define CHILD_PADDING 4 //I don't know, I guess this can be changed. + +static const char *rootParents[NUM_ROOTPARENTS] = +{ + "rfemurYZ", + "rhumerus", + "lfemurYZ", + "lhumerus" +}; + +static const char *otherParents[NUM_OTHERPARENTS] = +{ + "rhumerusX", + "rradius", + "rradiusX", + "lhumerusX", + "lradius", + "lradiusX", + "rfemurX", + "rtibia", + "rtalus", + "lfemurX", + "ltibia", + "ltalus" +}; + +static const char *bottomBones[NUM_BOTTOMBONES] = +{ + "rtarsal", + "rhand", + "ltarsal", + "lhand" +}; + +qboolean BoneIsRootParent(char *name) +{ + int i = 0; + + while (i < NUM_ROOTPARENTS) + { + if (!Q_stricmp(name, rootParents[i])) + { + return qtrue; + } + + i++; + } + + return qfalse; +} + +qboolean BoneIsOtherParent(char *name) +{ + int i = 0; + + while (i < NUM_OTHERPARENTS) + { + if (!Q_stricmp(name, otherParents[i])) + { + return qtrue; + } + + i++; + } + + return qfalse; +} + +qboolean BoneIsBottom(char *name) +{ + int i = 0; + + while (i < NUM_BOTTOMBONES) + { + if (!Q_stricmp(name, bottomBones[i])) + { + return qtrue; + } + + i++; + } + + return qfalse; +} + +void ShiftMemoryDown(mdxaSkelOffsets_t *offsets, mdxaHeader_t *mdxa, int boneIndex, byte **endMarker) +{ + int i = 0; + + //where the next bone starts + byte *nextBone = ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[boneIndex+1]); + int size = (*endMarker - nextBone); + + memmove((nextBone+CHILD_PADDING), nextBone, size); + memset(nextBone, 0, CHILD_PADDING); + *endMarker += CHILD_PADDING; + // Move the whole thing down CHILD_PADDING amount in memory, clear the new + // preceding space, and increment the end pointer. + + i = boneIndex+1; + + // Now add CHILD_PADDING amount to every offset beginning at the offset of + // the bone that was moved. + while (i < mdxa->numBones) + { + offsets->offsets[i] += CHILD_PADDING; + i++; + } + + mdxa->ofsFrames += CHILD_PADDING; + mdxa->ofsCompBonePool += CHILD_PADDING; + mdxa->ofsEnd += CHILD_PADDING; + // ofsSkel does not need to be updated because we are only moving memory + // after that point. +} + +//Proper/desired hierarchy list +static const char *BoneHierarchyList[] = +{ + "lfemurYZ", + "lfemurX", + "ltibia", + "ltalus", + "ltarsal", + + "rfemurYZ", + "rfemurX", + "rtibia", + "rtalus", + "rtarsal", + + "lhumerus", + "lhumerusX", + "lradius", + "lradiusX", + "lhand", + + "rhumerus", + "rhumerusX", + "rradius", + "rradiusX", + "rhand", + + 0 +}; + +//Gets the index of a child or parent. If child is passed as qfalse then parent is assumed. +int BoneParentChildIndex( + mdxaHeader_t *mdxa, + mdxaSkelOffsets_t *offsets, + mdxaSkel_t *boneInfo, + qboolean child) +{ + int i = 0; + int matchindex = -1; + mdxaSkel_t *bone; + const char *match = NULL; + + while (BoneHierarchyList[i]) + { + if (!Q_stricmp(boneInfo->name, BoneHierarchyList[i])) + { + // we have a match, the slot above this will be our desired parent. + // (or below for child) + if (child) + { + match = BoneHierarchyList[i+1]; + } + else + { + match = BoneHierarchyList[i-1]; + } + break; + } + i++; + } + + if (!match) + { //no good + return -1; + } + + i = 0; + + while (i < mdxa->numBones) + { + bone = (mdxaSkel_t *)((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + + if (bone && !Q_stricmp(bone->name, match)) + { //this is the one + matchindex = i; + break; + } + + i++; + } + + return matchindex; +} +#endif //CREATE_LIMB_HIERARCHY + +/* +================= +R_LoadMDXA - load a Ghoul 2 animation file +================= +*/ +qboolean R_LoadMDXA(model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached) +{ + + mdxaHeader_t *pinmodel, *mdxa; + int version; + int size; +#ifdef CREATE_LIMB_HIERARCHY + int oSize = 0; + byte *sizeMarker; +#endif + +#if 0 //#ifndef _M_IX86 + int j, k, i; + int frameSize; + mdxaFrame_t *cframe; + mdxaSkel_t *boneInfo; +#endif + + pinmodel = (mdxaHeader_t *)buffer; + // + // read some fields from the binary, but only LittleLong() them when we know this wasn't an + // already-cached model... + // + version = (pinmodel->version); + size = (pinmodel->ofsEnd); + + if (!bAlreadyCached) + { + LL(version); + LL(size); + } + + if (version != MDXA_VERSION) + { + Com_Printf( + S_COLOR_YELLOW "R_LoadMDXA: %s has wrong version (%i should be %i)\n", + mod_name, + version, + MDXA_VERSION); + return qfalse; + } + + mod->type = MOD_MDXA; + mod->dataSize += size; + + qboolean bAlreadyFound = qfalse; + +#ifdef CREATE_LIMB_HIERARCHY + oSize = size; + + int childNumber = (NUM_ROOTPARENTS + NUM_OTHERPARENTS); + + // Allocate us some extra space so we can shift memory down. + size += (childNumber * (CHILD_PADDING * 8)); +#endif // CREATE_LIMB_HIERARCHY + + mdxa = (mdxaHeader_t *)CModelCache->Allocate( + size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA); + mod->data.gla = mdxa; + + // I should probably eliminate 'bAlreadyFound', but wtf? + assert(bAlreadyCached == bAlreadyFound); + + if (!bAlreadyFound) + { +#ifdef CREATE_LIMB_HIERARCHY + memcpy(mdxa, buffer, oSize); +#else + // horrible new hackery, if !bAlreadyFound then we've just done a + // tag-morph, so we need to set the bool reference passed into this + // function to true, to tell the caller NOT to do an + // ri.FS_Freefile since we've hijacked that memory block... + // + // Aaaargh. Kill me now... + // + bAlreadyCached = qtrue; + assert(mdxa == buffer); +#endif + LL(mdxa->ident); + LL(mdxa->version); + LL(mdxa->numFrames); + LL(mdxa->numBones); + LL(mdxa->ofsFrames); + LL(mdxa->ofsEnd); + } + +#ifdef CREATE_LIMB_HIERARCHY + if (!bAlreadyFound) + { + mdxaSkel_t *boneParent; + + sizeMarker = (byte *)mdxa + mdxa->ofsEnd; + + // rww - This is probably temporary until we put actual hierarchy in + // for the models. It is necessary for the correct operation of + // ragdoll. + mdxaSkelOffsets_t *offsets = (mdxaSkelOffsets_t *)((byte *)mdxa + sizeof(mdxaHeader_t)); + + for (i = 0; i < mdxa->numBones; i++) + { + boneInfo = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[i]); + + if (boneInfo) + { + char *bname = boneInfo->name; + + if (BoneIsRootParent(bname)) + { + // These are the main parent bones. We don't want to change + // their parents, but we want to give them children. + ShiftMemoryDown(offsets, mdxa, i, &sizeMarker); + + boneInfo = (mdxaSkel_t *)((byte *)offsets + offsets->offsets[i]); + + int newChild = BoneParentChildIndex(mdxa, offsets, boneInfo, qtrue); + + if (newChild != -1) + { + boneInfo->numChildren++; + boneInfo->children[boneInfo->numChildren - 1] = newChild; + } + else + { + assert(!"Failed to find matching child for bone in hierarchy creation"); + } + } + else if (BoneIsOtherParent(bname) || BoneIsBottom(bname)) + { + if (!BoneIsBottom(bname)) + { // unless it's last in the chain it has the next bone as a child. + ShiftMemoryDown(offsets, mdxa, i, &sizeMarker); + + boneInfo = (mdxaSkel_t *) + ((byte *)mdxa + sizeof(mdxaHeader_t) + offsets->offsets[i]); + int newChild = BoneParentChildIndex(mdxa, offsets, boneInfo, qtrue); + + if (newChild != -1) + { + boneInfo->numChildren++; + boneInfo->children[boneInfo->numChildren - 1] = newChild; + } + else + { + assert(!"Failed to find matching child for bone in hierarchy creation"); + } + } + + // Before we set the parent we want to remove this as a + // child for whoever was parenting it. + int oldParent = boneInfo->parent; + + if (oldParent > -1) + { + boneParent = (mdxaSkel_t *) + ((byte *)offsets + offsets->offsets[oldParent]); + } + else + { + boneParent = NULL; + } + + if (boneParent) + { + k = 0; + + while (k < boneParent->numChildren) + { + if (boneParent->children[k] == i) + { // this bone is the child + k++; + while (k < boneParent->numChildren) + { + boneParent->children[k - 1] = boneParent->children[k]; + k++; + } + boneParent->children[k - 1] = 0; + boneParent->numChildren--; + break; + } + k++; + } + } + + // Now that we have cleared the original parent of + // ownership, mark the bone's new parent. + int newParent = BoneParentChildIndex(mdxa, offsets, boneInfo, qfalse); + + if (newParent != -1) + { + boneInfo->parent = newParent; + } + else + { + assert(!"Failed to find matching parent for bone in hierarchy creation"); + } + } + } + } + } +#endif // CREATE_LIMB_HIERARCHY + + if (mdxa->numFrames < 1) + { + Com_Printf(S_COLOR_YELLOW "R_LoadMDXA: %s has no frames\n", mod_name); + return qfalse; + } + + if (bAlreadyFound) + { + return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... + } + + return qtrue; +} + diff --git a/codemp/rd-rend2/tr_glsl.cpp b/codemp/rd-rend2/tr_glsl.cpp new file mode 100644 index 0000000000..5a3201fa52 --- /dev/null +++ b/codemp/rd-rend2/tr_glsl.cpp @@ -0,0 +1,2638 @@ +/* +=========================================================================== +Copyright (C) 2006-2009 Robert Beckebans + +This file is part of XreaL source code. + +XreaL source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +XreaL source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with XreaL source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_glsl.c +#include "tr_local.h" +#include "tr_allocator.h" +#include "glsl_shaders.h" + +void GLSL_BindNullProgram(void); + +const uniformBlockInfo_t uniformBlocksInfo[UNIFORM_BLOCK_COUNT] = { + { 0, "Camera", sizeof(CameraBlock) }, + { 1, "Scene", sizeof(SceneBlock) }, + { 2, "Lights", sizeof(LightsBlock) }, + { 3, "Fogs", sizeof(FogsBlock) }, + { 4, "Entity", sizeof(EntityBlock) }, + { 5, "ShaderInstance", sizeof(ShaderInstanceBlock) }, + { 6, "Bones", sizeof(SkeletonBoneMatricesBlock) }, + { 10, "SurfaceSprite", sizeof(SurfaceSpriteBlock) }, +}; + +typedef struct uniformInfo_s +{ + const char *name; + int type; + int size; +} +uniformInfo_t; + +// These must be in the same order as in uniform_t in tr_local.h. +static uniformInfo_t uniformsInfo[] = +{ + { "u_DiffuseMap", GLSL_INT, 1 }, + { "u_LightMap", GLSL_INT, 1 }, + { "u_NormalMap", GLSL_INT, 1 }, + { "u_DeluxeMap", GLSL_INT, 1 }, + { "u_SpecularMap", GLSL_INT, 1 }, + { "u_SSAOMap", GLSL_INT, 1 }, + + { "u_TextureMap", GLSL_INT, 1 }, + { "u_LevelsMap", GLSL_INT, 1 }, + { "u_CubeMap", GLSL_INT, 1 }, + { "u_EnvBrdfMap", GLSL_INT, 1 }, + + { "u_ScreenImageMap", GLSL_INT, 1 }, + { "u_ScreenDepthMap", GLSL_INT, 1 }, + + { "u_ShadowMap", GLSL_INT, 1 }, + { "u_ShadowMap2", GLSL_INT, 1 }, + + { "u_ShadowMvp", GLSL_MAT4x4, 1 }, + { "u_ShadowMvp2", GLSL_MAT4x4, 1 }, + { "u_ShadowMvp3", GLSL_MAT4x4, 1 }, + + { "u_EnableTextures", GLSL_VEC4, 1 }, + + { "u_DiffuseTexMatrix", GLSL_VEC4, 1 }, + { "u_DiffuseTexOffTurb", GLSL_VEC4, 1 }, + + { "u_TCGen0", GLSL_INT, 1 }, + { "u_TCGen0Vector0", GLSL_VEC3, 1 }, + { "u_TCGen0Vector1", GLSL_VEC3, 1 }, + { "u_TCGen1", GLSL_INT, 1 }, + + { "u_ColorGen", GLSL_INT, 1 }, + { "u_AlphaGen", GLSL_INT, 1 }, + { "u_Color", GLSL_VEC4, 1 }, + { "u_BaseColor", GLSL_VEC4, 1 }, + { "u_VertColor", GLSL_VEC4, 1 }, + + { "u_DlightInfo", GLSL_VEC4, 1 }, + { "u_LightForward", GLSL_VEC3, 1 }, + { "u_LightUp", GLSL_VEC3, 1 }, + { "u_LightRight", GLSL_VEC3, 1 }, + { "u_LightOrigin", GLSL_VEC4, 1 }, + { "u_ModelLightDir", GLSL_VEC3, 1 }, + { "u_LightRadius", GLSL_FLOAT, 1 }, + { "u_AmbientLight", GLSL_VEC3, 1 }, + { "u_DirectedLight", GLSL_VEC3, 1 }, + { "u_Disintegration", GLSL_VEC4, 1 }, + { "u_LightMask", GLSL_INT, 1 }, + { "u_FogIndex", GLSL_INT, 1 }, + + { "u_FogColorMask", GLSL_VEC4, 1 }, + + { "u_ModelMatrix", GLSL_MAT4x4, 1 }, + { "u_ModelViewProjectionMatrix", GLSL_MAT4x4, 1 }, + + { "u_Time", GLSL_FLOAT, 1 }, + { "u_VertexLerp" , GLSL_FLOAT, 1 }, + { "u_NormalScale", GLSL_VEC4, 1 }, + { "u_SpecularScale", GLSL_VEC4, 1 }, + { "u_ParallaxBias", GLSL_FLOAT, 1 }, + + { "u_ViewInfo", GLSL_VEC4, 1 }, + { "u_ViewOrigin", GLSL_VEC3, 1 }, + { "u_LocalViewOrigin", GLSL_VEC3, 1 }, + { "u_ViewForward", GLSL_VEC3, 1 }, + { "u_ViewLeft", GLSL_VEC3, 1 }, + { "u_ViewUp", GLSL_VEC3, 1 }, + + { "u_InvTexRes", GLSL_VEC2, 1 }, + { "u_AutoExposureMinMax", GLSL_VEC2, 1 }, + { "u_ToneMinAvgMaxLinear", GLSL_VEC3, 1 }, + + { "u_CubeMapInfo", GLSL_VEC4, 1 }, + + { "u_AlphaTestType", GLSL_INT, 1 }, + + { "u_FXVolumetricBase", GLSL_FLOAT, 1 }, + { "u_MapZExtents", GLSL_VEC2, 1 }, + { "u_ZoneOffset", GLSL_VEC2, 9 }, + { "u_EnvForce", GLSL_VEC3, 1 }, + { "u_RandomOffset", GLSL_VEC4, 1 }, + { "u_ChunkParticles", GLSL_INT, 1 }, +}; + +static void GLSL_PrintProgramInfoLog(GLuint object, qboolean developerOnly) +{ + char msgPart[1024]; + int maxLength = 0; + int printLevel = developerOnly ? PRINT_DEVELOPER : PRINT_ALL; + + qglGetProgramiv(object, GL_INFO_LOG_LENGTH, &maxLength); + + if (maxLength <= 0) + { + ri.Printf(printLevel, "No compile log.\n"); + return; + } + + ri.Printf(printLevel, "compile log:\n"); + + if (maxLength < 1023) + { + qglGetProgramInfoLog(object, maxLength, &maxLength, msgPart); + + msgPart[maxLength + 1] = '\0'; + + ri.Printf(printLevel, "%s\n", msgPart); + } + else + { + char *msg = (char *)Z_Malloc(maxLength, TAG_SHADERTEXT); + + qglGetProgramInfoLog(object, maxLength, &maxLength, msg); + + for(int i = 0; i < maxLength; i += 1023) + { + Q_strncpyz(msgPart, msg + i, sizeof(msgPart)); + + ri.Printf(printLevel, "%s\n", msgPart); + } + + Z_Free(msg); + } +} + +static void GLSL_PrintShaderInfoLog(GLuint object, qboolean developerOnly) +{ + char *msg; + static char msgPart[1024]; + int maxLength = 0; + int i; + int printLevel = developerOnly ? PRINT_DEVELOPER : PRINT_ALL; + + qglGetShaderiv(object, GL_INFO_LOG_LENGTH, &maxLength); + + if (maxLength <= 0) + { + ri.Printf(printLevel, "No compile log.\n"); + return; + } + + ri.Printf(printLevel, "compile log:\n"); + + if (maxLength < 1023) + { + qglGetShaderInfoLog(object, maxLength, &maxLength, msgPart); + + msgPart[maxLength + 1] = '\0'; + + ri.Printf(printLevel, "%s\n", msgPart); + } + else + { + msg = (char *)Z_Malloc(maxLength, TAG_SHADERTEXT); + + qglGetShaderInfoLog(object, maxLength, &maxLength, msg); + + for(i = 0; i < maxLength; i += 1024) + { + Q_strncpyz(msgPart, msg + i, sizeof(msgPart)); + + ri.Printf(printLevel, "%s\n", msgPart); + } + + Z_Free(msg); + } +} + +static void GLSL_PrintShaderSource(GLuint shader) +{ + int maxLength = 0; + qglGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &maxLength); + + if ( maxLength == 0 ) + { + Com_Printf("No shader source available to output\n"); + return; + } + + char *msg = (char *)Z_Malloc(maxLength, TAG_SHADERTEXT); + qglGetShaderSource(shader, maxLength, nullptr, msg); + + for (int i = 0; i < maxLength; i += 1023) + { + char msgPart[1024]; + Q_strncpyz(msgPart, msg + i, sizeof(msgPart)); + ri.Printf(PRINT_ALL, "%s\n", msgPart); + } + + Z_Free(msg); +} + +static size_t GLSL_GetShaderHeader( + GLenum shaderType, + const GLcharARB *extra, + int firstLineNumber, + char *dest, + size_t size) +{ + float fbufWidthScale, fbufHeightScale; + + dest[0] = '\0'; + + Q_strcat(dest, size, "#version 150 core\n"); + + Q_strcat(dest, size, + "#ifndef M_PI\n" + "#define M_PI 3.14159265358979323846\n" + "#endif\n"); + + Q_strcat(dest, size, + va("#ifndef deformGen_t\n" + "#define deformGen_t\n" + "#define DEFORM_NONE %i\n" + "#define DEFORM_WAVE %i\n" + "#define DEFORM_NORMALS %i\n" + "#define DEFORM_BULGE %i\n" + "#define DEFORM_BULGE_UNIFORM %i\n" + "#define DEFORM_MOVE %i\n" + "#define DEFORM_PROJECTION_SHADOW %i\n" + "#define DEFORM_DISINTEGRATION %i\n" + "#define WF_NONE %i\n" + "#define WF_SIN %i\n" + "#define WF_SQUARE %i\n" + "#define WF_TRIANGLE %i\n" + "#define WF_SAWTOOTH %i\n" + "#define WF_INVERSE_SAWTOOTH %i\n" + "#endif\n", + DEFORM_NONE, + DEFORM_WAVE, + DEFORM_NORMALS, + DEFORM_BULGE, + DEFORM_BULGE_UNIFORM, + DEFORM_MOVE, + DEFORM_PROJECTION_SHADOW, + DEFORM_DISINTEGRATION, + GF_NONE, + GF_SIN, + GF_SQUARE, + GF_TRIANGLE, + GF_SAWTOOTH, + GF_INVERSE_SAWTOOTH)); + + Q_strcat(dest, size, + va("#ifndef tcGen_t\n" + "#define tcGen_t\n" + "#define TCGEN_LIGHTMAP %i\n" + "#define TCGEN_LIGHTMAP1 %i\n" + "#define TCGEN_LIGHTMAP2 %i\n" + "#define TCGEN_LIGHTMAP3 %i\n" + "#define TCGEN_TEXTURE %i\n" + "#define TCGEN_ENVIRONMENT_MAPPED %i\n" + "#define TCGEN_FOG %i\n" + "#define TCGEN_VECTOR %i\n" + "#endif\n", + TCGEN_LIGHTMAP, + TCGEN_LIGHTMAP1, + TCGEN_LIGHTMAP2, + TCGEN_LIGHTMAP3, + TCGEN_TEXTURE, + TCGEN_ENVIRONMENT_MAPPED, + TCGEN_FOG, + TCGEN_VECTOR)); + + Q_strcat(dest, size, + va("#ifndef colorGen_t\n" + "#define colorGen_t\n" + "#define CGEN_LIGHTING_DIFFUSE %i\n" + "#define CGEN_DISINTEGRATION_1 %i\n" + "#define CGEN_DISINTEGRATION_2 %i\n" + "#endif\n", + CGEN_LIGHTING_DIFFUSE, + CGEN_DISINTEGRATION_1, + CGEN_DISINTEGRATION_2)); + + Q_strcat(dest, size, + va("#ifndef alphaGen_t\n" + "#define alphaGen_t\n" + "#define AGEN_LIGHTING_SPECULAR %i\n" + "#define AGEN_PORTAL %i\n" + "#endif\n", + AGEN_LIGHTING_SPECULAR, + AGEN_PORTAL)); + + Q_strcat(dest, size, + va("#define ALPHA_TEST_GT0 %d\n" + "#define ALPHA_TEST_LT128 %d\n" + "#define ALPHA_TEST_GE128 %d\n" + "#define ALPHA_TEST_GE192 %d\n", + ALPHA_TEST_GT0, + ALPHA_TEST_LT128, + ALPHA_TEST_GE128, + ALPHA_TEST_GE192)); + + Q_strcat(dest, size, + va("#define MAX_G2_BONES %i\n", + MAX_G2_BONES)); + + fbufWidthScale = (float)glConfig.vidWidth; + fbufHeightScale = (float)glConfig.vidHeight; + Q_strcat(dest, size, + va("#ifndef r_FBufScale\n" + "#define r_FBufScale vec2(%f, %f)\n" + "#endif\n", + fbufWidthScale, + fbufHeightScale)); + + if (r_cubeMapping->integer) + { + Q_strcat(dest, size, va("#define CUBEMAP_RESOLUTION float(%i)\n", CUBE_MAP_SIZE)); + Q_strcat(dest, size, va("#define ROUGHNESS_MIPS float(%i)\n", CUBE_MAP_ROUGHNESS_MIPS)); + } + + if (r_ssao->integer) + Q_strcat(dest, size, "#define USE_SSAO\n"); + + if (r_deluxeSpecular->value > 0.000001f) + { + Q_strcat(dest, size, va("#define r_deluxeSpecular %f\n", r_deluxeSpecular->value)); + } + + if (r_hdr->integer && (r_toneMap->integer || r_forceToneMap->integer)) + Q_strcat(dest, size, "#define USE_TONEMAPPING\n"); + + if (extra) + { + Q_strcat(dest, size, extra); + } + + // OK we added a lot of stuff but if we do something bad in the GLSL + // shaders then we want the proper line so we have to reset the line + // counting + Q_strcat(dest, size, va("\n#line %d\n", firstLineNumber - 1)); + + return strlen(dest); +} + +static bool GLSL_IsGPUShaderCompiled (GLuint shader) +{ + GLint compiled; + qglGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); + return (compiled == GL_TRUE); +} + +static GLuint GLSL_CompileGPUShader( + GLuint program, + const GLchar *buffer, + int size, + GLenum shaderType) +{ + GLuint shader = qglCreateShader(shaderType); + if ( shader == 0 ) + { + return 0; + } + + qglShaderSource(shader, 1, &buffer, &size); + qglCompileShader(shader); + + if ( !GLSL_IsGPUShaderCompiled(shader) ) + { + GLSL_PrintShaderSource(shader); + GLSL_PrintShaderInfoLog(shader, qfalse); + + qglDeleteShader(shader); + + ri.Error(ERR_FATAL, "Couldn't compile shader"); + return 0; + } + + return shader; +} + +static const char *GLSL_GetShaderFileSuffix( GLenum shaderType ) +{ + static struct + { + GLenum shaderType; + const char *extension; + } shaderToFileExtensionSuffix[] = { + { GL_VERTEX_SHADER, "vp" }, + { GL_FRAGMENT_SHADER, "fp" }, + { GL_GEOMETRY_SHADER, "gp" }, + }; + + for ( const auto& suffix : shaderToFileExtensionSuffix ) + { + if ( shaderType == suffix.shaderType ) + { + return suffix.extension; + } + } + + return nullptr; +} + +static size_t GLSL_LoadGPUShaderSource( + const char *name, + const char *fallback, + GLenum shaderType, + char *dest, + int destSize) +{ + const char *shaderSuffix = GLSL_GetShaderFileSuffix(shaderType); + assert(shaderSuffix != nullptr); + + char filename[MAX_QPATH]; + Com_sprintf(filename, sizeof(filename), "glsl/%s_%s.glsl", name, shaderSuffix); + + int shaderTextLen = 0; + GLcharARB *buffer = nullptr; + if ( r_externalGLSL->integer ) + { + shaderTextLen = ri.FS_ReadFile(filename, (void **)&buffer); + } + + const char *shaderText = nullptr; + if ( !buffer ) + { + if ( fallback ) + { + ri.Printf(PRINT_DEVELOPER, "...loading built-in '%s'\n", filename); + shaderText = fallback; + shaderTextLen = strlen(shaderText); + ri.Printf(PRINT_DEVELOPER, "...loading '%s'\n", filename); + } + else + { + ri.Printf(PRINT_DEVELOPER, "couldn't load '%s'\n", filename); + return 0; + } + } + else + { + ri.Printf(PRINT_DEVELOPER, "...loading '%s'\n", filename); + shaderText = buffer; + } + + int result = 0; + if ( destSize >= (shaderTextLen + 1) ) + { + Q_strncpyz(dest, shaderText, destSize); + result = strlen(dest); + } + + if ( buffer ) + { + ri.FS_FreeFile(buffer); + } + + return result; +} + +static void GLSL_LinkProgram(GLuint program) +{ + qglLinkProgram(program); + + GLint linked; + qglGetProgramiv(program, GL_LINK_STATUS, &linked); + if ( linked != GL_TRUE ) + { + GLSL_PrintProgramInfoLog(program, qfalse); + ri.Printf(PRINT_ALL, "\n"); + ri.Error(ERR_FATAL, "shaders failed to link"); + } +} + +static void GLSL_ShowProgramUniforms(GLuint program) +{ + int i, count, size; + GLenum type; + char uniformName[1000]; + + // install the executables in the program object as part of current state. + qglUseProgram(program); + + // check for GL Errors + + // query the number of active uniforms + qglGetProgramiv(program, GL_ACTIVE_UNIFORMS, &count); + + // Loop over each of the active uniforms, and set their value + for(i = 0; i < count; i++) + { + qglGetActiveUniform(program, i, sizeof(uniformName), NULL, &size, &type, uniformName); + + ri.Printf(PRINT_DEVELOPER, "active uniform: '%s'\n", uniformName); + } + + qglUseProgram(0); +} + +static void GLSL_BindShaderInterface( shaderProgram_t *program ) +{ + static const char *shaderInputNames[] = { + "attr_Position", // ATTR_INDEX_POSITION + "attr_TexCoord0", // ATTR_INDEX_TEXCOORD0 + "attr_TexCoord1", // ATTR_INDEX_TEXCOORD1 + "attr_TexCoord2", // ATTR_INDEX_TEXCOORD2 + "attr_TexCoord3", // ATTR_INDEX_TEXCOORD3 + "attr_TexCoord4", // ATTR_INDEX_TEXCOORD4 + "attr_Tangent", // ATTR_INDEX_TANGENT + "attr_Normal", // ATTR_INDEX_NORMAL + "attr_Color", // ATTR_INDEX_COLOR + "attr_LightDirection", // ATTR_INDEX_LIGHTDIRECTION + "attr_BoneIndexes", // ATTR_INDEX_BONE_INDEXES + "attr_BoneWeights", // ATTR_INDEX_BONE_WEIGHTS + "attr_Position2", // ATTR_INDEX_POSITION2 + "attr_Tangent2", // ATTR_INDEX_TANGENT2 + "attr_Normal2", // ATTR_INDEX_NORMAL2 + }; + + static const char *xfbVarNames[XFB_VAR_COUNT] = { + "var_Position", + "var_Velocity", + }; + + static const char *shaderOutputNames[] = { + "out_Color", // Color output + "out_Glow", // Glow output + }; + + const uint32_t attribs = program->attribs; + if (attribs != 0) + { + for ( int attribIndex = 0; attribIndex < ATTR_INDEX_MAX; ++attribIndex ) + { + if ( !(attribs & (1u << attribIndex)) ) + { + continue; + } + + qglBindAttribLocation(program->program, attribIndex, shaderInputNames[attribIndex]); + } + } + + for ( int outputIndex = 0; outputIndex < ARRAY_LEN(shaderOutputNames); ++outputIndex ) + { + qglBindFragDataLocation(program->program, outputIndex, shaderOutputNames[outputIndex]); + } + + const uint32_t xfbVars = program->xfbVariables; + if (xfbVars != 0) + { + size_t activeXfbVarsCount = 0; + const char *activeXfbVarNames[XFB_VAR_COUNT] = {}; + + for (uint32_t xfbVarIndex = 0; xfbVarIndex < XFB_VAR_COUNT; ++xfbVarIndex) + { + if ((xfbVars & (1u << xfbVarIndex)) != 0) + { + activeXfbVarNames[activeXfbVarsCount++] = xfbVarNames[xfbVarIndex]; + } + } + + qglTransformFeedbackVaryings( + program->program, activeXfbVarsCount, activeXfbVarNames, GL_INTERLEAVED_ATTRIBS); + } +} + +GLenum ToGLShaderType( GPUShaderType type ) +{ + switch ( type ) + { + case GPUSHADER_VERTEX: + return GL_VERTEX_SHADER; + + case GPUSHADER_FRAGMENT: + return GL_FRAGMENT_SHADER; + + case GPUSHADER_GEOMETRY: + return GL_GEOMETRY_SHADER; + + default: + assert(!"Invalid shader type"); + return 0; + } + + return 0; +} + +class ShaderProgramBuilder +{ + public: + ShaderProgramBuilder(); + ~ShaderProgramBuilder(); + + ShaderProgramBuilder(const ShaderProgramBuilder&) = delete; + ShaderProgramBuilder& operator=(const ShaderProgramBuilder&) = delete; + + void Start( + const char *name, + const uint32_t attribs, + const uint32_t xfbVariables); + bool AddShader(const GPUShaderDesc& shaderDesc, const char *extra); + bool Build(shaderProgram_t *program); + + private: + static const size_t MAX_SHADER_SOURCE_LEN = 16384; + + void ReleaseShaders(); + + const char *name; + uint32_t attribs; + uint32_t xfbVariables; + GLuint program; + GLuint shaderNames[GPUSHADER_TYPE_COUNT]; + size_t numShaderNames; + std::string shaderSource; +}; + +ShaderProgramBuilder::ShaderProgramBuilder() + : name(nullptr) + , attribs(0) + , program(0) + , shaderNames() + , numShaderNames(0) + , shaderSource(MAX_SHADER_SOURCE_LEN, '\0') +{ +} + +ShaderProgramBuilder::~ShaderProgramBuilder() +{ + if ( program ) + { + ReleaseShaders(); + qglDeleteProgram(program); + } +} + +void ShaderProgramBuilder::Start( + const char *name, + const uint32_t attribs, + const uint32_t xfbVariables) +{ + this->program = qglCreateProgram(); + this->name = name; + this->attribs = attribs; + this->xfbVariables = xfbVariables; +} + +bool ShaderProgramBuilder::AddShader( const GPUShaderDesc& shaderDesc, const char *extra ) +{ + static const int MAX_ATTEMPTS = 3; + const GLenum apiShader = ToGLShaderType(shaderDesc.type); + + size_t sourceLen = 0; + size_t headerLen = 0; + int attempts = 0; + while ( sourceLen == 0 && attempts < MAX_ATTEMPTS ) + { + headerLen = GLSL_GetShaderHeader( + apiShader, + extra, + shaderDesc.firstLineNumber, + &shaderSource[0], + shaderSource.size()); + + sourceLen = GLSL_LoadGPUShaderSource( + name, + shaderDesc.source, + apiShader, + &shaderSource[headerLen], + shaderSource.size() - headerLen); + + if ( sourceLen == 0 ) + { + shaderSource.resize(shaderSource.size() * 2); + } + + ++attempts; + } + + if ( sourceLen == 0 ) + { + ri.Printf( + PRINT_ALL, + "ShaderProgramBuilder::AddShader: Failed to allocate enough memory for " + "shader '%s'\n", + name); + + return false; + } + + const GLuint shader = GLSL_CompileGPUShader( + program, + shaderSource.c_str(), + sourceLen + headerLen, + apiShader); + if ( shader == 0 ) + { + ri.Printf( + PRINT_ALL, + "ShaderProgramBuilder::AddShader: Unable to load \"%s\"\n", + name); + return false; + } + + qglAttachShader(program, shader); + shaderNames[numShaderNames++] = shader; + + return true; +} + +bool ShaderProgramBuilder::Build( shaderProgram_t *shaderProgram ) +{ + const size_t nameBufferSize = strlen(name) + 1; + shaderProgram->name = (char *)Z_Malloc(nameBufferSize, TAG_GENERAL); + Q_strncpyz(shaderProgram->name, name, nameBufferSize); + + shaderProgram->program = program; + shaderProgram->attribs = attribs; + shaderProgram->xfbVariables = xfbVariables; + + GLSL_BindShaderInterface(shaderProgram); + GLSL_LinkProgram(shaderProgram->program); + + ReleaseShaders(); + program = 0; + + return true; +} + +void ShaderProgramBuilder::ReleaseShaders() +{ + for ( size_t i = 0; i < numShaderNames; ++i ) + { + qglDetachShader(program, shaderNames[i]); + qglDeleteShader(shaderNames[i]); + } + + numShaderNames = 0; +} + +static bool GLSL_LoadGPUShader( + ShaderProgramBuilder& builder, + shaderProgram_t *program, + const char *name, + const uint32_t attribs, + const uint32_t xfbVariables, + const GLcharARB *extra, + const GPUProgramDesc& programDesc) +{ + builder.Start(name, attribs, xfbVariables); + for ( int i = 0; i < programDesc.numShaders; ++i ) + { + const GPUShaderDesc& shaderDesc = programDesc.shaders[i]; + if ( !builder.AddShader(shaderDesc, extra) ) + { + return false; + } + } + return builder.Build(program); +} + +void GLSL_InitUniforms(shaderProgram_t *program) +{ + program->uniforms = (GLint *)Z_Malloc( + UNIFORM_COUNT * sizeof(*program->uniforms), TAG_GENERAL); + program->uniformBufferOffsets = (short *)Z_Malloc( + UNIFORM_COUNT * sizeof(*program->uniformBufferOffsets), TAG_GENERAL); + + GLint *uniforms = program->uniforms; + int size = 0; + for (int i = 0; i < UNIFORM_COUNT; i++) + { + uniforms[i] = qglGetUniformLocation(program->program, uniformsInfo[i].name); + if (uniforms[i] == -1) + continue; + + program->uniformBufferOffsets[i] = size; + switch(uniformsInfo[i].type) + { + case GLSL_INT: + size += sizeof(GLint) * uniformsInfo[i].size; + break; + case GLSL_FLOAT: + size += sizeof(GLfloat) * uniformsInfo[i].size; + break; + case GLSL_VEC2: + size += sizeof(float) * 2 * uniformsInfo[i].size; + break; + case GLSL_VEC3: + size += sizeof(float) * 3 * uniformsInfo[i].size; + break; + case GLSL_VEC4: + size += sizeof(float) * 4 * uniformsInfo[i].size; + break; + case GLSL_MAT4x3: + size += sizeof(float) * 12 * uniformsInfo[i].size; + break; + case GLSL_MAT4x4: + size += sizeof(float) * 16 * uniformsInfo[i].size; + break; + default: + break; + } + } + + program->uniformBuffer = (char *)Z_Malloc(size, TAG_SHADERTEXT, qtrue); + + program->uniformBlocks = 0; + for ( int i = 0; i < UNIFORM_BLOCK_COUNT; ++i ) + { + const GLuint blockIndex = qglGetUniformBlockIndex( + program->program, uniformBlocksInfo[i].name); + if (blockIndex == GL_INVALID_INDEX) + continue; + ri.Printf( + PRINT_DEVELOPER, + "Binding block %d (name '%s', size %zu bytes) to slot %d\n", + blockIndex, + uniformBlocksInfo[i].name, + uniformBlocksInfo[i].size, + uniformBlocksInfo[i].slot); + qglUniformBlockBinding( + program->program, blockIndex, uniformBlocksInfo[i].slot); + program->uniformBlocks |= (1u << i); + } + + GLint numActiveUniformBlocks = 0; + qglGetProgramiv(program->program, GL_ACTIVE_UNIFORM_BLOCKS, &numActiveUniformBlocks); + ri.Printf(PRINT_DEVELOPER, "..num uniform blocks: %d\n", numActiveUniformBlocks); + for (int i = 0; i < numActiveUniformBlocks; ++i) + { + char blockName[512]; + qglGetActiveUniformBlockName( + program->program, + i, + sizeof(blockName), + nullptr, + blockName); + + GLint blockSize = 0; + qglGetActiveUniformBlockiv( + program->program, i, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize); + + ri.Printf(PRINT_DEVELOPER, "..block %d: %s (%d bytes)\n", i, blockName, blockSize); + GLint numMembers = 0; + qglGetActiveUniformBlockiv( + program->program, i, GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS, &numMembers); + + if (numMembers > 0) + { + GLuint memberIndices[128]; + qglGetActiveUniformBlockiv( + program->program, + i, + GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, + (GLint *)memberIndices); + + GLint memberOffsets[128]; + qglGetActiveUniformsiv( + program->program, + numMembers, + memberIndices, + GL_UNIFORM_OFFSET, + memberOffsets); + + GLint memberTypes[128]; + qglGetActiveUniformsiv( + program->program, + numMembers, + memberIndices, + GL_UNIFORM_TYPE, + memberTypes); + + for (int j = 0; j < numMembers; ++j) + { + char memberName[512]; + qglGetActiveUniformName( + program->program, + memberIndices[j], + sizeof(memberName), + nullptr, + memberName); + + ri.Printf(PRINT_DEVELOPER, "....uniform '%s'\n", memberName); + ri.Printf(PRINT_DEVELOPER, "......offset: %d\n", memberOffsets[j]); + switch (memberTypes[j]) + { + case GL_FLOAT: + ri.Printf(PRINT_DEVELOPER, "......type: float\n"); + break; + case GL_FLOAT_VEC2: + ri.Printf(PRINT_DEVELOPER, "......type: vec2\n"); + break; + case GL_FLOAT_VEC3: + ri.Printf(PRINT_DEVELOPER, "......type: vec3\n"); + break; + case GL_FLOAT_VEC4: + ri.Printf(PRINT_DEVELOPER, "......type: vec4\n"); + break; + case GL_INT: + ri.Printf(PRINT_DEVELOPER, "......type: int\n"); + break; + default: + ri.Printf(PRINT_DEVELOPER, "......type: other\n"); + break; + } + } + } + } +} + +void GLSL_FinishGPUShader(shaderProgram_t *program) +{ +#if defined(_DEBUG) + GLSL_ShowProgramUniforms(program->program); + GL_CheckErrors(); +#endif +} + +void GLSL_SetUniforms( shaderProgram_t *program, UniformData *uniformData ) +{ + if (uniformData == nullptr) + return; + + UniformData *data = uniformData; + if (data == nullptr) + return; + + while ( data->index != UNIFORM_COUNT ) + { + switch ( uniformsInfo[data->index].type ) + { + case GLSL_INT: + { + assert(data->numElements == 1); + GLint *value = (GLint *)(data + 1); + GLSL_SetUniformInt(program, data->index, *value); + data = reinterpret_cast(value + data->numElements); + break; + } + + case GLSL_FLOAT: + { + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformFloatN(program, data->index, value, data->numElements); + data = reinterpret_cast(value + data->numElements); + break; + } + + case GLSL_VEC2: + { + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformVec2N(program, data->index, value, data->numElements); + data = reinterpret_cast(value + data->numElements*2); + break; + } + + case GLSL_VEC3: + { + assert(data->numElements == 1); + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformVec3(program, data->index, value); + data = reinterpret_cast(value + data->numElements*3); + break; + } + + case GLSL_VEC4: + { + assert(data->numElements == 1); + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformVec4(program, data->index, value); + data = reinterpret_cast(value + data->numElements*4); + break; + } + + case GLSL_MAT4x3: + { + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformMatrix4x3(program, data->index, value, data->numElements); + data = reinterpret_cast(value + data->numElements*12); + break; + } + + case GLSL_MAT4x4: + { + GLfloat *value = (GLfloat *)(data + 1); + GLSL_SetUniformMatrix4x4(program, data->index, value, data->numElements); + data = reinterpret_cast(value + data->numElements*16); + break; + } + + default: + { + assert(!"Invalid uniform data type"); + return; + } + } + } +} + +void GLSL_SetUniformInt(shaderProgram_t *program, int uniformNum, GLint value) +{ + GLint *uniforms = program->uniforms; + GLint *compare = (GLint *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_INT) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformInt: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (value == *compare) + { + return; + } + + *compare = value; + + qglUniform1i(uniforms[uniformNum], value); +} + +void GLSL_SetUniformFloat(shaderProgram_t *program, int uniformNum, GLfloat value) +{ + GLint *uniforms = program->uniforms; + GLfloat *compare = (GLfloat *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_FLOAT) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformFloat: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (value == *compare) + { + return; + } + + *compare = value; + + qglUniform1f(uniforms[uniformNum], value); +} + +void GLSL_SetUniformVec2(shaderProgram_t *program, int uniformNum, const vec2_t v) +{ + GLint *uniforms = program->uniforms; + float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_VEC2) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformVec2: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (v[0] == compare[0] && v[1] == compare[1]) + { + return; + } + + compare[0] = v[0]; + compare[1] = v[1]; + + qglUniform2f(uniforms[uniformNum], v[0], v[1]); +} + +void GLSL_SetUniformVec2N(shaderProgram_t *program, int uniformNum, const float *v, int numVec2s) +{ + GLint *uniforms = program->uniforms; + float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_VEC2) + { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformVec2: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (uniformsInfo[uniformNum].size < numVec2s) + { + ri.Printf(PRINT_WARNING, "GLSL_SetUniformVec2N: uniform %i only has %d elements! Tried to set %d\n", + uniformNum, + uniformsInfo[uniformNum].size, + numVec2s); + return; + } + + if (memcmp(compare, v, sizeof(vec2_t) * numVec2s) == 0) + { + return; + } + + memcpy(compare, v, sizeof(vec2_t) * numVec2s); + + qglUniform2fv(uniforms[uniformNum], numVec2s, v); +} + +void GLSL_SetUniformVec3(shaderProgram_t *program, int uniformNum, const vec3_t v) +{ + GLint *uniforms = program->uniforms; + float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_VEC3) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformVec3: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (VectorCompare(v, compare)) + { + return; + } + + VectorCopy(v, compare); + + qglUniform3f(uniforms[uniformNum], v[0], v[1], v[2]); +} + +void GLSL_SetUniformVec4(shaderProgram_t *program, int uniformNum, const vec4_t v) +{ + GLint *uniforms = program->uniforms; + float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_VEC4) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformVec4: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (VectorCompare4(v, compare)) + { + return; + } + + VectorCopy4(v, compare); + + qglUniform4f(uniforms[uniformNum], v[0], v[1], v[2], v[3]); +} + +void GLSL_SetUniformFloatN(shaderProgram_t *program, int uniformNum, const float *v, int numFloats) +{ + GLint *uniforms = program->uniforms; + float *compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_FLOAT) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformFloatN: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (uniformsInfo[uniformNum].size < numFloats) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformFloatN: uniform %i only has %d elements! Tried to set %d\n", + uniformNum, + uniformsInfo[uniformNum].size, + numFloats ); + return; + } + + if ( memcmp( compare, v, sizeof( float ) * numFloats ) == 0 ) + { + return; + } + + memcpy( compare, v, sizeof( float ) * numFloats ); + + qglUniform1fv(uniforms[uniformNum], numFloats, v); +} + +void GLSL_SetUniformMatrix4x3(shaderProgram_t *program, int uniformNum, const float *matrix, int numElements) +{ + GLint *uniforms = program->uniforms; + float *compare; + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_MAT4x3) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformMatrix4x3: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (uniformsInfo[uniformNum].size < numElements) + return; + + compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + if (memcmp (matrix, compare, sizeof (float) * 12 * numElements) == 0) + { + return; + } + + Com_Memcpy (compare, matrix, sizeof (float) * 12 * numElements); + + qglUniformMatrix4x3fv(uniforms[uniformNum], numElements, GL_FALSE, matrix); +} + +void GLSL_SetUniformMatrix4x4(shaderProgram_t *program, int uniformNum, const float *matrix, int numElements) +{ + GLint *uniforms = program->uniforms; + float *compare; + + if (uniforms[uniformNum] == -1) + return; + + if (uniformsInfo[uniformNum].type != GLSL_MAT4x4) + { + ri.Printf( PRINT_WARNING, "GLSL_SetUniformMatrix4x4: wrong type for uniform %i in program %s\n", uniformNum, program->name); + return; + } + + if (uniformsInfo[uniformNum].size < numElements) + return; + + compare = (float *)(program->uniformBuffer + program->uniformBufferOffsets[uniformNum]); + if (memcmp (matrix, compare, sizeof (float) * 16 * numElements) == 0) + { + return; + } + + Com_Memcpy (compare, matrix, sizeof (float) * 16 * numElements); + + qglUniformMatrix4fv(uniforms[uniformNum], numElements, GL_FALSE, matrix); +} + +void GLSL_DeleteGPUShader(shaderProgram_t *program) +{ + if(program->program) + { + qglDeleteProgram(program->program); + + Z_Free (program->name); + Z_Free (program->uniformBuffer); + Z_Free (program->uniformBufferOffsets); + Z_Free (program->uniforms); + + Com_Memset(program, 0, sizeof(*program)); + } +} + +static bool GLSL_IsValidPermutationForGeneric (int shaderCaps) +{ +#ifdef REND2_SP + if ( (shaderCaps & GENERICDEF_USE_VERTEX_ANIMATION) && + (shaderCaps & GENERICDEF_USE_SKELETAL_ANIMATION) ) + return false; +#endif // REND2_SP + return true; +} + +static bool GLSL_IsValidPermutationForFog (int shaderCaps) +{ +#ifdef REND2_SP + if ( (shaderCaps & FOGDEF_USE_VERTEX_ANIMATION) && + (shaderCaps & FOGDEF_USE_SKELETAL_ANIMATION) ) + return false; +#endif // REND2_SP + return true; +} + +static bool GLSL_IsValidPermutationForLight (int lightType, int shaderCaps) +{ + if ((shaderCaps & LIGHTDEF_USE_PARALLAXMAP) && !r_parallaxMapping->integer) + return false; + + if (!lightType && (shaderCaps & LIGHTDEF_USE_PARALLAXMAP)) + return false; + +#ifdef REND2_SP + if ( (shaderCaps & LIGHTDEF_USE_SKELETAL_ANIMATION) && + (shaderCaps & LIGHTDEF_USE_VERTEX_ANIMATION) ) + return false; +#endif // REND2_SP + return true; +} + +Block *FindBlock( const char *name, Block *blocks, size_t numBlocks ) +{ + for ( size_t i = 0; i < numBlocks; ++i ) + { + Block *block = blocks + i; + if ( Q_stricmpn(block->blockHeaderTitle, name, block->blockHeaderTitleLength) == 0 ) + { + return block; + } + } + + return nullptr; +} + +void GLSL_InitSplashScreenShader() +{ + const char *vs = + "#version 150 core\n" + "out vec2 var_TexCoords;\n" + "void main() {\n" + " vec2 position = vec2(2.0 * float(gl_VertexID & 2) - 1.0, 4.0 * float(gl_VertexID & 1) - 1.0);\n" + " gl_Position = vec4(position, 0.0, 1.0);\n" + " var_TexCoords = vec2(position.x * 0.5 + 0.5, 2.0 - (position.y * 0.5 + 0.5));\n" + "}"; + + const char *fs = + "#version 150 core\n" + "uniform sampler2D u_SplashTexture;\n" + "in vec2 var_TexCoords;\n" + "out vec4 out_Color;\n" + "void main() {\n" + " out_Color = texture(u_SplashTexture, var_TexCoords);\n" + "}"; + + GLuint vshader = qglCreateShader(GL_VERTEX_SHADER); + qglShaderSource(vshader, 1, &vs, NULL); + qglCompileShader(vshader); + + GLuint fshader = qglCreateShader(GL_FRAGMENT_SHADER); + qglShaderSource(fshader, 1, &fs, NULL); + qglCompileShader(fshader); + + GLuint program = qglCreateProgram(); + qglAttachShader(program, vshader); + qglAttachShader(program, fshader); + qglLinkProgram(program); + + size_t splashLen = strlen("splash"); + tr.splashScreenShader.program = program; + tr.splashScreenShader.name = (char *)Z_Malloc(splashLen + 1, TAG_GENERAL); + Q_strncpyz(tr.splashScreenShader.name, "splash", splashLen + 1); +} + +static const GPUProgramDesc *LoadProgramSource( + const char *programName, Allocator& allocator, const GPUProgramDesc& fallback ) +{ + const GPUProgramDesc *result = &fallback; + + if ( r_externalGLSL->integer ) + { + char *buffer; + char programPath[MAX_QPATH]; + Com_sprintf(programPath, sizeof(programPath), "glsl/%s.glsl", programName); + + long size = ri.FS_ReadFile(programPath, (void **)&buffer); + if ( size ) + { + GPUProgramDesc *externalProgramDesc = ojkAlloc(allocator); + *externalProgramDesc = ParseProgramSource(allocator, buffer); + result = externalProgramDesc; + ri.FS_FreeFile(buffer); + } + } + + return result; +} + +static int GLSL_LoadGPUProgramGeneric( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + int numPrograms = 0; + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("generic", allocator, fallback_genericProgram); + for ( int i = 0; i < GENERICDEF_COUNT; i++ ) + { + if (!GLSL_IsValidPermutationForGeneric(i)) + { + continue; + } + + uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0 | ATTR_NORMAL | ATTR_COLOR; + extradefines[0] = '\0'; + + if (i & GENERICDEF_USE_DEFORM_VERTEXES) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_DEFORM_VERTEXES\n"); + + if (i & GENERICDEF_USE_TCGEN_AND_TCMOD) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCGEN\n"); + Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCMOD\n"); + } +#ifdef REND2_SP + if (i & GENERICDEF_USE_VERTEX_ANIMATION) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTEX_ANIMATION\n"); + attribs |= ATTR_POSITION2 | ATTR_NORMAL2; + } +#endif // REND2_SP + if (i & GENERICDEF_USE_SKELETAL_ANIMATION) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); + attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; + } + + if (i & GENERICDEF_USE_FOG) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_FOG\n"); + + if (i & GENERICDEF_USE_RGBAGEN) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_RGBAGEN\n"); + + if (i & GENERICDEF_USE_GLOW_BUFFER) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_GLOW_BUFFER\n"); + + if (i & GENERICDEF_USE_ALPHA_TEST) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_ALPHA_TEST\n"); + + if (!GLSL_LoadGPUShader(builder, &tr.genericShader[i], "generic", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load generic shader!"); + } + + GLSL_InitUniforms(&tr.genericShader[i]); + + qglUseProgram(tr.genericShader[i].program); + GLSL_SetUniformInt(&tr.genericShader[i], UNIFORM_DIFFUSEMAP, TB_DIFFUSEMAP); + GLSL_SetUniformInt(&tr.genericShader[i], UNIFORM_LIGHTMAP, TB_LIGHTMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.genericShader[i]); + + ++numPrograms; + } + + return numPrograms; +} + +static int GLSL_LoadGPUProgramFogPass( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + int numPrograms = 0; + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("fogpass", allocator, fallback_fogpassProgram); + for (int i = 0; i < FOGDEF_COUNT; i++) + { + if (!GLSL_IsValidPermutationForFog(i)) + { + continue; + } + + uint32_t attribs = + (ATTR_POSITION | ATTR_NORMAL | ATTR_TEXCOORD0); + extradefines[0] = '\0'; + + if (i & FOGDEF_USE_DEFORM_VERTEXES) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_DEFORM_VERTEXES\n"); +#ifdef REND2_SP + if (i & FOGDEF_USE_VERTEX_ANIMATION) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTEX_ANIMATION\n"); + attribs |= ATTR_POSITION2 | ATTR_NORMAL2 + } +#endif // REND2_SP + if (i & FOGDEF_USE_SKELETAL_ANIMATION) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); + attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; + } + + if (i & FOGDEF_USE_FALLBACK_GLOBAL_FOG) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_FALLBACK_GLOBAL_FOG\n"); + + if (i & FOGDEF_USE_ALPHA_TEST) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_ALPHA_TEST\n"); + + if (!GLSL_LoadGPUShader(builder, &tr.fogShader[i], "fogpass", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load fogpass shader!"); + } + + GLSL_InitUniforms(&tr.fogShader[i]); + + qglUseProgram(tr.fogShader[i].program); + if (i & FOGDEF_USE_ALPHA_TEST) + GLSL_SetUniformInt(&tr.fogShader[i], UNIFORM_DIFFUSEMAP, 0); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.fogShader[i]); + + ++numPrograms; + } + + return numPrograms; +} + +static int GLSL_LoadGPUProgramRefraction( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc) +{ + int numPrograms = 0; + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("refraction", allocator, fallback_refractionProgram); + for (int i = 0; i < REFRACTIONDEF_COUNT; i++) + { + uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0 | ATTR_NORMAL | ATTR_COLOR; + extradefines[0] = '\0'; + + if (i & REFRACTIONDEF_USE_DEFORM_VERTEXES) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_DEFORM_VERTEXES\n"); + + if (i & REFRACTIONDEF_USE_TCGEN_AND_TCMOD) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCGEN\n"); + Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCMOD\n"); + } +#ifdef REND2_SP + if (i & REFRACTIONDEF_USE_VERTEX_ANIMATION) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTEX_ANIMATION\n"); + attribs |= ATTR_POSITION2 | ATTR_NORMAL2; + } +#endif // REND2_SP + if (i & REFRACTIONDEF_USE_SKELETAL_ANIMATION) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); + attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; + } + + if (i & REFRACTIONDEF_USE_RGBAGEN) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_RGBAGEN\n"); + + if (i & REFRACTIONDEF_USE_ALPHA_TEST) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_ALPHA_TEST\n"); + + if (i & REFRACTIONDEF_USE_SRGB_TRANSFORM) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LINEAR_LIGHT\n"); + + if (!GLSL_LoadGPUShader(builder, &tr.refractionShader[i], "refraction", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load refraction shader!"); + } + + GLSL_InitUniforms(&tr.refractionShader[i]); + + qglUseProgram(tr.refractionShader[i].program); + GLSL_SetUniformInt(&tr.refractionShader[i], UNIFORM_TEXTUREMAP, TB_COLORMAP); + GLSL_SetUniformInt(&tr.refractionShader[i], UNIFORM_LEVELSMAP, TB_LEVELSMAP); + GLSL_SetUniformInt(&tr.refractionShader[i], UNIFORM_SCREENDEPTHMAP, TB_SHADOWMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.refractionShader[i]); + + ++numPrograms; + } + + return numPrograms; +} + +static int GLSL_LoadGPUProgramLightAll( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + int numPrograms = 0; + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("lightall", allocator, fallback_lightallProgram); + const bool useFastLight = + (!r_normalMapping->integer && !r_specularMapping->integer); + for ( int i = 0; i < LIGHTDEF_COUNT; i++ ) + { + int lightType = i & LIGHTDEF_LIGHTTYPE_MASK; + + // skip impossible combos + if (!GLSL_IsValidPermutationForLight (lightType, i)) + continue; + + uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0 | ATTR_COLOR | ATTR_NORMAL; + + extradefines[0] = '\0'; + + if (r_hdr->integer && !glRefConfig.floatLightmap) + Q_strcat(extradefines, sizeof(extradefines), "#define RGBM_LIGHTMAP\n"); + + if (lightType) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHT\n"); + + if (useFastLight) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_FAST_LIGHT\n"); + + if (r_dlightMode->integer >= 2) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_DSHADOWS\n"); + + switch (lightType) + { + case LIGHTDEF_USE_LIGHTMAP: + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHTMAP\n"); + + if (r_deluxeMapping->integer && !useFastLight) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_DELUXEMAP\n"); + + attribs |= ATTR_TEXCOORD1 | ATTR_LIGHTDIRECTION; + break; + } + + case LIGHTDEF_USE_LIGHT_VECTOR: + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHT_VECTOR\n"); + break; + } + + case LIGHTDEF_USE_LIGHT_VERTEX: + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LIGHT_VERTEX\n"); + attribs |= ATTR_LIGHTDIRECTION; + break; + } + + default: + break; + } + + if (r_normalMapping->integer) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_NORMALMAP\n"); + + if ((i & LIGHTDEF_USE_PARALLAXMAP) && r_parallaxMapping->integer) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_PARALLAXMAP\n"); + + attribs |= ATTR_TANGENT; + } + + if (r_specularMapping->integer) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SPECULARMAP\n"); + if (i & LIGHTDEF_USE_SPEC_GLOSS) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SPECGLOSS\n"); + } + + if (r_cubeMapping->integer) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_CUBEMAP\n"); + } + + if (r_sunlightMode->integer) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SHADOWMAP\n"); + + if (r_sunlightMode->integer == 1) + Q_strcat(extradefines, sizeof(extradefines), "#define SHADOWMAP_MODULATE\n"); + else if (r_sunlightMode->integer == 2) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_PRIMARY_LIGHT\n"); + + if (r_shadowFilter->integer >= 1) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SHADOW_FILTER\n"); + + if (r_shadowFilter->integer >= 2) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SHADOW_FILTER2\n"); + + Q_strcat( + extradefines, sizeof(extradefines), + va("#define r_shadowMapSize %d\n", r_shadowMapSize->integer)); + Q_strcat( + extradefines, sizeof(extradefines), + va("#define r_shadowCascadeZFar %f\n", r_shadowCascadeZFar->value)); + } + + if (i & LIGHTDEF_USE_TCGEN_AND_TCMOD) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCGEN\n"); + Q_strcat(extradefines, sizeof(extradefines), "#define USE_TCMOD\n"); + } + + if (i & LIGHTDEF_USE_CLOTH_BRDF) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_CLOTH_BRDF\n"); + } +#ifdef REND2_SP + if (i & LIGHTDEF_USE_VERTEX_ANIMATION) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTEX_ANIMATION\n"); + attribs |= ATTR_POSITION2 | ATTR_NORMAL2; + + if (r_normalMapping->integer) + attribs |= ATTR_TANGENT2; + } + else +#endif // REND2_SP + if (i & LIGHTDEF_USE_SKELETAL_ANIMATION) + { + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); + attribs |= ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; + } + + if (i & LIGHTDEF_USE_ALPHA_TEST) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_ALPHA_TEST\n"); + + if (i & LIGHTDEF_USE_GLOW_BUFFER) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_GLOW_BUFFER\n"); + + if (!GLSL_LoadGPUShader(builder, &tr.lightallShader[i], "lightall", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load lightall shader!"); + } + + GLSL_InitUniforms(&tr.lightallShader[i]); + + qglUseProgram(tr.lightallShader[i].program); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_DIFFUSEMAP, TB_DIFFUSEMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_LIGHTMAP, TB_LIGHTMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_NORMALMAP, TB_NORMALMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_DELUXEMAP, TB_DELUXEMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SPECULARMAP, TB_SPECULARMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SHADOWMAP, TB_SHADOWMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_CUBEMAP, TB_CUBEMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_ENVBRDFMAP, TB_ENVBRDFMAP); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SHADOWMAP2, TB_SHADOWMAPARRAY); + GLSL_SetUniformInt(&tr.lightallShader[i], UNIFORM_SSAOMAP, TB_SSAOMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.lightallShader[i]); + + ++numPrograms; + } + + return numPrograms; +} + +static int GLSL_LoadGPUProgramBasicWithDefinitions( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc, + shaderProgram_t *shaderProgram, + const char *programName, + const GPUProgramDesc& programFallback, + const char *extraDefines, + const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0, + const uint32_t xfbVariables = NO_XFB_VARS) +{ + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + const GPUProgramDesc *programDesc = + LoadProgramSource(programName, allocator, programFallback); + if (!GLSL_LoadGPUShader( + builder, + shaderProgram, + programName, + attribs, + xfbVariables, + extraDefines, + *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load %s shader!", programName); + } + + return 1; +} + +static int GLSL_LoadGPUProgramBasic( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc, + shaderProgram_t *shaderProgram, + const char *programName, + const GPUProgramDesc& programFallback, + const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0, + const uint32_t xfbVariables = NO_XFB_VARS) +{ + return GLSL_LoadGPUProgramBasicWithDefinitions( + builder, + scratchAlloc, + shaderProgram, + programName, + programFallback, + nullptr, + attribs, + xfbVariables); +} + +static int GLSL_LoadGPUProgramTextureColor( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.textureColorShader, + "texturecolor", + fallback_texturecolorProgram); + + GLSL_InitUniforms(&tr.textureColorShader); + + qglUseProgram(tr.textureColorShader.program); + GLSL_SetUniformInt(&tr.textureColorShader, UNIFORM_TEXTUREMAP, TB_DIFFUSEMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.textureColorShader); + + return 1; +} + +static int GLSL_LoadGPUProgramPShadow( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + const char *extradefines = "#define USE_PCF\n#define USE_DISCARD\n"; + + GLSL_LoadGPUProgramBasicWithDefinitions( + builder, + scratchAlloc, + &tr.pshadowShader, + "pshadow", + fallback_pshadowProgram, + extradefines, + ATTR_POSITION | ATTR_NORMAL); + + GLSL_InitUniforms(&tr.pshadowShader); + + qglUseProgram(tr.pshadowShader.program); + GLSL_SetUniformInt(&tr.pshadowShader, UNIFORM_SHADOWMAP, TB_DIFFUSEMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.pshadowShader); + + return 1; +} + +static int GLSL_LoadGPUProgramVShadow( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc) +{ + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("shadowvolume", allocator, fallback_shadowvolumeProgram); + const uint32_t attribs = ATTR_POSITION | ATTR_BONE_INDEXES | ATTR_BONE_WEIGHTS; + + extradefines[0] = '\0'; + Q_strcat(extradefines, sizeof(extradefines), "#define USE_SKELETAL_ANIMATION\n"); + + if (!GLSL_LoadGPUShader(builder, &tr.volumeShadowShader, "shadowvolume", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load shadowvolume shader!"); + } + + GLSL_InitUniforms(&tr.volumeShadowShader); + GLSL_FinishGPUShader(&tr.volumeShadowShader); + + return 1; +} + +static int GLSL_LoadGPUProgramDownscale4x( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.down4xShader, + "down4x", + fallback_down4xProgram); + + GLSL_InitUniforms(&tr.down4xShader); + + qglUseProgram(tr.down4xShader.program); + GLSL_SetUniformInt(&tr.down4xShader, UNIFORM_TEXTUREMAP, TB_DIFFUSEMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.down4xShader); + + return 1; +} + +static int GLSL_LoadGPUProgramBokeh( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.bokehShader, + "bokeh", + fallback_bokehProgram); + + GLSL_InitUniforms(&tr.bokehShader); + + qglUseProgram(tr.bokehShader.program); + GLSL_SetUniformInt(&tr.bokehShader, UNIFORM_TEXTUREMAP, TB_DIFFUSEMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.bokehShader); + + return 1; +} + +static int GLSL_LoadGPUProgramTonemap( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("tonemap", allocator, fallback_tonemapProgram); + const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0; + + extradefines[0] = '\0'; + if (!GLSL_LoadGPUShader(builder, &tr.tonemapShader[0], "tonemap", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load tonemap shader!"); + } + + Q_strcat(extradefines, sizeof(extradefines), "#define USE_LINEAR_LIGHT\n"); + if (!GLSL_LoadGPUShader(builder, &tr.tonemapShader[1], "tonemap", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load tonemap shader!"); + } + + for (int i = 0; i < 2; i++) + { + GLSL_InitUniforms(&tr.tonemapShader[i]); + qglUseProgram(tr.tonemapShader[i].program); + GLSL_SetUniformInt(&tr.tonemapShader[i], UNIFORM_TEXTUREMAP, TB_COLORMAP); + GLSL_SetUniformInt(&tr.tonemapShader[i], UNIFORM_LEVELSMAP, TB_LEVELSMAP); + qglUseProgram(0); + GLSL_FinishGPUShader(&tr.tonemapShader[i]); + } + return 2; +} + +static int GLSL_LoadGPUProgramCalcLuminanceLevel( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + int numPrograms = 0; + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("calclevels4x", allocator, fallback_calclevels4xProgram); + for ( int i = 0; i < 2; i++ ) + { + const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0; + extradefines[0] = '\0'; + + if (!i) + Q_strcat(extradefines, sizeof(extradefines), "#define FIRST_PASS\n"); + + if (!GLSL_LoadGPUShader(builder, &tr.calclevels4xShader[i], "calclevels4x", attribs, + NO_XFB_VARS, extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load calclevels4x shader!"); + } + + GLSL_InitUniforms(&tr.calclevels4xShader[i]); + + qglUseProgram(tr.calclevels4xShader[i].program); + GLSL_SetUniformInt(&tr.calclevels4xShader[i], UNIFORM_TEXTUREMAP, TB_DIFFUSEMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.calclevels4xShader[i]); + + ++numPrograms; + } + + return numPrograms; +} + +static int GLSL_LoadGPUProgramSSAO( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.ssaoShader, + "ssao", + fallback_ssaoProgram); + + GLSL_InitUniforms(&tr.ssaoShader); + + qglUseProgram(tr.ssaoShader.program); + GLSL_SetUniformInt(&tr.ssaoShader, UNIFORM_SCREENDEPTHMAP, TB_COLORMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.ssaoShader); + + return 1; +} + +static int GLSL_LoadGPUProgramPrefilterEnvMap( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc) +{ + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.prefilterEnvMapShader, + "prefilterEnvMap", + fallback_prefilterEnvMapProgram); + + GLSL_InitUniforms(&tr.prefilterEnvMapShader); + + qglUseProgram(tr.prefilterEnvMapShader.program); + GLSL_SetUniformInt(&tr.prefilterEnvMapShader, UNIFORM_CUBEMAP, TB_CUBEMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.prefilterEnvMapShader); + + return 1; +} + +static int GLSL_LoadGPUProgramDepthBlur( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + int numPrograms = 0; + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("depthBlur", allocator, fallback_depthblurProgram); + for ( int i = 0; i < 2; i++ ) + { + const uint32_t attribs = ATTR_POSITION | ATTR_TEXCOORD0; + extradefines[0] = '\0'; + + if (i & 1) + Q_strcat(extradefines, sizeof(extradefines), "#define USE_VERTICAL_BLUR\n"); + else + Q_strcat(extradefines, sizeof(extradefines), "#define USE_HORIZONTAL_BLUR\n"); + + + if (!GLSL_LoadGPUShader(builder, &tr.depthBlurShader[i], "depthBlur", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load depthBlur shader!"); + } + + GLSL_InitUniforms(&tr.depthBlurShader[i]); + + qglUseProgram(tr.depthBlurShader[i].program); + GLSL_SetUniformInt(&tr.depthBlurShader[i], UNIFORM_SCREENIMAGEMAP, TB_COLORMAP); + GLSL_SetUniformInt(&tr.depthBlurShader[i], UNIFORM_SCREENDEPTHMAP, TB_LIGHTMAP); + qglUseProgram(0); + + GLSL_FinishGPUShader(&tr.depthBlurShader[i]); + + ++numPrograms; + } + + return numPrograms; +} + +static int GLSL_LoadGPUProgramGaussianBlur( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("gaussian_blur", allocator, fallback_gaussian_blurProgram); + const uint32_t attribs = 0; + + extradefines[0] = '\0'; + Q_strcat (extradefines, sizeof (extradefines), "#define BLUR_X"); + + if (!GLSL_LoadGPUShader(builder, &tr.gaussianBlurShader[0], "gaussian_blur", attribs, + NO_XFB_VARS, extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load gaussian_blur (X-direction) shader!"); + } + + if (!GLSL_LoadGPUShader(builder, &tr.gaussianBlurShader[1], "gaussian_blur", attribs, + NO_XFB_VARS, nullptr, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load gaussian_blur (Y-direction) shader!"); + } + + int numPrograms = 0; + for ( int i = 0; i < 2; i++ ) + { + GLSL_InitUniforms(&tr.gaussianBlurShader[i]); + GLSL_FinishGPUShader(&tr.gaussianBlurShader[i]); + ++numPrograms; + } + + return numPrograms; +} + +static int GLSL_LoadGPUProgramDynamicGlowUpsample( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.dglowUpsample, + "dglow_upsample", + fallback_dglow_upsampleProgram, + 0); + + GLSL_InitUniforms(&tr.dglowUpsample); + GLSL_FinishGPUShader(&tr.dglowUpsample); + return 1; +} + +static int GLSL_LoadGPUProgramDynamicGlowDownsample( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.dglowDownsample, + "dglow_downsample", + fallback_dglow_downsampleProgram, + 0); + + GLSL_InitUniforms(&tr.dglowDownsample); + GLSL_FinishGPUShader(&tr.dglowDownsample); + return 1; +} + +static int GLSL_LoadGPUProgramSurfaceSprites( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + int numPrograms = 0; + Allocator allocator(scratchAlloc.Base(), scratchAlloc.GetSize()); + + char extradefines[1200]; + const GPUProgramDesc *programDesc = + LoadProgramSource("surface_sprites", allocator, fallback_surface_spritesProgram); + const uint32_t attribs = ATTR_POSITION | ATTR_POSITION2 | ATTR_NORMAL | ATTR_COLOR; + for ( int i = 0; i < SSDEF_COUNT; ++i ) + { + extradefines[0] = '\0'; + + if ( (i & SSDEF_FACE_CAMERA) && (i & SSDEF_FACE_UP) ) + continue; + + if ( i & SSDEF_FACE_CAMERA ) + Q_strcat(extradefines, sizeof(extradefines), + "#define FACE_CAMERA\n"); + else if ( i & SSDEF_FACE_UP ) + Q_strcat(extradefines, sizeof(extradefines), + "#define FACE_UP\n"); + else if (i & SSDEF_FLATTENED) + Q_strcat(extradefines, sizeof(extradefines), + "#define FACE_FLATTENED\n"); + + if (i & SSDEF_FX_SPRITE) + Q_strcat(extradefines, sizeof(extradefines), + "#define FX_SPRITE\n"); + + if ( i & SSDEF_USE_FOG ) + Q_strcat(extradefines, sizeof(extradefines), + "#define USE_FOG\n"); + + if ( i & SSDEF_ALPHA_TEST ) + Q_strcat(extradefines, sizeof(extradefines), + "#define ALPHA_TEST\n"); + + if (i & SSDEF_ADDITIVE) + Q_strcat(extradefines, sizeof(extradefines), + "#define ADDITIVE_BLEND\n"); + + shaderProgram_t *program = tr.spriteShader + i; + if (!GLSL_LoadGPUShader(builder, program, "surface_sprites", attribs, NO_XFB_VARS, + extradefines, *programDesc)) + { + ri.Error(ERR_FATAL, "Could not load surface sprites shader!"); + } + + GLSL_InitUniforms(program); + GLSL_FinishGPUShader(program); + ++numPrograms; + } + + return numPrograms; +} + +static int GLSL_LoadGPUProgramWeather( + ShaderProgramBuilder& builder, + Allocator& scratchAlloc ) +{ + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.weatherShader, + "weather", + fallback_weatherProgram, + ATTR_POSITION | ATTR_COLOR); + + GLSL_InitUniforms(&tr.weatherShader); + qglUseProgram(tr.weatherShader.program); + GLSL_SetUniformInt(&tr.weatherShader, UNIFORM_SHADOWMAP, TB_SHADOWMAP); + GLSL_SetUniformInt(&tr.weatherShader, UNIFORM_DIFFUSEMAP, TB_DIFFUSEMAP); + qglUseProgram(0); + GLSL_FinishGPUShader(&tr.weatherShader); + + GLSL_LoadGPUProgramBasic( + builder, + scratchAlloc, + &tr.weatherUpdateShader, + "weatherUpdate", + fallback_weatherUpdateProgram, + ATTR_POSITION | ATTR_COLOR, + (1u << XFB_VAR_POSITION) | (1u << XFB_VAR_VELOCITY)); + + GLSL_InitUniforms(&tr.weatherUpdateShader); + GLSL_FinishGPUShader(&tr.weatherUpdateShader); + + return 2; +} + +void GLSL_LoadGPUShaders() +{ +#if 0 + // vertex size = 48 bytes + VertexFormat bspVertexFormat = { + { + { 3, false, GL_FLOAT, false, 0 }, // position + { 2, false, GL_HALF_FLOAT, false, 12 }, // tc0 + { 2, false, GL_HALF_FLOAT, false, 16 }, // tc1 + { 2, false, GL_HALF_FLOAT, false, 20 }, // tc2 + { 2, false, GL_HALF_FLOAT, false, 24 }, // tc3 + { 2, false, GL_HALF_FLOAT, false, 28 }, // tc4 + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 32 }, // tangent + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 36 }, // normal + { 4, false, GL_FLOAT, false, 40 }, // color + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 44 }, // light dir + } + }; + + // vertex size = 32 bytes + VertexFormat rectVertexFormat = { + { + { 3, false, GL_FLOAT, false, 0 }, // position + { 2, false, GL_HALF_FLOAT, false, 12 }, // tc0 + { 4, false, GL_FLOAT, false, 16 } // color + } + }; + + // vertex size = 32 bytes + VertexFormat g2VertexFormat = { + { + { 3, false, GL_FLOAT, false, 0 }, // position + { 2, false, GL_HALF_FLOAT, false, 12 }, // tc0 + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 16 }, // tangent + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 20 }, // normal + { 4, true, GL_UNSIGNED_BYTE, false, 24 }, // bone indices + { 4, false, GL_UNSIGNED_BYTE, true, 28 }, // bone weights + } + }; + + // vertex size = 44 bytes + VertexFormat md3VertexFormat = { + { + { 3, false, GL_FLOAT, false, 0 }, // position + { 2, false, GL_HALF_FLOAT, false, 12 }, // tc0 + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 16 }, // tangent + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 20 }, // normal + { 3, false,p GL_FLOAT, false, 24 }, // pos2 + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 36 }, // tangent + { 4, false, GL_UNSIGNED_INT_2_10_10_10_REV, true, 40 }, // normal + } + }; +#endif + + ri.Printf(PRINT_ALL, "------- GLSL_InitGPUShaders -------\n"); + + R_IssuePendingRenderCommands(); + + int startTime = ri.Milliseconds(); + + Allocator allocator(512 * 1024); + ShaderProgramBuilder builder; + + int numGenShaders = 0; + int numLightShaders = 0; + int numEtcShaders = 0; + numGenShaders += GLSL_LoadGPUProgramGeneric(builder, allocator); + numLightShaders += GLSL_LoadGPUProgramLightAll(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramFogPass(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramRefraction(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramTextureColor(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramPShadow(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramVShadow(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramDownscale4x(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramBokeh(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramTonemap(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramCalcLuminanceLevel(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramSSAO(builder, allocator); + if (r_cubeMapping->integer) + numEtcShaders += GLSL_LoadGPUProgramPrefilterEnvMap(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramDepthBlur(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramGaussianBlur(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramDynamicGlowUpsample(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramDynamicGlowDownsample(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramSurfaceSprites(builder, allocator); + numEtcShaders += GLSL_LoadGPUProgramWeather(builder, allocator); + + ri.Printf(PRINT_ALL, "loaded %i GLSL shaders (%i gen %i light %i etc) in %5.2f seconds\n", + numGenShaders + numLightShaders + numEtcShaders, numGenShaders, numLightShaders, + numEtcShaders, (ri.Milliseconds() - startTime) / 1000.0); +} + +void GLSL_ShutdownGPUShaders(void) +{ + int i; + + ri.Printf(PRINT_ALL, "------- GLSL_ShutdownGPUShaders -------\n"); + + for ( int i = 0; i < ATTR_INDEX_MAX; i++ ) + qglDisableVertexAttribArray(i); + + GLSL_BindNullProgram(); + + GLSL_DeleteGPUShader(&tr.splashScreenShader); + + for ( i = 0; i < GENERICDEF_COUNT; i++) + GLSL_DeleteGPUShader(&tr.genericShader[i]); + + for (i = 0; i < REFRACTIONDEF_COUNT; i++) + GLSL_DeleteGPUShader(&tr.refractionShader[i]); + + GLSL_DeleteGPUShader(&tr.textureColorShader); + + for ( i = 0; i < FOGDEF_COUNT; i++) + GLSL_DeleteGPUShader(&tr.fogShader[i]); + + for ( i = 0; i < LIGHTDEF_COUNT; i++) + GLSL_DeleteGPUShader(&tr.lightallShader[i]); + + GLSL_DeleteGPUShader(&tr.pshadowShader); + GLSL_DeleteGPUShader(&tr.volumeShadowShader); + GLSL_DeleteGPUShader(&tr.down4xShader); + GLSL_DeleteGPUShader(&tr.bokehShader); + + for (i = 0; i < 2; ++i) + GLSL_DeleteGPUShader(&tr.tonemapShader[i]); + + for ( i = 0; i < 2; i++) + GLSL_DeleteGPUShader(&tr.calclevels4xShader[i]); + + GLSL_DeleteGPUShader(&tr.ssaoShader); + + for ( i = 0; i < 2; i++) + GLSL_DeleteGPUShader(&tr.depthBlurShader[i]); + + GLSL_DeleteGPUShader(&tr.testcubeShader); + GLSL_DeleteGPUShader(&tr.prefilterEnvMapShader); + + for (i = 0; i < 2; ++i) + GLSL_DeleteGPUShader(&tr.gaussianBlurShader[i]); + + GLSL_DeleteGPUShader(&tr.glowCompositeShader); + GLSL_DeleteGPUShader(&tr.dglowDownsample); + GLSL_DeleteGPUShader(&tr.dglowUpsample); + + for (i = 0; i < SSDEF_COUNT; ++i) + GLSL_DeleteGPUShader(&tr.spriteShader[i]); + + GLSL_DeleteGPUShader(&tr.weatherUpdateShader); + GLSL_DeleteGPUShader(&tr.weatherShader); + + glState.currentProgram = 0; + qglUseProgram(0); +} + +void GLSL_BindProgram(shaderProgram_t * program) +{ + if(!program) + { + GLSL_BindNullProgram(); + return; + } + + if(r_logFile->integer) + { + // don't just call LogComment, or we will get a call to va() every frame! + GLimp_LogComment(va("--- GL_BindProgram( %s ) ---\n", program->name)); + } + + if(glState.currentProgram != program) + { + qglUseProgram(program->program); + glState.currentProgram = program; + backEnd.pc.c_glslShaderBinds++; + } +} + + +void GLSL_BindNullProgram(void) +{ + if(r_logFile->integer) + { + GLimp_LogComment("--- GL_BindNullProgram ---\n"); + } + + if(glState.currentProgram) + { + qglUseProgram(0); + glState.currentProgram = NULL; + } +} + +void GLSL_VertexAttribsState(uint32_t stateBits, VertexArraysProperties *vertexArraysOut) +{ + VertexArraysProperties vertexArraysLocal; + VertexArraysProperties *vertexArrays = vertexArraysOut; + + if ( !vertexArrays ) + { + vertexArrays = &vertexArraysLocal; + } + + if ( tess.useInternalVBO ) + { + CalculateVertexArraysProperties(stateBits, vertexArrays); + for ( int i = 0; i < vertexArrays->numVertexArrays; i++ ) + { + int attributeIndex = vertexArrays->enabledAttributes[i]; + vertexArrays->offsets[attributeIndex] += backEndData->currentFrame->dynamicVboCommitOffset; + } + } + else + { + CalculateVertexArraysFromVBO(stateBits, glState.currentVBO, vertexArrays); + } + + GLSL_VertexAttribPointers(vertexArrays); + +} + +void GL_VertexArraysToAttribs( + vertexAttribute_t *attribs, + size_t attribsCount, + const VertexArraysProperties *vertexArrays) +{ + assert(attribsCount == ATTR_INDEX_MAX); + + static const struct + { + int numComponents; + GLboolean integerAttribute; + GLenum type; + GLboolean normalize; + } attributes[ATTR_INDEX_MAX] = { + { 3, GL_FALSE, GL_FLOAT, GL_FALSE }, // position + { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc0 + { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc1 + { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc2 + { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc3 + { 2, GL_FALSE, GL_FLOAT, GL_FALSE }, // tc4 + { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // tangent + { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // normal + { 4, GL_FALSE, GL_FLOAT, GL_FALSE }, // color + { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // light direction + { 4, GL_TRUE, GL_UNSIGNED_BYTE, GL_FALSE }, // bone indices + { 4, GL_FALSE, GL_UNSIGNED_BYTE, GL_TRUE }, // bone weights +#ifdef REND2_SP + { 3, GL_FALSE, GL_FLOAT, GL_FALSE }, // pos2 + { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // tangent2 + { 4, GL_FALSE, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE }, // normal2 +#endif // REND2_SP + }; + + for ( int i = 0; i < vertexArrays->numVertexArrays; i++ ) + { + int attributeIndex = vertexArrays->enabledAttributes[i]; + vertexAttribute_t& attrib = attribs[i]; + + attrib.vbo = glState.currentVBO; + attrib.index = attributeIndex; + attrib.numComponents = attributes[attributeIndex].numComponents; + attrib.integerAttribute = attributes[attributeIndex].integerAttribute; + attrib.type = attributes[attributeIndex].type; + attrib.normalize = attributes[attributeIndex].normalize; + attrib.stride = vertexArrays->strides[attributeIndex]; + attrib.offset = vertexArrays->offsets[attributeIndex]; + attrib.stepRate = 0; + } +} + +void GLSL_VertexAttribPointers(const VertexArraysProperties *vertexArrays) +{ + // don't just call LogComment, or we will get a call to va() every frame! + if (r_logFile->integer) + { + GLimp_LogComment("--- GL_VertexAttribPointers() ---\n"); + } + + vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; + GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); + GL_VertexAttribPointers(vertexArrays->numVertexArrays, attribs); +} + + +shaderProgram_t *GLSL_GetGenericShaderProgram(int stage) +{ + shaderStage_t *pStage = tess.xstages[stage]; + int shaderAttribs = 0; + + if ( pStage->alphaTestType != ALPHA_TEST_NONE ) + shaderAttribs |= GENERICDEF_USE_ALPHA_TEST; + + if (backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1 | RF_DISINTEGRATE2)) + shaderAttribs |= GENERICDEF_USE_RGBAGEN; + + if (backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE2) + shaderAttribs |= GENERICDEF_USE_DEFORM_VERTEXES; + + switch (pStage->rgbGen) + { + case CGEN_LIGHTING_DIFFUSE: + shaderAttribs |= GENERICDEF_USE_RGBAGEN; + break; + default: + break; + } + + switch (pStage->alphaGen) + { + case AGEN_LIGHTING_SPECULAR: + case AGEN_PORTAL: + shaderAttribs |= GENERICDEF_USE_RGBAGEN; + break; + default: + break; + } + + if (tess.fogNum && + pStage->adjustColorsForFog != ACFF_NONE && + r_drawfog->integer) + shaderAttribs |= GENERICDEF_USE_FOG; + + if (pStage->bundle[0].tcGen != TCGEN_TEXTURE) + { + shaderAttribs |= GENERICDEF_USE_TCGEN_AND_TCMOD; + } + + if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) + { + shaderAttribs |= GENERICDEF_USE_DEFORM_VERTEXES; + } +#ifdef REND2_SP + if (glState.vertexAnimation) + { + shaderAttribs |= GENERICDEF_USE_VERTEX_ANIMATION; + } +#endif // REND2_SP + if (glState.skeletalAnimation) + { + shaderAttribs |= GENERICDEF_USE_SKELETAL_ANIMATION; + } + + if (pStage->bundle[0].numTexMods) + { + shaderAttribs |= GENERICDEF_USE_TCGEN_AND_TCMOD; + } + + if (pStage->glow) + { + shaderAttribs |= GENERICDEF_USE_GLOW_BUFFER; + } + + return &tr.genericShader[shaderAttribs]; +} diff --git a/codemp/rd-rend2/tr_glsl_parse.cpp b/codemp/rd-rend2/tr_glsl_parse.cpp new file mode 100644 index 0000000000..94fdb9fb6b --- /dev/null +++ b/codemp/rd-rend2/tr_glsl_parse.cpp @@ -0,0 +1,180 @@ +/* +=========================================================================== +Copyright (C) 2013 - 2016, OpenJK contributors + +This file is part of the OpenJK source code. + +OpenJK is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . +=========================================================================== +*/ + +#include "tr_local.h" +#include "tr_allocator.h" +#if defined(GLSL_BUILDTOOL) +#include +#endif + +namespace +{ + +Block *FindBlock( const char *name, Block *blocks, size_t numBlocks ) +{ + for ( size_t i = 0; i < numBlocks; ++i ) + { + Block *block = blocks + i; + if ( strncmp(block->blockHeaderTitle, name, block->blockHeaderTitleLength) == 0 ) + { + return block; + } + } + + return nullptr; +} + +// [M] strncpy_s is not present on linux and VS only function +#if !defined(_WIN32) +void strncpy_s( char *dest, size_t destSize, const char *src, size_t srcSize ) +{ + // This isn't really a safe version, but I know the inputs to expect. + size_t len = std::min(srcSize, destSize); + memcpy(dest, src, len); + if ( (destSize - len) > 0 ) + memset(dest + len, 0, destSize - len); +} +#endif + + +} + +GPUProgramDesc ParseProgramSource( Allocator& allocator, const char *text ) +{ + int numBlocks = 0; + Block blocks[MAX_BLOCKS]; + Block *prevBlock = nullptr; + + int i = 0; + int line = 1; + while ( text[i] ) + { + if ( strncmp(text + i, "/*[", 3) == 0 ) + { + int startHeaderTitle = i + 3; + int endHeaderTitle = -1; + int endHeaderText = -1; + int j = startHeaderTitle; + while ( text[j] ) + { + if ( text[j] == ']' ) + { + endHeaderTitle = j; + } + else if ( strncmp(text + j, "*/\n", 3) == 0 ) + { + endHeaderText = j; + line++; + break; + } + else if ( text[j] == '\n' ) + { + line++; + } + + ++j; + } + + if ( endHeaderTitle == -1 || endHeaderText == -1 ) + { +#if defined(GLSL_BUILDTOOL) + std::cerr << "Unclosed block marker\n"; +#else + Com_Printf(S_COLOR_YELLOW "Unclosed block marker\n"); +#endif + break; + } + + Block *block = blocks + numBlocks++; + block->blockHeaderTitle = text + startHeaderTitle; + block->blockHeaderTitleLength = endHeaderTitle - startHeaderTitle; + block->blockHeaderText = text + endHeaderTitle + 1; + block->blockHeaderTextLength = endHeaderText - endHeaderTitle - 1; + block->blockText = text + endHeaderText + 3; + block->blockTextLength = 0; + block->blockTextFirstLine = line; + + if ( prevBlock ) + { + prevBlock->blockTextLength = (text + i) - prevBlock->blockText; + } + prevBlock = block; + + i = endHeaderText + 3; + continue; + } + else if ( text[i] == '\n' ) + { + line++; + } + + ++i; + } + + if ( prevBlock ) + { + prevBlock->blockTextLength = (text + i) - prevBlock->blockText; + } + + static const char *shaderBlockNames[GPUSHADER_TYPE_COUNT] = { + "Vertex", "Fragment", "Geometry" + }; + + GPUProgramDesc theProgram = {}; + const Block *parsedBlocks[GPUSHADER_TYPE_COUNT] = {}; + for ( const auto& shaderBlockName : shaderBlockNames ) + { + Block *block = FindBlock(shaderBlockName, blocks, numBlocks); + if ( block ) + { + parsedBlocks[theProgram.numShaders++] = block; + } + } + + theProgram.shaders = ojkAllocArray(allocator, theProgram.numShaders); + + int shaderIndex = 0; + for ( int shaderType = 0; + shaderType < theProgram.numShaders; + ++shaderType ) + { + const Block *block = parsedBlocks[shaderType]; + if ( !block ) + { + continue; + } + + char *source = ojkAllocString(allocator, block->blockTextLength); + + strncpy_s( + source, + block->blockTextLength + 1, + block->blockText, + block->blockTextLength); + + GPUShaderDesc& shaderDesc = theProgram.shaders[shaderIndex]; + shaderDesc.type = static_cast(shaderType); + shaderDesc.source = source; + shaderDesc.firstLineNumber = block->blockTextFirstLine; + ++shaderIndex; + } + + return theProgram; +} diff --git a/codemp/rd-rend2/tr_image.cpp b/codemp/rd-rend2/tr_image.cpp new file mode 100644 index 0000000000..03e0f03292 --- /dev/null +++ b/codemp/rd-rend2/tr_image.cpp @@ -0,0 +1,3666 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_image.c +#include "tr_local.h" +#include "glext.h" + +static byte s_intensitytable[256]; +static unsigned char s_gammatable[256]; + +int gl_filter_min = GL_LINEAR_MIPMAP_NEAREST; +int gl_filter_max = GL_LINEAR; + +#define FILE_HASH_SIZE 1553 // Prime numbers are a good size for hash tables :) +#define NUM_IMAGES_PER_POOL_ALLOC 512 + +static struct ImagesPool +{ + image_t *pPool; + ImagesPool *pNext; +} *imagesPool; + +static image_t *hashTable[FILE_HASH_SIZE]; + +/* +Extends the size of the images pool allocator +*/ +static void R_ExtendImagesPool() +{ + ImagesPool *pool = (ImagesPool *)Z_Malloc(sizeof(*pool), TAG_GENERAL); + image_t *freeImages = (image_t *)Z_Malloc(sizeof(*freeImages) * NUM_IMAGES_PER_POOL_ALLOC, TAG_IMAGE_T); + + for ( int i = 0; i < (NUM_IMAGES_PER_POOL_ALLOC - 1); i++ ) + { + freeImages[i].poolNext = &freeImages[i + 1]; + } + freeImages[NUM_IMAGES_PER_POOL_ALLOC - 1].poolNext = tr.imagesFreeList; + + pool->pPool = freeImages; + pool->pNext = imagesPool; + imagesPool = pool; + + tr.imagesFreeList = freeImages; +} + +/* +** R_GammaCorrect +*/ +void R_GammaCorrect( byte *buffer, int bufSize ) { + int i; + + for ( i = 0; i < bufSize; i++ ) { + buffer[i] = s_gammatable[buffer[i]]; + } +} + +typedef struct { + const char *name; + int minimize, maximize; +} textureMode_t; + +textureMode_t modes[] = { + {"GL_NEAREST", GL_NEAREST, GL_NEAREST}, + {"GL_LINEAR", GL_LINEAR, GL_LINEAR}, + {"GL_NEAREST_MIPMAP_NEAREST", GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST}, + {"GL_LINEAR_MIPMAP_NEAREST", GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR}, + {"GL_NEAREST_MIPMAP_LINEAR", GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST}, + {"GL_LINEAR_MIPMAP_LINEAR", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR} +}; + +/* +================ +return a hash value for the filename +================ +*/ +static long generateHashValue( const char *fname ) { + int i; + long hash; + char letter; + + hash = 0; + i = 0; + while (fname[i] != '\0') { + letter = tolower(fname[i]); + if (letter =='.') break; // don't include extension + if (letter =='\\') letter = '/'; // damn path names + hash+=(long)(letter)*(i+119); + i++; + } + + return hash % FILE_HASH_SIZE; +} + +/* +=============== +GL_TextureMode +=============== +*/ +void GL_TextureMode( const char *string ) { + int i; + image_t *glt; + + for ( i=0 ; i< 6 ; i++ ) { + if ( !Q_stricmp( modes[i].name, string ) ) { + break; + } + } + + + if ( i == 6 ) { + ri.Printf (PRINT_ALL, "bad filter name\n"); + return; + } + + gl_filter_min = modes[i].minimize; + gl_filter_max = modes[i].maximize; + + if ( r_ext_texture_filter_anisotropic->value > glConfig.maxTextureFilterAnisotropy ) + { + ri.Cvar_SetValue ("r_ext_texture_filter_anisotropic", glConfig.maxTextureFilterAnisotropy); + } + + // change all the existing mipmap texture objects + glt = tr.images; + for ( i = 0 ; i < tr.numImages ; i++, glt = glt->poolNext ) { + if ( glt->flags & IMGFLAG_MIPMAP ) { + GL_Bind (glt); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); + + if ( r_ext_texture_filter_anisotropic->value > 0.0f ) + { + if ( glConfig.maxTextureFilterAnisotropy > 1.0f ) + { + qglTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, r_ext_texture_filter_anisotropic->value); + } + else + { + qglTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); + } + } + } + } +} + +/* +=============== +R_SumOfUsedImages +=============== +*/ +int R_SumOfUsedImages( void ) { + int total; + int i; + image_t *image = tr.images; + + total = 0; + for ( i = 0; i < tr.numImages; i++, image = image->poolNext ) { + if ( image->frameUsed == tr.frameCount ) { + total += image->uploadWidth * image->uploadHeight; + } + } + + return total; +} + +static float GetReadableSize( int bytes, const char **units ) +{ + float result = bytes; + *units = "b "; + + if (result >= 1024.0f) + { + result /= 1024.0f; + *units = "kb"; + } + + if (result >= 1024.0f) + { + result /= 1024.0f; + *units = "Mb"; + } + + if (result >= 1024.0f) + { + result /= 1024.0f; + *units = "Gb"; + } + + return result; +} + +/* +=============== +R_ImageList_f +=============== +*/ +void R_ImageList_f( void ) { + int i; + int estTotalSize = 0; + const char *sizeSuffix; + image_t *image = tr.images; + + ri.Printf(PRINT_ALL, "\n -w-- -h-- type -size- --name-------\n"); + + for ( i = 0 ; i < tr.numImages ; i++, image = image->poolNext ) + { + const char *format = "???? "; + int estSize; + + estSize = image->uploadHeight * image->uploadWidth; + + switch(image->internalFormat) + { + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: + format = "sDXT1"; + // 64 bits per 16 pixels, so 4 bits per pixel + estSize /= 2; + break; + case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: + format = "sDXT5"; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: + format = "sBPTC"; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT: + format = "LATC "; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: + format = "DXT1 "; + // 64 bits per 16 pixels, so 4 bits per pixel + estSize /= 2; + break; + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: + format = "DXT5 "; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: + format = "BPTC "; + // 128 bits per 16 pixels, so 1 byte per pixel + break; + case GL_RGB4_S3TC: + format = "S3TC "; + // same as DXT1? + estSize /= 2; + break; + case GL_RGBA4: + case GL_RGBA8: + case GL_RGBA: + format = "RGBA "; + // 4 bytes per pixel + estSize *= 4; + break; + case GL_RGB5: + case GL_RGB8: + case GL_RGB: + format = "RGB "; + // 3 bytes per pixel? + estSize *= 3; + break; + case GL_SRGB: + case GL_SRGB8: + format = "sRGB "; + // 3 bytes per pixel? + estSize *= 3; + break; + case GL_SRGB_ALPHA: + case GL_SRGB8_ALPHA8: + format = "sRGBA"; + // 4 bytes per pixel? + estSize *= 4; + break; + case GL_DEPTH_COMPONENT24: + format = "D24 "; + break; + } + + // mipmap adds about 50% + if (image->flags & IMGFLAG_MIPMAP) + estSize += estSize / 2; + + float printSize = GetReadableSize(estSize, &sizeSuffix); + + ri.Printf(PRINT_ALL, "%4i: %4ix%4i %s %7.2f%s %s\n", i, image->uploadWidth, image->uploadHeight, format, printSize, sizeSuffix, image->imgName); + estTotalSize += estSize; + } + + float printSize = GetReadableSize(estTotalSize, &sizeSuffix); + + ri.Printf (PRINT_ALL, " ---------\n"); + ri.Printf (PRINT_ALL, " approx %i bytes (%.2f%s)\n", estTotalSize, printSize, sizeSuffix); + ri.Printf (PRINT_ALL, " %i total images\n\n", tr.numImages ); +} + +//======================================================================= + +/* +================ +ResampleTexture + +Used to resample images in a more general than quartering fashion. + +This will only be filtered properly if the resampled size +is greater than half the original size. + +If a larger shrinking is needed, use the mipmap function +before or after. +================ +*/ +static void ResampleTexture( byte *in, int inwidth, int inheight, byte *out, + int outwidth, int outheight ) { + int i, j; + byte *inrow, *inrow2; + int frac, fracstep; + int p1[2048], p2[2048]; + byte *pix1, *pix2, *pix3, *pix4; + + if (outwidth>2048) + ri.Error(ERR_DROP, "ResampleTexture: max width"); + + fracstep = inwidth*0x10000/outwidth; + + frac = fracstep>>2; + for ( i=0 ; i>16); + frac += fracstep; + } + frac = 3*(fracstep>>2); + for ( i=0 ; i>16); + frac += fracstep; + } + + for (i=0 ; i>2; + *out++ = (pix1[1] + pix2[1] + pix3[1] + pix4[1])>>2; + *out++ = (pix1[2] + pix2[2] + pix3[2] + pix4[2])>>2; + *out++ = (pix1[3] + pix2[3] + pix3[3] + pix4[3])>>2; + } + } +} + +static void RGBAtoYCoCgA(const byte *in, byte *out, int width, int height) +{ + int x, y; + + for (y = 0; y < height; y++) + { + const byte *inbyte = in + y * width * 4; + byte *outbyte = out + y * width * 4; + + for (x = 0; x < width; x++) + { + byte r, g, b, a, rb2; + + r = *inbyte++; + g = *inbyte++; + b = *inbyte++; + a = *inbyte++; + rb2 = (r + b) >> 1; + + *outbyte++ = (g + rb2) >> 1; // Y = R/4 + G/2 + B/4 + *outbyte++ = (r - b + 256) >> 1; // Co = R/2 - B/2 + *outbyte++ = (g - rb2 + 256) >> 1; // Cg = -R/4 + G/2 - B/4 + *outbyte++ = a; + } + } +} + +static void YCoCgAtoRGBA(const byte *in, byte *out, int width, int height) +{ + int x, y; + + for (y = 0; y < height; y++) + { + const byte *inbyte = in + y * width * 4; + byte *outbyte = out + y * width * 4; + + for (x = 0; x < width; x++) + { + byte _Y, Co, Cg, a; + + _Y = *inbyte++; + Co = *inbyte++; + Cg = *inbyte++; + a = *inbyte++; + + *outbyte++ = CLAMP(_Y + Co - Cg, 0, 255); // R = Y + Co - Cg + *outbyte++ = CLAMP(_Y + Cg - 128, 0, 255); // G = Y + Cg + *outbyte++ = CLAMP(_Y - Co - Cg + 256, 0, 255); // B = Y - Co - Cg + *outbyte++ = a; + } + } +} + + +// uses a sobel filter to change a texture to a normal map +static void RGBAtoNormal(const byte *in, byte *out, int width, int height, qboolean clampToEdge) +{ + int x, y, max; + + // convert to heightmap, storing in alpha + // same as converting to Y in YCoCg + max = 1; + for (y = 0; y < height; y++) + { + const byte *inbyte = in + y * width * 4; + byte *outbyte = out + y * width * 4 + 3; + + for (x = 0; x < width; x++) + { + byte result = (inbyte[0] >> 2) + (inbyte[1] >> 1) + (inbyte[2] >> 2); + result = result * result / 255; // Make linear + *outbyte = result; + max = MAX(max, *outbyte); + outbyte += 4; + inbyte += 4; + } + } + + // level out heights + if (max < 255) + { + for (y = 0; y < height; y++) + { + byte *outbyte = out + y * width * 4 + 3; + + for (x = 0; x < width; x++) + { + *outbyte = *outbyte + (255 - max); + outbyte += 4; + } + } + } + + + // now run sobel filter over height values to generate X and Y + // then normalize + for (y = 0; y < height; y++) + { + byte *outbyte = out + y * width * 4; + + for (x = 0; x < width; x++) + { + // 0 1 2 + // 3 4 5 + // 6 7 8 + + byte s[9]; + int x2, y2, i; + vec3_t normal; + + i = 0; + for (y2 = -1; y2 <= 1; y2++) + { + int src_y = y + y2; + + if (clampToEdge) + { + src_y = CLAMP(src_y, 0, height - 1); + } + else + { + src_y = (src_y + height) % height; + } + + + for (x2 = -1; x2 <= 1; x2++) + { + int src_x = x + x2; + + if (clampToEdge) + { + src_x = CLAMP(src_x, 0, width - 1); + } + else + { + src_x = (src_x + width) % width; + } + + s[i++] = *(out + (src_y * width + src_x) * 4 + 3); + } + } + + normal[0] = s[0] - s[2] + + 2 * s[3] - 2 * s[5] + + s[6] - s[8]; + + normal[1] = s[0] + 2 * s[1] + s[2] + + - s[6] - 2 * s[7] - s[8]; + + normal[2] = s[4] * 4; + + if (!VectorNormalize2(normal, normal)) + { + VectorSet(normal, 0, 0, 1); + } + + *outbyte++ = FloatToOffsetByte(normal[0]); + *outbyte++ = FloatToOffsetByte(normal[1]); + *outbyte++ = FloatToOffsetByte(normal[2]); + outbyte++; + } + } +} + +#define COPYSAMPLE(a,b) *(unsigned int *)(a) = *(unsigned int *)(b) + +// based on Fast Curve Based Interpolation +// from Fast Artifacts-Free Image Interpolation (http://www.andreagiachetti.it/icbi/) +// assumes data has a 2 pixel thick border of clamped or wrapped data +// expects data to be a grid with even (0, 0), (2, 0), (0, 2), (2, 2) etc pixels filled +// only performs FCBI on specified component +static void DoFCBI(byte *in, byte *out, int width, int height, int component) +{ + int x, y; + byte *outbyte, *inbyte; + + // copy in to out + for (y = 2; y < height - 2; y += 2) + { + inbyte = in + (y * width + 2) * 4 + component; + outbyte = out + (y * width + 2) * 4 + component; + + for (x = 2; x < width - 2; x += 2) + { + *outbyte = *inbyte; + outbyte += 8; + inbyte += 8; + } + } + + for (y = 3; y < height - 3; y += 2) + { + // diagonals + // + // NWp - northwest interpolated pixel + // NEp - northeast interpolated pixel + // NWd - northwest first derivative + // NEd - northeast first derivative + // NWdd - northwest second derivative + // NEdd - northeast second derivative + // + // Uses these samples: + // + // 0 + // - - a - b - - + // - - - - - - - + // c - d - e - f + // 0 - - - - - - - + // g - h - i - j + // - - - - - - - + // - - k - l - - + // + // x+2 uses these samples: + // + // 0 + // - - - - a - b - - + // - - - - - - - - - + // - - c - d - e - f + // 0 - - - - - - - - - + // - - g - h - i - j + // - - - - - - - - - + // - - - - k - l - - + // + // so we can reuse 8 of them on next iteration + // + // a=b, c=d, d=e, e=f, g=h, h=i, i=j, k=l + // + // only b, f, j, and l need to be sampled on next iteration + + byte sa, sb, sc, sd, se, sf, sg, sh, si, sj, sk, sl; + byte *line1, *line2, *line3, *line4; + + x = 3; + + // optimization one + // SAMPLE2(sa, x-1, y-3); + //SAMPLE2(sc, x-3, y-1); SAMPLE2(sd, x-1, y-1); SAMPLE2(se, x+1, y-1); + //SAMPLE2(sg, x-3, y+1); SAMPLE2(sh, x-1, y+1); SAMPLE2(si, x+1, y+1); + // SAMPLE2(sk, x-1, y+3); + + // optimization two + line1 = in + ((y - 3) * width + (x - 1)) * 4 + component; + line2 = in + ((y - 1) * width + (x - 3)) * 4 + component; + line3 = in + ((y + 1) * width + (x - 3)) * 4 + component; + line4 = in + ((y + 3) * width + (x - 1)) * 4 + component; + + // COPYSAMPLE(sa, line1); line1 += 8; + //COPYSAMPLE(sc, line2); line2 += 8; COPYSAMPLE(sd, line2); line2 += 8; COPYSAMPLE(se, line2); line2 += 8; + //COPYSAMPLE(sg, line3); line3 += 8; COPYSAMPLE(sh, line3); line3 += 8; COPYSAMPLE(si, line3); line3 += 8; + // COPYSAMPLE(sk, line4); line4 += 8; + + sa = *line1; line1 += 8; + sc = *line2; line2 += 8; sd = *line2; line2 += 8; se = *line2; line2 += 8; + sg = *line3; line3 += 8; sh = *line3; line3 += 8; si = *line3; line3 += 8; + sk = *line4; line4 += 8; + + outbyte = out + (y * width + x) * 4 + component; + + for ( ; x < width - 3; x += 2) + { + int NWd, NEd, NWp, NEp; + + // original + // SAMPLE2(sa, x-1, y-3); SAMPLE2(sb, x+1, y-3); + //SAMPLE2(sc, x-3, y-1); SAMPLE2(sd, x-1, y-1); SAMPLE2(se, x+1, y-1); SAMPLE2(sf, x+3, y-1); + //SAMPLE2(sg, x-3, y+1); SAMPLE2(sh, x-1, y+1); SAMPLE2(si, x+1, y+1); SAMPLE2(sj, x+3, y+1); + // SAMPLE2(sk, x-1, y+3); SAMPLE2(sl, x+1, y+3); + + // optimization one + //SAMPLE2(sb, x+1, y-3); + //SAMPLE2(sf, x+3, y-1); + //SAMPLE2(sj, x+3, y+1); + //SAMPLE2(sl, x+1, y+3); + + // optimization two + //COPYSAMPLE(sb, line1); line1 += 8; + //COPYSAMPLE(sf, line2); line2 += 8; + //COPYSAMPLE(sj, line3); line3 += 8; + //COPYSAMPLE(sl, line4); line4 += 8; + + sb = *line1; line1 += 8; + sf = *line2; line2 += 8; + sj = *line3; line3 += 8; + sl = *line4; line4 += 8; + + NWp = sd + si; + NEp = se + sh; + NWd = abs(sd - si); + NEd = abs(se - sh); + + if (NWd > 100 || NEd > 100 || abs(NWp-NEp) > 200) + { + if (NWd < NEd) + *outbyte = NWp >> 1; + else + *outbyte = NEp >> 1; + } + else + { + int NWdd, NEdd; + + //NEdd = abs(sg + sd + sb - 3 * (se + sh) + sk + si + sf); + //NWdd = abs(sa + se + sj - 3 * (sd + si) + sc + sh + sl); + NEdd = abs(sg + sb - 3 * NEp + sk + sf + NWp); + NWdd = abs(sa + sj - 3 * NWp + sc + sl + NEp); + + if (NWdd > NEdd) + *outbyte = NWp >> 1; + else + *outbyte = NEp >> 1; + } + + outbyte += 8; + + // COPYSAMPLE(sa, sb); + //COPYSAMPLE(sc, sd); COPYSAMPLE(sd, se); COPYSAMPLE(se, sf); + //COPYSAMPLE(sg, sh); COPYSAMPLE(sh, si); COPYSAMPLE(si, sj); + // COPYSAMPLE(sk, sl); + + sa = sb; + sc = sd; sd = se; se = sf; + sg = sh; sh = si; si = sj; + sk = sl; + } + } + + // hack: copy out to in again + for (y = 3; y < height - 3; y += 2) + { + inbyte = out + (y * width + 3) * 4 + component; + outbyte = in + (y * width + 3) * 4 + component; + + for (x = 3; x < width - 3; x += 2) + { + *outbyte = *inbyte; + outbyte += 8; + inbyte += 8; + } + } + + for (y = 2; y < height - 3; y++) + { + // horizontal & vertical + // + // hp - horizontally interpolated pixel + // vp - vertically interpolated pixel + // hd - horizontal first derivative + // vd - vertical first derivative + // hdd - horizontal second derivative + // vdd - vertical second derivative + // Uses these samples: + // + // 0 + // - a - b - + // c - d - e + // 0 - f - g - + // h - i - j + // - k - l - + // + // x+2 uses these samples: + // + // 0 + // - - - a - b - + // - - c - d - e + // 0 - - - f - g - + // - - h - i - j + // - - - k - l - + // + // so we can reuse 7 of them on next iteration + // + // a=b, c=d, d=e, f=g, h=i, i=j, k=l + // + // only b, e, g, j, and l need to be sampled on next iteration + + byte sa, sb, sc, sd, se, sf, sg, sh, si, sj, sk, sl; + byte *line1, *line2, *line3, *line4, *line5; + + //x = (y + 1) % 2; + x = (y + 1) % 2 + 2; + + // optimization one + // SAMPLE2(sa, x-1, y-2); + //SAMPLE2(sc, x-2, y-1); SAMPLE2(sd, x, y-1); + // SAMPLE2(sf, x-1, y ); + //SAMPLE2(sh, x-2, y+1); SAMPLE2(si, x, y+1); + // SAMPLE2(sk, x-1, y+2); + + line1 = in + ((y - 2) * width + (x - 1)) * 4 + component; + line2 = in + ((y - 1) * width + (x - 2)) * 4 + component; + line3 = in + ((y ) * width + (x - 1)) * 4 + component; + line4 = in + ((y + 1) * width + (x - 2)) * 4 + component; + line5 = in + ((y + 2) * width + (x - 1)) * 4 + component; + + // COPYSAMPLE(sa, line1); line1 += 8; + //COPYSAMPLE(sc, line2); line2 += 8; COPYSAMPLE(sd, line2); line2 += 8; + // COPYSAMPLE(sf, line3); line3 += 8; + //COPYSAMPLE(sh, line4); line4 += 8; COPYSAMPLE(si, line4); line4 += 8; + // COPYSAMPLE(sk, line5); line5 += 8; + + sa = *line1; line1 += 8; + sc = *line2; line2 += 8; sd = *line2; line2 += 8; + sf = *line3; line3 += 8; + sh = *line4; line4 += 8; si = *line4; line4 += 8; + sk = *line5; line5 += 8; + + outbyte = out + (y * width + x) * 4 + component; + + for ( ; x < width - 3; x+=2) + { + int hd, vd, hp, vp; + + // SAMPLE2(sa, x-1, y-2); SAMPLE2(sb, x+1, y-2); + //SAMPLE2(sc, x-2, y-1); SAMPLE2(sd, x, y-1); SAMPLE2(se, x+2, y-1); + // SAMPLE2(sf, x-1, y ); SAMPLE2(sg, x+1, y ); + //SAMPLE2(sh, x-2, y+1); SAMPLE2(si, x, y+1); SAMPLE2(sj, x+2, y+1); + // SAMPLE2(sk, x-1, y+2); SAMPLE2(sl, x+1, y+2); + + // optimization one + //SAMPLE2(sb, x+1, y-2); + //SAMPLE2(se, x+2, y-1); + //SAMPLE2(sg, x+1, y ); + //SAMPLE2(sj, x+2, y+1); + //SAMPLE2(sl, x+1, y+2); + + //COPYSAMPLE(sb, line1); line1 += 8; + //COPYSAMPLE(se, line2); line2 += 8; + //COPYSAMPLE(sg, line3); line3 += 8; + //COPYSAMPLE(sj, line4); line4 += 8; + //COPYSAMPLE(sl, line5); line5 += 8; + + sb = *line1; line1 += 8; + se = *line2; line2 += 8; + sg = *line3; line3 += 8; + sj = *line4; line4 += 8; + sl = *line5; line5 += 8; + + hp = sf + sg; + vp = sd + si; + hd = abs(sf - sg); + vd = abs(sd - si); + + if (hd > 100 || vd > 100 || abs(hp-vp) > 200) + { + if (hd < vd) + *outbyte = hp >> 1; + else + *outbyte = vp >> 1; + } + else + { + int hdd, vdd; + + //hdd = abs(sc[i] + sd[i] + se[i] - 3 * (sf[i] + sg[i]) + sh[i] + si[i] + sj[i]); + //vdd = abs(sa[i] + sf[i] + sk[i] - 3 * (sd[i] + si[i]) + sb[i] + sg[i] + sl[i]); + + hdd = abs(sc + se - 3 * hp + sh + sj + vp); + vdd = abs(sa + sk - 3 * vp + sb + sl + hp); + + if (hdd > vdd) + *outbyte = hp >> 1; + else + *outbyte = vp >> 1; + } + + outbyte += 8; + + // COPYSAMPLE(sa, sb); + //COPYSAMPLE(sc, sd); COPYSAMPLE(sd, se); + // COPYSAMPLE(sf, sg); + //COPYSAMPLE(sh, si); COPYSAMPLE(si, sj); + // COPYSAMPLE(sk, sl); + sa = sb; + sc = sd; sd = se; + sf = sg; + sh = si; si = sj; + sk = sl; + } + } +} + +// Similar to FCBI, but throws out the second order derivatives for speed +static void DoFCBIQuick(byte *in, byte *out, int width, int height, int component) +{ + int x, y; + byte *outbyte, *inbyte; + + // copy in to out + for (y = 2; y < height - 2; y += 2) + { + inbyte = in + (y * width + 2) * 4 + component; + outbyte = out + (y * width + 2) * 4 + component; + + for (x = 2; x < width - 2; x += 2) + { + *outbyte = *inbyte; + outbyte += 8; + inbyte += 8; + } + } + + for (y = 3; y < height - 4; y += 2) + { + byte sd, se, sh, si; + byte *line2, *line3; + + x = 3; + + line2 = in + ((y - 1) * width + (x - 1)) * 4 + component; + line3 = in + ((y + 1) * width + (x - 1)) * 4 + component; + + sd = *line2; line2 += 8; + sh = *line3; line3 += 8; + + outbyte = out + (y * width + x) * 4 + component; + + for ( ; x < width - 4; x += 2) + { + int NWd, NEd, NWp, NEp; + + se = *line2; line2 += 8; + si = *line3; line3 += 8; + + NWp = sd + si; + NEp = se + sh; + NWd = abs(sd - si); + NEd = abs(se - sh); + + if (NWd < NEd) + *outbyte = NWp >> 1; + else + *outbyte = NEp >> 1; + + outbyte += 8; + + sd = se; + sh = si; + } + } + + // hack: copy out to in again + for (y = 3; y < height - 3; y += 2) + { + inbyte = out + (y * width + 3) * 4 + component; + outbyte = in + (y * width + 3) * 4 + component; + + for (x = 3; x < width - 3; x += 2) + { + *outbyte = *inbyte; + outbyte += 8; + inbyte += 8; + } + } + + for (y = 2; y < height - 3; y++) + { + byte sd, sf, sg, si; + byte *line2, *line3, *line4; + + x = (y + 1) % 2 + 2; + + line2 = in + ((y - 1) * width + (x )) * 4 + component; + line3 = in + ((y ) * width + (x - 1)) * 4 + component; + line4 = in + ((y + 1) * width + (x )) * 4 + component; + + outbyte = out + (y * width + x) * 4 + component; + + sf = *line3; line3 += 8; + + for ( ; x < width - 3; x+=2) + { + int hd, vd, hp, vp; + + sd = *line2; line2 += 8; + sg = *line3; line3 += 8; + si = *line4; line4 += 8; + + hp = sf + sg; + vp = sd + si; + hd = abs(sf - sg); + vd = abs(sd - si); + + if (hd < vd) + *outbyte = hp >> 1; + else + *outbyte = vp >> 1; + + outbyte += 8; + + sf = sg; + } + } +} + +// Similar to DoFCBIQuick, but just takes the average instead of checking derivatives +// as well, this operates on all four components +static void DoLinear(byte *in, byte *out, int width, int height) +{ + int x, y, i; + byte *outbyte, *inbyte; + + // copy in to out + for (y = 2; y < height - 2; y += 2) + { + x = 2; + + inbyte = in + (y * width + x) * 4; + outbyte = out + (y * width + x) * 4; + + for ( ; x < width - 2; x += 2) + { + COPYSAMPLE(outbyte, inbyte); + outbyte += 8; + inbyte += 8; + } + } + + for (y = 1; y < height - 1; y += 2) + { + byte sd[4] = {0}, se[4] = {0}, sh[4] = {0}, si[4] = {0}; + byte *line2, *line3; + + x = 1; + + line2 = in + ((y - 1) * width + (x - 1)) * 4; + line3 = in + ((y + 1) * width + (x - 1)) * 4; + + COPYSAMPLE(sd, line2); line2 += 8; + COPYSAMPLE(sh, line3); line3 += 8; + + outbyte = out + (y * width + x) * 4; + + for ( ; x < width - 1; x += 2) + { + COPYSAMPLE(se, line2); line2 += 8; + COPYSAMPLE(si, line3); line3 += 8; + + for (i = 0; i < 4; i++) + { + *outbyte++ = (sd[i] + si[i] + se[i] + sh[i]) >> 2; + } + + outbyte += 4; + + COPYSAMPLE(sd, se); + COPYSAMPLE(sh, si); + } + } + + // hack: copy out to in again + for (y = 1; y < height - 1; y += 2) + { + x = 1; + + inbyte = out + (y * width + x) * 4; + outbyte = in + (y * width + x) * 4; + + for ( ; x < width - 1; x += 2) + { + COPYSAMPLE(outbyte, inbyte); + outbyte += 8; + inbyte += 8; + } + } + + for (y = 1; y < height - 1; y++) + { + byte sd[4], sf[4], sg[4], si[4]; + byte *line2, *line3, *line4; + + x = y % 2 + 1; + + line2 = in + ((y - 1) * width + (x )) * 4; + line3 = in + ((y ) * width + (x - 1)) * 4; + line4 = in + ((y + 1) * width + (x )) * 4; + + COPYSAMPLE(sf, line3); line3 += 8; + + outbyte = out + (y * width + x) * 4; + + for ( ; x < width - 1; x += 2) + { + COPYSAMPLE(sd, line2); line2 += 8; + COPYSAMPLE(sg, line3); line3 += 8; + COPYSAMPLE(si, line4); line4 += 8; + + for (i = 0; i < 4; i++) + { + *outbyte++ = (sf[i] + sg[i] + sd[i] + si[i]) >> 2; + } + + outbyte += 4; + + COPYSAMPLE(sf, sg); + } + } +} + + +static void ExpandHalfTextureToGrid( byte *data, int width, int height) +{ + int x, y; + + for (y = height / 2; y > 0; y--) + { + byte *outbyte = data + ((y * 2 - 1) * (width) - 2) * 4; + byte *inbyte = data + (y * (width / 2) - 1) * 4; + + for (x = width / 2; x > 0; x--) + { + COPYSAMPLE(outbyte, inbyte); + + outbyte -= 8; + inbyte -= 4; + } + } +} + +static void FillInNormalizedZ(const byte *in, byte *out, int width, int height) +{ + int x, y; + + for (y = 0; y < height; y++) + { + const byte *inbyte = in + y * width * 4; + byte *outbyte = out + y * width * 4; + + for (x = 0; x < width; x++) + { + byte nx, ny, nz, h; + float fnx, fny, fll, fnz; + + nx = *inbyte++; + ny = *inbyte++; + inbyte++; + h = *inbyte++; + + fnx = OffsetByteToFloat(nx); + fny = OffsetByteToFloat(ny); + fll = 1.0f - fnx * fnx - fny * fny; + if (fll >= 0.0f) + fnz = (float)sqrt(fll); + else + fnz = 0.0f; + + nz = FloatToOffsetByte(fnz); + + *outbyte++ = nx; + *outbyte++ = ny; + *outbyte++ = nz; + *outbyte++ = h; + } + } +} + + +// size must be even +#define WORKBLOCK_SIZE 128 +#define WORKBLOCK_BORDER 4 +#define WORKBLOCK_REALSIZE (WORKBLOCK_SIZE + WORKBLOCK_BORDER * 2) + +// assumes that data has already been expanded into a 2x2 grid +static void FCBIByBlock(byte *data, int width, int height, qboolean clampToEdge, qboolean normalized) +{ + byte workdata[WORKBLOCK_REALSIZE * WORKBLOCK_REALSIZE * 4]; + byte outdata[WORKBLOCK_REALSIZE * WORKBLOCK_REALSIZE * 4]; + byte *inbyte, *outbyte; + int x, y; + int srcx, srcy; + + ExpandHalfTextureToGrid(data, width, height); + + for (y = 0; y < height; y += WORKBLOCK_SIZE) + { + for (x = 0; x < width; x += WORKBLOCK_SIZE) + { + int x2, y2; + int workwidth, workheight, fullworkwidth, fullworkheight; + + workwidth = MIN(WORKBLOCK_SIZE, width - x); + workheight = MIN(WORKBLOCK_SIZE, height - y); + + fullworkwidth = workwidth + WORKBLOCK_BORDER * 2; + fullworkheight = workheight + WORKBLOCK_BORDER * 2; + + //memset(workdata, 0, WORKBLOCK_REALSIZE * WORKBLOCK_REALSIZE * 4); + + // fill in work block + for (y2 = 0; y2 < fullworkheight; y2 += 2) + { + srcy = y + y2 - WORKBLOCK_BORDER; + + if (clampToEdge) + { + srcy = CLAMP(srcy, 0, height - 2); + } + else + { + srcy = (srcy + height) % height; + } + + outbyte = workdata + y2 * fullworkwidth * 4; + inbyte = data + srcy * width * 4; + + for (x2 = 0; x2 < fullworkwidth; x2 += 2) + { + srcx = x + x2 - WORKBLOCK_BORDER; + + if (clampToEdge) + { + srcx = CLAMP(srcx, 0, width - 2); + } + else + { + srcx = (srcx + width) % width; + } + + COPYSAMPLE(outbyte, inbyte + srcx * 4); + outbyte += 8; + } + } + + // submit work block + DoLinear(workdata, outdata, fullworkwidth, fullworkheight); + + if (!normalized) + { + switch (r_imageUpsampleType->integer) + { + case 0: + break; + case 1: + DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 0); + break; + case 2: + default: + DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 0); + break; + } + } + else + { + switch (r_imageUpsampleType->integer) + { + case 0: + break; + case 1: + DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 0); + DoFCBIQuick(workdata, outdata, fullworkwidth, fullworkheight, 1); + break; + case 2: + default: + DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 0); + DoFCBI(workdata, outdata, fullworkwidth, fullworkheight, 1); + break; + } + } + + // copy back work block + for (y2 = 0; y2 < workheight; y2++) + { + inbyte = outdata + ((y2 + WORKBLOCK_BORDER) * fullworkwidth + WORKBLOCK_BORDER) * 4; + outbyte = data + ((y + y2) * width + x) * 4; + for (x2 = 0; x2 < workwidth; x2++) + { + COPYSAMPLE(outbyte, inbyte); + outbyte += 4; + inbyte += 4; + } + } + } + } +} +#undef COPYSAMPLE + +/* +================ +R_LightScaleTexture + +Scale up the pixel values in a texture to increase the +lighting range +================ +*/ +void R_LightScaleTexture (byte *in, int inwidth, int inheight, qboolean only_gamma ) +{ + if ( only_gamma ) + { + if ( !glConfig.deviceSupportsGamma ) + { + int i, c; + byte *p; + + p = in; + + c = inwidth*inheight; + for (i=0 ; i> 1; + outHeight = inHeight >> 1; + temp = (unsigned int *)ri.Hunk_AllocateTempMemory( outWidth * outHeight * 4 ); + + inWidthMask = inWidth - 1; + inHeightMask = inHeight - 1; + + for ( i = 0 ; i < outHeight ; i++ ) { + for ( j = 0 ; j < outWidth ; j++ ) { + outpix = (byte *) ( temp + i * outWidth + j ); + for ( k = 0 ; k < 4 ; k++ ) { + total = + 1 * (&in[ 4*(((i*2-1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask)) ])[k] + + 2 * (&in[ 4*(((i*2-1)&inHeightMask)*inWidth + ((j*2 )&inWidthMask)) ])[k] + + 2 * (&in[ 4*(((i*2-1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask)) ])[k] + + 1 * (&in[ 4*(((i*2-1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask)) ])[k] + + + 2 * (&in[ 4*(((i*2 )&inHeightMask)*inWidth + ((j*2-1)&inWidthMask)) ])[k] + + 4 * (&in[ 4*(((i*2 )&inHeightMask)*inWidth + ((j*2 )&inWidthMask)) ])[k] + + 4 * (&in[ 4*(((i*2 )&inHeightMask)*inWidth + ((j*2+1)&inWidthMask)) ])[k] + + 2 * (&in[ 4*(((i*2 )&inHeightMask)*inWidth + ((j*2+2)&inWidthMask)) ])[k] + + + 2 * (&in[ 4*(((i*2+1)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask)) ])[k] + + 4 * (&in[ 4*(((i*2+1)&inHeightMask)*inWidth + ((j*2 )&inWidthMask)) ])[k] + + 4 * (&in[ 4*(((i*2+1)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask)) ])[k] + + 2 * (&in[ 4*(((i*2+1)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask)) ])[k] + + + 1 * (&in[ 4*(((i*2+2)&inHeightMask)*inWidth + ((j*2-1)&inWidthMask)) ])[k] + + 2 * (&in[ 4*(((i*2+2)&inHeightMask)*inWidth + ((j*2 )&inWidthMask)) ])[k] + + 2 * (&in[ 4*(((i*2+2)&inHeightMask)*inWidth + ((j*2+1)&inWidthMask)) ])[k] + + 1 * (&in[ 4*(((i*2+2)&inHeightMask)*inWidth + ((j*2+2)&inWidthMask)) ])[k]; + outpix[k] = total / 36; + } + } + } + + Com_Memcpy( in, temp, outWidth * outHeight * 4 ); + ri.Hunk_FreeTempMemory( temp ); +} + + +static void R_MipMapsRGB( byte *in, int inWidth, int inHeight) +{ + int i, j, k; + int outWidth, outHeight; + byte *temp; + + if ( r_simpleMipMaps->integer ) + return; + + outWidth = inWidth >> 1; + outHeight = inHeight >> 1; + temp = (byte *)ri.Hunk_AllocateTempMemory( outWidth * outHeight * 4 ); + + for ( i = 0 ; i < outHeight ; i++ ) { + byte *outbyte = temp + ( i * outWidth ) * 4; + byte *inbyte1 = in + ( i * 2 * inWidth ) * 4; + byte *inbyte2 = in + ( (i * 2 + 1) * inWidth ) * 4; + for ( j = 0 ; j < outWidth ; j++ ) { + for ( k = 0 ; k < 3 ; k++ ) { + float total, current; + + current = ByteToFloat(inbyte1[0]); total = sRGBtoRGB((double)current); + current = ByteToFloat(inbyte1[4]); total += sRGBtoRGB((double)current); + current = ByteToFloat(inbyte2[0]); total += sRGBtoRGB((double)current); + current = ByteToFloat(inbyte2[4]); total += sRGBtoRGB((double)current); + + total *= 0.25f; + + inbyte1++; + inbyte2++; + + current = RGBtosRGB(total); + *outbyte++ = FloatToByte(current); + } + *outbyte++ = (inbyte1[0] + inbyte1[4] + inbyte2[0] + inbyte2[4]) >> 2; + inbyte1 += 5; + inbyte2 += 5; + } + } + + Com_Memcpy( in, temp, outWidth * outHeight * 4 ); + ri.Hunk_FreeTempMemory( temp ); +} + +/* +================ +R_MipMap + +Operates in place, quartering the size of the texture +================ +*/ +static void R_MipMap (byte *in, int width, int height) { + + if ( !r_simpleMipMaps->integer ) + R_MipMap2( in, width, height ); + +} + + +static void R_MipMapLuminanceAlpha (const byte *in, byte *out, int width, int height) +{ + int i, j, row; + + if ( r_simpleMipMaps->integer ) + return; + + if ( width == 1 && height == 1 ) { + return; + } + + row = width * 4; + width >>= 1; + height >>= 1; + + if ( width == 0 || height == 0 ) { + width += height; // get largest + for (i=0 ; i> 1; + out[3] = (in[3] + in[7]) >> 1; + } + return; + } + + for (i=0 ; i> 2; + out[3] = (in[3] + in[7] + in[row+3] + in[row+7]) >> 2; + } + } + +} + + +static void R_MipMapNormalHeight (const byte *in, byte *out, int width, int height, qboolean swizzle) +{ + int i, j; + int row; + int sx = swizzle ? 3 : 0; + int sa = swizzle ? 0 : 3; + + if ( r_simpleMipMaps->integer ) + return; + + if ( width == 1 && height == 1 ) { + return; + } + + row = width * 4; + width >>= 1; + height >>= 1; + + for (i=0 ; i> 9; + data[1] = ( data[1] * inverseAlpha + premult[1] ) >> 9; + data[2] = ( data[2] * inverseAlpha + premult[2] ) >> 9; + } +} + +byte mipBlendColors[16][4] = { + {0,0,0,0}, + {255,0,0,128}, + {0,255,0,128}, + {0,0,255,128}, + {255,0,0,128}, + {0,255,0,128}, + {0,0,255,128}, + {255,0,0,128}, + {0,255,0,128}, + {0,0,255,128}, + {255,0,0,128}, + {0,255,0,128}, + {0,0,255,128}, + {255,0,0,128}, + {0,255,0,128}, + {0,0,255,128}, +}; + +static void RawImage_SwizzleRA( byte *data, int width, int height ) +{ + int i; + byte *ptr = data, swap; + + for (i=0; iinteger && scaled_width > width ) + scaled_width >>= 1; + if ( r_roundImagesDown->integer && scaled_height > height ) + scaled_height >>= 1; + + if ( picmip && data && resampledBuffer && r_imageUpsample->integer && + scaled_width < r_imageUpsampleMaxSize->integer && scaled_height < r_imageUpsampleMaxSize->integer) + { + int finalwidth, finalheight; + //int startTime, endTime; + + //startTime = ri.Milliseconds(); + + finalwidth = scaled_width << r_imageUpsample->integer; + finalheight = scaled_height << r_imageUpsample->integer; + + while ( finalwidth > r_imageUpsampleMaxSize->integer + || finalheight > r_imageUpsampleMaxSize->integer ) { + finalwidth >>= 1; + finalheight >>= 1; + } + + while ( finalwidth > glConfig.maxTextureSize + || finalheight > glConfig.maxTextureSize ) { + finalwidth >>= 1; + finalheight >>= 1; + } + + *resampledBuffer = (byte *)ri.Hunk_AllocateTempMemory( finalwidth * finalheight * 4 ); + + if (scaled_width != width || scaled_height != height) + { + ResampleTexture (*data, width, height, *resampledBuffer, scaled_width, scaled_height); + } + else + { + byte *inbyte, *outbyte; + int i; + + inbyte = *data; + outbyte = *resampledBuffer; + + for (i = width * height * 4; i > 0; i--) + { + *outbyte++ = *inbyte++; + } + } + + if (type == IMGTYPE_COLORALPHA) + RGBAtoYCoCgA(*resampledBuffer, *resampledBuffer, scaled_width, scaled_height); + + while (scaled_width < finalwidth || scaled_height < finalheight) + { + scaled_width <<= 1; + scaled_height <<= 1; + + FCBIByBlock(*resampledBuffer, scaled_width, scaled_height, clampToEdge, (qboolean)(type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT)); + } + + if (type == IMGTYPE_COLORALPHA) + { + YCoCgAtoRGBA(*resampledBuffer, *resampledBuffer, scaled_width, scaled_height); + } + else if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) + { + FillInNormalizedZ(*resampledBuffer, *resampledBuffer, scaled_width, scaled_height); + } + + + //endTime = ri.Milliseconds(); + + //ri.Printf(PRINT_ALL, "upsampled %dx%d to %dx%d in %dms\n", width, height, scaled_width, scaled_height, endTime - startTime); + + *data = *resampledBuffer; + width = scaled_width; + height = scaled_height; + } + else if ( scaled_width != width || scaled_height != height ) { + if (data && resampledBuffer) + { + *resampledBuffer = (byte *)ri.Hunk_AllocateTempMemory( scaled_width * scaled_height * 4 ); + ResampleTexture (*data, width, height, *resampledBuffer, scaled_width, scaled_height); + *data = *resampledBuffer; + } + width = scaled_width; + height = scaled_height; + } + + // + // perform optional picmip operation + // + if ( picmip ) { + scaled_width >>= r_picmip->integer; + scaled_height >>= r_picmip->integer; + } + + // + // clamp to minimum size + // + if (scaled_width < 1) { + scaled_width = 1; + } + if (scaled_height < 1) { + scaled_height = 1; + } + + // + // clamp to the current upper OpenGL limit + // scale both axis down equally so we don't have to + // deal with a half mip resampling + // + while ( scaled_width > glConfig.maxTextureSize + || scaled_height > glConfig.maxTextureSize ) { + scaled_width >>= 1; + scaled_height >>= 1; + } + + *inout_width = width; + *inout_height = height; + *inout_scaled_width = scaled_width; + *inout_scaled_height = scaled_height; +} + + +static qboolean RawImage_HasAlpha(const byte *scan, int numPixels) +{ + int i; + + if (!scan) + return qtrue; + + for ( i = 0; i < numPixels; i++ ) + { + if ( scan[i*4 + 3] != 255 ) + { + return qtrue; + } + } + + return qfalse; +} + +static GLenum RawImage_GetFormat(const byte *data, int numPixels, qboolean lightMap, imgType_t type, int flags) +{ + int samples = 3; + GLenum internalFormat = GL_RGB8; + qboolean forceNoCompression = (qboolean)(flags & IMGFLAG_NO_COMPRESSION); + qboolean normalmap = (qboolean)(type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT); + + if(normalmap) + { + if ((!RawImage_HasAlpha(data, numPixels) || (type == IMGTYPE_NORMAL)) && !forceNoCompression && (glRefConfig.textureCompression & TCR_LATC)) + { + internalFormat = GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT; + } + else + { + if ( !forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB ) + { + internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + } + else if ( r_texturebits->integer == 16 ) + { + internalFormat = GL_RGBA4; + } + else if ( r_texturebits->integer == 32 ) + { + internalFormat = GL_RGBA8; + } + else + { + internalFormat = GL_RGBA8; + } + } + } + else if(lightMap) + { +#if 0 + if(r_greyscale->integer) + internalFormat = GL_LUMINANCE; + else +#endif + internalFormat = GL_RGBA; + } + else + { + if (RawImage_HasAlpha(data, numPixels)) + { + samples = 4; + } + + // select proper internal format + if ( samples == 3 ) + { +#if 0 + if(r_greyscale->integer) + { + if(r_texturebits->integer == 16) + internalFormat = GL_LUMINANCE8; + else if(r_texturebits->integer == 32) + internalFormat = GL_LUMINANCE16; + else + internalFormat = GL_LUMINANCE; + } + else +#endif + { + if ( !forceNoCompression && (glRefConfig.textureCompression & TCR_BPTC) ) + { + internalFormat = GL_COMPRESSED_RGBA_BPTC_UNORM_ARB; + } + else if ( !forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB ) + { + internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; + } + else if ( !forceNoCompression && glConfig.textureCompression == TC_S3TC ) + { + internalFormat = GL_RGB4_S3TC; + } + else if ( r_texturebits->integer == 16 ) + { + internalFormat = GL_RGB5; + } + else if ( r_texturebits->integer == 32 ) + { + internalFormat = GL_RGB8; + } + else + { + internalFormat = GL_RGB8; + } + } + } + else if ( samples == 4 ) + { +#if 0 + if(r_greyscale->integer) + { + if(r_texturebits->integer == 16) + internalFormat = GL_LUMINANCE8_ALPHA8; + else if(r_texturebits->integer == 32) + internalFormat = GL_LUMINANCE16_ALPHA16; + else + internalFormat = GL_LUMINANCE_ALPHA; + } + else +#endif + { + if ( !forceNoCompression && (glRefConfig.textureCompression & TCR_BPTC) ) + { + internalFormat = GL_COMPRESSED_RGBA_BPTC_UNORM_ARB; + } + else if ( !forceNoCompression && glConfig.textureCompression == TC_S3TC_ARB ) + { + internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + } + else if ( r_texturebits->integer == 16 ) + { + internalFormat = GL_RGBA4; + } + else if ( r_texturebits->integer == 32 ) + { + internalFormat = GL_RGBA8; + } + else + { + internalFormat = GL_RGBA8; + } + } + } + + if (flags & IMGFLAG_SRGB) + { + switch(internalFormat) + { + case GL_RGB: + internalFormat = GL_SRGB8; + break; + + case GL_RGB4: + case GL_RGB5: + case GL_RGB8: + internalFormat = GL_SRGB8; + break; + + case GL_RGBA: + internalFormat = GL_SRGB_ALPHA; + break; + + case GL_RGBA4: + case GL_RGBA8: + internalFormat = GL_SRGB8_ALPHA8; + break; + + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: + internalFormat = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; + break; + + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: + internalFormat = GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; + break; + + case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: + internalFormat = GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB; + break; + } + } + } + + return internalFormat; +} + +static int CalcNumMipmapLevels ( int width, int height ) +{ + return static_cast(ceil (log2 (Q_max (width, height))) + 1); +} + +static qboolean IsBPTCTextureFormat( GLenum internalformat ) +{ + switch ( internalformat ) + { + case GL_COMPRESSED_RGBA_BPTC_UNORM_ARB: + case GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB: + case GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB: + case GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB: + return qtrue; + + default: + return qfalse; + } +} + +static qboolean ShouldUseImmutableTextures(int imageFlags, GLenum internalformat) +{ + if ( glRefConfig.hardwareVendor == IHV_AMD ) + { + // Corrupted texture data is seen when using BPTC + immutable textures + if ( IsBPTCTextureFormat( internalformat ) ) + { + return qfalse; + } + } + + if ( imageFlags & IMGFLAG_MUTABLE ) + { + return qfalse; + } + + return glRefConfig.immutableTextures; +} + +static void RawImage_UploadTexture( byte *data, int x, int y, int width, int height, GLenum internalFormat, imgType_t type, int flags, qboolean subtexture ) +{ + int dataFormat, dataType; + + switch (internalFormat) + { + case GL_DEPTH_COMPONENT: + case GL_DEPTH_COMPONENT16: + case GL_DEPTH_COMPONENT24: + case GL_DEPTH_COMPONENT32: + dataFormat = GL_DEPTH_COMPONENT; + dataType = GL_UNSIGNED_BYTE; + break; + case GL_RG16F: + dataFormat = GL_RG; + dataType = GL_HALF_FLOAT; + break; + case GL_RGB16F: + dataFormat = GL_RGB; + dataType = GL_HALF_FLOAT; + break; + case GL_RGBA16F: + dataFormat = GL_RGBA; + dataType = GL_HALF_FLOAT; + break; + case GL_RG32F: + dataFormat = GL_RG; + dataType = GL_FLOAT; + break; + case GL_RGBA32F: + dataFormat = GL_RGBA; + dataType = GL_FLOAT; + break; + default: + dataFormat = GL_RGBA; + dataType = GL_UNSIGNED_BYTE; + break; + } + + if ( subtexture ) + { + qglTexSubImage2D (GL_TEXTURE_2D, 0, x, y, width, height, dataFormat, dataType, data); + } + else + { + if ( ShouldUseImmutableTextures( flags, internalFormat ) ) + { + int numLevels = (flags & IMGFLAG_MIPMAP) ? CalcNumMipmapLevels (width, height) : 1; + + qglTexStorage2D (GL_TEXTURE_2D, numLevels, internalFormat, width, height); + + if ( data != NULL ) + { + qglTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, width, height, dataFormat, dataType, data); + } + } + else + { + qglTexImage2D (GL_TEXTURE_2D, 0, internalFormat, width, height, 0, dataFormat, dataType, data ); + } + } + + if ((flags & IMGFLAG_MIPMAP) && (!r_simpleMipMaps->integer) && + (data != NULL || !ShouldUseImmutableTextures(flags, internalFormat) )) + { + // Don't need to generate mipmaps if we are generating an immutable texture and + // the data is NULL. All levels have already been allocated by glTexStorage2D. + + int miplevel = 0; + + while (width > 1 || height > 1) + { + if (data) + { + if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) + { + if (internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) + { + R_MipMapLuminanceAlpha( data, data, width, height ); + } + else + { + R_MipMapNormalHeight( data, data, width, height, qtrue); + } + } + else if (flags & IMGFLAG_SRGB) + { + R_MipMapsRGB( data, width, height ); + } + else + { + R_MipMap( data, width, height ); + } + } + + width >>= 1; + height >>= 1; + if (width < 1) + width = 1; + if (height < 1) + height = 1; + miplevel++; + + if ( data && r_colorMipLevels->integer ) + R_BlendOverTexture( (byte *)data, width * height, mipBlendColors[miplevel] ); + + if ( subtexture ) + { + x >>= 1; + y >>= 1; + qglTexSubImage2D( GL_TEXTURE_2D, miplevel, x, y, width, height, dataFormat, dataType, data ); + } + else + { + if ( ShouldUseImmutableTextures(flags, internalFormat) ) + { + qglTexSubImage2D (GL_TEXTURE_2D, miplevel, 0, 0, width, height, dataFormat, dataType, data ); + } + else + { + qglTexImage2D (GL_TEXTURE_2D, miplevel, internalFormat, width, height, 0, dataFormat, dataType, data ); + } + } + } + } +} + +static bool IsPowerOfTwo ( int i ) +{ + return (i & (i - 1)) == 0; +} + +/* +=============== +Upload32 + +=============== +*/ +extern qboolean charSet; +static void Upload32( byte *data, int width, int height, imgType_t type, int flags, + qboolean lightMap, GLenum internalFormat, int *pUploadWidth, int *pUploadHeight) +{ + byte *scaledBuffer = NULL; + byte *resampledBuffer = NULL; + int scaled_width = width; + int scaled_height = height; + int i, c; + byte *scan; + + if ( !IsPowerOfTwo (width) || !IsPowerOfTwo (height) ) + { + RawImage_ScaleToPower2(&data, &width, &height, &scaled_width, &scaled_height, type, flags, &resampledBuffer); + } + + scaledBuffer = (byte *)ri.Hunk_AllocateTempMemory( sizeof( unsigned ) * scaled_width * scaled_height ); + + // + // scan the texture for each channel's max values + // and verify if the alpha channel is being used or not + // + c = width*height; + scan = data; + + if( r_greyscale->integer ) + { + for ( i = 0; i < c; i++ ) + { + byte luma = LUMA(scan[i*4], scan[i*4 + 1], scan[i*4 + 2]); + scan[i*4] = luma; + scan[i*4 + 1] = luma; + scan[i*4 + 2] = luma; + } + } + else if( r_greyscale->value ) + { + for ( i = 0; i < c; i++ ) + { + float luma = LUMA(scan[i*4], scan[i*4 + 1], scan[i*4 + 2]); + scan[i*4] = LERP(scan[i*4], luma, r_greyscale->value); + scan[i*4 + 1] = LERP(scan[i*4 + 1], luma, r_greyscale->value); + scan[i*4 + 2] = LERP(scan[i*4 + 2], luma, r_greyscale->value); + } + } + + // normals are always swizzled + if (type == IMGTYPE_NORMAL || type == IMGTYPE_NORMALHEIGHT) + { + RawImage_SwizzleRA(data, width, height); + } + + // LATC2 is only used for normals + if (internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) + { + byte *in = data; + int c = width * height; + while (c--) + { + in[0] = in[1]; + in[2] = in[1]; + in += 4; + } + } + + // copy or resample data as appropriate for first MIP level + if ( ( scaled_width == width ) && + ( scaled_height == height ) ) { + if (!(flags & IMGFLAG_MIPMAP)) + { + RawImage_UploadTexture( data, 0, 0, scaled_width, scaled_height, internalFormat, type, flags, qfalse ); + //qglTexImage2D (GL_TEXTURE_2D, 0, internalFormat, scaled_width, scaled_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + *pUploadWidth = scaled_width; + *pUploadHeight = scaled_height; + + goto done; + } + Com_Memcpy (scaledBuffer, data, width*height*4); + } + else if ( !r_simpleMipMaps->integer ) + { + // use the normal mip-mapping function to go down from here + while ( width > scaled_width || height > scaled_height ) { + + if (flags & IMGFLAG_SRGB) + { + R_MipMapsRGB( (byte *)data, width, height ); + } + else + { + R_MipMap( (byte *)data, width, height ); + } + + width >>= 1; + height >>= 1; + if ( width < 1 ) { + width = 1; + } + if ( height < 1 ) { + height = 1; + } + } + Com_Memcpy( scaledBuffer, data, width * height * 4 ); + } + + if (!(flags & IMGFLAG_NOLIGHTSCALE)) + R_LightScaleTexture (scaledBuffer, scaled_width, scaled_height, (qboolean)(!(flags & IMGFLAG_MIPMAP)) ); + + *pUploadWidth = scaled_width; + *pUploadHeight = scaled_height; + + RawImage_UploadTexture(scaledBuffer, 0, 0, scaled_width, scaled_height, internalFormat, type, flags, qfalse); + +done: + + if (flags & IMGFLAG_MIPMAP) + { + if (r_ext_texture_filter_anisotropic->value > 1.0f && glConfig.maxTextureFilterAnisotropy > 0.0f) + { + qglTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, + Com_Clamp( 1.0f, glConfig.maxTextureFilterAnisotropy, r_ext_texture_filter_anisotropic->value ) ); + } + + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); + } + else + { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + } + + GL_CheckErrors(); + + if ( scaledBuffer != 0 ) + ri.Hunk_FreeTempMemory( scaledBuffer ); + if ( resampledBuffer != 0 ) + ri.Hunk_FreeTempMemory( resampledBuffer ); +} + + +static void EmptyTexture( int width, int height, imgType_t type, int flags, + qboolean lightMap, GLenum internalFormat, int *pUploadWidth, int *pUploadHeight ) +{ + int scaled_width, scaled_height; + + RawImage_ScaleToPower2(NULL, &width, &height, &scaled_width, &scaled_height, type, flags, NULL); + + *pUploadWidth = scaled_width; + *pUploadHeight = scaled_height; + + RawImage_UploadTexture(NULL, 0, 0, scaled_width, scaled_height, internalFormat, type, flags, qfalse); + + if (flags & IMGFLAG_MIPMAP) + { + if (r_ext_texture_filter_anisotropic->integer > 1 && glConfig.maxTextureFilterAnisotropy > 0.0f) + { + qglTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, + (GLint)Com_Clamp( 1, glConfig.maxTextureFilterAnisotropy, r_ext_texture_filter_anisotropic->integer ) ); + } + + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl_filter_min); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl_filter_max); + } + else + { + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + } + + // Fix for sampling depth buffer on old nVidia cards + // from http://www.idevgames.com/forums/thread-4141-post-34844.html#pid34844 + switch(internalFormat) + { + case GL_DEPTH_COMPONENT: + case GL_DEPTH_COMPONENT16: + case GL_DEPTH_COMPONENT24: + case GL_DEPTH_COMPONENT32: + //qglTexParameterf(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + break; + default: + break; + } + + GL_CheckErrors(); +} + +static image_t *R_AllocImage() +{ + image_t *result; + + if ( !tr.imagesFreeList ) + { + R_ExtendImagesPool(); + } + + // Remove from free list + result = tr.imagesFreeList; + tr.imagesFreeList = tr.imagesFreeList->poolNext; + + // Add to list of used images + result->poolNext = tr.images; + tr.images = result; + + tr.numImages++; + + return result; +} + +#if 0 +static void R_FreeImage( image_t *imageToFree ) +{ + if ( imageToFree ) + { + // Images aren't deleted individually very often. Not a + // problem to do this really... + if ( imageToFree == tr.images ) + { + tr.images = imageToFree->poolNext; + imageToFree->poolNext = tr.imagesFreeList; + tr.imagesFreeList = imageToFree; + + tr.numImages--; + } + else + { + image_t *image = tr.images; + while ( image ) + { + if ( image->poolNext == imageToFree ) + { + image->poolNext = imageToFree->poolNext; + imageToFree->poolNext = tr.imagesFreeList; + tr.imagesFreeList = imageToFree; + + tr.numImages--; + break; + } + + image = image->poolNext; + } + } + } +} +#endif + +/* +================ +R_CreateImage + +This is the only way any 2d image_t are created +================ +*/ +image_t *R_CreateImage( const char *name, byte *pic, int width, int height, imgType_t type, int flags, int internalFormat ) { + image_t *image; + qboolean isLightmap = qfalse; + long hash; + int glWrapClampMode; + + if (strlen(name) >= MAX_QPATH ) { + ri.Error (ERR_DROP, "R_CreateImage: \"%s\" is too long", name); + } + if ( !strncmp( name, "*lightmap", 9 ) ) { + isLightmap = qtrue; + } + + image = R_AllocImage(); + qglGenTextures(1, &image->texnum); + + image->type = type; + image->flags = flags; + + Q_strncpyz (image->imgName, name, sizeof (image->imgName)); + + image->width = width; + image->height = height; + if (flags & IMGFLAG_CLAMPTOEDGE) + glWrapClampMode = GL_CLAMP_TO_EDGE; + else + glWrapClampMode = GL_REPEAT; + + if (!internalFormat) + { + if (image->flags & IMGFLAG_CUBEMAP) + internalFormat = r_hdr->integer ? GL_RGBA16F : GL_RGBA8; + else + internalFormat = RawImage_GetFormat(pic, width * height, isLightmap, image->type, image->flags); + } + + image->internalFormat = internalFormat; + + // lightmaps are always allocated on TMU 1 + if ( isLightmap ) { + image->TMU = 1; + } else { + image->TMU = 0; + } + + GL_SelectTexture( image->TMU ); + + if (image->flags & IMGFLAG_CUBEMAP) + { + GL_Bind(image); + qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + + int format = GL_BGRA; + switch (internalFormat) + { + case GL_DEPTH_COMPONENT: + case GL_DEPTH_COMPONENT16: + case GL_DEPTH_COMPONENT24: + case GL_DEPTH_COMPONENT32: + format = GL_DEPTH_COMPONENT; + break; + default: + break; + } + + if (image->flags & IMGFLAG_MIPMAP) + { + qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + } + else + { + qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + } + qglTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + if ( ShouldUseImmutableTextures( image->flags, internalFormat ) ) + { + int numLevels = (image->flags & IMGFLAG_MIPMAP) ? CalcNumMipmapLevels (width, height) : 1; + + qglTexStorage2D (GL_TEXTURE_CUBE_MAP, numLevels, internalFormat, width, height); + + if ( pic != NULL ) + { + for ( int i = 0; i < 6; i++ ) + { + qglTexSubImage2D (GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, pic); + } + } + } + else + { + qglTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); + qglTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); + qglTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); + qglTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); + qglTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); + qglTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, internalFormat, width, height, 0, format, GL_UNSIGNED_BYTE, pic); + } + + if (image->flags & IMGFLAG_MIPMAP) + qglGenerateMipmap(GL_TEXTURE_CUBE_MAP); + + image->uploadWidth = width; + image->uploadHeight = height; + } + else + { + GL_Bind(image); + + if (r_smartpicmip && r_smartpicmip->integer && Q_stricmpn(name, "textures/", 9)) { + image->flags &= ~(IMGFLAG_PICMIP); + } + + if (pic) + { + Upload32( pic, image->width, image->height, image->type, image->flags, + isLightmap, image->internalFormat, &image->uploadWidth, + &image->uploadHeight ); + } + else + { + EmptyTexture(image->width, image->height, image->type, image->flags, + isLightmap, image->internalFormat, &image->uploadWidth, + &image->uploadHeight ); + } + + qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glWrapClampMode ); + qglTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glWrapClampMode ); + + if (image->flags & IMGFLAG_MIPMAP && r_simpleMipMaps->integer) + qglGenerateMipmap(GL_TEXTURE_2D); + } + + GL_SelectTexture( 0 ); + + hash = generateHashValue(name); + image->next = hashTable[hash]; + hashTable[hash] = image; + + return image; +} + +/* +================ +R_Create2DImageArray + +This is the only way any 2d array sampler image_t are created +================ +*/ +image_t *R_Create2DImageArray(const char *name, byte *pic, int width, int height, int layers, imgType_t type, int flags, int internalFormat) +{ + image_t *image; + long hash; + int glWrapClampMode; + int format; + + if (strlen(name) >= MAX_QPATH) { + ri.Error(ERR_DROP, "R_Create2DImageArray: \"%s\" is too long", name); + } + + image = R_AllocImage(); + qglGenTextures(1, &image->texnum); + + image->type = type; + image->flags = flags | IMGFLAG_2D_ARRAY; + + Q_strncpyz(image->imgName, name, sizeof(image->imgName)); + + image->width = width; + image->height = height; + image->layers = layers; + image->internalFormat = internalFormat; + + if (flags & IMGFLAG_CLAMPTOEDGE) + glWrapClampMode = GL_CLAMP_TO_EDGE; + else + glWrapClampMode = GL_REPEAT; + + switch (internalFormat) + { + case GL_DEPTH_COMPONENT: + case GL_DEPTH_COMPONENT16: + case GL_DEPTH_COMPONENT24: + case GL_DEPTH_COMPONENT32: + format = GL_DEPTH_COMPONENT; + break; + default: + format = GL_BGRA; + break; + } + + GL_SelectTexture(0); + GL_Bind(image); + if (ShouldUseImmutableTextures(image->flags, internalFormat)) + qglTexStorage3D(GL_TEXTURE_2D_ARRAY, 0, internalFormat, width, height, layers); + else + qglTexImage3D(GL_TEXTURE_2D_ARRAY, 0, internalFormat, width, height, layers, 0, format, GL_UNSIGNED_BYTE, NULL); + + switch (internalFormat) + { + case GL_DEPTH_COMPONENT: + case GL_DEPTH_COMPONENT16: + case GL_DEPTH_COMPONENT24: + case GL_DEPTH_COMPONENT32: + + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + if (flags & IMGLFAG_SHADOWCOMP) + { + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); + qglTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); + } + else + { + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } + + break; + default: + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, glWrapClampMode); + qglTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, glWrapClampMode); + break; + } + qglBindTexture(GL_TEXTURE_2D_ARRAY, 0); + GL_SelectTexture(0); + + hash = generateHashValue(name); + image->next = hashTable[hash]; + hashTable[hash] = image; + + return image; +} + +void R_UpdateSubImage( image_t *image, byte *pic, int x, int y, int width, int height ) +{ + byte *scaledBuffer = NULL; + byte *resampledBuffer = NULL; + int scaled_width, scaled_height, scaled_x, scaled_y; + byte *data = pic; + + // normals are always swizzled + if (image->type == IMGTYPE_NORMAL || image->type == IMGTYPE_NORMALHEIGHT) + { + RawImage_SwizzleRA(pic, width, height); + } + + // LATC2 is only used for normals + if (image->internalFormat == GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT) + { + byte *in = data; + int c = width * height; + while (c--) + { + in[0] = in[1]; + in[2] = in[1]; + in += 4; + } + } + + + RawImage_ScaleToPower2(&pic, &width, &height, &scaled_width, &scaled_height, image->type, image->flags, &resampledBuffer); + + scaledBuffer = (byte *)ri.Hunk_AllocateTempMemory( sizeof( unsigned ) * scaled_width * scaled_height ); + + GL_SelectTexture( image->TMU ); + GL_Bind(image); + + // copy or resample data as appropriate for first MIP level + if ( ( scaled_width == width ) && + ( scaled_height == height ) ) { + if (!(image->flags & IMGFLAG_MIPMAP)) + { + scaled_x = x * scaled_width / width; + scaled_y = y * scaled_height / height; + RawImage_UploadTexture( data, scaled_x, scaled_y, scaled_width, scaled_height, image->internalFormat, image->type, image->flags, qtrue ); + //qglTexSubImage2D( GL_TEXTURE_2D, 0, scaled_x, scaled_y, scaled_width, scaled_height, GL_RGBA, GL_UNSIGNED_BYTE, data ); + + GL_CheckErrors(); + goto done; + } + Com_Memcpy (scaledBuffer, data, width*height*4); + } + else if ( !r_simpleMipMaps->integer ) + { + // use the normal mip-mapping function to go down from here + while ( width > scaled_width || height > scaled_height ) { + + if (image->flags & IMGFLAG_SRGB) + { + R_MipMapsRGB( (byte *)data, width, height ); + } + else + { + R_MipMap( (byte *)data, width, height ); + } + + width >>= 1; + height >>= 1; + x >>= 1; + y >>= 1; + if ( width < 1 ) { + width = 1; + } + if ( height < 1 ) { + height = 1; + } + } + Com_Memcpy( scaledBuffer, data, width * height * 4 ); + } + else if ( !r_simpleMipMaps->integer ) + { + qglGenerateMipmap(GL_TEXTURE_2D); + } + + if (!(image->flags & IMGFLAG_NOLIGHTSCALE)) + R_LightScaleTexture (scaledBuffer, scaled_width, scaled_height, (qboolean)(!(image->flags & IMGFLAG_MIPMAP)) ); + + scaled_x = x * scaled_width / width; + scaled_y = y * scaled_height / height; + RawImage_UploadTexture( (byte *)data, scaled_x, scaled_y, scaled_width, scaled_height, image->internalFormat, image->type, image->flags, qtrue ); + +done: + + GL_SelectTexture( 0 ); + + GL_CheckErrors(); + + if ( scaledBuffer != 0 ) + ri.Hunk_FreeTempMemory( scaledBuffer ); + if ( resampledBuffer != 0 ) + ri.Hunk_FreeTempMemory( resampledBuffer ); +} + +image_t* R_GetLoadedImage(const char *name, int flags) { + long hash; + image_t *image; + + hash = generateHashValue(name); + for (image = hashTable[hash]; image; image = image->next) { + if (!strcmp(name, image->imgName)) { + // the white image can be used with any set of parms, but other mismatches are errors + if (strcmp(name, "*white")) { + if (image->flags != flags) { + ri.Printf(PRINT_DEVELOPER, "WARNING: reused image %s with mixed flags (%i vs %i)\n", name, image->flags, flags); + } + } + return image; + } + } + return NULL; +} + +void R_LoadPackedMaterialImage(shaderStage_t *stage, const char *packedImageName, int flags) +{ + char packedName[MAX_QPATH]; + int packedWidth, packedHeight; + byte *packedPic; + image_t *image; + + if (!packedImageName) { + return; + } + + float baseSpecularScale = 1.0f; + switch (stage->specularType) + { + case SPEC_RMOS: + case SPEC_MOSR: + case SPEC_ORMS: + // Don't scale base specular + break; + default: + baseSpecularScale = 0.5f; // Basespecular is assumed to be 0.04 and shader assumes 0.08 + break; + } + + COM_StripExtension(packedImageName, packedName, sizeof(packedName)); + Q_strcat(packedName, sizeof(packedName), "_ORMS"); + + // + // see if the image is already loaded + // + image = R_GetLoadedImage(packedName, flags); + if (image != NULL) + { + // Don't scale occlusion, roughness and metalness + stage->specularScale[0] = + stage->specularScale[2] = + stage->specularScale[3] = 1.0f; + stage->specularScale[1] = baseSpecularScale; + + stage->bundle[TB_ORMSMAP].image[0] = image; + return; + } + + R_LoadImage(packedImageName, &packedPic, &packedWidth, &packedHeight); + if (packedPic == NULL) { + return; + } + + // Don't scale occlusion, roughness and metalness + stage->specularScale[0] = + stage->specularScale[2] = + stage->specularScale[3] = 1.0f; + stage->specularScale[1] = baseSpecularScale; + + GLint swizzle[4] = { GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA }; + + switch (stage->specularType) + { + case SPEC_RMO: + swizzle[0] = GL_BLUE; + swizzle[1] = GL_RED; + swizzle[2] = GL_GREEN; + swizzle[3] = GL_ONE; + break; + case SPEC_RMOS: + swizzle[0] = GL_BLUE; + swizzle[1] = GL_RED; + swizzle[2] = GL_GREEN; + swizzle[3] = GL_ALPHA; + break; + case SPEC_MOXR: + swizzle[0] = GL_GREEN; + swizzle[1] = GL_ALPHA; + swizzle[2] = GL_RED; + swizzle[3] = GL_ONE; + break; + case SPEC_MOSR: + swizzle[0] = GL_GREEN; + swizzle[1] = GL_ALPHA; + swizzle[2] = GL_RED; + swizzle[3] = GL_BLUE; + break; + case SPEC_ORM: + case SPEC_ORMS: + default: + break; + } + + stage->bundle[TB_ORMSMAP].image[0] = R_CreateImage(packedName, packedPic, packedWidth, packedHeight, IMGTYPE_COLORALPHA, flags & ~IMGFLAG_SRGB, 0); + glBindTexture(GL_TEXTURE_2D, stage->bundle[TB_ORMSMAP].image[0]->texnum); + glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzle); + Z_Free(packedPic); +} + +image_t *R_BuildSDRSpecGlossImage(shaderStage_t *stage, const char *specImageName, int flags) +{ + char sdrName[MAX_QPATH]; + int specWidth, specHeight; + byte *specPic; + image_t *image; + + if (!specImageName) + return NULL; + + COM_StripExtension(specImageName, sdrName, sizeof(sdrName)); + Q_strcat(sdrName, sizeof(sdrName), "_SDR"); + + // + // see if the image is already loaded + // + image = R_GetLoadedImage(sdrName, flags); + if (image != NULL) + return image; + + R_LoadImage(specImageName, &specPic, &specWidth, &specHeight); + if (specPic == NULL) + return NULL; + + byte *sdrSpecPic = (byte *)ri.Hunk_AllocateTempMemory(sizeof(unsigned) * specWidth * specHeight); + vec3_t currentColor; + for (int i = 0; i < specWidth * specHeight * 4; i += 4) + { + currentColor[0] = ByteToFloat(specPic[i + 0]); + currentColor[1] = ByteToFloat(specPic[i + 1]); + currentColor[2] = ByteToFloat(specPic[i + 2]); + + float ratio = + (sRGBtoRGB(currentColor[0]) + sRGBtoRGB(currentColor[1]) + sRGBtoRGB(currentColor[1])) / + (currentColor[0] + currentColor[1] + currentColor[2]); + + sdrSpecPic[i + 0] = FloatToByte(currentColor[0] * ratio); + sdrSpecPic[i + 1] = FloatToByte(currentColor[1] * ratio); + sdrSpecPic[i + 2] = FloatToByte(currentColor[2] * ratio); + sdrSpecPic[i + 3] = specPic[i + 3]; + } + ri.Hunk_FreeTempMemory(specPic); + + return R_CreateImage(sdrName, sdrSpecPic, specWidth, specHeight, IMGTYPE_COLORALPHA, flags & ~IMGFLAG_SRGB, 0); +} + +static void R_CreateNormalMap ( const char *name, byte *pic, int width, int height, int flags ) +{ + char normalName[MAX_QPATH]; + image_t *normalImage; + int normalWidth, normalHeight; + int normalFlags; + + normalFlags = (flags & ~(IMGFLAG_GENNORMALMAP | IMGFLAG_SRGB)) | IMGFLAG_NOLIGHTSCALE; + + COM_StripExtension(name, normalName, sizeof(normalName)); + Q_strcat(normalName, sizeof(normalName), "_n"); + + // find normalmap in case it's there + normalImage = R_FindImageFile(normalName, IMGTYPE_NORMAL, normalFlags); + + // if not, generate it + if (normalImage == NULL) + { + byte *normalPic; + int x, y; + + normalWidth = width; + normalHeight = height; + normalPic = (byte *)Z_Malloc(width * height * 4, TAG_GENERAL); + RGBAtoNormal(pic, normalPic, width, height, (qboolean)(flags & IMGFLAG_CLAMPTOEDGE)); + +#if 1 + // Brighten up the original image to work with the normal map + RGBAtoYCoCgA(pic, pic, width, height); + for (y = 0; y < height; y++) + { + byte *picbyte = pic + y * width * 4; + byte *normbyte = normalPic + y * width * 4; + for (x = 0; x < width; x++) + { + int div = MAX(normbyte[2] - 127, 16); + picbyte[0] = CLAMP(picbyte[0] * 128 / div, 0, 255); + picbyte += 4; + normbyte += 4; + } + } + YCoCgAtoRGBA(pic, pic, width, height); +#else + // Blur original image's luma to work with the normal map + { + byte *blurPic; + + RGBAtoYCoCgA(pic, pic, width, height); + blurPic = ri.Malloc(width * height); + + for (y = 1; y < height - 1; y++) + { + byte *picbyte = pic + y * width * 4; + byte *blurbyte = blurPic + y * width; + + picbyte += 4; + blurbyte += 1; + + for (x = 1; x < width - 1; x++) + { + int result; + + result = *(picbyte - (width + 1) * 4) + *(picbyte - width * 4) + *(picbyte - (width - 1) * 4) + + *(picbyte - 1 * 4) + *(picbyte ) + *(picbyte + 1 * 4) + + *(picbyte + (width - 1) * 4) + *(picbyte + width * 4) + *(picbyte + (width + 1) * 4); + + result /= 9; + + *blurbyte = result; + picbyte += 4; + blurbyte += 1; + } + } + + // FIXME: do borders + + for (y = 1; y < height - 1; y++) + { + byte *picbyte = pic + y * width * 4; + byte *blurbyte = blurPic + y * width; + + picbyte += 4; + blurbyte += 1; + + for (x = 1; x < width - 1; x++) + { + picbyte[0] = *blurbyte; + picbyte += 4; + blurbyte += 1; + } + } + + ri.Free(blurPic); + + YCoCgAtoRGBA(pic, pic, width, height); + } +#endif + + R_CreateImage( normalName, normalPic, normalWidth, normalHeight, IMGTYPE_NORMAL, normalFlags, 0 ); + Z_Free( normalPic ); + } +} + +/* +=============== +R_FindImageFile + +Finds or loads the given image. +Returns NULL if it fails, not a default image. +============== +*/ +image_t *R_FindImageFile( const char *name, imgType_t type, int flags ) +{ + image_t *image; + int width, height; + byte *pic; + int internalFormat = 0; + int loadFlags = flags; + + if (!name) { + return NULL; + } + + if ((image = R_GetLoadedImage(name, flags)) != NULL) + return image; + + // + // load the pic from disk + // + if (r_hdr->integer && (flags & IMGFLAG_HDR || flags & IMGFLAG_HDR_LIGHTMAP)) + { + char filename[MAX_QPATH]; + Com_sprintf(filename, sizeof(filename), "%s.hdr", name); + float *floatBuffer; + R_LoadHDRImage(filename, &pic, &width, &height); + if (pic == NULL) + { + R_LoadImage(name, &pic, &width, &height); + } + else + { + for (int i = 0; i < width*height; i++) + { + vec4_t color; + floatBuffer = (float*)pic; + memcpy(color, &floatBuffer[i*3], 12); + if (flags & IMGFLAG_HDR_LIGHTMAP) + { + color[0] = color[0] / M_PI; + color[1] = color[1] / M_PI; + color[2] = color[2] / M_PI; + } + color[3] = 1.0f; + + uint16_t *hdr_color = (uint16_t *)(&pic[i * 8]); + hdr_color[0] = FloatToHalf(color[0]); + hdr_color[1] = FloatToHalf(color[1]); + hdr_color[2] = FloatToHalf(color[2]); + hdr_color[3] = FloatToHalf(1.0f); + } + internalFormat = GL_RGBA16F; + loadFlags = flags & ~(IMGFLAG_GENNORMALMAP | IMGFLAG_MIPMAP); + } + } + else + { + R_LoadImage(name, &pic, &width, &height); + } + + if ( pic == NULL ) { + return NULL; + } + + if (r_normalMapping->integer && !(type == IMGTYPE_NORMAL) && + (flags & IMGFLAG_PICMIP) && (flags & IMGFLAG_MIPMAP) && (flags & IMGFLAG_GENNORMALMAP)) + { + R_CreateNormalMap( name, pic, width, height, flags ); + } + + // flip height info, so we don't need to do this in the shader later + if (type == IMGTYPE_NORMALHEIGHT) + { + for (int i = 0; i < width*height; i++) + { + pic[4 * i + 3] = 255 - pic[4 * i + 3]; + } + } + + image = R_CreateImage( name, pic, width, height, type, loadFlags, internalFormat); + Z_Free( pic ); + + return image; +} + + +/* +================ +R_CreateDlightImage +================ +*/ +#define DLIGHT_SIZE 16 +static void R_CreateDlightImage( void ) { + int width, height; + byte *pic; + + R_LoadImage("gfx/2d/dlight", &pic, &width, &height); + if (pic) + { + tr.dlightImage = R_CreateImage("*dlight", pic, width, height, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0 ); + Z_Free(pic); + } + else + { // if we dont get a successful load + int x,y; + byte data[DLIGHT_SIZE][DLIGHT_SIZE][4]; + int b; + + // make a centered inverse-square falloff blob for dynamic lighting + for (x=0 ; x 255) { + b = 255; + } else if ( b < 75 ) { + b = 0; + } + data[y][x][0] = + data[y][x][1] = + data[y][x][2] = b; + data[y][x][3] = 255; + } + } + tr.dlightImage = R_CreateImage("*dlight", (byte *)data, DLIGHT_SIZE, DLIGHT_SIZE, IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, 0 ); + } +} + + +/* +================= +R_InitFogTable +================= +*/ +void R_InitFogTable( void ) { + int i; + float d; + float exp; + + exp = 0.5; + + for ( i = 0 ; i < FOG_TABLE_SIZE ; i++ ) { + d = pow ( (float)i/(FOG_TABLE_SIZE-1), exp ); + + tr.fogTable[i] = d; + } +} + +/* +================ +R_FogFactor + +Returns a 0.0 to 1.0 fog density value +This is called for each texel of the fog texture on startup +and for each vertex of transparent shaders in fog dynamically +================ +*/ +float R_FogFactor( float s, float t ) { + float d; + + s -= 1.0/512; + if ( s < 0 ) { + return 0; + } + if ( t < 1.0/32 ) { + return 0; + } + if ( t < 31.0/32 ) { + s *= (t - 1.0f/32.0f) / (30.0f/32.0f); + } + + // we need to leave a lot of clamp range + s *= 8; + + if ( s > 1.0 ) { + s = 1.0; + } + + d = tr.fogTable[ (int)(s * (FOG_TABLE_SIZE-1)) ]; + + return d; +} + +/* +================ +R_CreateFogImage +================ +*/ +#define FOG_S 256 +#define FOG_T 32 +static void R_CreateFogImage( void ) { + int x,y; + byte *data; + float d; + float borderColor[4]; + + data = (byte *)ri.Hunk_AllocateTempMemory( FOG_S * FOG_T * 4 ); + + // S is distance, T is depth + for (x=0 ; xinteger) + return; + + uint16_t data[LUT_WIDTH][LUT_HEIGHT][3]; + + unsigned const numSamples = 1024; + + for (unsigned y = 0; y < LUT_HEIGHT; ++y) + { + float const NdotV = (y + 0.5f) / LUT_HEIGHT; + float const vx = sqrtf(1.0f - NdotV * NdotV); + float const vy = 0.0f; + float const vz = NdotV; + + for (unsigned x = 0; x < LUT_WIDTH; ++x) + { + float const roughness = (x + 0.5f) / LUT_WIDTH; + float const m = roughness * roughness; + float const m2 = m * m; + + float scale = 0.0f; + float bias = 0.0f; + float velvet = 0.0f; + + for (unsigned i = 0; i < numSamples; ++i) + { + float const e1 = (float)i / numSamples; + float const e2 = (float)((double)ReverseBits(i) / (double)0x100000000LL); + float const phi = 2.0f * M_PI * e1; + + // GGX Distribution + { + float const cosTheta = sqrtf((1.0f - e2) / (1.0f + (m2 - 1.0f) * e2)); + float const sinTheta = sqrtf(1.0f - cosTheta * cosTheta); + + float const hx = sinTheta * cosf(phi); + float const hy = sinTheta * sinf(phi); + float const hz = cosTheta; + + float const vdh = vx * hx + vy * hy + vz * hz; + float const lz = 2.0f * vdh * hz - vz; + + float const NdotL = MAX(lz, 0.0f); + float const NdotH = MAX(hz, 0.0f); + float const VdotH = MAX(vdh, 0.0f); + + if (NdotL > 0.0f) + { + float const visibility = GSmithCorrelated(roughness, NdotV, NdotL); + float const NdotLVisPDF = NdotL * visibility * (4.0f * VdotH / NdotH); + float const fresnel = powf(1.0f - VdotH, 5.0f); + + scale += NdotLVisPDF * (1.0f - fresnel); + bias += NdotLVisPDF * fresnel; + } + } + + // Charlie Distribution + { + float const sinTheta = sqrtf(powf(e2, (2.0f * roughness) / ((2.0f * roughness) + 1.0f))); + float const cosTheta = sqrtf(1.0f - sinTheta * sinTheta); + + float const hx = sinTheta * cosf(phi); + float const hy = sinTheta * sinf(phi); + float const hz = cosTheta; + + float const vdh = vx * hx + vy * hy + vz * hz; + float const lz = 2.0f * vdh * hz - vz; + + float const NdotL = MAX(lz, 0.0f); + float const NdotH = MAX(hz, 0.0f); + float const VdotH = MAX(vdh, 0.0f); + + if (NdotL > 0.0f) + { + float const velvetV = V_Neubelt(NdotV, NdotL); + float const rcp_pdf = 4.0f * VdotH / NdotH; + velvet += NdotL * velvetV * rcp_pdf; + } + } + } + + scale /= numSamples; + bias /= numSamples; + velvet /= numSamples; + + data[y][x][0] = FloatToHalf(scale); + data[y][x][1] = FloatToHalf(bias); + data[y][x][2] = FloatToHalf(velvet); + } + } + + tr.envBrdfImage = R_CreateImage( + "*envBrdfLUT", + (byte*)data, + LUT_WIDTH, + LUT_HEIGHT, + IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, + GL_RGB16F); +} + +/* +================== +R_CreateDefaultImage +================== +*/ +#define DEFAULT_SIZE 16 +static void R_CreateDefaultImage( void ) { + int x; + byte data[DEFAULT_SIZE][DEFAULT_SIZE][4]; + + // the default image will be a box, to allow you to see the mapping coordinates + Com_Memset( data, 32, sizeof( data ) ); + for ( x = 0 ; x < DEFAULT_SIZE ; x++ ) { + data[0][x][0] = + data[0][x][1] = + data[0][x][2] = + data[0][x][3] = 255; + + data[x][0][0] = + data[x][0][1] = + data[x][0][2] = + data[x][0][3] = 255; + + data[DEFAULT_SIZE-1][x][0] = + data[DEFAULT_SIZE-1][x][1] = + data[DEFAULT_SIZE-1][x][2] = + data[DEFAULT_SIZE-1][x][3] = 255; + + data[x][DEFAULT_SIZE-1][0] = + data[x][DEFAULT_SIZE-1][1] = + data[x][DEFAULT_SIZE-1][2] = + data[x][DEFAULT_SIZE-1][3] = 255; + } + tr.defaultImage = R_CreateImage( + "*default", (byte *)data, DEFAULT_SIZE, DEFAULT_SIZE, + IMGTYPE_COLORALPHA, IMGFLAG_MIPMAP, GL_RGBA8); +} + +/* +================== +R_CreateBuiltinImages +================== +*/ +void R_CreateBuiltinImages( void ) { + int x,y; + byte data[DEFAULT_SIZE][DEFAULT_SIZE][4]; + + R_CreateDefaultImage(); + + // we use a solid white image instead of disabling texturing + Com_Memset( data, 255, sizeof( data ) ); + tr.whiteImage = R_CreateImage( + "*white", (byte *)data, 8, 8, IMGTYPE_COLORALPHA, IMGFLAG_NONE, + GL_RGBA8); + + if (r_dlightMode->integer >= 2) + { + tr.pointShadowArrayImage = R_Create2DImageArray( + va("*pointshadowmapImage"), + NULL, + DSHADOW_MAP_SIZE, + DSHADOW_MAP_SIZE, + MAX_DLIGHTS*6, + IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, + GL_DEPTH_COMPONENT16); + } + + // with overbright bits active, we need an image which is some fraction of + // full color, for default lightmaps, etc + for (x = 0; x < DEFAULT_SIZE; x++) { + for (y =0; y < DEFAULT_SIZE; y++) { + data[y][x][0] = + data[y][x][1] = + data[y][x][2] = tr.identityLightByte; + data[y][x][3] = 255; + } + } + + tr.identityLightImage = R_CreateImage( + "*identityLight", (byte *)data, 8, 8, IMGTYPE_COLORALPHA, + IMGFLAG_NONE, 0); + + // scratchimage is usually used for cinematic drawing + for (x = 0; x < 32; x++) { + tr.scratchImage[x] = R_CreateImage( + "*scratch", (byte *)data, DEFAULT_SIZE, DEFAULT_SIZE, + IMGTYPE_COLORALPHA, + IMGFLAG_PICMIP | IMGFLAG_CLAMPTOEDGE | IMGFLAG_MUTABLE, 0); + } + + R_CreateDlightImage(); + R_CreateFogImage(); + R_CreateEnvBrdfLUT(); + + int width = glConfig.vidWidth; + int height = glConfig.vidHeight; + + int hdrFormat = GL_RGBA8; + if (r_hdr->integer) + hdrFormat = GL_RGBA16F; + + int rgbFormat = GL_RGBA8; + + tr.renderImage = R_CreateImage( + "_render", NULL, width, height, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + + tr.glowImage = R_CreateImage( + "*glow", NULL, width, height, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + + int glowImageWidth = width; + int glowImageHeight = height; + for (int i = 0; i < ARRAY_LEN(tr.glowImageScaled); i++) + { + tr.glowImageScaled[i] = R_CreateImage( + va("*glowScaled%d", i), NULL, glowImageWidth, glowImageHeight, + IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, + hdrFormat); + + glowImageWidth = Q_max(1, glowImageWidth >> 1); + glowImageHeight = Q_max(1, glowImageHeight >> 1); + } + + if (r_drawSunRays->integer) + tr.sunRaysImage = R_CreateImage( + "*sunRays", NULL, width, height, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, rgbFormat); + + tr.renderDepthImage = R_CreateImage( + "*renderdepth", NULL, width, height, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_DEPTH24_STENCIL8); + tr.textureDepthImage = R_CreateImage( + "*texturedepth", NULL, PSHADOW_MAP_SIZE, PSHADOW_MAP_SIZE, + IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, + GL_DEPTH_COMPONENT24); + + { + unsigned short sdata[4]; + void *p; + + if (hdrFormat == GL_RGBA16F) + { + sdata[0] = FloatToHalf(0.0f); + sdata[1] = FloatToHalf(0.45f); + sdata[2] = FloatToHalf(1.0f); + sdata[3] = FloatToHalf(1.0f); + p = &sdata[0]; + } + else + { + data[0][0][0] = 0; + data[0][0][1] = 0.45f * 255; + data[0][0][2] = 255; + data[0][0][3] = 255; + p = data; + } + + tr.calcLevelsImage = R_CreateImage( + "*calcLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + tr.targetLevelsImage = R_CreateImage( + "*targetLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + tr.fixedLevelsImage = R_CreateImage( + "*fixedLevels", (byte *)p, 1, 1, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, hdrFormat); + } + + for (x = 0; x < 2; x++) + { + tr.textureScratchImage[x] = R_CreateImage( + va("*textureScratch%d", x), NULL, 256, 256, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_RGBA8); + } + + for (x = 0; x < 2; x++) + { + tr.quarterImage[x] = R_CreateImage( + va("*quarter%d", x), NULL, width / 2, height / 2, + IMGTYPE_COLORALPHA, IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, + GL_RGBA8); + } + + if (r_ssao->integer) + { + tr.screenSsaoImage = R_CreateImage( + "*screenSsao", NULL, width / 2, height / 2, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_RGBA8); + tr.hdrDepthImage = R_CreateImage( + "*hdrDepth", NULL, width, height, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_R32F); + } + + if (r_shadows->integer == 4) + { + tr.pshadowArrayImage = R_Create2DImageArray( + va("*pshadowmapArray"), + NULL, + PSHADOW_MAP_SIZE, + PSHADOW_MAP_SIZE, + MAX_DRAWN_PSHADOWS, + IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, + GL_DEPTH_COMPONENT16); + } + + if (r_sunlightMode->integer) + { + tr.sunShadowArrayImage = R_Create2DImageArray( + va("*sunShadowmapArray"), + NULL, + r_shadowMapSize->integer, + r_shadowMapSize->integer, + 3, // number of cascades + IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE | IMGLFAG_SHADOWCOMP | IMGFLAG_MUTABLE, + GL_DEPTH_COMPONENT16); + + tr.screenShadowImage = R_CreateImage( + "*screenShadow", NULL, width, height, IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, GL_R8); + } + + if (r_cubeMapping->integer) + { + tr.renderCubeImage = R_CreateImage( + "*renderCube", NULL, CUBE_MAP_SIZE, CUBE_MAP_SIZE, + IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | + IMGFLAG_CLAMPTOEDGE | + IMGFLAG_MIPMAP | + IMGFLAG_CUBEMAP, + hdrFormat); + + tr.renderCubeDepthImage = R_CreateImage( + "*renderdepth", NULL, CUBE_MAP_SIZE, CUBE_MAP_SIZE, + IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | + IMGFLAG_CLAMPTOEDGE, + GL_DEPTH24_STENCIL8); + } + + tr.weatherDepthImage = R_CreateImage( + "*weatherDepth", + nullptr, + 1024, + 1024, + IMGTYPE_COLORALPHA, + IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE, + GL_DEPTH_COMPONENT16); +} + + +/* +=============== +R_SetColorMappings +=============== +*/ +void R_SetColorMappings( void ) { + int i, j; + float g; + int inf; + + // setup the overbright lighting + tr.overbrightBits = r_overBrightBits->integer; + + // allow 2 overbright bits + if ( tr.overbrightBits > 2 ) { + tr.overbrightBits = 2; + } else if ( tr.overbrightBits < 0 ) { + tr.overbrightBits = 0; + } + + tr.identityLight = 1.0f / ( 1 << tr.overbrightBits ); + tr.identityLightByte = 255 * tr.identityLight; + + if ( r_intensity->value <= 1 ) { + ri.Cvar_Set( "r_intensity", "1" ); + } + + if ( r_gamma->value < 0.5f ) { + ri.Cvar_Set( "r_gamma", "0.5" ); + } else if ( r_gamma->value > 3.0f ) { + ri.Cvar_Set( "r_gamma", "3.0" ); + } + + g = r_gamma->value; + + for ( i = 0; i < 256; i++ ) { + if ( g == 1 ) { + inf = i; + } else { + inf = 255 * pow ( i/255.0f, 1.0f / g ) + 0.5f; + } + inf <<= tr.overbrightBits; + if (inf < 0) { + inf = 0; + } + if (inf > 255) { + inf = 255; + } + s_gammatable[i] = inf; + } + + for (i=0 ; i<256 ; i++) { + j = i * r_intensity->value; + if (j > 255) { + j = 255; + } + s_intensitytable[i] = j; + } + + if ( glConfig.deviceSupportsGamma ) + { + ri.WIN_SetGamma( &glConfig, s_gammatable, s_gammatable, s_gammatable ); + } +} + +/* +Initialise the images pool allocator +*/ +void R_InitImagesPool() +{ + Com_Memset(hashTable, 0, sizeof(hashTable)); + + imagesPool = NULL; + tr.imagesFreeList = NULL; + R_ExtendImagesPool(); +} + +/* +=============== +R_InitImages +=============== +*/ +void R_InitImages( void ) { + // build brightness translation tables + R_SetColorMappings(); + + // create default texture and white texture + R_CreateBuiltinImages(); +} + +/* +=============== +R_DeleteTextures +=============== +*/ +void R_DeleteTextures( void ) { + image_t *image = tr.images; + while ( image ) + { + qglDeleteTextures(1, &image->texnum); + image = image->poolNext; + } + + tr.numImages = 0; + + // Free pool and allocated images + while ( imagesPool ) + { + ImagesPool *pNext = imagesPool->pNext; + Z_Free(imagesPool->pPool); + Z_Free(imagesPool); + + imagesPool = pNext; + } + + Com_Memset( glState.currenttextures, 0, sizeof( glState.currenttextures ) ); + GL_SelectTexture( 1 ); + qglBindTexture( GL_TEXTURE_2D, 0 ); + GL_SelectTexture( 0 ); + qglBindTexture( GL_TEXTURE_2D, 0 ); +} diff --git a/codemp/rd-rend2/tr_image_stb.cpp b/codemp/rd-rend2/tr_image_stb.cpp new file mode 100644 index 0000000000..17a2baae20 --- /dev/null +++ b/codemp/rd-rend2/tr_image_stb.cpp @@ -0,0 +1,89 @@ +/* +=========================================================================== +Copyright (C) 1999 - 2005, Id Software, Inc. +Copyright (C) 2000 - 2013, Raven Software, Inc. +Copyright (C) 2001 - 2013, Activision, Inc. +Copyright (C) 2005 - 2015, ioquake3 contributors +Copyright (C) 2013 - 2015, OpenJK contributors + +This file is part of the OpenJK source code. + +OpenJK is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . +=========================================================================== +*/ + +#include "tr_local.h" + +static void* R_LocalMalloc(size_t size) +{ + return ri.Hunk_AllocateTempMemory(size); +} + +static void* R_LocalReallocSized(void *ptr, size_t old_size, size_t new_size) +{ + void *mem = ri.Hunk_AllocateTempMemory(new_size); + if (ptr) + { + memcpy(mem, ptr, old_size); + ri.Hunk_FreeTempMemory(ptr); + } + return mem; +} +static void R_LocalFree(void *ptr) +{ + if (ptr) + ri.Hunk_FreeTempMemory(ptr); +} + +#define STBI_MALLOC R_LocalMalloc +#define STBI_REALLOC_SIZED R_LocalReallocSized +#define STBI_FREE R_LocalFree + +#define STB_IMAGE_IMPLEMENTATION + +#define STBI_TEMP_ON_STACK +#define STBI_ONLY_HDR +#include + +#define IMG_BYTE 0 +#define IMG_FLOAT 1 + +// Loads a HDR image from file. +void R_LoadHDRImage( const char *filename, byte **data, int *width, int *height ) +{ + byte *buf = NULL; + int x, y, n; + int len = ri.FS_ReadFile (filename, (void **)&buf); + if ( len <= 0 || buf == NULL ) + { + return; + } + stbi_set_flip_vertically_on_load(0); + *data = (byte *)stbi_loadf_from_memory(buf, len, &x, &y, &n, 3); + + ri.FS_FreeFile(buf); + + if (!data) + ri.Printf(PRINT_DEVELOPER, "R_LoadHDRImage(%s) failed: %s\n", filename, stbi_failure_reason()); + + if (width) + *width = x; + else + *width = 0; + + if (height) + *height = y; + else + *height = 0; + +} diff --git a/codemp/rd-rend2/tr_init.cpp b/codemp/rd-rend2/tr_init.cpp new file mode 100644 index 0000000000..6ab261e5a5 --- /dev/null +++ b/codemp/rd-rend2/tr_init.cpp @@ -0,0 +1,2435 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_init.c -- functions that are not called every frame + +#include "tr_local.h" +#include "ghoul2/g2_local.h" +#include "tr_cache.h" +#include "tr_allocator.h" +#include "tr_weather.h" +#include + +#ifdef _G2_GORE +#include "G2_gore_r2.h" +#endif + +static size_t STATIC_UNIFORM_BUFFER_SIZE = 1 * 1024 * 1024; +static size_t FRAME_UNIFORM_BUFFER_SIZE = 8*1024*1024; +static size_t FRAME_VERTEX_BUFFER_SIZE = 12*1024*1024; +static size_t FRAME_INDEX_BUFFER_SIZE = 4*1024*1024; + +#if defined(_WIN32) +extern "C" { + __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; + __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; +} +#endif + +glconfig_t glConfig; +glconfigExt_t glConfigExt; +glRefConfig_t glRefConfig; +glstate_t glState; +window_t window; + +cvar_t *se_language; + +cvar_t *r_verbose; +cvar_t *r_ignore; + +cvar_t *r_detailTextures; + +cvar_t *r_znear; +cvar_t *r_zproj; +cvar_t *r_stereoSeparation; + +cvar_t *r_skipBackEnd; + +cvar_t *r_stereo; +cvar_t *r_anaglyphMode; + +cvar_t *r_greyscale; + +cvar_t *r_measureOverdraw; + +cvar_t *r_inGameVideo; +cvar_t *r_fastsky; +cvar_t *r_drawSun; +cvar_t *r_dynamiclight; + +cvar_t *r_lodbias; +cvar_t *r_lodscale; +cvar_t *r_autolodscalevalue; + +cvar_t *r_norefresh; +cvar_t *r_drawentities; +cvar_t *r_drawworld; +cvar_t *r_drawfog; +cvar_t *r_speeds; +cvar_t *r_fullbright; +cvar_t *r_novis; +cvar_t *r_nocull; +cvar_t *r_facePlaneCull; +cvar_t *r_showcluster; +cvar_t *r_nocurves; + +cvar_t *r_allowExtensions; + +cvar_t *r_ext_compressed_textures; +cvar_t *r_ext_multitexture; +cvar_t *r_ext_compiled_vertex_array; +cvar_t *r_ext_texture_env_add; +cvar_t *r_ext_texture_filter_anisotropic; +cvar_t *r_ext_preferred_tc_method; + +cvar_t *r_ext_draw_range_elements; +cvar_t *r_ext_multi_draw_arrays; +cvar_t *r_ext_texture_float; +cvar_t *r_arb_half_float_pixel; +cvar_t *r_ext_framebuffer_multisample; +cvar_t *r_arb_seamless_cube_map; +cvar_t *r_arb_vertex_type_2_10_10_10_rev; +cvar_t *r_arb_buffer_storage; + +cvar_t *r_mergeMultidraws; +cvar_t *r_mergeLeafSurfaces; + +cvar_t *r_cameraExposure; + +cvar_t *r_externalGLSL; + +cvar_t *r_hdr; +cvar_t *r_floatLightmap; + +cvar_t *r_toneMap; +cvar_t *r_forceToneMap; +cvar_t *r_forceToneMapMin; +cvar_t *r_forceToneMapAvg; +cvar_t *r_forceToneMapMax; + +cvar_t *r_autoExposure; +cvar_t *r_forceAutoExposure; +cvar_t *r_forceAutoExposureMin; +cvar_t *r_forceAutoExposureMax; + +cvar_t *r_depthPrepass; +cvar_t *r_ssao; + +cvar_t *r_normalMapping; +cvar_t *r_specularMapping; +cvar_t *r_deluxeMapping; +cvar_t *r_deluxeSpecular; +cvar_t *r_parallaxMapping; +cvar_t *r_forceParallaxBias; +cvar_t *r_cubeMapping; +cvar_t *r_cubeMappingBounces; +cvar_t *r_baseNormalX; +cvar_t *r_baseNormalY; +cvar_t *r_baseParallax; +cvar_t *r_baseSpecular; +cvar_t *r_dlightMode; +cvar_t *r_pshadowDist; +cvar_t *r_imageUpsample; +cvar_t *r_imageUpsampleMaxSize; +cvar_t *r_imageUpsampleType; +cvar_t *r_genNormalMaps; +cvar_t *r_forceSun; +cvar_t *r_forceSunMapLightScale; +cvar_t *r_forceSunLightScale; +cvar_t *r_forceSunAmbientScale; +cvar_t *r_sunlightMode; +cvar_t *r_drawSunRays; +cvar_t *r_sunShadows; +cvar_t *r_shadowFilter; +cvar_t *r_shadowMapSize; +cvar_t *r_shadowCascadeZNear; +cvar_t *r_shadowCascadeZFar; +cvar_t *r_shadowCascadeZBias; +cvar_t *r_ignoreDstAlpha; + +cvar_t *r_smartpicmip; +cvar_t *r_ignoreGLErrors; +cvar_t *r_logFile; + +cvar_t *r_texturebits; + +cvar_t *r_drawBuffer; +cvar_t *r_lightmap; +cvar_t *r_distanceCull; +cvar_t *r_vertexLight; +cvar_t *r_uiFullScreen; +cvar_t *r_shadows; +cvar_t *r_flares; +cvar_t *r_nobind; +cvar_t *r_singleShader; +cvar_t *r_roundImagesDown; +cvar_t *r_colorMipLevels; +cvar_t *r_picmip; +cvar_t *r_showtris; +cvar_t *r_showsky; +cvar_t *r_shownormals; +cvar_t *r_finish; +cvar_t *r_clear; +cvar_t *r_markcount; +cvar_t *r_textureMode; +cvar_t *r_offsetFactor; +cvar_t *r_offsetUnits; +cvar_t *r_shadowOffsetFactor; +cvar_t *r_shadowOffsetUnits; +cvar_t *r_gamma; +cvar_t *r_intensity; +cvar_t *r_lockpvs; +cvar_t *r_noportals; +cvar_t *r_portalOnly; + +cvar_t *r_subdivisions; +cvar_t *r_lodCurveError; + + + +cvar_t *r_overBrightBits; +cvar_t *r_mapOverBrightBits; + +cvar_t *r_debugSurface; +cvar_t *r_simpleMipMaps; + +cvar_t *r_showImages; + +cvar_t *r_ambientScale; +cvar_t *r_directedScale; +cvar_t *r_debugLight; +cvar_t *r_debugSort; +cvar_t *r_printShaders; +cvar_t *r_saveFontData; + +#ifdef _DEBUG +cvar_t *r_noPrecacheGLA; +#endif + +cvar_t *r_noServerGhoul2; +cvar_t *r_Ghoul2AnimSmooth=0; +cvar_t *r_Ghoul2UnSqashAfterSmooth=0; +//cvar_t *r_Ghoul2UnSqash; +//cvar_t *r_Ghoul2TimeBase=0; from single player +//cvar_t *r_Ghoul2NoLerp; +//cvar_t *r_Ghoul2NoBlend; +//cvar_t *r_Ghoul2BlendMultiplier=0; + +cvar_t *broadsword=0; +cvar_t *broadsword_kickbones=0; +cvar_t *broadsword_kickorigin=0; +cvar_t *broadsword_playflop=0; +cvar_t *broadsword_dontstopanim=0; +cvar_t *broadsword_waitforshot=0; +cvar_t *broadsword_smallbbox=0; +cvar_t *broadsword_extra1=0; +cvar_t *broadsword_extra2=0; + +cvar_t *broadsword_effcorr=0; +cvar_t *broadsword_ragtobase=0; +cvar_t *broadsword_dircap=0; + +cvar_t *r_marksOnTriangleMeshes; + +cvar_t *r_aviMotionJpegQuality; +cvar_t *r_screenshotJpegQuality; +cvar_t *r_surfaceSprites; + +// the limits apply to the sum of all scenes in a frame -- +// the main view, all the 3D icons, etc +#define DEFAULT_MAX_POLYS 600 +#define DEFAULT_MAX_POLYVERTS 3000 +cvar_t *r_maxpolys; +cvar_t *r_maxpolyverts; +int max_polys; +int max_polyverts; + +cvar_t *r_dynamicGlow; +cvar_t *r_dynamicGlowPasses; +cvar_t *r_dynamicGlowDelta; +cvar_t *r_dynamicGlowIntensity; +cvar_t *r_dynamicGlowSoft; +cvar_t *r_dynamicGlowWidth; +cvar_t *r_dynamicGlowHeight; + +cvar_t *r_debugContext; +cvar_t *r_debugWeather; + +cvar_t *r_aspectCorrectFonts; +cvar_t *cl_ratioFix; + +extern void RB_SetGL2D (void); +static void R_Splash() +{ + const GLfloat black[] = { 0.0f, 0.0f, 0.0f, 1.0f }; + float ratio = (float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth); + + qglViewport( 0, 0, glConfig.vidWidth, glConfig.vidHeight ); + qglClearBufferfv(GL_COLOR, 0, black); + qglClear(GL_DEPTH_BUFFER_BIT); + + GLSL_InitSplashScreenShader(); + + GL_Cull(CT_TWO_SIDED); + + image_t *pImage = R_FindImageFile( "menu/splash", IMGTYPE_COLORALPHA, IMGFLAG_NONE); + if (cl_ratioFix->integer && ratio >= 0.74f && ratio <= 0.76f) + pImage = R_FindImageFile("menu/splash_16_9", IMGTYPE_COLORALPHA, IMGFLAG_NONE); + if (pImage ) + GL_Bind( pImage ); + + GL_State(GLS_DEPTHTEST_DISABLE); + GLSL_BindProgram(&tr.splashScreenShader); + RB_InstantTriangle(); + + ri.WIN_Present(&window); +} + +/* +** GLW_CheckForExtension + + Cannot use strstr directly to differentiate between (for eg) reg_combiners and reg_combiners2 +*/ +bool GL_CheckForExtension(const char *ext) +{ + const char *ptr = Q_stristr( glConfigExt.originalExtensionString, ext ); + if (ptr == NULL) + return false; + ptr += strlen(ext); + return ((*ptr == ' ') || (*ptr == '\0')); // verify it's complete string. +} + + +void GLW_InitTextureCompression( void ) +{ + bool newer_tc, old_tc; + + // Check for available tc methods. + newer_tc = GL_CheckForExtension("ARB_texture_compression") && GL_CheckForExtension("EXT_texture_compression_s3tc"); + old_tc = GL_CheckForExtension("GL_S3_s3tc"); + + if ( old_tc ) + { + Com_Printf ("...GL_S3_s3tc available\n" ); + } + + if ( newer_tc ) + { + Com_Printf ("...GL_EXT_texture_compression_s3tc available\n" ); + } + + if ( !r_ext_compressed_textures->value ) + { + // Compressed textures are off + glConfig.textureCompression = TC_NONE; + Com_Printf ("...ignoring texture compression\n" ); + } + else if ( !old_tc && !newer_tc ) + { + // Requesting texture compression, but no method found + glConfig.textureCompression = TC_NONE; + Com_Printf ("...no supported texture compression method found\n" ); + Com_Printf (".....ignoring texture compression\n" ); + } + else + { + // some form of supported texture compression is avaiable, so see if the user has a preference + if ( r_ext_preferred_tc_method->integer == TC_NONE ) + { + // No preference, so pick the best + if ( newer_tc ) + { + Com_Printf ("...no tc preference specified\n" ); + Com_Printf (".....using GL_EXT_texture_compression_s3tc\n" ); + glConfig.textureCompression = TC_S3TC_DXT; + } + else + { + Com_Printf ("...no tc preference specified\n" ); + Com_Printf (".....using GL_S3_s3tc\n" ); + glConfig.textureCompression = TC_S3TC; + } + } + else + { + // User has specified a preference, now see if this request can be honored + if ( old_tc && newer_tc ) + { + // both are avaiable, so we can use the desired tc method + if ( r_ext_preferred_tc_method->integer == TC_S3TC ) + { + Com_Printf ("...using preferred tc method, GL_S3_s3tc\n" ); + glConfig.textureCompression = TC_S3TC; + } + else + { + Com_Printf ("...using preferred tc method, GL_EXT_texture_compression_s3tc\n" ); + glConfig.textureCompression = TC_S3TC_DXT; + } + } + else + { + // Both methods are not available, so this gets trickier + if ( r_ext_preferred_tc_method->integer == TC_S3TC ) + { + // Preferring to user older compression + if ( old_tc ) + { + Com_Printf ("...using GL_S3_s3tc\n" ); + glConfig.textureCompression = TC_S3TC; + } + else + { + // Drat, preference can't be honored + Com_Printf ("...preferred tc method, GL_S3_s3tc not available\n" ); + Com_Printf (".....falling back to GL_EXT_texture_compression_s3tc\n" ); + glConfig.textureCompression = TC_S3TC_DXT; + } + } + else + { + // Preferring to user newer compression + if ( newer_tc ) + { + Com_Printf ("...using GL_EXT_texture_compression_s3tc\n" ); + glConfig.textureCompression = TC_S3TC_DXT; + } + else + { + // Drat, preference can't be honored + Com_Printf ("...preferred tc method, GL_EXT_texture_compression_s3tc not available\n" ); + Com_Printf (".....falling back to GL_S3_s3tc\n" ); + glConfig.textureCompression = TC_S3TC; + } + } + } + } + } +} + +// Truncates the GL extensions string by only allowing up to 'maxExtensions' extensions in the string. +static const char *TruncateGLExtensionsString (const char *extensionsString, int maxExtensions) +{ + const char *p = extensionsString; + const char *q; + int numExtensions = 0; + size_t extensionsLen = strlen (extensionsString); + + char *truncatedExtensions; + + while ( (q = strchr (p, ' ')) != NULL && numExtensions <= maxExtensions ) + { + p = q + 1; + numExtensions++; + } + + if ( q != NULL ) + { + // We still have more extensions. We'll call this the end + + extensionsLen = p - extensionsString - 1; + } + + truncatedExtensions = (char *)Z_Malloc(extensionsLen + 1, TAG_GENERAL); + Q_strncpyz (truncatedExtensions, extensionsString, extensionsLen + 1); + + return truncatedExtensions; +} + +static const char *GetGLExtensionsString() +{ + GLint numExtensions; + glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions); + size_t extensionStringLen = 0; + + for ( int i = 0; i < numExtensions; i++ ) + { + extensionStringLen += strlen((const char *)qglGetStringi(GL_EXTENSIONS, i)) + 1; + } + + char *extensionString = (char *)Z_Malloc(extensionStringLen + 1, TAG_GENERAL); + char *p = extensionString; + for ( int i = 0; i < numExtensions; i++ ) + { + const char *extension = (const char *)qglGetStringi(GL_EXTENSIONS, i); + while ( *extension != '\0' ) + *p++ = *extension++; + + *p++ = ' '; + } + + *p = '\0'; + assert((p - extensionString) == extensionStringLen); + + return extensionString; +} + +/* +** InitOpenGL +** +** This function is responsible for initializing a valid OpenGL subsystem. This +** is done by calling GLimp_Init (which gives us a working OGL subsystem) then +** setting variables, checking GL constants, and reporting the gfx system config +** to the user. +*/ +static void InitOpenGL( void ) +{ + // + // initialize OS specific portions of the renderer + // + // GLimp_Init directly or indirectly references the following cvars: + // - r_fullscreen + // - r_mode + // - r_(color|depth|stencil)bits + // - r_ignorehwgamma + // - r_gamma + // + + if ( glConfig.vidWidth == 0 ) + { + windowDesc_t windowDesc = {}; + memset(&glConfig, 0, sizeof(glConfig)); + + windowDesc.api = GRAPHICS_API_OPENGL; + windowDesc.gl.majorVersion = 3; + windowDesc.gl.minorVersion = 2; + windowDesc.gl.profile = GLPROFILE_CORE; + if ( r_debugContext->integer ) + windowDesc.gl.contextFlags = GLCONTEXT_DEBUG; + + window = ri.WIN_Init(&windowDesc, &glConfig); + + GLimp_InitCoreFunctions(); + + Com_Printf( "GL_RENDERER: %s\n", (char *)qglGetString (GL_RENDERER) ); + + // get our config strings + glConfig.vendor_string = (const char *)qglGetString (GL_VENDOR); + glConfig.renderer_string = (const char *)qglGetString (GL_RENDERER); + glConfig.version_string = (const char *)qglGetString (GL_VERSION); + glConfig.extensions_string = GetGLExtensionsString(); + + glConfigExt.originalExtensionString = glConfig.extensions_string; + glConfig.extensions_string = TruncateGLExtensionsString(glConfigExt.originalExtensionString, 128); + + // OpenGL driver constants + qglGetIntegerv( GL_MAX_TEXTURE_SIZE, &glConfig.maxTextureSize ); + + // Determine GPU IHV + if ( Q_stristr( glConfig.vendor_string, "ATI Technologies Inc." ) ) + { + glRefConfig.hardwareVendor = IHV_AMD; + } + else if ( Q_stristr( glConfig.vendor_string, "NVIDIA" ) ) + { + glRefConfig.hardwareVendor = IHV_NVIDIA; + } + else if ( Q_stristr( glConfig.vendor_string, "INTEL") ) + { + glRefConfig.hardwareVendor = IHV_INTEL; + } + else + { + glRefConfig.hardwareVendor = IHV_UNKNOWN; + } + + // stubbed or broken drivers may have reported 0... + glConfig.maxTextureSize = Q_max(0, glConfig.maxTextureSize); + + // initialize extensions + GLimp_InitExtensions(); + + // Create the default VAO + GLuint vao; + qglGenVertexArrays(1, &vao); + qglBindVertexArray(vao); + tr.globalVao = vao; + + // set default state + GL_SetDefaultState(); + + R_Splash(); //get something on screen asap + } + else + { + // set default state + GL_SetDefaultState(); + } +} + +/* +================== +GL_CheckErrors +================== +*/ +void GL_CheckErrs( const char *file, int line ) { +#if defined(_DEBUG) + GLenum err; + char s[64]; + + err = qglGetError(); + if ( err == GL_NO_ERROR ) { + return; + } + if ( r_ignoreGLErrors->integer ) { + return; + } + switch( err ) { + case GL_INVALID_ENUM: + strcpy( s, "GL_INVALID_ENUM" ); + break; + case GL_INVALID_VALUE: + strcpy( s, "GL_INVALID_VALUE" ); + break; + case GL_INVALID_OPERATION: + strcpy( s, "GL_INVALID_OPERATION" ); + break; + case GL_OUT_OF_MEMORY: + strcpy( s, "GL_OUT_OF_MEMORY" ); + break; + default: + Com_sprintf( s, sizeof(s), "%i", err); + break; + } + + ri.Error( ERR_FATAL, "GL_CheckErrors: %s in %s at line %d", s , file, line); +#endif +} + +/* +============================================================================== + + SCREEN SHOTS + +NOTE TTimo +some thoughts about the screenshots system: +screenshots get written in fs_homepath + fs_gamedir +vanilla q3 .. baseq3/screenshots/ *.tga +team arena .. missionpack/screenshots/ *.tga + +two commands: "screenshot" and "screenshotJPEG" +we use statics to store a count and start writing the first screenshot/screenshot????.tga (.jpg) available +(with FS_FileExists / FS_FOpenFileWrite calls) +FIXME: the statics don't get a reinit between fs_game changes + +============================================================================== +*/ + +/* +================== +RB_ReadPixels + +Reads an image but takes care of alignment issues for reading RGB images. + +Reads a minimum offset for where the RGB data starts in the image from +integer stored at pointer offset. When the function has returned the actual +offset was written back to address offset. This address will always have an +alignment of packAlign to ensure efficient copying. + +Stores the length of padding after a line of pixels to address padlen + +Return value must be freed with ri.Hunk_FreeTempMemory() +================== +*/ + +static byte *RB_ReadPixels( + int x, int y, int width, int height, size_t *offset, int *padlen) +{ + byte *buffer, *bufstart; + int padwidth, linelen; + GLint packAlign; + + qglGetIntegerv(GL_PACK_ALIGNMENT, &packAlign); + + linelen = width * 3; + padwidth = PAD(linelen, packAlign); + + // Allocate a few more bytes so that we can choose an alignment we like + buffer = (byte *)ri.Hunk_AllocateTempMemory(padwidth * height + *offset + packAlign - 1); + + bufstart = (byte*)(PADP((intptr_t) buffer + *offset, packAlign)); + qglReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, bufstart); + + *offset = bufstart - buffer; + *padlen = padwidth - linelen; + + return buffer; +} + +static void ConvertRGBtoBGR( + byte *dst, const byte *src, int stride, int width, int height) +{ + const byte *row = src; + for (int y = 0; y < height; ++y) + { + const byte *pixelRGB = row; + for (int x = 0; x < width; ++x) + { + // swap rgb to bgr + const byte temp = pixelRGB[0]; + *dst++ = pixelRGB[2]; + *dst++ = pixelRGB[1]; + *dst++ = temp; + + pixelRGB += 3; + } + + row += stride; + } +} + +static void R_SaveTGA( + const char *filename, + const byte *pixels, + int width, + int height, + int stride) +{ + const size_t headerSize = 18; + const size_t pixelBufferSize = stride * height; + const size_t bufferSize = headerSize + pixelBufferSize; + + byte *buffer = (byte *)ri.Hunk_AllocateTempMemory(bufferSize); + + // Write TGA header + Com_Memset(buffer, 0, headerSize); + buffer[2] = 2; // uncompressed type + buffer[12] = width & 255; + buffer[13] = width >> 8; + buffer[14] = height & 255; + buffer[15] = height >> 8; + buffer[16] = 24; // pixel size + + ConvertRGBtoBGR(buffer + headerSize, pixels, stride, width, height); + + ri.FS_WriteFile(filename, buffer, bufferSize); + ri.Hunk_FreeTempMemory(buffer); +} + +/* +================== +R_SaveScreenshotTGA +================== +*/ +static void R_SaveScreenshotTGA( + const screenshotReadback_t *screenshotReadback, byte *pixels) +{ + R_SaveTGA( + screenshotReadback->filename, + pixels, + screenshotReadback->width, + screenshotReadback->height, + screenshotReadback->strideInBytes); +} + +/* +================== +R_SaveScreenshotPNG +================== +*/ +static void R_SaveScreenshotPNG( + const screenshotReadback_t *screenshotReadback, byte *pixels) +{ + RE_SavePNG( + screenshotReadback->filename, + pixels, + screenshotReadback->width, + screenshotReadback->height, + 3); +} + +/* +================== +R_SaveScreenshotJPG +================== +*/ +static void R_SaveScreenshotJPG( + const screenshotReadback_t *screenshotReadback, byte *pixels) +{ + RE_SaveJPG( + screenshotReadback->filename, + r_screenshotJpegQuality->integer, + screenshotReadback->width, + screenshotReadback->height, + pixels, + screenshotReadback->strideInBytes - screenshotReadback->rowInBytes); +} + +void R_SaveScreenshot(screenshotReadback_t *screenshotReadback) +{ + qglBindBuffer(GL_PIXEL_PACK_BUFFER, screenshotReadback->pbo); + + byte *pixelBuffer = static_cast( + qglMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY)); + + if (pixelBuffer == nullptr) + { + ri.Printf( + PRINT_ALL, + S_COLOR_RED "Failed to read screenshot data from GPU\n"); + } + else + { + const int height = screenshotReadback->height; + const int stride = screenshotReadback->strideInBytes; + const size_t pixelBufferSize = stride * height; + + byte *pixels = (byte *)ri.Hunk_AllocateTempMemory(pixelBufferSize); + Com_Memcpy(pixels, pixelBuffer, pixelBufferSize); + qglUnmapBuffer(GL_PIXEL_PACK_BUFFER); + + if (glConfig.deviceSupportsGamma) + R_GammaCorrect(pixels, pixelBufferSize); + + switch (screenshotReadback->format) + { + case SSF_JPEG: + R_SaveScreenshotJPG(screenshotReadback, pixels); + break; + + case SSF_TGA: + R_SaveScreenshotTGA(screenshotReadback, pixels); + break; + + case SSF_PNG: + R_SaveScreenshotPNG(screenshotReadback, pixels); + break; + } + + ri.Hunk_FreeTempMemory(pixels); + } + + qglDeleteBuffers(1, &screenshotReadback->pbo); + screenshotReadback->pbo = 0; +} + +/* +================== +R_TakeScreenshotCmd +================== +*/ +const void *RB_TakeScreenshotCmd( const void *data ) { + const screenshotCommand_t *cmd; + + cmd = (const screenshotCommand_t *)data; + + // finish any 2D drawing if needed + if (tess.numIndexes) + RB_EndSurface(); + + const int frameNumber = backEndData->realFrameNumber; + gpuFrame_t *thisFrame = &backEndData->frames[frameNumber % MAX_FRAMES]; + screenshotReadback_t *screenshot = &thisFrame->screenshotReadback; + + GLint packAlign; + qglGetIntegerv(GL_PACK_ALIGNMENT, &packAlign); + + const int linelen = cmd->width * 3; + const int strideInBytes = PAD(linelen, packAlign); + + qglGenBuffers(1, &screenshot->pbo); + qglBindBuffer(GL_PIXEL_PACK_BUFFER, screenshot->pbo); + qglBufferData( + GL_PIXEL_PACK_BUFFER, + strideInBytes * cmd->height, + nullptr, + GL_STATIC_COPY); + qglReadPixels( + cmd->x, cmd->y, cmd->width, cmd->height, GL_RGB, GL_UNSIGNED_BYTE, 0); + + screenshot->strideInBytes = strideInBytes; + screenshot->rowInBytes = linelen; + screenshot->width = cmd->width; + screenshot->height = cmd->height; + screenshot->format = cmd->format; + Q_strncpyz( + screenshot->filename, cmd->fileName, sizeof(screenshot->filename)); + + return (const void *)(cmd + 1); +} + +/* +================== +R_TakeScreenshot +================== +*/ +void R_TakeScreenshot( int x, int y, int width, int height, char *name, screenshotFormat_t format ) { + static char fileName[MAX_OSPATH]; // bad things if two screenshots per frame? + screenshotCommand_t *cmd; + + cmd = (screenshotCommand_t *)R_GetCommandBuffer( sizeof( *cmd ) ); + if ( !cmd ) { + return; + } + cmd->commandId = RC_SCREENSHOT; + + cmd->x = x; + cmd->y = y; + cmd->width = width; + cmd->height = height; + Q_strncpyz( fileName, name, sizeof(fileName) ); + cmd->fileName = fileName; + cmd->format = format; +} + +/* +================== +R_ScreenshotFilename +================== +*/ +void R_ScreenshotFilename( char *buf, int bufSize, const char *ext ) { + time_t rawtime; + char timeStr[32] = {0}; // should really only reach ~19 chars + + time( &rawtime ); + strftime( timeStr, sizeof( timeStr ), "%Y-%m-%d_%H-%M-%S", localtime( &rawtime ) ); // or gmtime + + Com_sprintf( buf, bufSize, "screenshots/shot%s%s", timeStr, ext ); +} + +/* +==================== +R_LevelShot + +levelshots are specialized 256*256 thumbnails for +the menu system, sampled down from full screen distorted images +==================== +*/ +#define LEVELSHOTSIZE 256 +static void R_LevelShot( void ) { + char checkname[MAX_OSPATH]; + byte *buffer; + byte *source, *allsource; + byte *src, *dst; + size_t offset = 0; + int padlen; + int x, y; + int r, g, b; + float xScale, yScale; + int xx, yy; + + Com_sprintf( checkname, sizeof(checkname), "levelshots/%s.tga", tr.world->baseName ); + + allsource = RB_ReadPixels(0, 0, glConfig.vidWidth, glConfig.vidHeight, &offset, &padlen); + source = allsource + offset; + + buffer = (byte *)ri.Hunk_AllocateTempMemory(LEVELSHOTSIZE * LEVELSHOTSIZE*3 + 18); + Com_Memset (buffer, 0, 18); + buffer[2] = 2; // uncompressed type + buffer[12] = LEVELSHOTSIZE & 255; + buffer[13] = LEVELSHOTSIZE >> 8; + buffer[14] = LEVELSHOTSIZE & 255; + buffer[15] = LEVELSHOTSIZE >> 8; + buffer[16] = 24; // pixel size + + // resample from source + xScale = glConfig.vidWidth / (4.0*LEVELSHOTSIZE); + yScale = glConfig.vidHeight / (3.0*LEVELSHOTSIZE); + for ( y = 0 ; y < LEVELSHOTSIZE ; y++ ) { + for ( x = 0 ; x < LEVELSHOTSIZE ; x++ ) { + r = g = b = 0; + for ( yy = 0 ; yy < 3 ; yy++ ) { + for ( xx = 0 ; xx < 4 ; xx++ ) { + src = source + 3 * ( glConfig.vidWidth * (int)( (y*3+yy)*yScale ) + (int)( (x*4+xx)*xScale ) ); + r += src[0]; + g += src[1]; + b += src[2]; + } + } + dst = buffer + 18 + 3 * ( y * LEVELSHOTSIZE + x ); + dst[0] = b / 12; + dst[1] = g / 12; + dst[2] = r / 12; + } + } + + // gamma correct + if ( ( tr.overbrightBits > 0 ) && glConfig.deviceSupportsGamma ) { + R_GammaCorrect( buffer + 18, LEVELSHOTSIZE * LEVELSHOTSIZE * 3 ); + } + + ri.FS_WriteFile( checkname, buffer, LEVELSHOTSIZE * LEVELSHOTSIZE*3 + 18 ); + + ri.Hunk_FreeTempMemory( buffer ); + ri.Hunk_FreeTempMemory( allsource ); + + ri.Printf( PRINT_ALL, "Wrote %s\n", checkname ); +} + +/* +================== +R_ScreenShotTGA_f + +screenshot +screenshot [silent] +screenshot [levelshot] +screenshot [filename] + +Doesn't print the pacifier message if there is a second arg +================== +*/ +void R_ScreenShotTGA_f (void) { + char checkname[MAX_OSPATH] = {0}; + qboolean silent = qfalse; + + if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + R_LevelShot(); + return; + } + + if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + silent = qtrue; + + if ( ri.Cmd_Argc() == 2 && !silent ) { + // explicit filename + Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.tga", ri.Cmd_Argv( 1 ) ); + } + else { + // timestamp the file + R_ScreenshotFilename( checkname, sizeof( checkname ), ".tga" ); + + if ( ri.FS_FileExists( checkname ) ) { + Com_Printf( "ScreenShot: Couldn't create a file\n"); + return; + } + } + + R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_TGA ); + + if ( !silent ) + ri.Printf (PRINT_ALL, "Wrote %s\n", checkname); +} + +void R_ScreenShotPNG_f (void) { + char checkname[MAX_OSPATH] = {0}; + qboolean silent = qfalse; + + if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + R_LevelShot(); + return; + } + + if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + silent = qtrue; + + if ( ri.Cmd_Argc() == 2 && !silent ) { + // explicit filename + Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.png", ri.Cmd_Argv( 1 ) ); + } + else { + // timestamp the file + R_ScreenshotFilename( checkname, sizeof( checkname ), ".png" ); + + if ( ri.FS_FileExists( checkname ) ) { + Com_Printf( "ScreenShot: Couldn't create a file\n"); + return; + } + } + + R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_PNG ); + + if ( !silent ) + ri.Printf (PRINT_ALL, "Wrote %s\n", checkname); +} + +void R_ScreenShotJPEG_f (void) { + char checkname[MAX_OSPATH] = {0}; + qboolean silent = qfalse; + + if ( !strcmp( ri.Cmd_Argv(1), "levelshot" ) ) { + R_LevelShot(); + return; + } + + if ( !strcmp( ri.Cmd_Argv(1), "silent" ) ) + silent = qtrue; + + if ( ri.Cmd_Argc() == 2 && !silent ) { + // explicit filename + Com_sprintf( checkname, sizeof( checkname ), "screenshots/%s.jpg", ri.Cmd_Argv( 1 ) ); + } + else { + // timestamp the file + R_ScreenshotFilename( checkname, sizeof( checkname ), ".jpg" ); + + if ( ri.FS_FileExists( checkname ) ) { + Com_Printf( "ScreenShot: Couldn't create a file\n"); + return; + } + } + + R_TakeScreenshot( 0, 0, glConfig.vidWidth, glConfig.vidHeight, checkname, SSF_JPEG ); + + if ( !silent ) + ri.Printf (PRINT_ALL, "Wrote %s\n", checkname); +} + +//============================================================================ + +/* +================== +RB_TakeVideoFrameCmd +================== +*/ +const void *RB_TakeVideoFrameCmd( const void *data ) +{ + const videoFrameCommand_t *cmd; + byte *cBuf; + size_t memcount, linelen; + int padwidth, avipadwidth, padlen, avipadlen; + GLint packAlign; + + // finish any 2D drawing if needed + if(tess.numIndexes) + RB_EndSurface(); + + cmd = (const videoFrameCommand_t *)data; + + qglGetIntegerv(GL_PACK_ALIGNMENT, &packAlign); + + linelen = cmd->width * 3; + + // Alignment stuff for glReadPixels + padwidth = PAD(linelen, packAlign); + padlen = padwidth - linelen; + // AVI line padding + avipadwidth = PAD(linelen, AVI_LINE_PADDING); + avipadlen = avipadwidth - linelen; + + cBuf = (byte*)(PADP(cmd->captureBuffer, packAlign)); + + qglReadPixels(0, 0, cmd->width, cmd->height, GL_RGB, + GL_UNSIGNED_BYTE, cBuf); + + memcount = padwidth * cmd->height; + + // gamma correct + if(glConfig.deviceSupportsGamma) + R_GammaCorrect(cBuf, memcount); + + if(cmd->motionJpeg) + { + memcount = RE_SaveJPGToBuffer(cmd->encodeBuffer, linelen * cmd->height, + r_aviMotionJpegQuality->integer, + cmd->width, cmd->height, cBuf, padlen); + ri.CL_WriteAVIVideoFrame(cmd->encodeBuffer, memcount); + } + else + { + byte *lineend, *memend; + byte *srcptr, *destptr; + + srcptr = cBuf; + destptr = cmd->encodeBuffer; + memend = srcptr + memcount; + + // swap R and B and remove line paddings + while(srcptr < memend) + { + lineend = srcptr + linelen; + while(srcptr < lineend) + { + *destptr++ = srcptr[2]; + *destptr++ = srcptr[1]; + *destptr++ = srcptr[0]; + srcptr += 3; + } + + Com_Memset(destptr, '\0', avipadlen); + destptr += avipadlen; + + srcptr += padlen; + } + + ri.CL_WriteAVIVideoFrame(cmd->encodeBuffer, avipadwidth * cmd->height); + } + + return (const void *)(cmd + 1); +} + +//============================================================================ + +/* +** GL_SetDefaultState +*/ +void GL_SetDefaultState( void ) +{ + qglClearDepth( 1.0f ); + + qglCullFace(GL_FRONT); + + // initialize downstream texture unit if we're running + // in a multitexture environment + GL_SelectTexture( 1 ); + GL_TextureMode( r_textureMode->string ); + GL_SelectTexture( 0 ); + + GL_TextureMode( r_textureMode->string ); + + //qglShadeModel( GL_SMOOTH ); + qglDepthFunc( GL_LEQUAL ); + + Com_Memset(&glState, 0, sizeof(glState)); + + // + // make sure our GL state vector is set correctly + // + glState.glStateBits = GLS_DEPTHTEST_DISABLE | GLS_DEPTHMASK_TRUE; + glState.maxDepth = 1.0f; + qglDepthRange(0.0f, 1.0f); + + qglUseProgram(0); + + qglBindBuffer(GL_ARRAY_BUFFER, 0); + qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + qglPolygonMode (GL_FRONT_AND_BACK, GL_FILL); + qglDepthMask( GL_TRUE ); + qglDisable( GL_DEPTH_TEST ); + qglEnable( GL_SCISSOR_TEST ); + qglEnable(GL_PROGRAM_POINT_SIZE); + qglDisable( GL_CULL_FACE ); + qglDisable( GL_BLEND ); + + qglEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); + + qglStencilFunc(GL_ALWAYS, 0, 0xff); + qglStencilOpSeparate(GL_FRONT, GL_KEEP, GL_INCR_WRAP, GL_KEEP); + qglStencilOpSeparate(GL_BACK, GL_KEEP, GL_DECR_WRAP, GL_KEEP); + + // set default vertex color + qglVertexAttrib4f(ATTR_INDEX_COLOR, 1.0f, 1.0f, 1.0f, 1.0f); +} + +/* +================ +R_PrintLongString + +Workaround for ri.Printf's 1024 characters buffer limit. +================ +*/ +void R_PrintLongString(const char *string) { + char buffer[1024]; + const char *p; + int size = strlen(string); + + p = string; + while(size > 0) + { + Q_strncpyz(buffer, p, sizeof (buffer) ); + ri.Printf( PRINT_ALL, "%s", buffer ); + p += 1023; + size -= 1023; + } +} + +/* +================ +GfxInfo_f +================ +*/ +static void GfxInfo_f( void ) +{ + const char *enablestrings[] = + { + "disabled", + "enabled" + }; + const char *fsstrings[] = + { + "windowed", + "fullscreen" + }; + const char *noborderstrings[] = + { + "", + "noborder " + }; + + int fullscreen = ri.Cvar_VariableIntegerValue("r_fullscreen"); + int noborder = ri.Cvar_VariableIntegerValue("r_noborder"); + + ri.Printf( PRINT_ALL, "\nGL_VENDOR: %s\n", glConfig.vendor_string ); + ri.Printf( PRINT_ALL, "GL_RENDERER: %s\n", glConfig.renderer_string ); + ri.Printf( PRINT_ALL, "GL_VERSION: %s\n", glConfig.version_string ); + ri.Printf( PRINT_ALL, "GL_EXTENSIONS: " ); + R_PrintLongString( glConfigExt.originalExtensionString ); + ri.Printf( PRINT_ALL, "\n" ); + ri.Printf( PRINT_ALL, "GL_MAX_TEXTURE_SIZE: %d\n", glConfig.maxTextureSize ); + ri.Printf( PRINT_ALL, "\nPIXELFORMAT: color(%d-bits) Z(%d-bit) stencil(%d-bits)\n", glConfig.colorBits, glConfig.depthBits, glConfig.stencilBits ); + ri.Printf( PRINT_ALL, "MODE: %d, %d x %d %s%s hz:", + ri.Cvar_VariableIntegerValue("r_mode"), + glConfig.vidWidth, glConfig.vidHeight, + fullscreen == 0 ? noborderstrings[noborder == 1] : noborderstrings[0], + fsstrings[fullscreen == 1] ); + if ( glConfig.displayFrequency ) + { + ri.Printf( PRINT_ALL, "%d\n", glConfig.displayFrequency ); + } + else + { + ri.Printf( PRINT_ALL, "N/A\n" ); + } + if ( glConfig.deviceSupportsGamma ) + { + ri.Printf( PRINT_ALL, "GAMMA: hardware w/ %d overbright bits\n", tr.overbrightBits ); + } + else + { + ri.Printf( PRINT_ALL, "GAMMA: software w/ %d overbright bits\n", tr.overbrightBits ); + } + + ri.Printf( PRINT_ALL, "texturemode: %s\n", r_textureMode->string ); + ri.Printf( PRINT_ALL, "picmip: %d\n", r_picmip->integer ); + ri.Printf( PRINT_ALL, "texture bits: %d\n", r_texturebits->integer ); + + if ( r_vertexLight->integer ) + { + ri.Printf( PRINT_ALL, "HACK: using vertex lightmap approximation\n" ); + } + int displayRefresh = ri.Cvar_VariableIntegerValue("r_displayRefresh"); + if ( displayRefresh ) { + ri.Printf( PRINT_ALL, "Display refresh set to %d\n", displayRefresh ); + } + + if ( r_finish->integer ) { + ri.Printf( PRINT_ALL, "Forcing glFinish\n" ); + } + + ri.Printf( PRINT_ALL, "Dynamic Glow: %s\n", enablestrings[r_dynamicGlow->integer != 0] ); +} + +/* +================ +GfxMemInfo_f +================ +*/ +void GfxMemInfo_f( void ) +{ + switch (glRefConfig.memInfo) + { + case MI_NONE: + { + ri.Printf(PRINT_ALL, "No extension found for GPU memory info.\n"); + } + break; + case MI_NVX: + { + int value; + + qglGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX: %ikb\n", value); + + qglGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX: %ikb\n", value); + + qglGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX: %ikb\n", value); + + qglGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_EVICTION_COUNT_NVX: %i\n", value); + + qglGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &value); + ri.Printf(PRINT_ALL, "GPU_MEMORY_INFO_EVICTED_MEMORY_NVX: %ikb\n", value); + } + break; + case MI_ATI: + { + // GL_ATI_meminfo + int value[4]; + + qglGetIntegerv(GL_VBO_FREE_MEMORY_ATI, &value[0]); + ri.Printf(PRINT_ALL, "VBO_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); + + qglGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, &value[0]); + ri.Printf(PRINT_ALL, "TEXTURE_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); + + qglGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, &value[0]); + ri.Printf(PRINT_ALL, "RENDERBUFFER_FREE_MEMORY_ATI: %ikb total %ikb largest aux: %ikb total %ikb largest\n", value[0], value[1], value[2], value[3]); + } + break; + } +} + +static void R_CaptureFrameData_f() +{ + int argc = ri.Cmd_Argc(); + if ( argc <= 1 ) + { + ri.Printf( PRINT_ALL, "Usage: %s \n", ri.Cmd_Argv(0)); + return; + } + + + const char *cmd = ri.Cmd_Argv(1); + if ( Q_stricmp(cmd, "single") == 0 ) + tr.numFramesToCapture = 1; + else if ( Q_stricmp(cmd, "multi") == 0 ) + tr.numFramesToCapture = atoi(ri.Cmd_Argv(1)); + + int len = ri.FS_FOpenFileByMode("rend2.log", &tr.debugFile, FS_APPEND); + if ( len == -1 || !tr.debugFile ) + { + ri.Printf( PRINT_ERROR, "Failed to open rend2 log file\n" ); + tr.numFramesToCapture = 0; + } +} + +void R_RemapSkyShader_f (void) { + int num; + + if (ri.Cmd_Argc() != 2 || !strlen(ri.Cmd_Argv(1))) { + ri.Printf(PRINT_ALL, "Usage: /remapSky \n"); + return; + } + + for (num = 0; num < tr.numShaders; num++) { + if (tr.shaders[num]->isSky) + { + R_RemapShader(tr.shaders[num]->name, ri.Cmd_Argv(1), NULL); + } + } +} + +void R_ClearRemaps_f(void) { + int num; + + for (num = 0; num < tr.numShaders; num++) { + tr.shaders[num]->remappedShader = NULL; + } +} + + +typedef struct consoleCommand_s { + const char *cmd; + xcommand_t func; +} consoleCommand_t; + +static consoleCommand_t commands[] = { + { "imagelist", R_ImageList_f }, + { "shaderlist", R_ShaderList_f }, + { "skinlist", R_SkinList_f }, + { "fontlist", R_FontList_f }, + { "screenshot", R_ScreenShotJPEG_f }, + { "screenshot_png", R_ScreenShotPNG_f }, + { "screenshot_tga", R_ScreenShotTGA_f }, + { "gfxinfo", GfxInfo_f }, + { "gfxmeminfo", GfxMemInfo_f }, + { "r_we", R_WorldEffect_f }, + //{ "imagecacheinfo", RE_RegisterImages_Info_f }, + { "modellist", R_Modellist_f }, + //{ "modelcacheinfo", RE_RegisterModels_Info_f }, + { "r_cleardecals", RE_ClearDecals }, + { "remapSky", R_RemapSkyShader_f }, + { "clearRemaps", R_ClearRemaps_f }, + { "vbolist", R_VBOList_f }, + { "capframes", R_CaptureFrameData_f }, +}; + +static const size_t numCommands = ARRAY_LEN( commands ); + + +/* +=============== +R_Register +=============== +*/ +void R_Register( void ) +{ + // + // latched and archived variables + // + r_allowExtensions = ri.Cvar_Get( "r_allowExtensions", "1", CVAR_ARCHIVE | CVAR_LATCH, "Allow GL extensions" ); + r_ext_compressed_textures = ri.Cvar_Get( "r_ext_compress_textures", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable texture compression" ); + r_ext_multitexture = ri.Cvar_Get( "r_ext_multitexture", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); + r_ext_compiled_vertex_array = ri.Cvar_Get( "r_ext_compiled_vertex_array", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); + r_ext_texture_env_add = ri.Cvar_Get( "r_ext_texture_env_add", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); + r_ext_preferred_tc_method = ri.Cvar_Get( "r_ext_preferred_tc_method", "0", CVAR_ARCHIVE | CVAR_LATCH, "Preferred texture compression method" ); + + r_ext_draw_range_elements = ri.Cvar_Get( "r_ext_draw_range_elements", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); + r_ext_multi_draw_arrays = ri.Cvar_Get( "r_ext_multi_draw_arrays", "1", CVAR_ARCHIVE | CVAR_LATCH, "Unused" ); + r_ext_texture_float = ri.Cvar_Get( "r_ext_texture_float", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable floating-point textures" ); + r_arb_half_float_pixel = ri.Cvar_Get( "r_arb_half_float_pixel", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable ARB_half_float GL extension" ); + r_ext_framebuffer_multisample = ri.Cvar_Get( "r_ext_multisample", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable framebuffer MSAA" ); + r_arb_seamless_cube_map = ri.Cvar_Get( "r_arb_seamless_cube_map", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable seamless cube map filtering GL extension" ); + r_arb_vertex_type_2_10_10_10_rev = ri.Cvar_Get( "r_arb_vertex_type_2_10_10_10_rev", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable 1010102 UI data type" ); + r_arb_buffer_storage = ri.Cvar_Get( "r_arb_buffer_storage", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable buffer storage GL extension" ); + r_ext_texture_filter_anisotropic = ri.Cvar_Get( "r_ext_texture_filter_anisotropic", "16", CVAR_ARCHIVE, "Disable/enable anisotropic texture filtering" ); + + r_dynamicGlow = ri.Cvar_Get( "r_dynamicGlow", "0", CVAR_ARCHIVE, "" ); + r_dynamicGlowPasses = ri.Cvar_Get( "r_dynamicGlowPasses", "5", CVAR_ARCHIVE, "" ); + r_dynamicGlowDelta = ri.Cvar_Get( "r_dynamicGlowDelta", "0.8f", CVAR_ARCHIVE, "" ); + r_dynamicGlowIntensity = ri.Cvar_Get( "r_dynamicGlowIntensity", "1.13f", CVAR_ARCHIVE, "" ); + r_dynamicGlowSoft = ri.Cvar_Get( "r_dynamicGlowSoft", "1", CVAR_ARCHIVE, "" ); + r_dynamicGlowWidth = ri.Cvar_Get( "r_dynamicGlowWidth", "320", CVAR_ARCHIVE|CVAR_LATCH, "" ); + r_dynamicGlowHeight = ri.Cvar_Get( "r_dynamicGlowHeight", "240", CVAR_ARCHIVE|CVAR_LATCH, "" ); + + r_debugContext = ri.Cvar_Get( "r_debugContext", "0", CVAR_LATCH, "" ); + r_debugWeather = ri.Cvar_Get( "r_debugWeather", "0", CVAR_ARCHIVE, "" ); + + r_picmip = ri.Cvar_Get ("r_picmip", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); + ri.Cvar_CheckRange( r_picmip, 0, 16, qtrue ); + r_smartpicmip = ri.Cvar_Get( "r_smartpicmip", "1", CVAR_ARCHIVE_ND|CVAR_LATCH, "Applies r_picmip setting to map textures only." ); + r_roundImagesDown = ri.Cvar_Get ("r_roundImagesDown", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_colorMipLevels = ri.Cvar_Get ("r_colorMipLevels", "0", CVAR_LATCH, "" ); + r_detailTextures = ri.Cvar_Get( "r_detailtextures", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_texturebits = ri.Cvar_Get( "r_texturebits", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_overBrightBits = ri.Cvar_Get ("r_overBrightBits", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_simpleMipMaps = ri.Cvar_Get( "r_simpleMipMaps", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_vertexLight = ri.Cvar_Get( "r_vertexLight", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_uiFullScreen = ri.Cvar_Get( "r_uifullscreen", "0", 0, ""); + r_subdivisions = ri.Cvar_Get ("r_subdivisions", "4", CVAR_ARCHIVE | CVAR_LATCH, ""); + ri.Cvar_CheckRange( r_subdivisions, 4, 80, qfalse ); + r_stereo = ri.Cvar_Get( "r_stereo", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + r_greyscale = ri.Cvar_Get("r_greyscale", "0", CVAR_ARCHIVE | CVAR_LATCH, ""); + ri.Cvar_CheckRange(r_greyscale, 0, 1, qfalse); + + r_externalGLSL = ri.Cvar_Get( "r_externalGLSL", "0", CVAR_LATCH, "" ); + + r_hdr = ri.Cvar_Get( "r_hdr", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable rendering in HDR" ); + r_floatLightmap = ri.Cvar_Get( "r_floatLightmap", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable HDR lightmap support" ); + + r_toneMap = ri.Cvar_Get( "r_toneMap", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable tonemapping" ); + r_forceToneMap = ri.Cvar_Get( "r_forceToneMap", "0", CVAR_CHEAT, "" ); + r_forceToneMapMin = ri.Cvar_Get( "r_forceToneMapMin", "-8.0", CVAR_CHEAT, "" ); + r_forceToneMapAvg = ri.Cvar_Get( "r_forceToneMapAvg", "-2.0", CVAR_CHEAT, "" ); + r_forceToneMapMax = ri.Cvar_Get( "r_forceToneMapMax", "0.0", CVAR_CHEAT, "" ); + + r_autoExposure = ri.Cvar_Get( "r_autoExposure", "1", CVAR_ARCHIVE, "Disable/enable auto exposure" ); + r_forceAutoExposure = ri.Cvar_Get( "r_forceAutoExposure", "0", CVAR_CHEAT, "" ); + r_forceAutoExposureMin = ri.Cvar_Get( "r_forceAutoExposureMin", "-2.0", CVAR_CHEAT, "" ); + r_forceAutoExposureMax = ri.Cvar_Get( "r_forceAutoExposureMax", "2.0", CVAR_CHEAT, "" ); + + r_cameraExposure = ri.Cvar_Get( "r_cameraExposure", "0", CVAR_CHEAT, "" ); + + r_depthPrepass = ri.Cvar_Get( "r_depthPrepass", "1", CVAR_ARCHIVE, "" ); + r_ssao = ri.Cvar_Get( "r_ssao", "0", CVAR_LATCH | CVAR_ARCHIVE, "" ); + + r_normalMapping = ri.Cvar_Get( "r_normalMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable normal mapping" ); + r_specularMapping = ri.Cvar_Get( "r_specularMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable specular mapping" ); + r_deluxeMapping = ri.Cvar_Get( "r_deluxeMapping", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable reading deluxemaps when compiled with q3map2" ); + r_deluxeSpecular = ri.Cvar_Get("r_deluxeSpecular", "1", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable/scale the specular response from deluxemaps"); + r_parallaxMapping = ri.Cvar_Get( "r_parallaxMapping", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable parallax mapping" ); + r_cubeMapping = ri.Cvar_Get( "r_cubeMapping", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable cubemapping" ); + r_cubeMappingBounces = ri.Cvar_Get("r_cubeMappingBounces", "0", CVAR_ARCHIVE | CVAR_LATCH, "Renders cubemaps multiple times to get reflections in reflections"); + ri.Cvar_CheckRange(r_cubeMappingBounces, 0, 2, qfalse); + r_baseNormalX = ri.Cvar_Get( "r_baseNormalX", "1.0", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_baseNormalY = ri.Cvar_Get( "r_baseNormalY", "1.0", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_baseParallax = ri.Cvar_Get( "r_baseParallax", "0.05", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_baseSpecular = ri.Cvar_Get( "r_baseSpecular", "0.04", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_dlightMode = ri.Cvar_Get( "r_dlightMode", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_pshadowDist = ri.Cvar_Get( "r_pshadowDist", "128", CVAR_ARCHIVE, "" ); + r_imageUpsample = ri.Cvar_Get( "r_imageUpsample", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_imageUpsampleMaxSize = ri.Cvar_Get( "r_imageUpsampleMaxSize", "1024", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_imageUpsampleType = ri.Cvar_Get( "r_imageUpsampleType", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_genNormalMaps = ri.Cvar_Get( "r_genNormalMaps", "0", CVAR_ARCHIVE | CVAR_LATCH, "Disable/enable generating normal maps from diffuse maps" ); + + r_forceSun = ri.Cvar_Get( "r_forceSun", "0", CVAR_CHEAT, "" ); + r_forceSunMapLightScale = ri.Cvar_Get( "r_forceSunMapLightScale", "1.0", CVAR_CHEAT, "" ); + r_forceSunLightScale = ri.Cvar_Get( "r_forceSunLightScale", "1.0", CVAR_CHEAT, "" ); + r_forceSunAmbientScale = ri.Cvar_Get( "r_forceSunAmbientScale", "0.5", CVAR_CHEAT, "" ); + r_drawSunRays = ri.Cvar_Get( "r_drawSunRays", "0", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_sunlightMode = ri.Cvar_Get( "r_sunlightMode", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + + r_sunShadows = ri.Cvar_Get( "r_sunShadows", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_shadowFilter = ri.Cvar_Get( "r_shadowFilter", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_shadowMapSize = ri.Cvar_Get( "r_shadowMapSize", "1024", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_shadowCascadeZNear = ri.Cvar_Get( "r_shadowCascadeZNear", "4", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_shadowCascadeZFar = ri.Cvar_Get( "r_shadowCascadeZFar", "3072", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_shadowCascadeZBias = ri.Cvar_Get( "r_shadowCascadeZBias", "-320", CVAR_ARCHIVE | CVAR_LATCH, "" ); + r_ignoreDstAlpha = ri.Cvar_Get( "r_ignoreDstAlpha", "1", CVAR_ARCHIVE | CVAR_LATCH, "" ); + + // + // temporary latched variables that can only change over a restart + // + r_fullbright = ri.Cvar_Get ("r_fullbright", "0", CVAR_LATCH|CVAR_CHEAT, "" ); + r_mapOverBrightBits = ri.Cvar_Get ("r_mapOverBrightBits", "0", CVAR_LATCH, "" ); + r_intensity = ri.Cvar_Get ("r_intensity", "1", CVAR_LATCH, "" ); + r_singleShader = ri.Cvar_Get ("r_singleShader", "0", CVAR_CHEAT | CVAR_LATCH, "" ); + + // + // archived variables that can change at any time + // + r_lodCurveError = ri.Cvar_Get( "r_lodCurveError", "250", CVAR_ARCHIVE|CVAR_CHEAT, "" ); + r_lodbias = ri.Cvar_Get( "r_lodbias", "0", CVAR_ARCHIVE, "" ); + r_flares = ri.Cvar_Get ("r_flares", "0", CVAR_ARCHIVE, "" ); + r_znear = ri.Cvar_Get( "r_znear", "4", CVAR_CHEAT, "" ); + ri.Cvar_CheckRange( r_znear, 0.001f, 200, qfalse ); + r_autolodscalevalue = ri.Cvar_Get( "r_autolodscalevalue", "0", CVAR_ROM, "" ); + r_zproj = ri.Cvar_Get( "r_zproj", "64", CVAR_ARCHIVE, "" ); + r_stereoSeparation = ri.Cvar_Get( "r_stereoSeparation", "64", CVAR_ARCHIVE, "" ); + r_ignoreGLErrors = ri.Cvar_Get( "r_ignoreGLErrors", "1", CVAR_ARCHIVE, "" ); + r_fastsky = ri.Cvar_Get( "r_fastsky", "0", CVAR_ARCHIVE, "" ); + r_inGameVideo = ri.Cvar_Get( "r_inGameVideo", "1", CVAR_ARCHIVE, "" ); + r_drawSun = ri.Cvar_Get( "r_drawSun", "0", CVAR_ARCHIVE, "" ); + r_dynamiclight = ri.Cvar_Get( "r_dynamiclight", "1", CVAR_ARCHIVE, "" ); + r_finish = ri.Cvar_Get ("r_finish", "0", CVAR_ARCHIVE, ""); + r_textureMode = ri.Cvar_Get( "r_textureMode", "GL_LINEAR_MIPMAP_NEAREST", CVAR_ARCHIVE, "" ); + r_markcount = ri.Cvar_Get( "r_markcount", "100", CVAR_ARCHIVE, "" ); + r_gamma = ri.Cvar_Get( "r_gamma", "1", CVAR_ARCHIVE, "" ); + r_facePlaneCull = ri.Cvar_Get ("r_facePlaneCull", "1", CVAR_ARCHIVE, "" ); + + r_ambientScale = ri.Cvar_Get( "r_ambientScale", "0.6", CVAR_CHEAT, "" ); + r_directedScale = ri.Cvar_Get( "r_directedScale", "1", CVAR_CHEAT, "" ); + + r_anaglyphMode = ri.Cvar_Get("r_anaglyphMode", "0", CVAR_ARCHIVE, ""); + r_mergeMultidraws = ri.Cvar_Get("r_mergeMultidraws", "1", CVAR_ARCHIVE, ""); + r_mergeLeafSurfaces = ri.Cvar_Get("r_mergeLeafSurfaces", "1", CVAR_ARCHIVE, ""); + + // + // temporary variables that can change at any time + // + r_showImages = ri.Cvar_Get( "r_showImages", "0", CVAR_TEMP, "" ); + + r_debugLight = ri.Cvar_Get( "r_debuglight", "0", CVAR_TEMP, "" ); + r_debugSort = ri.Cvar_Get( "r_debugSort", "0", CVAR_CHEAT, "" ); + r_printShaders = ri.Cvar_Get( "r_printShaders", "0", 0, "" ); + r_saveFontData = ri.Cvar_Get( "r_saveFontData", "0", 0, "" ); + + r_forceParallaxBias = ri.Cvar_Get("r_forceParallaxBias", "0", CVAR_TEMP, ""); + ri.Cvar_CheckRange(r_forceParallaxBias, 0.0f, 1.0f, qfalse); + + r_nocurves = ri.Cvar_Get ("r_nocurves", "0", CVAR_CHEAT, "" ); + r_drawworld = ri.Cvar_Get ("r_drawworld", "1", CVAR_CHEAT, "" ); + r_drawfog = ri.Cvar_Get("r_drawfog", "2", CVAR_CHEAT, ""); + r_lightmap = ri.Cvar_Get ("r_lightmap", "0", 0, "" ); + r_distanceCull = ri.Cvar_Get( "r_distanceCull", "0", CVAR_ARCHIVE_ND, "" ); + + r_portalOnly = ri.Cvar_Get ("r_portalOnly", "0", CVAR_CHEAT, "" ); + + r_skipBackEnd = ri.Cvar_Get ("r_skipBackEnd", "0", CVAR_CHEAT, ""); + + r_measureOverdraw = ri.Cvar_Get( "r_measureOverdraw", "0", CVAR_CHEAT, "" ); + r_lodscale = ri.Cvar_Get( "r_lodscale", "5", CVAR_CHEAT, "" ); + r_norefresh = ri.Cvar_Get ("r_norefresh", "0", CVAR_CHEAT, ""); + r_drawentities = ri.Cvar_Get ("r_drawentities", "1", CVAR_CHEAT, "" ); + r_ignore = ri.Cvar_Get( "r_ignore", "1", CVAR_CHEAT, "" ); + r_nocull = ri.Cvar_Get ("r_nocull", "0", CVAR_CHEAT, ""); + r_novis = ri.Cvar_Get ("r_novis", "0", CVAR_CHEAT, ""); + r_showcluster = ri.Cvar_Get ("r_showcluster", "0", CVAR_CHEAT, ""); + r_speeds = ri.Cvar_Get ("r_speeds", "0", CVAR_CHEAT, ""); + r_verbose = ri.Cvar_Get( "r_verbose", "0", CVAR_CHEAT, "" ); + r_logFile = ri.Cvar_Get( "r_logFile", "0", CVAR_CHEAT, "" ); + r_debugSurface = ri.Cvar_Get ("r_debugSurface", "0", CVAR_CHEAT, ""); + r_nobind = ri.Cvar_Get ("r_nobind", "0", CVAR_CHEAT, ""); + r_showtris = ri.Cvar_Get ("r_showtris", "0", CVAR_CHEAT, ""); + r_showsky = ri.Cvar_Get ("r_showsky", "0", CVAR_CHEAT, ""); + r_shownormals = ri.Cvar_Get ("r_shownormals", "0", CVAR_CHEAT, ""); + r_clear = ri.Cvar_Get ("r_clear", "0", CVAR_CHEAT, ""); + r_offsetFactor = ri.Cvar_Get( "r_offsetfactor", "-1", CVAR_CHEAT, "" ); + r_offsetUnits = ri.Cvar_Get( "r_offsetunits", "-2", CVAR_CHEAT, "" ); + + r_shadowOffsetFactor = ri.Cvar_Get("r_shadowOffsetFactor", "1.0", CVAR_CHEAT, ""); + r_shadowOffsetUnits = ri.Cvar_Get("r_shadowOffsetUnits", "1.0", CVAR_CHEAT, ""); + + r_drawBuffer = ri.Cvar_Get( "r_drawBuffer", "GL_BACK", CVAR_CHEAT, "" ); + r_lockpvs = ri.Cvar_Get ("r_lockpvs", "0", CVAR_CHEAT, ""); + r_noportals = ri.Cvar_Get ("r_noportals", "0", CVAR_CHEAT, ""); + r_shadows = ri.Cvar_Get( "cg_shadows", "1", 0, "" ); + + r_marksOnTriangleMeshes = ri.Cvar_Get("r_marksOnTriangleMeshes", "0", CVAR_ARCHIVE, ""); + + r_aviMotionJpegQuality = ri.Cvar_Get("r_aviMotionJpegQuality", "90", CVAR_ARCHIVE, ""); + r_screenshotJpegQuality = ri.Cvar_Get("r_screenshotJpegQuality", "90", CVAR_ARCHIVE, ""); + r_surfaceSprites = ri.Cvar_Get("r_surfaceSprites", "1", CVAR_ARCHIVE, ""); + + r_aspectCorrectFonts = ri.Cvar_Get( "r_aspectCorrectFonts", "0", CVAR_ARCHIVE, "" ); + cl_ratioFix = ri.Cvar_Get( "cl_ratioFix", "1", CVAR_ARCHIVE, "" ); + r_maxpolys = ri.Cvar_Get( "r_maxpolys", XSTRING( DEFAULT_MAX_POLYS ), 0, ""); + r_maxpolyverts = ri.Cvar_Get( "r_maxpolyverts", XSTRING( DEFAULT_MAX_POLYVERTS ), 0, "" ); + +/* +Ghoul2 Insert Start +*/ +#ifdef _DEBUG + r_noPrecacheGLA = ri.Cvar_Get( "r_noPrecacheGLA", "0", CVAR_CHEAT, "" ); +#endif + r_noServerGhoul2 = ri.Cvar_Get( "r_noserverghoul2", "0", CVAR_CHEAT, "" ); + r_Ghoul2AnimSmooth = ri.Cvar_Get( "r_ghoul2animsmooth", "0.3", CVAR_NONE, "" ); + r_Ghoul2UnSqashAfterSmooth = ri.Cvar_Get( "r_ghoul2unsqashaftersmooth", "1", CVAR_NONE, "" ); + broadsword = ri.Cvar_Get( "broadsword", "0", CVAR_ARCHIVE, "" ); + broadsword_kickbones = ri.Cvar_Get( "broadsword_kickbones", "1", CVAR_NONE, "" ); + broadsword_kickorigin = ri.Cvar_Get( "broadsword_kickorigin", "1", CVAR_NONE, "" ); + broadsword_dontstopanim = ri.Cvar_Get( "broadsword_dontstopanim", "0", CVAR_NONE, "" ); + broadsword_waitforshot = ri.Cvar_Get( "broadsword_waitforshot", "0", CVAR_NONE, "" ); + broadsword_playflop = ri.Cvar_Get( "broadsword_playflop", "1", CVAR_NONE, "" ); + broadsword_smallbbox = ri.Cvar_Get( "broadsword_smallbbox", "0", CVAR_NONE, "" ); + broadsword_extra1 = ri.Cvar_Get( "broadsword_extra1", "0", CVAR_NONE, "" ); + broadsword_extra2 = ri.Cvar_Get( "broadsword_extra2", "0", CVAR_NONE, "" ); + broadsword_effcorr = ri.Cvar_Get( "broadsword_effcorr", "1", CVAR_NONE, "" ); + broadsword_ragtobase = ri.Cvar_Get( "broadsword_ragtobase", "2", CVAR_NONE, "" ); + broadsword_dircap = ri.Cvar_Get( "broadsword_dircap", "64", CVAR_NONE, "" ); +/* +Ghoul2 Insert End +*/ + + se_language = ri.Cvar_Get ( "se_language", "english", CVAR_ARCHIVE | CVAR_NORESTART, "" ); + + for ( size_t i = 0; i < numCommands; i++ ) + ri.Cmd_AddCommand( commands[i].cmd, commands[i].func, "" ); +} + +void R_InitQueries(void) +{ + if (r_drawSunRays->integer) + qglGenQueries(ARRAY_LEN(tr.sunFlareQuery), tr.sunFlareQuery); +} + +void R_ShutDownQueries(void) +{ + if (r_drawSunRays->integer) + qglDeleteQueries(ARRAY_LEN(tr.sunFlareQuery), tr.sunFlareQuery); +} + +void RE_SetLightStyle (int style, int color); + +static void R_InitBackEndFrameData() +{ + GLuint timerQueries[MAX_GPU_TIMERS*MAX_FRAMES]; + qglGenQueries(MAX_GPU_TIMERS*MAX_FRAMES, timerQueries); + + GLuint ubos[MAX_FRAMES]; + qglGenBuffers(MAX_FRAMES, ubos); + + for ( int i = 0; i < MAX_FRAMES; i++ ) + { + gpuFrame_t *frame = backEndData->frames + i; + const GLbitfield mapBits = GL_MAP_WRITE_BIT | GL_MAP_COHERENT_BIT | GL_MAP_PERSISTENT_BIT; + + frame->ubo = ubos[i]; + frame->uboWriteOffset = 0; + frame->uboSize = FRAME_UNIFORM_BUFFER_SIZE; + qglBindBuffer(GL_UNIFORM_BUFFER, frame->ubo); + glState.currentGlobalUBO = frame->ubo; + + // TODO: persistently mapped UBOs + qglBufferData(GL_UNIFORM_BUFFER, FRAME_UNIFORM_BUFFER_SIZE, + nullptr, GL_DYNAMIC_DRAW); + + frame->dynamicVbo = R_CreateVBO(nullptr, FRAME_VERTEX_BUFFER_SIZE, + VBO_USAGE_DYNAMIC); + frame->dynamicVboCommitOffset = 0; + frame->dynamicVboWriteOffset = 0; + + frame->dynamicIbo = R_CreateIBO(nullptr, FRAME_INDEX_BUFFER_SIZE, + VBO_USAGE_DYNAMIC); + frame->dynamicIboCommitOffset = 0; + frame->dynamicIboWriteOffset = 0; + + if ( glRefConfig.immutableBuffers ) + { + R_BindVBO(frame->dynamicVbo); + frame->dynamicVboMemory = qglMapBufferRange(GL_ARRAY_BUFFER, 0, + frame->dynamicVbo->vertexesSize, mapBits); + + R_BindIBO(frame->dynamicIbo); + frame->dynamicIboMemory = qglMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, 0, + frame->dynamicIbo->indexesSize, mapBits); + } + else + { + frame->dynamicVboMemory = nullptr; + frame->dynamicIboMemory = nullptr; + } + + for ( int j = 0; j < MAX_GPU_TIMERS; j++ ) + { + gpuTimer_t *timer = frame->timers + j; + timer->queryName = timerQueries[i*MAX_GPU_TIMERS + j]; + } + } + + backEndData->currentFrame = backEndData->frames; +} + +#ifdef _G2_GORE +static void R_InitGoreVao() +{ + tr.goreVBO = R_CreateVBO( + nullptr, + sizeof(g2GoreVert_t) * MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_VERTS * MAX_FRAMES, + VBO_USAGE_DYNAMIC); + tr.goreVBO->offsets[ATTR_INDEX_POSITION] = offsetof(g2GoreVert_t, position); + tr.goreVBO->offsets[ATTR_INDEX_NORMAL] = offsetof(g2GoreVert_t, normal); + tr.goreVBO->offsets[ATTR_INDEX_TEXCOORD0] = offsetof(g2GoreVert_t, texCoords); + tr.goreVBO->offsets[ATTR_INDEX_BONE_INDEXES] = offsetof(g2GoreVert_t, bonerefs); + tr.goreVBO->offsets[ATTR_INDEX_BONE_WEIGHTS] = offsetof(g2GoreVert_t, weights); + tr.goreVBO->offsets[ATTR_INDEX_TANGENT] = offsetof(g2GoreVert_t, tangents); + + tr.goreVBO->strides[ATTR_INDEX_POSITION] = sizeof(g2GoreVert_t); + tr.goreVBO->strides[ATTR_INDEX_NORMAL] = sizeof(g2GoreVert_t); + tr.goreVBO->strides[ATTR_INDEX_TEXCOORD0] = sizeof(g2GoreVert_t); + tr.goreVBO->strides[ATTR_INDEX_BONE_INDEXES] = sizeof(g2GoreVert_t); + tr.goreVBO->strides[ATTR_INDEX_BONE_WEIGHTS] = sizeof(g2GoreVert_t); + tr.goreVBO->strides[ATTR_INDEX_TANGENT] = sizeof(g2GoreVert_t); + + tr.goreVBO->sizes[ATTR_INDEX_POSITION] = sizeof(vec3_t); + tr.goreVBO->sizes[ATTR_INDEX_NORMAL] = sizeof(uint32_t); + tr.goreVBO->sizes[ATTR_INDEX_TEXCOORD0] = sizeof(vec2_t); + tr.goreVBO->sizes[ATTR_INDEX_BONE_WEIGHTS] = sizeof(byte); + tr.goreVBO->sizes[ATTR_INDEX_BONE_INDEXES] = sizeof(byte); + tr.goreVBO->sizes[ATTR_INDEX_TANGENT] = sizeof(uint32_t); + + tr.goreIBO = R_CreateIBO( + nullptr, + sizeof(glIndex_t) * MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_INDECIES * MAX_FRAMES, + VBO_USAGE_DYNAMIC); + + tr.goreIBOCurrentIndex = 0; + tr.goreVBOCurrentIndex = 0; +} +#endif + +static void R_InitStaticConstants() +{ + const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; + size_t alignedBlockSize = 0; + + qglBindBuffer(GL_UNIFORM_BUFFER, tr.staticUbo); + qglBufferData( + GL_UNIFORM_BUFFER, + STATIC_UNIFORM_BUFFER_SIZE, + nullptr, + GL_STATIC_DRAW); + + // Setup static 2d camera data + EntityBlock entity2DBlock = {}; + entity2DBlock.fxVolumetricBase = -1.0f; + Matrix16Identity(entity2DBlock.modelMatrix); + tr.entity2DUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, 0, sizeof(entity2DBlock), &entity2DBlock); + alignedBlockSize += (sizeof(EntityBlock) + alignment) & ~alignment; + + // Setup static 2d camera data + CameraBlock a2DCameraBlock = {}; + Matrix16Ortho( + 0.0f, + 640.0f, + 480.0f, + 0.0f, + 0.0f, + 1.0f, + a2DCameraBlock.viewProjectionMatrix); + + tr.camera2DUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, tr.camera2DUboOffset, sizeof(a2DCameraBlock), &a2DCameraBlock); + alignedBlockSize += (sizeof(CameraBlock) + alignment) & ~alignment; + + // Setup static flare entity data + EntityBlock entityFlareBlock = {}; + entityFlareBlock.fxVolumetricBase = -1.0f; + Matrix16Identity(entityFlareBlock.modelMatrix); + + tr.entityFlareUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, tr.entityFlareUboOffset, sizeof(entityFlareBlock), &entityFlareBlock); + alignedBlockSize += (sizeof(EntityBlock) + alignment) & ~alignment; + + // Setup static flare camera data + CameraBlock flareCameraBlock = {}; + Matrix16Ortho( + 0.0f, + glConfig.vidWidth, + glConfig.vidHeight, + 0.0f, + -99999.0f, + 99999.0f, + flareCameraBlock.viewProjectionMatrix); + + tr.cameraFlareUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, tr.cameraFlareUboOffset, sizeof(flareCameraBlock), &flareCameraBlock); + alignedBlockSize += (sizeof(CameraBlock) + alignment) & ~alignment; + + // Setup default light block + LightsBlock lightsBlock = {}; + lightsBlock.numLights = 0; + + tr.defaultLightsUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, tr.defaultLightsUboOffset, sizeof(lightsBlock), &lightsBlock); + alignedBlockSize += (sizeof(LightsBlock) + alignment) & ~alignment; + + // Setup default scene block + SceneBlock sceneBlock = {}; + sceneBlock.globalFogIndex = -1; + sceneBlock.currentTime = 0.1f; + sceneBlock.frameTime = 0.1f; + + tr.defaultSceneUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, tr.defaultSceneUboOffset, sizeof(sceneBlock), &sceneBlock); + alignedBlockSize += (sizeof(SceneBlock) + alignment) & ~alignment; + + // Setup default fogs block + FogsBlock fogsBlock = {}; + fogsBlock.numFogs = 0; + tr.defaultFogsUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, tr.defaultFogsUboOffset, sizeof(fogsBlock), &fogsBlock); + alignedBlockSize += (sizeof(FogsBlock) + alignment) & ~alignment; + + // Setup default shader instance block + ShaderInstanceBlock shaderInstanceBlock = {}; + tr.defaultShaderInstanceUboOffset = alignedBlockSize; + qglBufferSubData( + GL_UNIFORM_BUFFER, tr.defaultShaderInstanceUboOffset, sizeof(shaderInstanceBlock), &shaderInstanceBlock); + alignedBlockSize += (sizeof(ShaderInstanceBlock) + alignment) & ~alignment; + + qglBindBuffer(GL_UNIFORM_BUFFER, NULL); + glState.currentGlobalUBO = -1; + + GL_CheckErrors(); +} + +static void R_ShutdownBackEndFrameData() +{ + if ( !backEndData ) + return; + + for ( int i = 0; i < MAX_FRAMES; i++ ) + { + gpuFrame_t *frame = backEndData->frames + i; + + if (frame->sync) + { + qglDeleteSync(frame->sync); + frame->sync = NULL; + } + + qglDeleteBuffers(1, &frame->ubo); + + if ( glRefConfig.immutableBuffers ) + { + R_BindVBO(frame->dynamicVbo); + R_BindIBO(frame->dynamicIbo); + qglUnmapBuffer(GL_ARRAY_BUFFER); + qglUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); + } + + for ( int j = 0; j < MAX_GPU_TIMERS; j++ ) + { + gpuTimer_t *timer = frame->timers + j; + qglDeleteQueries(1, &timer->queryName); + } + } +} + +/* +=============== +R_Init +=============== +*/ +void R_Init( void ) { + byte *ptr; + int i; + + ri.Printf( PRINT_ALL, "----- R_Init -----\n" ); + + // clear all our internal state + Com_Memset( &tr, 0, sizeof( tr ) ); + Com_Memset( &backEnd, 0, sizeof( backEnd ) ); + Com_Memset( &tess, 0, sizeof( tess ) ); + + + // + // init function tables + // + for ( i = 0; i < FUNCTABLE_SIZE; i++ ) + { + tr.sinTable[i] = sin( DEG2RAD( i * 360.0f / ( ( float ) ( FUNCTABLE_SIZE - 1 ) ) ) ); + tr.squareTable[i] = ( i < FUNCTABLE_SIZE/2 ) ? 1.0f : -1.0f; + tr.sawToothTable[i] = (float)i / FUNCTABLE_SIZE; + tr.inverseSawToothTable[i] = 1.0f - tr.sawToothTable[i]; + + if ( i < FUNCTABLE_SIZE / 2 ) + { + if ( i < FUNCTABLE_SIZE / 4 ) + { + tr.triangleTable[i] = ( float ) i / ( FUNCTABLE_SIZE / 4 ); + } + else + { + tr.triangleTable[i] = 1.0f - tr.triangleTable[i-FUNCTABLE_SIZE / 4]; + } + } + else + { + tr.triangleTable[i] = -tr.triangleTable[i-FUNCTABLE_SIZE/2]; + } + } + + R_InitFogTable(); + + R_ImageLoader_Init(); + R_NoiseInit(); + R_Register(); + + max_polys = Q_min( r_maxpolys->integer, DEFAULT_MAX_POLYS ); + max_polyverts = Q_min( r_maxpolyverts->integer, DEFAULT_MAX_POLYVERTS ); + + ptr = (byte*)ri.Hunk_Alloc( + sizeof( *backEndData ) + + sizeof(srfPoly_t) * max_polys + + sizeof(polyVert_t) * max_polyverts + + sizeof(Allocator) + + PER_FRAME_MEMORY_BYTES, + h_low); + + backEndData = (backEndData_t *)ptr; + ptr = (byte *)(backEndData + 1); + + backEndData->polys = (srfPoly_t *)ptr; + ptr += sizeof(*backEndData->polys) * max_polys; + + backEndData->polyVerts = (polyVert_t *)ptr; + ptr += sizeof(*backEndData->polyVerts) * max_polyverts; + + backEndData->perFrameMemory = new(ptr) Allocator(ptr + sizeof(*backEndData->perFrameMemory), PER_FRAME_MEMORY_BYTES); + + R_InitNextFrame(); + + for ( int i = 0; i < MAX_LIGHT_STYLES; i++ ) + { + RE_SetLightStyle (i, -1); + } + + R_InitImagesPool(); + + InitOpenGL(); + R_Set2DRatio(); + + R_InitGPUBuffers(); + + R_InitStaticConstants(); + R_InitBackEndFrameData(); + R_InitImages(); + +#ifdef _G2_GORE + R_InitGoreVao(); +#endif + + FBO_Init(); + + GLSL_LoadGPUShaders(); + + R_InitShaders (qfalse); + + R_InitSkins(); + + R_InitFonts(); + + R_ModelInit(); + + R_InitDecals(); + + R_InitQueries(); + + R_InitWeatherSystem(); + +#if defined(_DEBUG) + GLenum err = qglGetError(); + if ( err != GL_NO_ERROR ) + ri.Printf( PRINT_ALL, "glGetError() = 0x%x\n", err ); +#endif + + RestoreGhoul2InfoArray(); + + // print info + GfxInfo_f(); + ri.Printf( PRINT_ALL, "----- finished R_Init -----\n" ); +} + +/* +=============== +RE_Shutdown +=============== +*/ +void RE_Shutdown( qboolean destroyWindow, qboolean restarting ) { + + ri.Printf( PRINT_ALL, "RE_Shutdown( %i )\n", destroyWindow ); + + for ( size_t i = 0; i < numCommands; i++ ) + ri.Cmd_RemoveCommand( commands[i].cmd ); + + // Flush here to make sure all the fences are processed + qglFlush(); + + R_IssuePendingRenderCommands(); + + R_ShutdownBackEndFrameData(); + + R_ShutdownWeatherSystem(); + + R_ShutdownFonts(); + if ( tr.registered ) { + R_ShutDownQueries(); + FBO_Shutdown(); + R_DeleteTextures(); + R_DestroyGPUBuffers(); + GLSL_ShutdownGPUShaders(); + + if ( destroyWindow && restarting ) + { + ri.Z_Free((void *)glConfig.extensions_string); + ri.Z_Free((void *)glConfigExt.originalExtensionString); + + qglDeleteVertexArrays(1, &tr.globalVao); + SaveGhoul2InfoArray(); + } + } + + // shut down platform specific OpenGL stuff + if ( destroyWindow ) { + ri.WIN_Shutdown(); + } + + tr.registered = qfalse; + backEndData = NULL; +} + +/* +============= +RE_EndRegistration + +Touch all images to make sure they are resident +============= +*/ +void RE_EndRegistration( void ) { + R_IssuePendingRenderCommands(); + if (!ri.Sys_LowPhysicalMemory()) { + RB_ShowImages(); + } +} + +// HACK +extern qboolean gG2_GBMNoReconstruct; +extern qboolean gG2_GBMUseSPMethod; +static void G2API_BoltMatrixReconstruction( qboolean reconstruct ) { gG2_GBMNoReconstruct = (qboolean)!reconstruct; } +static void G2API_BoltMatrixSPMethod( qboolean spMethod ) { gG2_GBMUseSPMethod = spMethod; } + +static float GetDistanceCull( void ) { return tr.distanceCull; } + +extern void R_SVModelInit( void ); //tr_model.cpp + +static void GetRealRes( int *w, int *h ) { + *w = glConfig.vidWidth; + *h = glConfig.vidHeight; +} + +static const cplane_t* RE_GetFrustum(void) +{ + return tr.viewParms.frustum; +} + +static const vec_t* RE_GetViewPosition(void) +{ + return tr.viewParms.ori.origin; +} + + +// STUBS, REPLACEME +qboolean stub_InitializeWireframeAutomap() { return qtrue; } + +void RE_GetLightStyle(int style, color4ub_t color) +{ + if (style >= MAX_LIGHT_STYLES) + { + Com_Error( ERR_FATAL, "RE_GetLightStyle: %d is out of range", style ); + return; + } + + byteAlias_t *baDest = (byteAlias_t *)&color, *baSource = (byteAlias_t *)&styleColors[style]; + baDest->i = baSource->i; +} + +void RE_SetLightStyle(int style, int color) +{ + if (style >= MAX_LIGHT_STYLES) + { + Com_Error( ERR_FATAL, "RE_SetLightStyle: %d is out of range", style ); + return; + } + + byteAlias_t *ba = (byteAlias_t *)&styleColors[style]; + if ( ba->i != color) { + ba->i = color; + } +} + +void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal); + +void R_Set2DRatio(void) { + if (cl_ratioFix->integer) + tr.widthRatioCoef = ((float)(SCREEN_WIDTH * glConfig.vidHeight) / (float)(SCREEN_HEIGHT * glConfig.vidWidth)); + else + tr.widthRatioCoef = 1.0f; + + if (tr.widthRatioCoef > 1) + tr.widthRatioCoef = 1.0f; +} + +void RE_WorldEffectCommand(const char *cmd); + +void stub_RE_AddWeatherZone ( vec3_t mins, vec3_t maxs ) {} // Intentionally left blank. Rend2 reads the zones manually on bsp load +static void RE_SetRefractionProperties ( float distortionAlpha, float distortionStretch, qboolean distortionPrePost, qboolean distortionNegate ) { } + +void C_LevelLoadBegin(const char *psMapName, ForceReload_e eForceReload) +{ + static char sPrevMapName[MAX_QPATH]={0}; + bool bDeleteModels = eForceReload == eForceReload_MODELS || eForceReload == eForceReload_ALL; + + if( bDeleteModels ) + CModelCache->DeleteAll(); + else if( ri.Cvar_VariableIntegerValue( "sv_pure" ) ) + CModelCache->DumpNonPure(); + + tr.numBSPModels = 0; + + /* If we're switching to the same level, don't increment current level */ + if (Q_stricmp( psMapName,sPrevMapName )) + { + Q_strncpyz( sPrevMapName, psMapName, sizeof(sPrevMapName) ); + tr.currentLevel++; + } +} + +int C_GetLevel( void ) +{ + return tr.currentLevel; +} + +void C_LevelLoadEnd( void ) +{ + CModelCache->LevelLoadEnd( qfalse ); + ri.SND_RegisterAudio_LevelLoadEnd( qfalse ); + ri.S_RestartMusic(); +} + +/* +@@@@@@@@@@@@@@@@@@@@@ +GetRefAPI + +@@@@@@@@@@@@@@@@@@@@@ +*/ +extern "C" { +Q_EXPORT refexport_t* QDECL GetRefAPI ( int apiVersion, refimport_t *rimp ) { + static refexport_t re; + + assert( rimp ); + ri = *rimp; + + Com_Memset( &re, 0, sizeof( re ) ); + + if ( apiVersion != REF_API_VERSION ) { + ri.Printf(PRINT_ALL, "Mismatched REF_API_VERSION: expected %i, got %i\n", + REF_API_VERSION, apiVersion ); + return NULL; + } + + // the RE_ functions are Renderer Entry points + + re.Shutdown = RE_Shutdown; + + re.BeginRegistration = RE_BeginRegistration; + re.RegisterModel = RE_RegisterModel; + re.RegisterServerModel = RE_RegisterServerModel; + re.RegisterSkin = RE_RegisterSkin; + re.RegisterServerSkin = RE_RegisterServerSkin; + re.RegisterShader = RE_RegisterShader; + re.RegisterShaderNoMip = RE_RegisterShaderNoMip; + re.ShaderNameFromIndex = RE_ShaderNameFromIndex; + re.LoadWorld = RE_LoadWorldMap; + re.SetWorldVisData = RE_SetWorldVisData; + re.EndRegistration = RE_EndRegistration; + + re.BeginFrame = RE_BeginFrame; + re.EndFrame = RE_EndFrame; + + re.MarkFragments = R_MarkFragments; + re.LerpTag = R_LerpTag; + re.ModelBounds = R_ModelBounds; + + re.DrawRotatePic = RE_RotatePic; + re.DrawRotatePic2 = RE_RotatePic2; + + re.ClearScene = RE_ClearScene; + re.ClearDecals = RE_ClearDecals; + re.AddRefEntityToScene = RE_AddRefEntityToScene; + re.AddMiniRefEntityToScene = RE_AddMiniRefEntityToScene; + re.AddPolyToScene = RE_AddPolyToScene; + re.AddDecalToScene = RE_AddDecalToScene; + re.LightForPoint = R_LightForPoint; + re.AddLightToScene = RE_AddLightToScene; + re.AddAdditiveLightToScene = RE_AddAdditiveLightToScene; + re.RenderScene = RE_RenderScene; + + re.SetColor = RE_SetColor; + re.DrawStretchPic = RE_StretchPic; + re.DrawStretchRaw = RE_StretchRaw; + re.UploadCinematic = RE_UploadCinematic; + + re.RegisterFont = RE_RegisterFont; + re.Font_StrLenPixels = RE_Font_StrLenPixels; + re.Font_StrLenChars = RE_Font_StrLenChars; + re.Font_HeightPixels = RE_Font_HeightPixels; + re.Font_DrawString = RE_Font_DrawString; + re.Language_IsAsian = Language_IsAsian; + re.Language_UsesSpaces = Language_UsesSpaces; + re.AnyLanguage_ReadCharFromString = AnyLanguage_ReadCharFromString; + re.RemapShader = R_RemapShader; + re.GetEntityToken = R_GetEntityToken; + re.inPVS = R_inPVS; + + re.GetLightStyle = RE_GetLightStyle; + re.SetLightStyle = RE_SetLightStyle; + re.GetBModelVerts = RE_GetBModelVerts; + + re.SetRangedFog = RE_SetRangedFog; + re.SetRefractionProperties = RE_SetRefractionProperties; + re.GetDistanceCull = GetDistanceCull; + re.GetRealRes = GetRealRes; + // R_AutomapElevationAdjustment + re.InitializeWireframeAutomap = stub_InitializeWireframeAutomap; + re.AddWeatherZone = stub_RE_AddWeatherZone; + re.WorldEffectCommand = RE_WorldEffectCommand; + re.RegisterMedia_LevelLoadBegin = C_LevelLoadBegin; + re.RegisterMedia_LevelLoadEnd = C_LevelLoadEnd; + re.RegisterMedia_GetLevel = C_GetLevel; + re.RegisterImages_LevelLoadEnd = C_Images_LevelLoadEnd; + re.RegisterModels_LevelLoadEnd = C_Models_LevelLoadEnd; + + re.TakeVideoFrame = RE_TakeVideoFrame; + + re.InitSkins = R_InitSkins; + re.InitShaders = R_InitShaders; + re.SVModelInit = R_SVModelInit; + re.HunkClearCrap = RE_HunkClearCrap; + + re.G2API_AddBolt = G2API_AddBolt; + re.G2API_AddBoltSurfNum = G2API_AddBoltSurfNum; + re.G2API_AddSurface = G2API_AddSurface; + re.G2API_AnimateG2ModelsRag = G2API_AnimateG2ModelsRag; + re.G2API_AttachEnt = G2API_AttachEnt; + re.G2API_AttachG2Model = G2API_AttachG2Model; + re.G2API_AttachInstanceToEntNum = G2API_AttachInstanceToEntNum; + re.G2API_AbsurdSmoothing = G2API_AbsurdSmoothing; + re.G2API_BoltMatrixReconstruction = G2API_BoltMatrixReconstruction; + re.G2API_BoltMatrixSPMethod = G2API_BoltMatrixSPMethod; + re.G2API_CleanEntAttachments = G2API_CleanEntAttachments; + re.G2API_CleanGhoul2Models = G2API_CleanGhoul2Models; + re.G2API_ClearAttachedInstance = G2API_ClearAttachedInstance; + re.G2API_CollisionDetect = G2API_CollisionDetect; + re.G2API_CollisionDetectCache = G2API_CollisionDetectCache; + re.G2API_CopyGhoul2Instance = G2API_CopyGhoul2Instance; + re.G2API_CopySpecificG2Model = G2API_CopySpecificG2Model; + re.G2API_DetachG2Model = G2API_DetachG2Model; + re.G2API_DoesBoneExist = G2API_DoesBoneExist; + re.G2API_DuplicateGhoul2Instance = G2API_DuplicateGhoul2Instance; + re.G2API_FreeSaveBuffer = G2API_FreeSaveBuffer; + re.G2API_GetAnimFileName = G2API_GetAnimFileName; + re.G2API_GetAnimFileNameIndex = G2API_GetAnimFileNameIndex; + re.G2API_GetAnimRange = G2API_GetAnimRange; + re.G2API_GetBoltMatrix = G2API_GetBoltMatrix; + re.G2API_GetBoneAnim = G2API_GetBoneAnim; + re.G2API_GetBoneIndex = G2API_GetBoneIndex; + re.G2API_GetGhoul2ModelFlags = G2API_GetGhoul2ModelFlags; + re.G2API_GetGLAName = G2API_GetGLAName; + re.G2API_GetModelName = G2API_GetModelName; + re.G2API_GetParentSurface = G2API_GetParentSurface; + re.G2API_GetRagBonePos = G2API_GetRagBonePos; + re.G2API_GetSurfaceIndex = G2API_GetSurfaceIndex; + re.G2API_GetSurfaceName = G2API_GetSurfaceName; + re.G2API_GetSurfaceOnOff = G2API_GetSurfaceOnOff; + re.G2API_GetSurfaceRenderStatus = G2API_GetSurfaceRenderStatus; + re.G2API_GetTime = G2API_GetTime; + re.G2API_Ghoul2Size = G2API_Ghoul2Size; + re.G2API_GiveMeVectorFromMatrix = G2API_GiveMeVectorFromMatrix; + re.G2API_HasGhoul2ModelOnIndex = G2API_HasGhoul2ModelOnIndex; + re.G2API_HaveWeGhoul2Models = G2API_HaveWeGhoul2Models; + re.G2API_IKMove = G2API_IKMove; + re.G2API_InitGhoul2Model = G2API_InitGhoul2Model; + re.G2API_IsGhoul2InfovValid = G2API_IsGhoul2InfovValid; + re.G2API_IsPaused = G2API_IsPaused; + re.G2API_ListBones = G2API_ListBones; + re.G2API_ListSurfaces = G2API_ListSurfaces; + re.G2API_LoadGhoul2Models = G2API_LoadGhoul2Models; + re.G2API_LoadSaveCodeDestructGhoul2Info = G2API_LoadSaveCodeDestructGhoul2Info; + re.G2API_OverrideServerWithClientData = G2API_OverrideServerWithClientData; + re.G2API_PauseBoneAnim = G2API_PauseBoneAnim; + re.G2API_PrecacheGhoul2Model = G2API_PrecacheGhoul2Model; + re.G2API_RagEffectorGoal = G2API_RagEffectorGoal; + re.G2API_RagEffectorKick = G2API_RagEffectorKick; + re.G2API_RagForceSolve = G2API_RagForceSolve; + re.G2API_RagPCJConstraint = G2API_RagPCJConstraint; + re.G2API_RagPCJGradientSpeed = G2API_RagPCJGradientSpeed; + re.G2API_RemoveBolt = G2API_RemoveBolt; + re.G2API_RemoveBone = G2API_RemoveBone; + re.G2API_RemoveGhoul2Model = G2API_RemoveGhoul2Model; + re.G2API_RemoveGhoul2Models = G2API_RemoveGhoul2Models; + re.G2API_RemoveSurface = G2API_RemoveSurface; + re.G2API_ResetRagDoll = G2API_ResetRagDoll; + re.G2API_SaveGhoul2Models = G2API_SaveGhoul2Models; + re.G2API_SetBoltInfo = G2API_SetBoltInfo; + re.G2API_SetBoneAngles = G2API_SetBoneAngles; + re.G2API_SetBoneAnglesIndex = G2API_SetBoneAnglesIndex; + re.G2API_SetBoneAnglesMatrix = G2API_SetBoneAnglesMatrix; + re.G2API_SetBoneAnglesMatrixIndex = G2API_SetBoneAnglesMatrixIndex; + re.G2API_SetBoneAnim = G2API_SetBoneAnim; + re.G2API_SetBoneAnimIndex = G2API_SetBoneAnimIndex; + re.G2API_SetBoneIKState = G2API_SetBoneIKState; + re.G2API_SetGhoul2ModelIndexes = G2API_SetGhoul2ModelIndexes; + re.G2API_SetGhoul2ModelFlags = G2API_SetGhoul2ModelFlags; + re.G2API_SetLodBias = G2API_SetLodBias; + re.G2API_SetNewOrigin = G2API_SetNewOrigin; + re.G2API_SetRagDoll = G2API_SetRagDoll; + re.G2API_SetRootSurface = G2API_SetRootSurface; + re.G2API_SetShader = G2API_SetShader; + re.G2API_SetSkin = G2API_SetSkin; + re.G2API_SetSurfaceOnOff = G2API_SetSurfaceOnOff; + re.G2API_SetTime = G2API_SetTime; + re.G2API_SkinlessModel = G2API_SkinlessModel; + re.G2API_StopBoneAngles = G2API_StopBoneAngles; + re.G2API_StopBoneAnglesIndex = G2API_StopBoneAnglesIndex; + re.G2API_StopBoneAnim = G2API_StopBoneAnim; + re.G2API_StopBoneAnimIndex = G2API_StopBoneAnimIndex; + + #ifdef _G2_GORE + re.G2API_GetNumGoreMarks = G2API_GetNumGoreMarks; + re.G2API_AddSkinGore = G2API_AddSkinGore; + re.G2API_ClearSkinGore = G2API_ClearSkinGore; + #endif // _SOF2 + + /* + Ghoul2 Insert End + */ + + // Custom + re.ext.GetFrustum = RE_GetFrustum; + re.ext.GetViewPosition = RE_GetViewPosition; + + re.ext.Font_StrLenPixels = RE_Font_StrLenPixelsNew; + + return &re; +} +} diff --git a/codemp/rd-rend2/tr_light.cpp b/codemp/rd-rend2/tr_light.cpp new file mode 100644 index 0000000000..abd63d36bf --- /dev/null +++ b/codemp/rd-rend2/tr_light.cpp @@ -0,0 +1,519 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_light.c + +#include "tr_local.h" + +#define DLIGHT_AT_RADIUS 16 +// at the edge of a dlight's influence, this amount of light will be added + +#define DLIGHT_MINIMUM_RADIUS 16 +// never calculate a range less than this to prevent huge light numbers + + +/* +=============== +R_TransformDlights + +Transforms the origins of an array of dlights. +Used by both the front end (for DlightBmodel) and +the back end (before doing the lighting calculation) +=============== +*/ +void R_TransformDlights( int count, dlight_t *dl, orientationr_t *ori) { + int i; + vec3_t temp; + + for ( i = 0 ; i < count ; i++, dl++ ) { + VectorSubtract( dl->origin, ori->origin, temp ); + dl->transformed[0] = DotProduct( temp, ori->axis[0] ); + dl->transformed[1] = DotProduct( temp, ori->axis[1] ); + dl->transformed[2] = DotProduct( temp, ori->axis[2] ); + } +} + +/* +============= +R_DlightBmodel + +Determine which dynamic lights may effect this bmodel +============= +*/ +void R_DlightBmodel( bmodel_t *bmodel, trRefEntity_t *ent ) { + int i, j; + dlight_t *dl; + int mask; + msurface_t *surf; + + // transform all the lights + R_TransformDlights( tr.refdef.num_dlights, tr.refdef.dlights, &tr.ori ); + + mask = 0; + for ( i=0 ; itransformed[j] - bmodel->bounds[1][j] > dl->radius ) { + break; + } + if ( bmodel->bounds[0][j] - dl->transformed[j] > dl->radius ) { + break; + } + } + if ( j < 3 ) { + continue; + } + + // we need to check this light + mask |= 1 << i; + } + + ent->needDlights = (qboolean)(mask != 0); + + // set the dlight bits in all the surfaces + for ( i = 0 ; i < bmodel->numSurfaces ; i++ ) { + surf = tr.world->surfaces + bmodel->firstSurface + i; + + switch(*surf->data) + { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + case SF_VBO_MESH: + ((srfBspSurface_t *)surf->data)->dlightBits = mask; + break; + + default: + break; + } + } +} + + +/* +============================================================================= + +LIGHT SAMPLING + +============================================================================= +*/ + +extern cvar_t *r_ambientScale; +extern cvar_t *r_directedScale; +extern cvar_t *r_debugLight; + +/* +================= +R_SetupEntityLightingGrid + +================= +*/ +static void R_SetupEntityLightingGrid( trRefEntity_t *ent, world_t *world ) { + vec3_t lightOrigin; + int pos[3]; + int i, j; + float frac[3]; + int gridStep[3]; + vec3_t direction; + float totalFactor; + uint32_t startGridPos; + + if (r_fullbright->integer || r_ambientScale->integer == -1 || (ent->e.renderfx & RF_FULLBRIGHT)) + { + ent->ambientLight[0] = ent->ambientLight[1] = ent->ambientLight[2] = 255.0; + ent->directedLight[0] = ent->directedLight[1] = ent->directedLight[2] = 255.0; + VectorCopy( tr.sunDirection, ent->lightDir ); + return; + } + + if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) { + // seperate lightOrigins are needed so an object that is + // sinking into the ground can still be lit, and so + // multi-part models can be lit identically + VectorCopy( ent->e.lightingOrigin, lightOrigin ); + } else { + VectorCopy( ent->e.origin, lightOrigin ); + } + + VectorSubtract( lightOrigin, world->lightGridOrigin, lightOrigin ); + for ( i = 0 ; i < 3 ; i++ ) { + float v; + + v = lightOrigin[i]*world->lightGridInverseSize[i]; + pos[i] = floor( v ); + frac[i] = v - pos[i]; + if ( pos[i] < 0 ) { + pos[i] = 0; + } else if ( pos[i] >= world->lightGridBounds[i] - 1 ) { + pos[i] = world->lightGridBounds[i] - 1; + } + } + + VectorClear( ent->ambientLight ); + VectorClear( ent->directedLight ); + VectorClear( direction ); + + assert( world->lightGridData ); // NULL with -nolight maps + + // trilerp the light value + gridStep[0] = 1; + gridStep[1] = 1 * world->lightGridBounds[0]; + gridStep[2] = 1 * world->lightGridBounds[0] * world->lightGridBounds[1]; + startGridPos = pos[0] * gridStep[0] + pos[1] * gridStep[1] + pos[2] * gridStep[2]; + + totalFactor = 0; + for ( i = 0 ; i < 8 ; i++ ) { + float factor; + mgrid_t *data; + uint32_t gridPos; + int lat, lng; + vec3_t normal; + + #if idppc + float d0, d1, d2, d3, d4, d5; + #endif + + factor = 1.0; + gridPos = startGridPos; + + for ( j = 0 ; j < 3 ; j++ ) { + if ( i & (1<= world->numGridArrayElements) + {//we've gone off the array somehow + continue; + } + + data = world->lightGridData + *(world->lightGridArray+gridPos); + if ( data->styles[0] == LS_LSNONE ) + { + continue; // ignore samples in walls + } + + totalFactor += factor; + #if idppc + d0 = data[0]; d1 = data[1]; d2 = data[2]; + d3 = data[3]; d4 = data[4]; d5 = data[5]; + + ent->ambientLight[0] += factor * d0; + ent->ambientLight[1] += factor * d1; + ent->ambientLight[2] += factor * d2; + + ent->directedLight[0] += factor * d3; + ent->directedLight[1] += factor * d4; + ent->directedLight[2] += factor * d5; + #else + if (world->hdrLightGrid) + { + float *hdrData = world->hdrLightGrid + (gridPos * 6); + ent->ambientLight[0] += factor * hdrData[0] * 255.0f; + ent->ambientLight[1] += factor * hdrData[1] * 255.0f; + ent->ambientLight[2] += factor * hdrData[2] * 255.0f; + + ent->directedLight[0] += factor * hdrData[3] * 255.0f; + ent->directedLight[1] += factor * hdrData[4] * 255.0f; + ent->directedLight[2] += factor * hdrData[5] * 255.0f; + } + else + { + for(j=0;jstyles[j] != LS_LSNONE) + { + const byte style= data->styles[j]; + + ent->ambientLight[0] += factor * data->ambientLight[j][0] * styleColors[style][0] / 255.0f; + ent->ambientLight[1] += factor * data->ambientLight[j][1] * styleColors[style][1] / 255.0f; + ent->ambientLight[2] += factor * data->ambientLight[j][2] * styleColors[style][2] / 255.0f; + + ent->directedLight[0] += factor * data->directLight[j][0] * styleColors[style][0] / 255.0f; + ent->directedLight[1] += factor * data->directLight[j][1] * styleColors[style][1] / 255.0f; + ent->directedLight[2] += factor * data->directLight[j][2] * styleColors[style][2] / 255.0f; + } + else + { + break; + } + } + } + #endif + lat = data->latLong[1]; + lng = data->latLong[0]; + lat *= (FUNCTABLE_SIZE/256); + lng *= (FUNCTABLE_SIZE/256); + + // decode X as cos( lat ) * sin( long ) + // decode Y as sin( lat ) * sin( long ) + // decode Z as cos( long ) + + normal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + normal[1] = tr.sinTable[lat] * tr.sinTable[lng]; + normal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + + VectorMA( direction, factor, normal, direction ); + } + + if ( totalFactor > 0 && totalFactor < 0.99 ) { + totalFactor = 1.0f / totalFactor; + VectorScale( ent->ambientLight, totalFactor, ent->ambientLight ); + VectorScale( ent->directedLight, totalFactor, ent->directedLight ); + } + + VectorScale( ent->ambientLight, r_ambientScale->value, ent->ambientLight ); + VectorScale( ent->directedLight, r_directedScale->value, ent->directedLight ); + + VectorNormalize2( direction, ent->lightDir ); +} + + +/* +=============== +LogLight +=============== +*/ +static void LogLight( trRefEntity_t *ent ) { + int max1, max2; + + if ( !(ent->e.renderfx & RF_FIRST_PERSON ) ) { + return; + } + + max1 = ent->ambientLight[0]; + if ( ent->ambientLight[1] > max1 ) { + max1 = ent->ambientLight[1]; + } else if ( ent->ambientLight[2] > max1 ) { + max1 = ent->ambientLight[2]; + } + + max2 = ent->directedLight[0]; + if ( ent->directedLight[1] > max2 ) { + max2 = ent->directedLight[1]; + } else if ( ent->directedLight[2] > max2 ) { + max2 = ent->directedLight[2]; + } + + ri.Printf( PRINT_ALL, "amb:%i dir:%i\n", max1, max2 ); +} + +/* +================= +R_SetupEntityLighting + +Calculates all the lighting values that will be used +by the Calc_* functions +================= +*/ +void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ) { + int i; + float d; + vec3_t lightDir; + vec3_t lightOrigin; + + // lighting calculations + if ( ent->lightingCalculated ) { + return; + } + ent->lightingCalculated = qtrue; + + // + // trace a sample point down to find ambient light + // + if ( ent->e.renderfx & RF_LIGHTING_ORIGIN ) { + // seperate lightOrigins are needed so an object that is + // sinking into the ground can still be lit, and so + // multi-part models can be lit identically + VectorCopy( ent->e.lightingOrigin, lightOrigin ); + } else { + VectorCopy( ent->e.origin, lightOrigin ); + } + + // if NOWORLDMODEL, only use dynamic lights (menu system, etc) + if ( !(refdef->rdflags & RDF_NOWORLDMODEL ) + && tr.world->lightGridData ) { + R_SetupEntityLightingGrid( ent, tr.world ); + } else { + ent->ambientLight[0] = ent->ambientLight[1] = + ent->ambientLight[2] = tr.identityLight * 150; + ent->directedLight[0] = ent->directedLight[1] = + ent->directedLight[2] = tr.identityLight * 150; + VectorCopy( tr.sunDirection, ent->lightDir ); + } + + // only do min lighting when there is no hdr light data + if (tr.hdrLighting != qtrue) + { + // bonus items and view weapons have a fixed minimum add + if (1/*!r_hdr->integer*/) { + // give everything a minimum light add + ent->ambientLight[0] += tr.identityLight * 32; + ent->ambientLight[1] += tr.identityLight * 32; + ent->ambientLight[2] += tr.identityLight * 32; + } + + if (ent->e.renderfx & RF_MINLIGHT) + { //the minlight flag is now for items rotating on their holo thing + if (ent->e.shaderRGBA[0] == 255 && + ent->e.shaderRGBA[1] == 255 && + ent->e.shaderRGBA[2] == 0) + { + ent->ambientLight[0] += tr.identityLight * 255; + ent->ambientLight[1] += tr.identityLight * 255; + ent->ambientLight[2] += tr.identityLight * 0; + } + else + { + ent->ambientLight[0] += tr.identityLight * 16; + ent->ambientLight[1] += tr.identityLight * 96; + ent->ambientLight[2] += tr.identityLight * 150; + } + } + } + + d = VectorLength( ent->directedLight ); + VectorScale( ent->lightDir, d, lightDir ); + + // clamp ambient + if (tr.hdrLighting != qtrue) + { + for ( i = 0 ; i < 3 ; i++ ) { + if ( ent->ambientLight[i] > tr.identityLightByte ) { + ent->ambientLight[i] = tr.identityLightByte; + } + } + } + + if ( r_debugLight->integer ) { + LogLight( ent ); + } + + // save out the byte packet version + ((byte *)&ent->ambientLightInt)[0] = Q_ftol(ent->ambientLight[0]); + ((byte *)&ent->ambientLightInt)[1] = Q_ftol(ent->ambientLight[1]); + ((byte *)&ent->ambientLightInt)[2] = Q_ftol(ent->ambientLight[2]); + ((byte *)&ent->ambientLightInt)[3] = 0xff; + + // transform the direction to local space + VectorNormalize( lightDir ); + VectorCopy(lightDir, ent->lightDir); + + ent->modelLightDir[0] = DotProduct( lightDir, ent->e.axis[0] ); + ent->modelLightDir[1] = DotProduct( lightDir, ent->e.axis[1] ); + ent->modelLightDir[2] = DotProduct( lightDir, ent->e.axis[2] ); +} + +/* +================= +R_LightForPoint +================= +*/ +int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ) +{ + trRefEntity_t ent; + + if ( tr.world->lightGridData == NULL ) + return qfalse; + + Com_Memset(&ent, 0, sizeof(ent)); + VectorCopy( point, ent.e.origin ); + R_SetupEntityLightingGrid( &ent, tr.world ); + VectorCopy(ent.ambientLight, ambientLight); + VectorCopy(ent.directedLight, directedLight); + VectorCopy(ent.lightDir, lightDir); + + return qtrue; +} + + +int R_LightDirForPoint( vec3_t point, vec3_t lightDir, vec3_t normal, world_t *world ) +{ + trRefEntity_t ent; + + if ( world->lightGridData == NULL ) + return qfalse; + + Com_Memset(&ent, 0, sizeof(ent)); + VectorCopy( point, ent.e.origin ); + R_SetupEntityLightingGrid( &ent, world ); + + if (DotProduct(ent.lightDir, normal) > 0.2f) + VectorCopy(ent.lightDir, lightDir); + else + VectorCopy(normal, lightDir); + + return qtrue; +} + +int R_DLightsForPoint(const vec3_t point, const float radius) +{ + int dlightBits = 0; + vec3_t delta; + dlight_t currentDlight; + float distance; + float radiusSum; + for (int i = 0; i < tr.refdef.num_dlights; i++) + { + currentDlight = tr.refdef.dlights[i]; + + VectorSubtract(point, currentDlight.origin, delta); + distance = VectorLength(delta); + radiusSum = radius + currentDlight.radius; + + if (distance < radiusSum) + dlightBits |= 1 << i; + } + return dlightBits; +} + +int R_CubemapForPoint( const vec3_t point ) +{ + int cubemapIndex = -1; + + if (r_cubeMapping->integer && tr.numCubemaps) + { + int i; + float shortest = (float)WORLD_SIZE * (float)WORLD_SIZE; + + for (i = 0; i < tr.numCubemaps; i++) + { + vec3_t diff; + float length; + + VectorSubtract(point, tr.cubemaps[i].origin, diff); + length = DotProduct(diff, diff); + + if (shortest > length) + { + shortest = length; + cubemapIndex = i; + } + } + } + + return cubemapIndex + 1; +} diff --git a/codemp/rd-rend2/tr_local.h b/codemp/rd-rend2/tr_local.h new file mode 100644 index 0000000000..78f602709b --- /dev/null +++ b/codemp/rd-rend2/tr_local.h @@ -0,0 +1,3928 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + + +#ifndef TR_LOCAL_H +#define TR_LOCAL_H + +#include "qcommon/q_shared.h" +#include "qcommon/qfiles.h" +#include "qcommon/qcommon.h" +#include "rd-common/tr_public.h" +#include "rd-common/tr_common.h" +#include "tr_allocator.h" +#include "tr_extratypes.h" +#include "tr_extramath.h" +#include "tr_fbo.h" +#include "tr_postprocess.h" +#include "iqm.h" +#include "qgl.h" +#include +#include +#include +#include + +#define GL_INDEX_TYPE GL_UNSIGNED_INT +typedef unsigned int glIndex_t; + +#define BUFFER_OFFSET(i) ((char *)NULL + (i)) + +// 14 bits +// can't be increased without changing bit packing for drawsurfs +// see QSORT_SHADERNUM_SHIFT +#define SHADERNUM_BITS 14 +#define MAX_SHADERS (1<or.origin in local coordinates + float modelViewMatrix[16]; + float modelMatrix[16]; +} orientationr_t; + +void R_SetOrientationOriginAndAxis( + orientationr_t& orientation, + const vec3_t origin, + const vec3_t forward, + const vec3_t left, + const vec3_t up); +void R_SetOrientationOriginAndAxis( + orientationr_t& orientation, + const vec3_t origin, + const matrix3_t axis); + +typedef enum +{ + VBO_USAGE_STATIC, + VBO_USAGE_DYNAMIC, + VBO_USAGE_XFB +} vboUsage_t; + +typedef struct VBO_s +{ + uint32_t vertexesVBO; + int vertexesSize; // amount of memory data allocated for all vertices in bytes + + uint32_t offsets[ATTR_INDEX_MAX]; + uint32_t strides[ATTR_INDEX_MAX]; + uint32_t sizes[ATTR_INDEX_MAX]; +} VBO_t; + +typedef struct IBO_s +{ + uint32_t indexesVBO; + int indexesSize; // amount of memory data allocated for all triangles in bytes +// uint32_t ofsIndexes; +} IBO_t; + +//=============================================================================== + +typedef enum { + SS_BAD, + SS_PORTAL, // mirrors, portals, viewscreens + SS_ENVIRONMENT, // sky box + SS_OPAQUE, // opaque + + SS_DECAL, // scorch marks, etc. + SS_SEE_THROUGH, // ladders, grates, grills that may have small blended edges + // in addition to alpha test + SS_BANNER, + + SS_INSIDE, // inside body parts (i.e. heart) + SS_MID_INSIDE, + SS_MIDDLE, + SS_MID_OUTSIDE, + SS_OUTSIDE, // outside body parts (i.e. ribs) + + SS_FOG, + + SS_UNDERWATER, // for items that should be drawn in front of the water plane + + SS_BLEND0, // regular transparency and filters + SS_BLEND1, // generally only used for additive type effects + SS_BLEND2, + SS_BLEND3, + + SS_BLEND6, + SS_STENCIL_SHADOW, + SS_ALMOST_NEAREST, // gun smoke puffs + + SS_NEAREST // blood blobs +} shaderSort_t; + + +#define MAX_SHADER_STAGES 8 + +typedef enum { + GF_NONE, + + GF_SIN, + GF_SQUARE, + GF_TRIANGLE, + GF_SAWTOOTH, + GF_INVERSE_SAWTOOTH, + + GF_NOISE, + GF_RAND + +} genFunc_t; + + +typedef enum { + DEFORM_NONE, + DEFORM_WAVE, + DEFORM_NORMALS, + DEFORM_BULGE, + DEFORM_BULGE_UNIFORM, + DEFORM_MOVE, + DEFORM_PROJECTION_SHADOW, + DEFORM_AUTOSPRITE, + DEFORM_AUTOSPRITE2, + DEFORM_TEXT0, + DEFORM_TEXT1, + DEFORM_TEXT2, + DEFORM_TEXT3, + DEFORM_TEXT4, + DEFORM_TEXT5, + DEFORM_TEXT6, + DEFORM_TEXT7, + DEFORM_DISINTEGRATION +} deform_t; + +// deformVertexes types that can be handled by the GPU +typedef enum +{ + // do not edit: same as genFunc_t + + DGEN_NONE, + DGEN_WAVE_SIN, + DGEN_WAVE_SQUARE, + DGEN_WAVE_TRIANGLE, + DGEN_WAVE_SAWTOOTH, + DGEN_WAVE_INVERSE_SAWTOOTH, + DGEN_WAVE_NOISE, + + // do not edit until this line + + DGEN_BULGE, + DGEN_NORMALS, + DGEN_MOVE, +} deformGen_t; + +typedef enum { + AGEN_IDENTITY, + AGEN_SKIP, + AGEN_ENTITY, + AGEN_ONE_MINUS_ENTITY, + AGEN_VERTEX, + AGEN_ONE_MINUS_VERTEX, + AGEN_LIGHTING_SPECULAR, + AGEN_WAVEFORM, + AGEN_PORTAL, + AGEN_CONST +} alphaGen_t; + +typedef enum { + CGEN_BAD, + CGEN_IDENTITY_LIGHTING, // tr.identityLight + CGEN_IDENTITY, // always (1,1,1,1) + CGEN_ENTITY, // grabbed from entity's modulate field + CGEN_ONE_MINUS_ENTITY, // grabbed from 1 - entity.modulate + CGEN_EXACT_VERTEX, // tess.vertexColors + CGEN_VERTEX, // tess.vertexColors * tr.identityLight + CGEN_EXACT_VERTEX_LIT, // like CGEN_EXACT_VERTEX but takes a light direction from the lightgrid + CGEN_VERTEX_LIT, // like CGEN_VERTEX but takes a light direction from the lightgrid + CGEN_ONE_MINUS_VERTEX, + CGEN_WAVEFORM, // programmatically generated + CGEN_LIGHTING_DIFFUSE, + CGEN_LIGHTING_DIFFUSE_ENTITY, // diffuse lighting * entity + CGEN_FOG, // standard fog + CGEN_CONST, // fixed color + CGEN_LIGHTMAPSTYLE, // lightmap style + CGEN_DISINTEGRATION_1, + CGEN_DISINTEGRATION_2 +} colorGen_t; + +typedef enum { + TCGEN_BAD, + TCGEN_IDENTITY, // clear to 0,0 + TCGEN_LIGHTMAP, + TCGEN_LIGHTMAP1, + TCGEN_LIGHTMAP2, + TCGEN_LIGHTMAP3, + TCGEN_TEXTURE, + TCGEN_ENVIRONMENT_MAPPED, + TCGEN_FOG, + TCGEN_VECTOR // S and T from world coordinates +} texCoordGen_t; + +typedef enum { + ACFF_NONE, + ACFF_MODULATE_RGB, + ACFF_MODULATE_RGBA, + ACFF_MODULATE_ALPHA +} acff_t; + +typedef struct { + genFunc_t func; + + float base; + float amplitude; + float phase; + float frequency; +} waveForm_t; + +#define TR_MAX_TEXMODS 4 + +typedef enum { + TMOD_NONE, + TMOD_TRANSFORM, + TMOD_TURBULENT, + TMOD_SCROLL, + TMOD_SCALE, + TMOD_STRETCH, + TMOD_ROTATE, + TMOD_ENTITY_TRANSLATE +} texMod_t; + +#define MAX_SHADER_DEFORMS 3 +typedef struct { + deform_t deformation; // vertex coordinate modification type + + vec3_t moveVector; + waveForm_t deformationWave; + float deformationSpread; + + float bulgeWidth; + float bulgeHeight; + float bulgeSpeed; +} deformStage_t; + + +typedef struct { + texMod_t type; + + // used for TMOD_TURBULENT and TMOD_STRETCH + waveForm_t wave; + + // used for TMOD_TRANSFORM + float matrix[2][2]; // s' = s * m[0][0] + t * m[1][0] + trans[0] + float translate[2]; // t' = s * m[0][1] + t * m[0][1] + trans[1] + + // used for TMOD_SCALE + float scale[2]; // s *= scale[0] + // t *= scale[1] + + // used for TMOD_SCROLL + float scroll[2]; // s' = s + scroll[0] * time + // t' = t + scroll[1] * time + + // + = clockwise + // - = counterclockwise + float rotateSpeed; + +} texModInfo_t; + +enum surfaceSpriteType_t +{ + SURFSPRITE_NONE, + SURFSPRITE_VERTICAL, + SURFSPRITE_ORIENTED, + SURFSPRITE_EFFECT, + SURFSPRITE_WEATHERFX, + SURFSPRITE_FLATTENED, +}; + +enum surfaceSpriteOrientation_t +{ + SURFSPRITE_FACING_NORMAL, + SURFSPRITE_FACING_UP, + SURFSPRITE_FACING_DOWN, + SURFSPRITE_FACING_ANY, +}; + +struct SurfaceSpriteBlock +{ + vec2_t fxGrow; + float fxDuration; + float fadeStartDistance; + float fadeEndDistance; + float fadeScale; + float wind; + float windIdle; + float fxAlphaStart; + float fxAlphaEnd; + float pad0[2]; +}; + +struct CameraBlock +{ + matrix_t viewProjectionMatrix; + vec4_t viewInfo; + vec3_t viewOrigin; + float pad0; + vec3_t viewForward; + float pad1; + vec3_t viewLeft; + float pad2; + vec3_t viewUp; + float pad3; +}; + +struct SceneBlock +{ + vec4_t primaryLightOrigin; + vec3_t primaryLightAmbient; + int globalFogIndex; + vec3_t primaryLightColor; + float primaryLightRadius; + float currentTime; + float frameTime; + float pad0[2]; +}; + +struct LightsBlock +{ + struct Light + { + vec4_t origin; + vec3_t color; + float radius; + }; + + matrix_t shadowVP1; + matrix_t shadowVP2; + matrix_t shadowVP3; + + int numLights; + float pad0[3]; + + Light lights[MAX_DLIGHTS]; +}; + +struct FogsBlock +{ + struct Fog + { + vec4_t plane; + vec4_t color; + float depthToOpaque; + int hasPlane; + float pad1[2]; + }; + + int numFogs; + float pad0[3]; + Fog fogs[16]; +}; + +struct EntityBlock +{ + matrix_t modelMatrix; + vec4_t lightOrigin; + vec3_t ambientLight; + float lightRadius; + vec3_t directedLight; + float fxVolumetricBase; + vec3_t modelLightDir; + float vertexLerp; + vec3_t localViewOrigin; + float entityTime; +}; + +struct ShaderInstanceBlock +{ + vec4_t deformParams0; + vec4_t deformParams1; + float time; + float portalRange; + int deformType; + int deformFunc; +}; + +struct SkeletonBoneMatricesBlock +{ + mat3x4_t matrices[MAX_G2_BONES]; +}; + +struct surfaceSprite_t +{ + surfaceSpriteType_t type; + + float width; + float height; + float density; + float wind; + float windIdle; + float fadeDist; + float fadeMax; + float fadeScale; + float fxAlphaStart; + float fxAlphaEnd; + float fxDuration; + float vertSkew; + + vec2_t variance; + vec2_t fxGrow; + surfaceSpriteOrientation_t facing; + + int spriteUboOffset; +}; + +#define MAX_IMAGE_ANIMATIONS (32) + +typedef struct { + image_t *image[MAX_IMAGE_ANIMATIONS]; + int numImageAnimations; + float imageAnimationSpeed; + + texCoordGen_t tcGen; + vec3_t tcGenVectors[2]; + + int numTexMods; + texModInfo_t *texMods; + + int videoMapHandle; + qboolean isLightmap; + qboolean oneShotAnimMap; + qboolean isVideoMap; +} textureBundle_t; + +enum +{ + TB_COLORMAP = 0, + TB_DIFFUSEMAP = 0, + TB_LIGHTMAP = 1, + TB_LEVELSMAP = 1, + TB_COLORMAP2 = 1, + TB_NORMALMAP = 2, + TB_DELUXEMAP = 3, + TB_SPECULARMAP = 4, + TB_ORMSMAP = 4, + TB_SHADOWMAP = 5, + TB_CUBEMAP = 6, + TB_ENVBRDFMAP = 7, + TB_SHADOWMAPARRAY = 8, + TB_SSAOMAP = 9, + NUM_TEXTURE_BUNDLES = 10 +}; + +typedef enum +{ + // material shader stage types + ST_COLORMAP = 0, // vanilla Q3A style shader treatening + ST_DIFFUSEMAP = 0, // treat color and diffusemap the same + ST_GLSL +} stageType_t; + +typedef enum +{ + SPEC_NONE, // no specular found + SPEC_SPECGLOSS, // Specular Gloss + SPEC_RMO, // calculate spec from rmo texture with a specular of 0.04 for dielectric materials + SPEC_RMOS, // calculate spec from rmos texture with a specular of 0.0 - 0.08 from input + SPEC_MOXR, // calculate spec from moxr texture with a specular of 0.04 for dielectric materials + SPEC_MOSR, // calculate spec from mosr texture with a specular of 0.0 - 0.08 from input + SPEC_ORM, // calculate spec from orm texture with a specular of 0.04 for dielectric materials + SPEC_ORMS, // calculate spec from orms texture with a specular of 0.0 - 0.08 from input +} specularType_t; + +enum AlphaTestType +{ + ALPHA_TEST_NONE, + ALPHA_TEST_GT0, + ALPHA_TEST_LT128, + ALPHA_TEST_GE128, + ALPHA_TEST_GE192, +}; + +// any change in the LIGHTMAP_* defines here MUST be reflected in +// R_FindShader() in tr_bsp.c +#define LIGHTMAP_EXTERNAL -5 +#define LIGHTMAP_2D -4 // shader is for 2D rendering +#define LIGHTMAP_BY_VERTEX -3 // pre-lit triangle models +#define LIGHTMAP_WHITEIMAGE -2 +#define LIGHTMAP_NONE -1 + +typedef struct { + qboolean active; + qboolean isDetail; + qboolean glow; + qboolean cloth; + + AlphaTestType alphaTestType; + + textureBundle_t bundle[NUM_TEXTURE_BUNDLES]; + + waveForm_t rgbWave; + colorGen_t rgbGen; + + waveForm_t alphaWave; + alphaGen_t alphaGen; + + float constantColor[4]; // for CGEN_CONST and AGEN_CONST + + uint32_t stateBits; // GLS_xxxx mask + + acff_t adjustColorsForFog; + + int lightmapStyle; + + stageType_t type; + specularType_t specularType; + struct shaderProgram_s *glslShaderGroup; + int glslShaderIndex; + + vec4_t normalScale; + vec4_t specularScale; + float parallaxBias; + + surfaceSprite_t *ss; + +} shaderStage_t; + +struct shaderCommands_s; + +typedef enum { + CT_FRONT_SIDED, + CT_BACK_SIDED, + CT_TWO_SIDED +} cullType_t; + +typedef enum { + FP_NONE, // surface is translucent and will just be adjusted properly + FP_EQUAL, // surface is opaque but possibly alpha tested + FP_LE // surface is trnaslucent, but still needs a fog pass (fog surface) +} fogPass_t; + +typedef struct { + float cloudHeight; + image_t *outerbox[6]; +} skyParms_t; + +typedef struct { + vec3_t color; + float depthForOpaque; +} fogParms_t; + + +typedef struct shader_s { + char name[MAX_QPATH]; // game path, including extension + int lightmapIndex[MAXLIGHTMAPS]; // for a shader to match, both name and all lightmapIndex must match + byte styles[MAXLIGHTMAPS]; + + int index; // this shader == tr.shaders[index] + int sortedIndex; // this shader == tr.sortedShaders[sortedIndex] + + float sort; // lower numbered shaders draw before higher numbered + + qboolean defaultShader; // we want to return index 0 if the shader failed to + // load for some reason, but R_FindShader should + // still keep a name allocated for it, so if + // something calls RE_RegisterShader again with + // the same name, we don't try looking for it again + + qboolean explicitlyDefined; // found in a .shader file + + int surfaceFlags; // if explicitlyDefined, this will have SURF_* flags + int contentFlags; + + qboolean entityMergable; // merge across entites optimizable (smoke, blood) + + qboolean isSky; + skyParms_t sky; + fogParms_t fogParms; + + float portalRange; // distance to fog out at + qboolean isPortal; + + cullType_t cullType; // CT_FRONT_SIDED, CT_BACK_SIDED, or CT_TWO_SIDED + qboolean polygonOffset; // set for decals and other items that must be offset + qboolean noMipMaps; // for console fonts, 2D elements, etc. + qboolean noPicMip; // for images that must always be full resolution + qboolean noTC; // for images that don't want to be texture compressed (eg skies) + + fogPass_t fogPass; // draw a blended pass, possibly with depth test equals + + int vertexAttribs; // not all shaders will need all data to be gathered + + int numDeforms; + deformStage_t deforms[MAX_SHADER_DEFORMS]; + + int numUnfoggedPasses; + int numSurfaceSpriteStages; + GLuint spriteUbo; + int ShaderInstanceUboOffset; + + shaderStage_t *stages[MAX_SHADER_STAGES]; + + void (*optimalStageIteratorFunc)( void ); + qboolean isHDRLit; + qboolean useSimpleDepthShader; + qboolean useDistortion; + + float clampTime; // time this shader is clamped to + float timeOffset; // current time offset for this shader + + struct shader_s *remappedShader; // current shader this one is remapped too + + struct shader_s *next; +} shader_t; + +QINLINE qboolean ShaderRequiresCPUDeforms(const shader_t * shader) +{ + if ( shader->numDeforms > 1 ) + { + return qtrue; + } + + if ( shader->numDeforms > 0 ) + { + switch (shader->deforms[0].deformation) + { + case DEFORM_NONE: + case DEFORM_NORMALS: + case DEFORM_WAVE: + case DEFORM_BULGE: + case DEFORM_MOVE: + case DEFORM_PROJECTION_SHADOW: + return qfalse; + + default: + return qtrue; + } + } + + assert( shader->numDeforms == 0 ); + + return qfalse; +} + +enum +{ + GLS_SRCBLEND_ZERO = (1 << 0), + GLS_SRCBLEND_ONE = (1 << 1), + GLS_SRCBLEND_DST_COLOR = (1 << 2), + GLS_SRCBLEND_ONE_MINUS_DST_COLOR = (1 << 3), + GLS_SRCBLEND_SRC_ALPHA = (1 << 4), + GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA = (1 << 5), + GLS_SRCBLEND_DST_ALPHA = (1 << 6), + GLS_SRCBLEND_ONE_MINUS_DST_ALPHA = (1 << 7), + GLS_SRCBLEND_ALPHA_SATURATE = (1 << 8), + + GLS_SRCBLEND_BITS = GLS_SRCBLEND_ZERO + | GLS_SRCBLEND_ONE + | GLS_SRCBLEND_DST_COLOR + | GLS_SRCBLEND_ONE_MINUS_DST_COLOR + | GLS_SRCBLEND_SRC_ALPHA + | GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA + | GLS_SRCBLEND_DST_ALPHA + | GLS_SRCBLEND_ONE_MINUS_DST_ALPHA + | GLS_SRCBLEND_ALPHA_SATURATE, + + GLS_DSTBLEND_ZERO = (1 << 9), + GLS_DSTBLEND_ONE = (1 << 10), + GLS_DSTBLEND_SRC_COLOR = (1 << 11), + GLS_DSTBLEND_ONE_MINUS_SRC_COLOR = (1 << 12), + GLS_DSTBLEND_SRC_ALPHA = (1 << 13), + GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA = (1 << 14), + GLS_DSTBLEND_DST_ALPHA = (1 << 15), + GLS_DSTBLEND_ONE_MINUS_DST_ALPHA = (1 << 16), + + GLS_DSTBLEND_BITS = GLS_DSTBLEND_ZERO + | GLS_DSTBLEND_ONE + | GLS_DSTBLEND_SRC_COLOR + | GLS_DSTBLEND_ONE_MINUS_SRC_COLOR + | GLS_DSTBLEND_SRC_ALPHA + | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA + | GLS_DSTBLEND_DST_ALPHA + | GLS_DSTBLEND_ONE_MINUS_DST_ALPHA, + + GLS_DEPTHMASK_TRUE = (1 << 17), + + GLS_POLYMODE_LINE = (1 << 18), + + GLS_DEPTHTEST_DISABLE = (1 << 19), + + GLS_DEPTHFUNC_LESS = (1 << 20), + GLS_DEPTHFUNC_EQUAL = (1 << 21), + GLS_DEPTHFUNC_GREATER = (1 << 22), + + GLS_DEPTHFUNC_BITS = GLS_DEPTHFUNC_LESS + | GLS_DEPTHFUNC_EQUAL + | GLS_DEPTHFUNC_GREATER, + + GLS_REDMASK_FALSE = (1 << 23), + GLS_GREENMASK_FALSE = (1 << 24), + GLS_BLUEMASK_FALSE = (1 << 25), + GLS_ALPHAMASK_FALSE = (1 << 26), + + GLS_COLORMASK_BITS = GLS_REDMASK_FALSE + | GLS_GREENMASK_FALSE + | GLS_BLUEMASK_FALSE + | GLS_ALPHAMASK_FALSE, + + GLS_STENCILTEST_ENABLE = (1 << 27), + + GLS_POLYGON_OFFSET_FILL = (1 << 28), + + GLS_DEFAULT = GLS_DEPTHMASK_TRUE +}; + +struct Attribute +{ + int numComponents; + bool integerAttribute; + GLenum type; + bool normalize; + int offset; +}; + +const int MAX_ATTRIBUTES = 8; +struct VertexFormat +{ + Attribute attributes[MAX_ATTRIBUTES]; +}; + +enum +{ + ATTR_POSITION = 0x0001, + ATTR_TEXCOORD0 = 0x0002, + ATTR_TEXCOORD1 = 0x0004, + ATTR_TEXCOORD2 = 0x0008, + ATTR_TEXCOORD3 = 0x0010, + ATTR_TEXCOORD4 = 0x0020, + ATTR_TANGENT = 0x0040, + ATTR_NORMAL = 0x0080, + ATTR_COLOR = 0x0100, + ATTR_LIGHTDIRECTION = 0x0200, + ATTR_BONE_INDEXES = 0x0400, + ATTR_BONE_WEIGHTS = 0x0800, + + // for .md3 interpolation and some sprite data + ATTR_POSITION2 = 0x1000, +#ifdef REND2_SP + ATTR_TANGENT2 = 0x2000, + ATTR_NORMAL2 = 0x4000, +#endif // REND2_SP + + ATTR_DEFAULT = ATTR_POSITION, + ATTR_BITS = ATTR_POSITION | + ATTR_TEXCOORD0 | + ATTR_TEXCOORD1 | + ATTR_TEXCOORD2 | + ATTR_TEXCOORD3 | + ATTR_TEXCOORD4 | + ATTR_TANGENT | + ATTR_NORMAL | + ATTR_COLOR | + ATTR_LIGHTDIRECTION | + ATTR_BONE_INDEXES | + ATTR_BONE_WEIGHTS | + ATTR_POSITION2 +#ifdef REND2_SP + | + ATTR_TANGENT2 | + ATTR_NORMAL2 +#endif // REND2_SP +}; + +enum +{ + GENERICDEF_USE_DEFORM_VERTEXES = 0x0001, + GENERICDEF_USE_TCGEN_AND_TCMOD = 0x0002, + GENERICDEF_USE_FOG = 0x0004, + GENERICDEF_USE_RGBAGEN = 0x0008, + GENERICDEF_USE_SKELETAL_ANIMATION = 0x0010, + GENERICDEF_USE_GLOW_BUFFER = 0x0020, + GENERICDEF_USE_ALPHA_TEST = 0x0040, +#ifdef REND2_SP + GENERICDEF_USE_VERTEX_ANIMATION = 0x0080, + GENERICDEF_ALL = 0x00FF, +#else + GENERICDEF_ALL = 0x007F, +#endif // REND2_SP + + GENERICDEF_COUNT = GENERICDEF_ALL + 1, +}; + +enum +{ + FOGDEF_USE_DEFORM_VERTEXES = 0x0001, + FOGDEF_USE_SKELETAL_ANIMATION = 0x0002, + FOGDEF_USE_ALPHA_TEST = 0x0004, + FOGDEF_USE_FALLBACK_GLOBAL_FOG = 0x0008, +#ifdef REND2_SP + FOGDEF_USE_VERTEX_ANIMATION = 0x0010, + FOGDEF_ALL = 0x001F, +#else + FOGDEF_ALL = 0x000F, +#endif // REND2_SP + + FOGDEF_COUNT = FOGDEF_ALL + 1, +}; + +enum +{ + REFRACTIONDEF_USE_DEFORM_VERTEXES = 0x0001, + REFRACTIONDEF_USE_TCGEN_AND_TCMOD = 0x0002, + REFRACTIONDEF_USE_RGBAGEN = 0x0004, + REFRACTIONDEF_USE_SKELETAL_ANIMATION = 0x0008, + REFRACTIONDEF_USE_ALPHA_TEST = 0x0010, + REFRACTIONDEF_USE_SRGB_TRANSFORM = 0x0020, +#ifdef REND2_SP + REFRACTIONDEF_USE_VERTEX_ANIMATION = 0x0040, + REFRACTIONDEF_ALL = 0x007F, +#else + REFRACTIONDEF_ALL = 0x003F, +#endif // REND2_SP + + REFRACTIONDEF_COUNT = REFRACTIONDEF_ALL + 1, +}; + +enum +{ + LIGHTDEF_USE_LIGHTMAP = 0x0001, + LIGHTDEF_USE_LIGHT_VECTOR = 0x0002, + LIGHTDEF_USE_LIGHT_VERTEX = 0x0003, + LIGHTDEF_USE_TCGEN_AND_TCMOD = 0x0004, + LIGHTDEF_USE_PARALLAXMAP = 0x0008, +// LIGHTDEF_USE_SHADOWMAP = 0x0010, + LIGHTDEF_USE_SKELETAL_ANIMATION = 0x0010, + LIGHTDEF_USE_GLOW_BUFFER = 0x0020, + LIGHTDEF_USE_ALPHA_TEST = 0x0040, + LIGHTDEF_USE_CLOTH_BRDF = 0x0080, + LIGHTDEF_USE_SPEC_GLOSS = 0x0100, + + LIGHTDEF_LIGHTTYPE_MASK = LIGHTDEF_USE_LIGHTMAP | + LIGHTDEF_USE_LIGHT_VECTOR | + LIGHTDEF_USE_LIGHT_VERTEX, + +#ifdef REND2_SP + LIGHTDEF_USE_VERTEX_ANIMATION = 0x0200, + LIGHTDEF_ALL = 0x03FF, +#else + LIGHTDEF_ALL = 0x01FF, +#endif // REND2_SP + + LIGHTDEF_COUNT = LIGHTDEF_ALL + 1 +}; + +enum +{ + SSDEF_FACE_CAMERA = 0x01, + SSDEF_ALPHA_TEST = 0x02, + SSDEF_FACE_UP = 0x04, + SSDEF_FX_SPRITE = 0x08, + SSDEF_USE_FOG = 0x10, + SSDEF_FOG_MODULATE = 0x20, + SSDEF_ADDITIVE = 0x40, + SSDEF_FLATTENED = 0x80, + + SSDEF_ALL = 0xFF, + SSDEF_COUNT = SSDEF_ALL + 1 +}; + +enum +{ + GLSL_INT, + GLSL_FLOAT, + GLSL_VEC2, + GLSL_VEC3, + GLSL_VEC4, + GLSL_MAT4x3, + GLSL_MAT4x4, +}; + +enum uniformBlock_t +{ + UNIFORM_BLOCK_CAMERA, + UNIFORM_BLOCK_SCENE, + UNIFORM_BLOCK_LIGHTS, + UNIFORM_BLOCK_FOGS, + UNIFORM_BLOCK_ENTITY, + UNIFORM_BLOCK_SHADER_INSTANCE, + UNIFORM_BLOCK_BONES, + UNIFORM_BLOCK_SURFACESPRITE, + UNIFORM_BLOCK_COUNT +}; + +struct uniformBlockInfo_t +{ + int slot; + const char *name; + size_t size; +}; +extern const uniformBlockInfo_t uniformBlocksInfo[UNIFORM_BLOCK_COUNT]; + +#define MAX_BLOCKS (32) +#define MAX_BLOCK_NAME_LEN (32) +struct Block +{ + const char *blockText; + size_t blockTextLength; + int blockTextFirstLine; + + const char *blockHeaderTitle; + size_t blockHeaderTitleLength; + + const char *blockHeaderText; + size_t blockHeaderTextLength; +}; + +enum GPUShaderType +{ + GPUSHADER_VERTEX, + GPUSHADER_FRAGMENT, + GPUSHADER_GEOMETRY, + GPUSHADER_TYPE_COUNT +}; + +struct GPUShaderDesc +{ + GPUShaderType type; + const char *source; + int firstLineNumber; +}; + +struct GPUProgramDesc +{ + size_t numShaders; + GPUShaderDesc *shaders; +}; + +typedef enum +{ + UNIFORM_DIFFUSEMAP = 0, + UNIFORM_LIGHTMAP, + UNIFORM_NORMALMAP, + UNIFORM_DELUXEMAP, + UNIFORM_SPECULARMAP, + UNIFORM_SSAOMAP, + + UNIFORM_TEXTUREMAP, + UNIFORM_LEVELSMAP, + UNIFORM_CUBEMAP, + UNIFORM_ENVBRDFMAP, + + UNIFORM_SCREENIMAGEMAP, + UNIFORM_SCREENDEPTHMAP, + + UNIFORM_SHADOWMAP, + UNIFORM_SHADOWMAP2, + + UNIFORM_SHADOWMVP, + UNIFORM_SHADOWMVP2, + UNIFORM_SHADOWMVP3, + + UNIFORM_ENABLETEXTURES, + + UNIFORM_DIFFUSETEXMATRIX, + UNIFORM_DIFFUSETEXOFFTURB, + + UNIFORM_TCGEN0, + UNIFORM_TCGEN0VECTOR0, + UNIFORM_TCGEN0VECTOR1, + UNIFORM_TCGEN1, + + UNIFORM_COLORGEN, + UNIFORM_ALPHAGEN, + UNIFORM_COLOR, + UNIFORM_BASECOLOR, + UNIFORM_VERTCOLOR, + + UNIFORM_DLIGHTINFO, + UNIFORM_LIGHTFORWARD, + UNIFORM_LIGHTUP, + UNIFORM_LIGHTRIGHT, + UNIFORM_LIGHTORIGIN, + UNIFORM_MODELLIGHTDIR, + UNIFORM_LIGHTRADIUS, + UNIFORM_AMBIENTLIGHT, + UNIFORM_DIRECTEDLIGHT, + UNIFORM_DISINTEGRATION, + UNIFORM_LIGHTMASK, + UNIFORM_FOGINDEX, + + UNIFORM_FOGCOLORMASK, + + UNIFORM_MODELMATRIX, + UNIFORM_MODELVIEWPROJECTIONMATRIX, + + UNIFORM_TIME, + UNIFORM_VERTEXLERP, + UNIFORM_NORMALSCALE, + UNIFORM_SPECULARSCALE, + UNIFORM_PARALLAXBIAS, + + UNIFORM_VIEWINFO, // znear, zfar, width/2, height/2 + UNIFORM_VIEWORIGIN, + UNIFORM_LOCALVIEWORIGIN, + UNIFORM_VIEWFORWARD, + UNIFORM_VIEWLEFT, + UNIFORM_VIEWUP, + + UNIFORM_INVTEXRES, + UNIFORM_AUTOEXPOSUREMINMAX, + UNIFORM_TONEMINAVGMAXLINEAR, + + UNIFORM_CUBEMAPINFO, + + UNIFORM_ALPHA_TEST_TYPE, + + UNIFORM_FX_VOLUMETRIC_BASE, + UNIFORM_MAPZEXTENTS, + UNIFORM_ZONEOFFSET, + UNIFORM_ENVFORCE, + UNIFORM_RANDOMOFFSET, + UNIFORM_CHUNK_PARTICLES, + + UNIFORM_COUNT +} uniform_t; + +struct UniformData +{ + uniform_t index; + int numElements; + + // uniform data follows immediately afterwards + //char data[1]; +}; + +// shaderProgram_t represents a collection of GLSL shaders which form a +// GLSL shader program +typedef struct shaderProgram_s +{ + char *name; + + GLuint program; + uint32_t attribs; // vertex array attributes + uint32_t xfbVariables; // transform feedback variables + + // uniform parameters + GLint *uniforms; + short *uniformBufferOffsets; + char *uniformBuffer; + + // uniform blocks + uint32_t uniformBlocks; +} shaderProgram_t; + +// trRefdef_t holds everything that comes in refdef_t, +// as well as the locally generated scene information +typedef struct { + int x, y, width, height; + float fov_x, fov_y; + vec3_t vieworg; + vec3_t viewaxis[3]; // transformation matrix + + stereoFrame_t stereoFrame; + + int time; // time in milliseconds for shader effects and other time dependent rendering issues + int rdflags; // RDF_NOWORLDMODEL, etc + + // 1 bits will prevent the associated area from rendering at all + byte areamask[MAX_MAP_AREA_BYTES]; + qboolean areamaskModified; // qtrue if areamask changed since last scene + + float floatTime; // tr.refdef.time / 1000.0 + float frameTime; // delta last frame to frame now + float lastTime; // last frame time + + float blurFactor; + + // text messages for deform text shaders + char text[MAX_RENDER_STRINGS][MAX_RENDER_STRING_LENGTH]; + + int num_entities; + trRefEntity_t *entities; + + int num_dlights; + struct dlight_s *dlights; + + int numPolys; + struct srfPoly_s *polys; + + int fistDrawSurf; + int numDrawSurfs; + struct drawSurf_s *drawSurfs; + + int num_pshadows; + struct pshadow_s *pshadows; + + float sunShadowMvp[3][16]; + float sunDir[4]; + float sunCol[4]; + float sunAmbCol[4]; + float colorScale; + + float autoExposureMinMax[2]; + float toneMinAvgMaxLinear[3]; +} trRefdef_t; + + +//================================================================================= + + +typedef struct { + int originalBrushNumber; + vec3_t bounds[2]; + + vec4_t color; + float tcScale; // texture coordinate vector scales + fogParms_t parms; + + // for clipping distance in fog when outside + qboolean hasSurface; + float surface[4]; +} fog_t; + +enum viewParmFlag_t { + VPF_NOVIEWMODEL = 0x01, // Don't render the view model + VPF_DEPTHSHADOW = 0x02, // Rendering depth-only + VPF_DEPTHCLAMP = 0x04, // Perform depth clamping when rendering z pass + VPF_ORTHOGRAPHIC = 0x08, // Use orthographic projection + VPF_USESUNLIGHT = 0x10, + VPF_FARPLANEFRUSTUM = 0x20, // Use far clipping plane + VPF_NOCUBEMAPS = 0x40, // Don't render cubemaps + VPF_POINTSHADOW = 0x80,// Rendering pointlight shadow + VPF_SHADOWCASCADES = 0x100,// Rendering sun shadow cascades + VPF_NOCLEAR = 0x200, +}; +using viewParmFlags_t = uint32_t; + +enum viewParmType_t { + VPT_SKYPORTAL, + VPT_SUN_SHADOWS, + VPT_PLAYER_SHADOWS, + VPT_POINT_SHADOWS, + VPT_PORTAL, + VPT_MAIN, + VPT_ALL +}; + +typedef struct { + orientationr_t ori; + orientationr_t world; + vec3_t pvsOrigin; // may be different than or.origin for portals + qboolean isPortal; // true if this view is through a portal + qboolean isMirror; // the portal is a mirror, invert the face culling + qboolean isSkyPortal; + int flags; + int frameSceneNum; // copied from tr.frameSceneNum + int frameCount; // copied from tr.frameCount + cplane_t portalPlane; // clip anything behind this if mirroring + int viewportX, viewportY, viewportWidth, viewportHeight; + int scissorX, scissorY, scissorWidth, scissorHeight; + FBO_t *targetFbo; + int targetFboLayer; + float fovX, fovY; + float projectionMatrix[16]; + cplane_t frustum[5]; + vec3_t visBounds[2]; + float zFar; + float zNear; + stereoFrame_t stereoFrame; + int currentViewParm; + viewParmType_t viewParmType; +} viewParms_t; + + +/* +============================================================================== + +SURFACES + +============================================================================== +*/ +typedef byte color4ub_t[4]; + +// any changes in surfaceType must be mirrored in rb_surfaceTable[] +typedef enum surfaceType_e +{ + SF_BAD, + SF_SKIP, // ignore + SF_FACE, + SF_GRID, + SF_TRIANGLES, + SF_POLY, + SF_MDV, + SF_MDR, + SF_IQM, + SF_MDX, + SF_FLARE, + SF_ENTITY, // beams, rails, lightning, etc that can be determined by entity + SF_VBO_MESH, + SF_VBO_MDVMESH, + SF_SPRITES, + SF_WEATHER, + + SF_NUM_SURFACE_TYPES, + SF_MAX = 0x7fffffff // ensures that sizeof( surfaceType_t ) == sizeof( int ) +} surfaceType_t; + +/* +the drawsurf sort data is packed into a single 32 bit value so it can be +compared quickly during the qsorting process +*/ +#define QSORT_CUBEMAP_SHIFT 0 +#define QSORT_CUBEMAP_BITS 6 +#define QSORT_CUBEMAP_MASK ((1 << QSORT_CUBEMAP_BITS) - 1) + +#define QSORT_ENTITYNUM_SHIFT (QSORT_CUBEMAP_SHIFT + QSORT_CUBEMAP_BITS) +#define QSORT_ENTITYNUM_BITS REFENTITYNUM_BITS +#define QSORT_ENTITYNUM_MASK ((1 << QSORT_ENTITYNUM_BITS) - 1) + +#define QSORT_SHADERNUM_SHIFT (QSORT_ENTITYNUM_SHIFT + QSORT_ENTITYNUM_BITS) +#define QSORT_SHADERNUM_BITS SHADERNUM_BITS +#define QSORT_SHADERNUM_MASK ((1 << QSORT_SHADERNUM_BITS) - 1) + +#define QSORT_POSTRENDER_SHIFT (QSORT_SHADERNUM_SHIFT + QSORT_SHADERNUM_BITS) +#define QSORT_POSTRENDER_BITS 1 +#define QSORT_POSTRENDER_MASK ((1 << QSORT_POSTRENDER_BITS) - 1) + +#if QSORT_POSTRENDER_SHIFT >= 32 + #error "Sort field needs to be expanded" +#endif + +typedef struct drawSurf_s { + uint32_t sort; // bit combination for fast compares + uint32_t dlightBits; + surfaceType_t *surface; // any of surface*_t + int fogIndex; +} drawSurf_t; + +#define MAX_FACE_POINTS 64 + +#define MAX_PATCH_SIZE 32 // max dimensions of a patch mesh in map file +#define MAX_GRID_SIZE 65 // max dimensions of a grid mesh in memory + +// when cgame directly specifies a polygon, it becomes a srfPoly_t +// as soon as it is called +typedef struct srfPoly_s { + surfaceType_t surfaceType; + struct srfPoly_s *next; + qhandle_t hShader; + int fogIndex; + int numVerts; + polyVert_t *verts; +} srfPoly_t; + +typedef struct srfFlare_s { + surfaceType_t surfaceType; + vec3_t origin; + vec3_t normal; + vec3_t color; + shader_t *shader; + bool portal_ranged; +} srfFlare_t; + +struct vertexAttribute_t; +struct srfSprites_t +{ + surfaceType_t surfaceType; + + shader_t *shader; + const surfaceSprite_t *sprite; + int baseVertex; + int numSprites; + int numIndices; + VBO_t *vbo; + IBO_t *ibo; + + int fogIndex; + AlphaTestType alphaTestType; + + int numAttributes; + vertexAttribute_t *attributes; +}; + +struct srfWeather_t +{ + surfaceType_t surfaceType; +}; + +typedef struct +{ + vec3_t xyz; + vec2_t st; + vec2_t lightmap[MAXLIGHTMAPS]; + vec3_t normal; + vec4_t tangent; + vec3_t lightdir; + vec4_t vertexColors[MAXLIGHTMAPS]; + +#if DEBUG_OPTIMIZEVERTICES + unsigned int id; +#endif +} srfVert_t; + +#ifdef _G2_GORE +typedef struct +{ + vec3_t position; + uint32_t normal; + vec2_t texCoords; + byte bonerefs[4]; + byte weights[4]; + uint32_t tangents; +} g2GoreVert_t; + +typedef struct srfG2GoreSurface_s +{ + surfaceType_t surfaceType; + + // indexes + int numIndexes; + glIndex_t *indexes; + + // vertexes + int numVerts; + g2GoreVert_t *verts; + + // BSP VBO offsets + int firstVert; + int firstIndex; + +} srfG2GoreSurface_t; +#endif + +// srfBspSurface_t covers SF_GRID, SF_TRIANGLES, SF_POLY, and SF_VBO_MESH +typedef struct srfBspSurface_s +{ + surfaceType_t surfaceType; + + // dynamic lighting information + int dlightBits; + int pshadowBits; + + // culling information + vec3_t cullBounds[2]; + vec3_t cullOrigin; + float cullRadius; + cplane_t cullPlane; + + // indexes + int numIndexes; + glIndex_t *indexes; + + // vertexes + int numVerts; + srfVert_t *verts; + + // BSP VBO offsets + int firstVert; + int firstIndex; + glIndex_t minIndex; + glIndex_t maxIndex; + + // static render data + VBO_t *vbo; + IBO_t *ibo; + + // SF_GRID specific variables after here + + // lod information, which may be different + // than the culling information to allow for + // groups of curves that LOD as a unit + vec3_t lodOrigin; + float lodRadius; + int lodFixed; + int lodStitched; + + // vertexes + int width, height; + float *widthLodError; + float *heightLodError; +} srfBspSurface_t; + +// inter-quake-model +typedef struct { + int num_vertexes; + int num_triangles; + int num_frames; + int num_surfaces; + int num_joints; + int num_poses; + struct srfIQModel_s *surfaces; + + float *positions; + float *texcoords; + float *normals; + float *tangents; + byte *blendIndexes; + union { + float *f; + byte *b; + } blendWeights; + byte *colors; + int *triangles; + + // depending upon the exporter, blend indices and weights might be int/float + // as opposed to the recommended byte/byte, for example Noesis exports + // int/float whereas the official IQM tool exports byte/byte + byte blendWeightsType; // IQM_UBYTE or IQM_FLOAT + + int *jointParents; + float *jointMats; + float *poseMats; + float *bounds; + char *names; +} iqmData_t; + +// inter-quake-model surface +typedef struct srfIQModel_s { + surfaceType_t surfaceType; + char name[MAX_QPATH]; + shader_t *shader; + iqmData_t *data; + int first_vertex, num_vertexes; + int first_triangle, num_triangles; +} srfIQModel_t; + +typedef struct srfVBOMDVMesh_s +{ + surfaceType_t surfaceType; + + struct mdvModel_s *mdvModel; + struct mdvSurface_s *mdvSurface; + + // backEnd stats + int indexOffset; + int numIndexes; + int numVerts; + glIndex_t minIndex; + glIndex_t maxIndex; + + // static render data + VBO_t *vbo; + IBO_t *ibo; +} srfVBOMDVMesh_t; + +extern void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])(void *); + +/* +============================================================================== + +SHADOWS + +============================================================================== +*/ + +typedef struct pshadow_s +{ + float sort; + + int numEntities; + int entityNums[8]; + vec3_t entityOrigins[8]; + float entityRadiuses[8]; + + float viewRadius; + vec3_t viewOrigin; + + vec3_t lightViewAxis[3]; + vec3_t lightOrigin; + float lightRadius; + cplane_t cullPlane; +} pshadow_t; + + +/* +============================================================================== + +BRUSH MODELS + +============================================================================== +*/ + + +// +// in memory representation +// + +#define SIDE_FRONT 0 +#define SIDE_BACK 1 +#define SIDE_ON 2 + +#define CULLINFO_NONE 0 +#define CULLINFO_BOX 1 +#define CULLINFO_SPHERE 2 +#define CULLINFO_PLANE 4 + +typedef struct cullinfo_s { + int type; + vec3_t bounds[2]; + vec3_t localOrigin; + float radius; + cplane_t plane; +} cullinfo_t; + +typedef struct msurface_s { + struct shader_s *shader; + int fogIndex; + int cubemapIndex; + cullinfo_t cullinfo; + + int numSurfaceSprites; + srfSprites_t *surfaceSprites; + + surfaceType_t *data; // any of srf*_t +} msurface_t; + + +#define CONTENTS_NODE -1 +typedef struct mnode_s { + // common with leaf and node + int contents; // -1 for nodes, to differentiate from leafs + int visCounts[MAX_VISCOUNTS]; // node needs to be traversed if current + vec3_t mins, maxs; // for bounding box culling + struct mnode_s *parent; + + // node specific + cplane_t *plane; + struct mnode_s *children[2]; + + // leaf specific + int cluster; + int area; + + int firstmarksurface; + int nummarksurfaces; +} mnode_t; + +typedef struct { + vec3_t bounds[2]; // for culling + int worldIndex; + int firstSurface; + int numSurfaces; +} bmodel_t; + +typedef struct +{ + byte ambientLight[MAXLIGHTMAPS][3]; + byte directLight[MAXLIGHTMAPS][3]; + byte styles[MAXLIGHTMAPS]; + byte latLong[2]; +// byte pad[2]; // to align to a cache line +} mgrid_t; + +typedef struct { + char name[MAX_QPATH]; // ie: maps/tim_dm2.bsp + char baseName[MAX_QPATH]; // ie: tim_dm2 + + int dataSize; + + int numShaders; + dshader_t *shaders; + + int numBModels; + bmodel_t *bmodels; + + int numplanes; + cplane_t *planes; + + int numnodes; // includes leafs + int numDecisionNodes; + mnode_t *nodes; + + int numWorldSurfaces; + + int numsurfaces; + msurface_t *surfaces; + int *surfacesViewCount; + int *surfacesDlightBits; + int *surfacesPshadowBits; + + int numMergedSurfaces; + msurface_t *mergedSurfaces; + int *mergedSurfacesViewCount; + int *mergedSurfacesDlightBits; + int *mergedSurfacesPshadowBits; + + int nummarksurfaces; + int *marksurfaces; + int *viewSurfaces; + + int numfogs; + fog_t *fogs; + const fog_t *globalFog; + int globalFogIndex; + + vec3_t lightGridOrigin; + vec3_t lightGridSize; + vec3_t lightGridInverseSize; + int lightGridBounds[3]; + float *hdrLightGrid; + int lightGridOffsets[8]; + + vec3_t lightGridStep; + + mgrid_t *lightGridData; + word *lightGridArray; + int numGridArrayElements; + + + int skyboxportal; + int numClusters; + int clusterBytes; + const byte *vis; // may be passed in by CM_LoadMap to save space + byte *novis; // clusterBytes of 0xff (everything is visible) + + char *entityString; + char *entityParsePoint; + +} world_t; + + +/* +============================================================================== +MDV MODELS - meta format for vertex animation models like .md2, .md3, .mdc +============================================================================== +*/ +typedef struct +{ + float bounds[2][3]; + float localOrigin[3]; + float radius; +} mdvFrame_t; + +typedef struct +{ + float origin[3]; + float axis[3][3]; +} mdvTag_t; + +typedef struct +{ + char name[MAX_QPATH]; // tag name +} mdvTagName_t; + +typedef struct +{ + vec3_t xyz; + vec3_t normal; + vec3_t tangent; + vec3_t bitangent; +} mdvVertex_t; + +typedef struct +{ + float st[2]; +} mdvSt_t; + +typedef struct mdvSurface_s +{ + surfaceType_t surfaceType; + + char name[MAX_QPATH]; // polyset name + + int numShaderIndexes; + int *shaderIndexes; + + int numVerts; + mdvVertex_t *verts; + mdvSt_t *st; + + int numIndexes; + glIndex_t *indexes; + + struct mdvModel_s *model; +} mdvSurface_t; + +typedef struct mdvModel_s +{ + int numFrames; + mdvFrame_t *frames; + + int numTags; + mdvTag_t *tags; + mdvTagName_t *tagNames; + + int numSurfaces; + mdvSurface_t *surfaces; + + int numVBOSurfaces; + srfVBOMDVMesh_t *vboSurfaces; + + int numSkins; +} mdvModel_t; + + +//====================================================================== + +typedef enum { + MOD_BAD, + MOD_BRUSH, + MOD_MESH, + MOD_MDR, + MOD_IQM, +/* +Ghoul2 Insert Start +*/ + MOD_MDXM, + MOD_MDXA +/* +Ghoul2 Insert End +*/ +} modtype_t; + +typedef struct mdxmVBOMesh_s +{ + surfaceType_t surfaceType; + + int indexOffset; + int minIndex; + int maxIndex; + int numIndexes; + int numVertexes; + + VBO_t *vbo; + IBO_t *ibo; +} mdxmVBOMesh_t; + +typedef struct mdxmVBOModel_s +{ + int numVBOMeshes; + mdxmVBOMesh_t *vboMeshes; + + VBO_t *vbo; + IBO_t *ibo; +} mdxmVBOModel_t; + +typedef struct mdxmData_s +{ + mdxmHeader_t *header; + + // int numLODs; // available in header->numLODs + mdxmVBOModel_t *vboModels; +} mdxmData_t; + +typedef struct model_s { + char name[MAX_QPATH]; + modtype_t type; + int index; // model = tr.models[model->index] + + int dataSize; // just for listing purposes + union + { + bmodel_t *bmodel; // type == MOD_BRUSH + mdvModel_t *mdv[MD3_MAX_LODS]; // type == MOD_MESH + mdrHeader_t *mdr; // type == MOD_MDR + iqmData_t *iqm; // type == MOD_IQM + mdxmData_t *glm; // type == MOD_MDXM + mdxaHeader_t *gla; // type == MOD_MDXA + } data; + + int numLods; +} model_t; + + +#define MAX_MOD_KNOWN 1024 + +void R_ModelInit (void); + +model_t *R_GetModelByHandle( qhandle_t hModel ); +int R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, + float frac, const char *tagName ); +void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs ); + +void R_Modellist_f (void); + +//==================================================== + +#define MAX_DRAWIMAGES 2048 +#define MAX_SKINS 1024 + + +#define MAX_DRAWSURFS 0x10000 +#define DRAWSURF_MASK (MAX_DRAWSURFS-1) + +extern int gl_filter_min, gl_filter_max; + +/* +** performanceCounters_t +*/ +typedef struct { + int c_sphere_cull_patch_in, c_sphere_cull_patch_clip, c_sphere_cull_patch_out; + int c_box_cull_patch_in, c_box_cull_patch_clip, c_box_cull_patch_out; + int c_sphere_cull_md3_in, c_sphere_cull_md3_clip, c_sphere_cull_md3_out; + int c_box_cull_md3_in, c_box_cull_md3_clip, c_box_cull_md3_out; + + int c_leafs; + int c_dlightSurfaces; + int c_dlightSurfacesCulled; +} frontEndCounters_t; + +#define FOG_TABLE_SIZE 256 +#define FUNCTABLE_SIZE 1024 +#define FUNCTABLE_SIZE2 10 +#define FUNCTABLE_MASK (FUNCTABLE_SIZE-1) + +struct vertexAttribute_t +{ + VBO_t *vbo; + int index; + int numComponents; + GLboolean integerAttribute; + GLenum type; + GLboolean normalize; + int stride; + int offset; + int stepRate; +}; + +#define MAX_UBO_BINDINGS (16) +struct bufferBinding_t +{ + GLuint buffer; + int offset; + int size; +}; + +// the renderer front end should never modify glstate_t +typedef struct glstate_s { + int currenttextures[NUM_TEXTURE_BUNDLES]; + int currenttmu; + int texEnv[2]; + int faceCulling; + float minDepth; + float maxDepth; + uint32_t glStateBits; + uint32_t vertexAttribsState; + vertexAttribute_t currentVaoAttribs[ATTR_INDEX_MAX]; + uint32_t vertexAttribsNewFrame; + uint32_t vertexAttribsOldFrame; + float vertexAttribsInterpolation; + int vertexAttribsTexCoordOffset[2]; + qboolean vertexAnimation; + qboolean skeletalAnimation; + qboolean genShadows; + shaderProgram_t *currentProgram; + FBO_t *currentFBO; + VBO_t *currentVBO; + IBO_t *currentIBO; + bufferBinding_t currentXFBBO; + GLuint currentGlobalUBO; + bufferBinding_t currentUBOs[MAX_UBO_BINDINGS]; + matrix_t modelview; + matrix_t projection; + matrix_t modelviewProjection; +} glstate_t; + +typedef enum { + MI_NONE, + MI_NVX, + MI_ATI +} memInfo_t; + +typedef enum { + TCR_NONE = 0x0000, + TCR_LATC = 0x0001, + TCR_BPTC = 0x0002, +} textureCompressionRef_t; + +typedef enum { + IHV_UNKNOWN, + + IHV_NVIDIA, + IHV_AMD, + IHV_INTEL +} gpuIhv_t; + +// We can't change glConfig_t without breaking DLL/vms compatibility, so +// store extensions we have here. +typedef struct { + int glslMajorVersion; + int glslMinorVersion; + + gpuIhv_t hardwareVendor; + + memInfo_t memInfo; + + int maxRenderbufferSize; + int maxColorAttachments; + + int textureCompression; + int uniformBufferOffsetAlignment; + int maxUniformBlockSize; + int maxUniformBufferBindings; + + qboolean immutableTextures; + qboolean immutableBuffers; + + qboolean debugContext; + qboolean timerQuery; + + qboolean floatLightmap; +} glRefConfig_t; + +enum +{ + TRI_BIN_0_19, + TRI_BIN_20_49, + TRI_BIN_50_99, + TRI_BIN_100_299, + TRI_BIN_300_599, + TRI_BIN_600_999, + TRI_BIN_1000_1499, + TRI_BIN_1500_1999, + TRI_BIN_2000_2999, + TRI_BIN_3000_PLUS, + + NUM_TRI_BINS, +}; + +typedef struct { + int c_surfaces, c_shaders, c_vertexes, c_indexes, c_totalIndexes; + int c_surfBatches; + float c_overDraw; + + int c_vboVertexBuffers; + int c_vboIndexBuffers; + int c_vboVertexes; + int c_vboIndexes; + + int c_staticVboDraws; + int c_dynamicVboDraws; + int c_dynamicVboTotalSize; + + int c_multidraws; + int c_multidrawsMerged; + + int c_dlightVertexes; + int c_dlightIndexes; + + int c_flareAdds; + int c_flareTests; + int c_flareRenders; + + int c_glslShaderBinds; + int c_genericDraws; + int c_lightallDraws; + int c_fogDraws; + int c_dlightDraws; + + int c_triangleCountBins[NUM_TRI_BINS]; + + int msec; // total msec for backend run +} backEndCounters_t; + +// all state modified by the back end is seperated +// from the front end state +typedef struct { + trRefdef_t refdef; + viewParms_t viewParms; + orientationr_t ori; + backEndCounters_t pc; + trRefEntity_t *currentEntity; + qboolean skyRenderedThisView; // flag for drawing sun + + qboolean projection2D; // if qtrue, drawstretchpic doesn't need to change modes + float color2D[4]; + trRefEntity_t entity2D; // currentEntity will point at this when doing 2D rendering + trRefEntity_t entityFlare; // currentEntity will point at this when doing flare rendering + + FBO_t *last2DFBO; + qboolean colorMask[4]; + qboolean framePostProcessed; + qboolean depthFill; + qboolean refractionFill; +} backEndState_t; + +/* +** trGlobals_t +** +** Most renderer globals are defined here. +** backend functions should never modify any of these fields, +** but may read fields that aren't dynamically modified +** by the frontend. +*/ +struct weatherSystem_t; +typedef struct trGlobals_s { + qboolean registered; // cleared at shutdown, set at beginRegistration + + window_t window; + + fileHandle_t debugFile; + int numFramesToCapture; + + int visIndex; + int visClusters[MAX_VISCOUNTS]; + int visCounts[MAX_VISCOUNTS]; // incremented every time a new vis cluster is entered + + int frameCount; // incremented every frame + int sceneCount; // incremented every scene + int viewCount; // incremented every view (twice a scene if portaled) + // and every R_MarkFragments call + + int frameSceneNum; // zeroed at RE_BeginFrame + + GLuint globalVao; + + qboolean worldMapLoaded; + qboolean worldInternalLightmapping; // qtrue indicates lightmap atlasing + qboolean worldDeluxeMapping; + qboolean worldInternalDeluxeMapping; + vec2_t autoExposureMinMax; + vec3_t toneMinAvgMaxLevel; + world_t *world; + char worldName[MAX_QPATH]; + + const byte *externalVisData; // from RE_SetWorldVisData, shared with CM_Load + + image_t *defaultImage; + image_t *scratchImage[32]; + image_t *fogImage; + image_t *dlightImage; // inverse-quare highlight for projective adding + image_t *flareImage; + image_t *whiteImage; // full of 0xff + image_t *identityLightImage; // full of tr.identityLightByte + + image_t *renderImage; + image_t *glowImage; + image_t *glowImageScaled[6]; + image_t *sunRaysImage; + image_t *renderDepthImage; + image_t *pshadowArrayImage; + image_t *textureScratchImage[2]; + image_t *quarterImage[2]; + image_t *calcLevelsImage; + image_t *targetLevelsImage; + image_t *fixedLevelsImage; + image_t *sunShadowArrayImage; + image_t *pointShadowArrayImage; + image_t *screenShadowImage; + image_t *screenSsaoImage; + image_t *hdrDepthImage; + image_t *renderCubeImage; + image_t *renderCubeDepthImage; + image_t *envBrdfImage; + image_t *textureDepthImage; + image_t *weatherDepthImage; + + FBO_t *renderFbo; + FBO_t *glowFboScaled[6]; + FBO_t *msaaResolveFbo; + FBO_t *sunRaysFbo; + FBO_t *depthFbo; + FBO_t *pshadowFbos[MAX_DRAWN_PSHADOWS]; + FBO_t *shadowCubeFbo[MAX_DLIGHTS*6]; + FBO_t *textureScratchFbo[2]; + FBO_t *quarterFbo[2]; + FBO_t *calcLevelsFbo; + FBO_t *targetLevelsFbo; + FBO_t *sunShadowFbo[3]; + FBO_t *screenShadowFbo; + FBO_t *screenSsaoFbo; + FBO_t *hdrDepthFbo; + FBO_t *renderCubeFbo[6]; + FBO_t *filterCubeFbo; + FBO_t *weatherDepthFbo; + + shader_t *defaultShader; + shader_t *shadowShader; + shader_t *distortionShader; + shader_t *projectionShadowShader; + shader_t *weatherInternalShader; + + shader_t *flareShader; + shader_t *sunShader; + shader_t *sunFlareShader; + + int numLightmaps; + int lightmapSize; + image_t **lightmaps; + image_t **deluxemaps; + + qboolean hdrLighting; + + vec2i_t lightmapAtlasSize; + vec2i_t lightmapsPerAtlasSide; + + int numCubemaps; + cubemap_t *cubemaps; + + trRefEntity_t worldEntity; // point currentEntity at this when rendering world + model_t *currentModel; + + weatherSystem_t *weatherSystem; + + // + // GPU shader programs + // + shaderProgram_t splashScreenShader; + shaderProgram_t genericShader[GENERICDEF_COUNT]; + shaderProgram_t refractionShader[REFRACTIONDEF_COUNT]; + shaderProgram_t textureColorShader; + shaderProgram_t fogShader[FOGDEF_COUNT]; + shaderProgram_t lightallShader[LIGHTDEF_COUNT]; + shaderProgram_t pshadowShader; + shaderProgram_t volumeShadowShader; + shaderProgram_t down4xShader; + shaderProgram_t bokehShader; + shaderProgram_t tonemapShader[2]; + shaderProgram_t calclevels4xShader[2]; + shaderProgram_t ssaoShader; + shaderProgram_t depthBlurShader[2]; + shaderProgram_t testcubeShader; + shaderProgram_t prefilterEnvMapShader; + shaderProgram_t gaussianBlurShader[2]; + shaderProgram_t glowCompositeShader; + shaderProgram_t dglowDownsample; + shaderProgram_t dglowUpsample; + shaderProgram_t spriteShader[SSDEF_COUNT]; + shaderProgram_t weatherUpdateShader; + shaderProgram_t weatherShader; + + GLuint staticUbo; + GLuint spriteUbos[MAX_SUB_BSP + 1]; + GLuint shaderInstanceUbo; + int shaderInstanceUboWriteOffset; + int entity2DUboOffset; + int camera2DUboOffset; + int entityFlareUboOffset; + int cameraFlareUboOffset; + int defaultLightsUboOffset; + int defaultSceneUboOffset; + int defaultFogsUboOffset; + int defaultShaderInstanceUboOffset; + + int cameraUboOffsets[3 + MAX_DLIGHTS * 6 + 3 + MAX_DRAWN_PSHADOWS]; + int sceneUboOffset; + int lightsUboOffset; + int fogsUboOffset; + int skyEntityUboOffset; + int entityUboOffsets[REFENTITYNUM_WORLD + 1]; + int animationBoneUboOffset; + + // ----------------------------------------- + + viewParms_t viewParms; + viewParms_t cachedViewParms[3 + MAX_DLIGHTS * 6 + 3 + MAX_DRAWN_PSHADOWS]; + int numCachedViewParms; + + viewParms_t skyPortalParms; + byte skyPortalAreaMask[MAX_MAP_AREA_BYTES]; + int skyPortalEntities; + + float identityLight; // 1.0 / ( 1 << overbrightBits ) + int identityLightByte; // identityLight * 255 + int overbrightBits; // r_overbrightBits->integer, but set to 0 if no hw gamma + + orientationr_t ori; // for current entity + + trRefdef_t refdef; + + int viewCluster; + + float mapLightScale; + float sunShadowScale; + + qboolean sunShadows; + vec3_t sunLight; // from the sky shader for this level + vec3_t sunDirection; + + frontEndCounters_t pc; + int frontEndMsec; // not in pc due to clearing issue + + int numTimedBlocks; + + // + // put large tables at the end, so most elements will be + // within the +/32K indexed range on risc processors + // + model_t *models[MAX_MOD_KNOWN]; + int numModels; + + world_t *bspModels[MAX_SUB_BSP]; + int numBspModels; + + int numImages; + image_t *images; + image_t *imagesFreeList; + + int numFBOs; + FBO_t *fbos[MAX_FBOS]; + + int numVBOs; + VBO_t *vbos[MAX_VBOS]; + + int numIBOs; + IBO_t *ibos[MAX_IBOS]; + +#ifdef _G2_GORE + VBO_t *goreVBO; + int goreVBOCurrentIndex; + IBO_t *goreIBO; + int goreIBOCurrentIndex; +#endif + + // shader indexes from other modules will be looked up in tr.shaders[] + // shader indexes from drawsurfs will be looked up in sortedShaders[] + // lower indexed sortedShaders must be rendered first (opaque surfaces before translucent) + int numShaders; + shader_t *shaders[MAX_SHADERS]; + shader_t *sortedShaders[MAX_SHADERS]; + + int numSkins; + skin_t *skins[MAX_SKINS]; + + GLuint sunFlareQuery[2]; + int sunFlareQueryIndex; + qboolean sunFlareQueryActive[2]; + + float sinTable[FUNCTABLE_SIZE]; + float squareTable[FUNCTABLE_SIZE]; + float triangleTable[FUNCTABLE_SIZE]; + float sawToothTable[FUNCTABLE_SIZE]; + float inverseSawToothTable[FUNCTABLE_SIZE]; + float fogTable[FOG_TABLE_SIZE]; + + float rangedFog; + float distanceCull, distanceCullSquared; //rwwRMG - added + + float widthRatioCoef; + + // Specific to Jedi Academy + int numBSPModels; + int currentLevel; + + bool explicitToneMap; +} trGlobals_t; + +struct glconfigExt_t +{ + glconfig_t *glConfig; + + const char *originalExtensionString; +}; + +extern backEndState_t backEnd; +extern trGlobals_t tr; +extern glstate_t glState; // outside of TR since it shouldn't be cleared during ref re-init +extern glRefConfig_t glRefConfig; +extern window_t window; + +// +// cvars +// +extern cvar_t *r_railWidth; +extern cvar_t *r_railCoreWidth; +extern cvar_t *r_railSegmentLength; + +extern cvar_t *r_ignore; // used for debugging anything +extern cvar_t *r_verbose; // used for verbose debug spew + +extern cvar_t *r_znear; // near Z clip plane +extern cvar_t *r_zproj; // z distance of projection plane +extern cvar_t *r_stereoSeparation; // separation of cameras for stereo rendering + +extern cvar_t *r_measureOverdraw; // enables stencil buffer overdraw measurement + +extern cvar_t *r_lodbias; // push/pull LOD transitions +extern cvar_t *r_lodscale; + +extern cvar_t *r_inGameVideo; // controls whether in game video should be draw +extern cvar_t *r_fastsky; // controls whether sky should be cleared or drawn +extern cvar_t *r_drawSun; // controls drawing of sun quad +extern cvar_t *r_dynamiclight; // dynamic lights enabled/disabled + +extern cvar_t *r_norefresh; // bypasses the ref rendering +extern cvar_t *r_drawentities; // disable/enable entity rendering +extern cvar_t *r_drawworld; // disable/enable world rendering +extern cvar_t *r_speeds; // various levels of information display +extern cvar_t *r_detailTextures; // enables/disables detail texturing stages +extern cvar_t *r_novis; // disable/enable usage of PVS +extern cvar_t *r_nocull; +extern cvar_t *r_facePlaneCull; // enables culling of planar surfaces with back side test +extern cvar_t *r_nocurves; +extern cvar_t *r_showcluster; + +extern cvar_t *r_gamma; + +extern cvar_t *r_ext_draw_range_elements; +extern cvar_t *r_ext_multi_draw_arrays; +extern cvar_t *r_ext_framebuffer_object; +extern cvar_t *r_ext_texture_float; +extern cvar_t *r_arb_half_float_pixel; +extern cvar_t *r_ext_framebuffer_multisample; +extern cvar_t *r_arb_seamless_cube_map; +extern cvar_t *r_arb_vertex_type_2_10_10_10_rev; +extern cvar_t *r_arb_buffer_storage; + +extern cvar_t *r_smartpicmip; + +extern cvar_t *r_nobind; // turns off binding to appropriate textures +extern cvar_t *r_singleShader; // make most world faces use default shader +extern cvar_t *r_roundImagesDown; +extern cvar_t *r_colorMipLevels; // development aid to see texture mip usage +extern cvar_t *r_picmip; // controls picmip values +extern cvar_t *r_finish; +extern cvar_t *r_textureMode; +extern cvar_t *r_offsetFactor; +extern cvar_t *r_offsetUnits; + +extern cvar_t *r_fullbright; // avoid lightmap pass +extern cvar_t *r_lightmap; // render lightmaps only +extern cvar_t *r_distanceCull; // distancecull +extern cvar_t *r_vertexLight; // vertex lighting mode for better performance +extern cvar_t *r_uiFullScreen; // ui is running fullscreen + +extern cvar_t *r_logFile; // number of frames to emit GL logs +extern cvar_t *r_showtris; // enables wireframe rendering of the world +extern cvar_t *r_showsky; // forces sky in front of all surfaces +extern cvar_t *r_shownormals; // draws wireframe normals +extern cvar_t *r_clear; // force screen clear every frame + +extern cvar_t *r_shadows; // controls shadows: 0 = none, 1 = blur, 2 = stencil, 3 = black planar projection +extern cvar_t *r_flares; // light flares + +extern cvar_t *r_intensity; + +extern cvar_t *r_lockpvs; +extern cvar_t *r_noportals; +extern cvar_t *r_portalOnly; + +extern cvar_t *r_subdivisions; +extern cvar_t *r_lodCurveError; +extern cvar_t *r_skipBackEnd; + +extern cvar_t *r_anaglyphMode; + +extern cvar_t *r_mergeMultidraws; +extern cvar_t *r_mergeLeafSurfaces; + +extern cvar_t *r_externalGLSL; + +extern cvar_t *r_hdr; +extern cvar_t *r_floatLightmap; + +extern cvar_t *r_toneMap; +extern cvar_t *r_forceToneMap; +extern cvar_t *r_forceToneMapMin; +extern cvar_t *r_forceToneMapAvg; +extern cvar_t *r_forceToneMapMax; + +extern cvar_t *r_autoExposure; +extern cvar_t *r_forceAutoExposure; +extern cvar_t *r_forceAutoExposureMin; +extern cvar_t *r_forceAutoExposureMax; + +extern cvar_t *r_cameraExposure; + +extern cvar_t *r_depthPrepass; +extern cvar_t *r_ssao; + +extern cvar_t *r_normalMapping; +extern cvar_t *r_specularMapping; +extern cvar_t *r_deluxeMapping; +extern cvar_t *r_parallaxMapping; +extern cvar_t *r_forceParallaxBias; +extern cvar_t *r_cubeMapping; +extern cvar_t *r_cubeMappingBounces; +extern cvar_t *r_baseNormalX; +extern cvar_t *r_baseNormalY; +extern cvar_t *r_baseParallax; +extern cvar_t *r_baseSpecular; +extern cvar_t *r_dlightMode; +extern cvar_t *r_pshadowDist; +extern cvar_t *r_recalcMD3Normals; +extern cvar_t *r_imageUpsample; +extern cvar_t *r_imageUpsampleMaxSize; +extern cvar_t *r_imageUpsampleType; +extern cvar_t *r_genNormalMaps; +extern cvar_t *r_forceSun; +extern cvar_t *r_forceSunMapLightScale; +extern cvar_t *r_forceSunLightScale; +extern cvar_t *r_forceSunAmbientScale; +extern cvar_t *r_sunlightMode; +extern cvar_t *r_drawSunRays; +extern cvar_t *r_sunShadows; +extern cvar_t *r_shadowFilter; +extern cvar_t *r_shadowMapSize; +extern cvar_t *r_shadowCascadeZNear; +extern cvar_t *r_shadowCascadeZFar; +extern cvar_t *r_shadowCascadeZBias; + +extern cvar_t *r_greyscale; + +extern cvar_t *r_ignoreGLErrors; + +extern cvar_t *r_overBrightBits; +extern cvar_t *r_mapOverBrightBits; + +extern cvar_t *r_debugSurface; +extern cvar_t *r_simpleMipMaps; + +extern cvar_t *r_showImages; +extern cvar_t *r_debugSort; + +extern cvar_t *r_printShaders; + +extern cvar_t *r_marksOnTriangleMeshes; + +extern cvar_t *r_dynamicGlow; +extern cvar_t *r_dynamicGlowPasses; +extern cvar_t *r_dynamicGlowDelta; +extern cvar_t *r_dynamicGlowIntensity; +extern cvar_t *r_dynamicGlowSoft; +extern cvar_t *r_dynamicGlowWidth; +extern cvar_t *r_dynamicGlowHeight; + +extern cvar_t *r_debugContext; +extern cvar_t *r_debugWeather; + +//==================================================================== + +struct packedVertex_t +{ + vec3_t position; + uint32_t normal; + uint32_t tangent; + vec2_t texcoords[1 + MAXLIGHTMAPS]; + vec4_t colors[MAXLIGHTMAPS]; + uint32_t lightDirection; +}; + +struct packedTangentSpace_t +{ + vec4_t tangentAndSign; +}; + +void R_GenerateDrawSurfs( viewParms_t *viewParms, trRefdef_t *refdef ); +void R_SetupViewParmsForOrthoRendering( + int viewportWidth, + int viewportHeight, + FBO_t *fbo, + viewParmFlags_t viewParmsFlags, + const orientationr_t& orientation, + const vec3_t viewBounds[2]); +void R_SortAndSubmitDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ); + +void R_SwapBuffers( int ); + +void R_RenderView( viewParms_t *parms ); +void R_RenderDlightCubemaps(const refdef_t *fd); +void R_SetupPshadowMaps(const refdef_t *fd); +void R_RenderCubemapSide( int cubemapIndex, int cubemapSide, bool bounce); +void R_GatherFrameViews(trRefdef_t *refdef); + +void R_AddMD3Surfaces( trRefEntity_t *e, int entityNum ); +void R_AddPolygonSurfaces( const trRefdef_t *refdef ); + +void R_DecomposeSort( uint32_t sort, int *entityNum, shader_t **shader, int *cubemap, int *postRender ); +uint32_t R_CreateSortKey(int entityNum, int sortedShaderIndex, int cubemapIndex, int postRender); +void R_AddDrawSurf( surfaceType_t *surface, int entityNum, shader_t *shader, + int fogIndex, int dlightMap, int postRender, int cubemap ); +bool R_IsPostRenderEntity ( const trRefEntity_t *refEntity ); + +void R_CalcMikkTSpaceBSPSurface(int numSurfaces, packedVertex_t *vertices, glIndex_t *indices); +void R_CalcMikkTSpaceMD3Surface(int numSurfaces, mdvVertex_t *verts, uint32_t *tangents, mdvSt_t *texcoords, glIndex_t *indices); +void R_CalcMikkTSpaceGlmSurface(int numSurfaces, mdxmVertex_t *vertices, mdxmVertexTexCoord_t *textureCoordinates, uint32_t *tangents, glIndex_t *indices); + +void R_CalcTexDirs(vec3_t sdir, vec3_t tdir, const vec3_t v1, const vec3_t v2, + const vec3_t v3, const vec2_t w1, const vec2_t w2, const vec2_t w3); +void R_CalcTbnFromNormalAndTexDirs(vec3_t tangent, vec3_t bitangent, vec3_t normal, vec3_t sdir, vec3_t tdir); +qboolean R_CalcTangentVectors(srfVert_t * dv[3]); + +#define CULL_IN 0 // completely unclipped +#define CULL_CLIP 1 // clipped by one or more planes +#define CULL_OUT 2 // completely outside the clipping planes +void R_LocalNormalToWorld (const vec3_t local, vec3_t world); +void R_LocalPointToWorld (const vec3_t local, vec3_t world); +int R_CullBox (vec3_t bounds[2]); +int R_CullLocalBox (vec3_t bounds[2]); +int R_CullPointAndRadiusEx( const vec3_t origin, float radius, const cplane_t* frustum, int numPlanes ); +int R_CullPointAndRadius( const vec3_t origin, float radius ); +int R_CullLocalPointAndRadius( const vec3_t origin, float radius ); + +void R_SetupProjection(viewParms_t *dest, float zProj, float zFar, qboolean computeFrustum); +void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, orientationr_t *ori ); +void R_BindAnimatedImageToTMU( textureBundle_t *bundle, int tmu ); + +/* +** GL wrapper/helper functions +*/ +void GL_Bind( image_t *image ); +void GL_BindToTMU( image_t *image, int tmu ); +void GL_SetDefaultState (void); +void GL_SelectTexture( int unit ); +void GL_TextureMode( const char *string ); +void GL_CheckErrs( const char *file, int line ); +#define GL_CheckErrors(...) GL_CheckErrs(__FILE__, __LINE__) +void GL_State( uint32_t stateVector ); +void GL_SetProjectionMatrix(matrix_t matrix); +void GL_SetModelviewMatrix(matrix_t matrix); +void GL_Cull( int cullType ); +void GL_DepthRange( float min, float max ); +void GL_VertexAttribPointers(size_t numAttributes, + vertexAttribute_t *attributes); +void GL_DrawIndexed(GLenum primitiveType, int numIndices, GLenum indexType, + int offset, int numInstances, int baseVertex); +void GL_MultiDrawIndexed(GLenum primitiveType, int *numIndices, + glIndex_t **offsets, int numDraws); +void GL_Draw( GLenum primitiveType, int firstVertex, int numVertices, int numInstances ); + +#define LERP( a, b, w ) ( ( a ) * ( 1.0f - ( w ) ) + ( b ) * ( w ) ) +#define LUMA( red, green, blue ) ( 0.2126f * ( red ) + 0.7152f * ( green ) + 0.0722f * ( blue ) ) + +extern glconfig_t glConfig; +extern glconfigExt_t glConfigExt; + +typedef _skinSurface_t skinSurface_t; + +void RE_StretchRaw (int x, int y, int w, int h, int cols, int rows, const byte *data, int client, qboolean dirty); +void RE_UploadCinematic (int cols, int rows, const byte *data, int client, qboolean dirty); +void RE_SetRangedFog ( float range ); + + +void RE_BeginRegistration( glconfig_t *glconfig ); +void RE_LoadWorldMap( const char *mapname ); +void RE_SetWorldVisData( const byte *vis ); +qhandle_t RE_RegisterServerModel( const char *name ); +qhandle_t RE_RegisterModel( const char *name ); +qhandle_t RE_RegisterServerSkin( const char *name ); +qhandle_t RE_RegisterSkin( const char *name ); +void RE_Shutdown(qboolean destroyWindow, qboolean restarting); +world_t *R_LoadBSP(const char *name, int *bspIndex = nullptr); + +qboolean R_GetEntityToken( char *buffer, int size ); + +model_t *R_AllocModel( void ); + +void R_Init( void ); +void R_UpdateSubImage( image_t *image, byte *pic, int x, int y, int width, int height ); + +void R_SetColorMappings( void ); +void R_GammaCorrect( byte *buffer, int bufSize ); +void R_Set2DRatio(void); + +void R_ImageList_f( void ); +void R_SkinList_f( void ); +void R_FontList_f( void ); +// https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=516 +const void *RB_TakeScreenshotCmd( const void *data ); + +void R_SaveScreenshot(struct screenshotReadback_t *screenshotReadback); + +void R_ScreenShotTGA_f( void ); +void R_ScreenShotPNG_f( void ); +void R_ScreenShotJPEG_f( void ); + +void R_InitFogTable( void ); +float R_FogFactor( float s, float t ); +void R_InitImagesPool(); +void R_InitImages( void ); +void R_LoadHDRImage(const char *filename, byte **data, int *width, int *height); +void R_DeleteTextures( void ); +int R_SumOfUsedImages( void ); +void R_InitSkins( void ); +skin_t *R_GetSkinByHandle( qhandle_t hSkin ); + +int R_ComputeLOD( trRefEntity_t *ent ); + +const void *RB_TakeVideoFrameCmd( const void *data ); +void RE_HunkClearCrap(void); + +// +// tr_shader.c +// +extern const int lightmapsNone[MAXLIGHTMAPS]; +extern const int lightmaps2d[MAXLIGHTMAPS]; +extern const int lightmapsVertex[MAXLIGHTMAPS]; +extern const int lightmapsFullBright[MAXLIGHTMAPS]; +extern const byte stylesDefault[MAXLIGHTMAPS]; + +shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage ); +shader_t *R_GetShaderByHandle( qhandle_t hShader ); +shader_t *R_FindShaderByName( const char *name ); +void R_InitShaders( qboolean server ); +void R_ShaderList_f( void ); +void R_RemapShader(const char *oldShader, const char *newShader, const char *timeOffset); +shader_t *R_CreateShaderFromTextureBundle( + const char *name, + const textureBundle_t *bundle, + uint32_t stateBits); + +/* +==================================================================== + +IMPLEMENTATION SPECIFIC FUNCTIONS + +==================================================================== +*/ + +QINLINE void GLimp_LogComment( char *comment ) {} +void GLimp_InitExtensions(); +void GLimp_InitCoreFunctions(); + +/* +==================================================================== + +TESSELATOR/SHADER DECLARATIONS + +==================================================================== +*/ + +typedef struct stageVars +{ + color4ub_t colors[SHADER_MAX_VERTEXES]; + vec2_t texcoords[NUM_TEXTURE_BUNDLES][SHADER_MAX_VERTEXES]; +} stageVars_t; + +#define MAX_MULTIDRAW_PRIMITIVES 16384 + +const int NUM_TESS_TEXCOORDS = 1 + MAXLIGHTMAPS; +struct shaderCommands_s +{ + glIndex_t indexes[SHADER_MAX_INDEXES] QALIGN(16); + vec4_t xyz[SHADER_MAX_VERTEXES] QALIGN(16); + uint32_t normal[SHADER_MAX_VERTEXES] QALIGN(16); + uint32_t tangent[SHADER_MAX_VERTEXES] QALIGN(16); + vec2_t texCoords[SHADER_MAX_VERTEXES][NUM_TESS_TEXCOORDS] QALIGN(16); + vec4_t vertexColors[SHADER_MAX_VERTEXES] QALIGN(16); + uint32_t lightdir[SHADER_MAX_VERTEXES] QALIGN(16); + //int vertexDlightBits[SHADER_MAX_VERTEXES] QALIGN(16); + + IBO_t *externalIBO; + qboolean useInternalVBO; + + stageVars_t svars QALIGN(16); + + //color4ub_t constantColor255[SHADER_MAX_VERTEXES] QALIGN(16); + + shader_t *shader; + float shaderTime; + int fogNum; + int cubemapIndex; +#ifdef REND2_SP_MAYBE + bool scale; // uses texCoords[input->firstIndex] for storage + bool fade; // uses svars.colors[input->firstIndex] for storage +#endif + int dlightBits; // or together of all vertexDlightBits + int pshadowBits; + + int firstIndex; + int numIndexes; + int numVertexes; + glIndex_t minIndex; + glIndex_t maxIndex; + + int multiDrawPrimitives; + GLsizei multiDrawNumIndexes[MAX_MULTIDRAW_PRIMITIVES]; + glIndex_t *multiDrawFirstIndex[MAX_MULTIDRAW_PRIMITIVES]; + glIndex_t *multiDrawLastIndex[MAX_MULTIDRAW_PRIMITIVES]; + glIndex_t multiDrawMinIndex[MAX_MULTIDRAW_PRIMITIVES]; + glIndex_t multiDrawMaxIndex[MAX_MULTIDRAW_PRIMITIVES]; + + // info extracted from current shader + int numPasses; + void (*currentStageIteratorFunc)( void ); + shaderStage_t **xstages; +}; + +struct drawState_t +{ + uint32_t stateBits; +}; + +#ifdef _WIN32 + typedef __declspec(align(16)) shaderCommands_s shaderCommands_t; +#else + typedef struct shaderCommands_s shaderCommands_t; +#endif +extern shaderCommands_t tess; +extern color4ub_t styleColors[MAX_LIGHT_STYLES]; + +void RB_BeginSurface(shader_t *shader, int fogNum, int cubemapIndex ); +void RB_EndSurface(void); +void RB_CheckOverflow( int verts, int indexes ); +#define RB_CHECKOVERFLOW(v,i) if (tess.numVertexes + (v) >= SHADER_MAX_VERTEXES || tess.numIndexes + (i) >= SHADER_MAX_INDEXES ) {RB_CheckOverflow(v,i);} + +void R_DrawElementsVBO( int numIndexes, glIndex_t firstIndex, glIndex_t minIndex, glIndex_t maxIndex ); +void RB_StageIteratorGeneric( void ); +void RB_StageIteratorSky( void ); + +void RB_AddQuadStamp( vec3_t origin, vec3_t left, vec3_t up, float color[4] ); +void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, float color[4], float s1, float t1, float s2, float t2 ); +void RB_InstantQuad( vec4_t quadVerts[4] ); +void RB_InstantQuad2(vec4_t quadVerts[4], vec2_t texCoords[4]); +void RB_InstantTriangle(); + +void RB_ShowImages( void ); + + +/* +============================================================ + +WORLD MAP + +============================================================ +*/ +world_t *R_GetWorld(int worldIndex); +void R_AddBrushModelSurfaces( trRefEntity_t *e, int entityNum ); +void R_AddWorldSurfaces( viewParms_t *viewParms, trRefdef_t *refdef ); +void R_MarkLeaves(void); +void R_RecursiveWorldNode(mnode_t *node, int planeBits, int dlightBits, int pshadowBits); +qboolean R_inPVS( const vec3_t p1, const vec3_t p2, byte *mask ); + + +/* +============================================================ + +FLARES + +============================================================ +*/ + +void R_ClearFlares( void ); + +void RB_AddFlare( void *surface, int fogNum, vec3_t point, vec3_t color, vec3_t normal ); +void RB_AddDlightFlares( void ); +void RB_RenderFlares (void); + +/* +============================================================ + +LIGHTS + +============================================================ +*/ + +void R_DlightBmodel( bmodel_t *bmodel, trRefEntity_t *ent ); +void R_SetupEntityLighting( const trRefdef_t *refdef, trRefEntity_t *ent ); +void R_TransformDlights( int count, dlight_t *dl, orientationr_t *ori ); +int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir ); +int R_LightDirForPoint( vec3_t point, vec3_t lightDir, vec3_t normal, world_t *world ); +int R_DLightsForPoint(const vec3_t point, const float radius); +int R_CubemapForPoint( const vec3_t point ); + +/* +============================================================ + +SKIES + +============================================================ +*/ + +void R_BuildCloudData( shaderCommands_t *shader ); +void R_InitSkyTexCoords( float cloudLayerHeight ); +void RB_DrawSun( float scale, shader_t *shader ); +void RB_ClipSkyPolygons( shaderCommands_t *shader ); + +/* +============================================================ + +CURVE TESSELATION + +============================================================ +*/ + +#define PATCH_STITCHING + +srfBspSurface_t *R_SubdividePatchToGrid( int width, int height, + srfVert_t points[MAX_PATCH_SIZE*MAX_PATCH_SIZE] ); +srfBspSurface_t *R_GridInsertColumn( srfBspSurface_t *grid, int column, int row, vec3_t point, float loderror ); +srfBspSurface_t *R_GridInsertRow( srfBspSurface_t *grid, int row, int column, vec3_t point, float loderror ); +void R_FreeSurfaceGridMesh( srfBspSurface_t *grid ); + +/* +============================================================ + +MARKERS, POLYGON PROJECTION ON WORLD POLYGONS + +============================================================ +*/ + +int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection, + int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ); + + +/* +============================================================ + +VERTEX BUFFER OBJECTS + +============================================================ +*/ + +struct VertexArraysProperties +{ + size_t vertexDataSize; + int numVertexArrays; + + int enabledAttributes[ATTR_INDEX_MAX]; + int offsets[ATTR_INDEX_MAX]; + int sizes[ATTR_INDEX_MAX]; + int strides[ATTR_INDEX_MAX]; + int streamStrides[ATTR_INDEX_MAX]; + void *streams[ATTR_INDEX_MAX]; +}; + +uint32_t R_VboPackTangent(vec4_t v); +uint32_t R_VboPackNormal(vec3_t v); +void R_VboUnpackTangent(vec4_t v, uint32_t b); +void R_VboUnpackNormal(vec3_t v, uint32_t b); + +VBO_t *R_CreateVBO(byte * vertexes, int vertexesSize, vboUsage_t usage); +IBO_t *R_CreateIBO(byte * indexes, int indexesSize, vboUsage_t usage); + +void R_BindVBO(VBO_t * vbo); +void R_BindNullVBO(void); + +void R_BindIBO(IBO_t * ibo); +void R_BindNullIBO(void); + +void R_InitGPUBuffers(void); +void R_DestroyGPUBuffers(void); +void R_VBOList_f(void); + +void RB_UpdateVBOs(unsigned int attribBits); +#ifdef _G2_GORE +void RB_UpdateGoreVBO(srfG2GoreSurface_t *goreSurface); +#endif +void RB_CommitInternalBufferData(); + +void RB_BindUniformBlock(GLuint ubo, uniformBlock_t block, int offset); +int RB_BindAndUpdateFrameUniformBlock(uniformBlock_t block, void *data); +void RB_AddShaderToShaderInstanceUBO(shader_t *shader); +int RB_AddShaderInstanceBlock(void *data); +void RB_UpdateConstants(const trRefdef_t *refdef); +void RB_BeginConstantsUpdate(struct gpuFrame_t *frame); +void RB_EndConstantsUpdate(const struct gpuFrame_t *frame); +int RB_AppendConstantsData(struct gpuFrame_t *frame, const void *data, size_t dataSize); +void CalculateVertexArraysProperties(uint32_t attributes, VertexArraysProperties *properties); +void CalculateVertexArraysFromVBO(uint32_t attributes, const VBO_t *vbo, VertexArraysProperties *properties); + +/* +============================================================ + +SHADOWS + +============================================================ +*/ + +void RB_ShadowTessEnd(shaderCommands_t *input, const VertexArraysProperties *vertexArrays); +void RB_ShadowFinish(void); +void RB_ProjectionShadowDeform(void); + +/* +============================================================ + +GLSL + +============================================================ +*/ + +void GLSL_InitSplashScreenShader(); +void GLSL_LoadGPUShaders(); +void GLSL_ShutdownGPUShaders(void); +void GLSL_VertexAttribsState(uint32_t stateBits, VertexArraysProperties *vertexArrays); +void GLSL_VertexAttribPointers(const VertexArraysProperties *vertexArrays); +void GL_VertexArraysToAttribs( vertexAttribute_t *attribs, + size_t attribsCount, const VertexArraysProperties *vertexArrays ); +void GLSL_BindProgram(shaderProgram_t * program); +void GLSL_BindNullProgram(void); + +void GLSL_SetUniformInt(shaderProgram_t *program, int uniformNum, GLint value); +void GLSL_SetUniformFloat(shaderProgram_t *program, int uniformNum, GLfloat value); +void GLSL_SetUniformFloatN(shaderProgram_t *program, int uniformNum, const float *v, int numFloats); +void GLSL_SetUniformVec2(shaderProgram_t *program, int uniformNum, const vec2_t v); +void GLSL_SetUniformVec2N(shaderProgram_t *program, int uniformNum, const float *v, int numVec2s); +void GLSL_SetUniformVec3(shaderProgram_t *program, int uniformNum, const vec3_t v); +void GLSL_SetUniformVec4(shaderProgram_t *program, int uniformNum, const vec4_t v); +void GLSL_SetUniformMatrix4x3(shaderProgram_t *program, int uniformNum, const float *matrix, int numElements = 1); +void GLSL_SetUniformMatrix4x4(shaderProgram_t *program, int uniformNum, const float *matrix, int numElements = 1); +void GLSL_SetUniforms( shaderProgram_t *program, UniformData *uniformData ); + +shaderProgram_t *GLSL_GetGenericShaderProgram(int stage); + +/* +============================================================ + +SCENE GENERATION + +============================================================ +*/ + +void R_InitNextFrame( void ); + +void RE_ClearScene( void ); +void RE_AddRefEntityToScene( const refEntity_t *ent ); +void RE_AddMiniRefEntityToScene( const miniRefEntity_t *miniRefEnt ); +void RE_AddPolyToScene( qhandle_t hShader , int numVerts, const polyVert_t *verts, int num ); +void RE_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ); +void RE_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ); +void RE_BeginScene( const refdef_t *fd ); +void RE_RenderScene( const refdef_t *fd ); +void RE_EndScene( void ); + +/* +============================================================= + +UNCOMPRESSING BONES + +============================================================= +*/ + +#define MC_BITS_X (16) +#define MC_BITS_Y (16) +#define MC_BITS_Z (16) +#define MC_BITS_VECT (16) + +#define MC_SCALE_X (1.0f/64) +#define MC_SCALE_Y (1.0f/64) +#define MC_SCALE_Z (1.0f/64) + +void MC_UnCompress(float mat[3][4],const unsigned char * comp); + +/* +============================================================= + +ANIMATED MODELS + +============================================================= +*/ + +void R_MDRAddAnimSurfaces( trRefEntity_t *ent, int entityNum ); +void RB_MDRSurfaceAnim( mdrSurface_t *surface ); +qboolean R_LoadIQM (model_t *mod, void *buffer, int filesize, const char *name ); +void R_AddIQMSurfaces( trRefEntity_t *ent, int entityNum ); +void RB_IQMSurfaceAnim( surfaceType_t *surface ); +int R_IQMLerpTag( orientation_t *tag, iqmData_t *data, + int startFrame, int endFrame, + float frac, const char *tagName ); + +/* +Ghoul2 Insert Start +*/ +#ifdef _MSC_VER +#pragma warning (disable: 4512) //default assignment operator could not be gened +#endif +class CRenderableSurface +{ +public: + // ident of this surface - required so the materials renderer knows what + // sort of surface this refers to + int ident; + + CBoneCache *boneCache; + mdxmVBOMesh_t *vboMesh; + + // tell the renderer to render shadows for this surface + qboolean genShadows; + int dlightBits; + int pshadowBits; + + // pointer to surface data loaded into file - only used by client renderer + // DO NOT USE IN GAME SIDE - if there is a vid restart this will be out of + // wack on the game + mdxmSurface_t *surfaceData; + +#ifdef _G2_GORE + // alternate texture coordinates + srfG2GoreSurface_t *alternateTex; + void *goreChain; + + float scale; + float fade; + + // this is a number between 0 and 1 that dictates the progression of the + // bullet impact + float impactTime; +#endif + + CRenderableSurface& operator =( const CRenderableSurface& src ) + { + ident = src.ident; + boneCache = src.boneCache; + surfaceData = src.surfaceData; +#ifdef _G2_GORE + alternateTex = src.alternateTex; + goreChain = src.goreChain; +#endif + vboMesh = src.vboMesh; + + return *this; + } + + CRenderableSurface() + : ident(SF_MDX) + , boneCache(nullptr) + , vboMesh(nullptr) + , surfaceData(nullptr) +#ifdef _G2_GORE + , alternateTex(nullptr) + , goreChain(nullptr) + , scale(1.0f) + , fade(0.0f) + , impactTime(0.0f) +#endif + { + } + + void Init() + { + ident = SF_MDX; + boneCache = nullptr; + surfaceData = nullptr; +#ifdef _G2_GORE + alternateTex = nullptr; + goreChain = nullptr; +#endif + vboMesh = nullptr; + genShadows = qfalse; + } +}; + +void R_AddGhoulSurfaces( trRefEntity_t *ent, int entityNum ); +void RB_SurfaceGhoul( CRenderableSurface *surf ); +void RB_TransformBones(const trRefEntity_t *ent, const trRefdef_t *refdef, int currentFrameNum, gpuFrame_t *frame); +int RB_GetBoneUboOffset(CRenderableSurface *surf); +void RB_SetBoneUboOffset(CRenderableSurface *surf, int offset, int currentFrameNum); +void RB_FillBoneBlock(CRenderableSurface *surf, mat3x4_t *outMatrices); +/* +Ghoul2 Insert End +*/ + +/* +============================================================= +============================================================= +*/ +void R_TransformModelToClip( const vec3_t src, const float *modelViewMatrix, const float *projectionMatrix, + vec4_t eye, vec4_t dst ); +void R_TransformClipToWindow( const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window ); + +void RB_DeformTessGeometry( void ); + +void RB_CalcFogTexCoords( float *dstTexCoords ); + +void RB_CalcScaleTexMatrix( const float scale[2], float *matrix ); +void RB_CalcScrollTexMatrix( const float scrollSpeed[2], float *matrix ); +void RB_CalcRotateTexMatrix( float degsPerSecond, float *matrix ); +void RB_CalcTurbulentFactors( const waveForm_t *wf, float *amplitude, float *now ); +void RB_CalcTransformTexMatrix( const texModInfo_t *tmi, float *matrix ); +void RB_CalcStretchTexMatrix( const waveForm_t *wf, float *matrix ); + +void RB_CalcModulateColorsByFog( unsigned char *dstColors ); +float RB_CalcWaveAlphaSingle( const waveForm_t *wf ); +float RB_CalcWaveColorSingle( const waveForm_t *wf ); + +/* +============================================================= + +RENDERER BACK END FUNCTIONS + +============================================================= +*/ + +void RB_ExecuteRenderCommands( const void *data ); + +/* +============================================================= + +RENDERER BACK END COMMAND QUEUE + +============================================================= +*/ + +#define MAX_RENDER_COMMANDS 0x80000 + +typedef struct renderCommandList_s { + byte cmds[MAX_RENDER_COMMANDS]; + int used; +} renderCommandList_t; + +typedef struct setColorCommand_s { + int commandId; + float color[4]; +} setColorCommand_t; + +typedef struct drawBufferCommand_s { + int commandId; + int buffer; +} drawBufferCommand_t; + +typedef struct subImageCommand_s { + int commandId; + image_t *image; + int width; + int height; + void *data; +} subImageCommand_t; + +typedef struct swapBuffersCommand_s { + int commandId; +} swapBuffersCommand_t; + +typedef struct endFrameCommand_s { + int commandId; + int buffer; +} endFrameCommand_t; + +typedef struct stretchPicCommand_s { + int commandId; + shader_t *shader; + float x, y; + float w, h; + float s1, t1; + float s2, t2; +} stretchPicCommand_t; + +typedef struct rotatePicCommand_s { + int commandId; + shader_t *shader; + float x, y; + float w, h; + float s1, t1; + float s2, t2; + float a; +} rotatePicCommand_t; + +typedef struct drawSurfsCommand_s { + int commandId; + trRefdef_t refdef; + viewParms_t viewParms; + drawSurf_t *drawSurfs; + int numDrawSurfs; +} drawSurfsCommand_t; + +typedef enum { + SSF_JPEG, + SSF_TGA, + SSF_PNG +} screenshotFormat_t; + +typedef struct screenShotCommand_s { + int commandId; + int x; + int y; + int width; + int height; + char *fileName; + screenshotFormat_t format; +} screenshotCommand_t; + +typedef struct videoFrameCommand_s { + int commandId; + int width; + int height; + byte *captureBuffer; + byte *encodeBuffer; + qboolean motionJpeg; +} videoFrameCommand_t; + +typedef struct colorMaskCommand_s { + int commandId; + + GLboolean rgba[4]; +} colorMaskCommand_t; + +typedef struct clearDepthCommand_s { + int commandId; +} clearDepthCommand_t; + +typedef struct convolveCubemapCommand_s { + int commandId; + cubemap_t *cubemap; + int cubemapId; +} convolveCubemapCommand_t; + +typedef struct postProcessCommand_s { + int commandId; + trRefdef_t refdef; + viewParms_t viewParms; +} postProcessCommand_t; + +typedef struct beginTimedBlockCommand_s { + int commandId; + qhandle_t timerHandle; + const char *name; +} beginTimedBlockCommand_t; + +typedef struct endTimedBlockCommand_s { + int commandId; + qhandle_t timerHandle; +} endTimedBlockCommand_t; + +typedef enum { + RC_END_OF_LIST, + RC_SET_COLOR, + RC_STRETCH_PIC, + RC_ROTATE_PIC, + RC_ROTATE_PIC2, + RC_DRAW_SURFS, + RC_DRAW_BUFFER, + RC_SWAP_BUFFERS, + RC_SCREENSHOT, + RC_VIDEOFRAME, + RC_COLORMASK, + RC_CLEARDEPTH, + RC_CONVOLVECUBEMAP, + RC_POSTPROCESS, + RC_BEGIN_TIMED_BLOCK, + RC_END_TIMED_BLOCK +} renderCommand_t; + +struct gpuTimer_t +{ + const char *name; + GLuint queryName; +}; + +struct gpuTimedBlock_t +{ + const char *name; + GLuint beginTimer; + GLuint endTimer; +}; + +struct screenshotReadback_t +{ + GLuint pbo; + int strideInBytes; + int rowInBytes; + int width; + int height; + screenshotFormat_t format; + char filename[MAX_QPATH]; +}; + +#define MAX_GPU_TIMERS (512) +struct gpuFrame_t +{ + GLsync sync; + GLuint ubo; + size_t uboWriteOffset; + size_t uboSize; + size_t uboMapBase; + void *uboMemory; + + screenshotReadback_t screenshotReadback; + + VBO_t *dynamicVbo; + void *dynamicVboMemory; + size_t dynamicVboWriteOffset; + size_t dynamicVboCommitOffset; + + IBO_t *dynamicIbo; + void *dynamicIboMemory; + size_t dynamicIboWriteOffset; + size_t dynamicIboCommitOffset; + + int numTimers; + int numTimedBlocks; + + gpuTimer_t timers[MAX_GPU_TIMERS]; + gpuTimedBlock_t timedBlocks[MAX_GPU_TIMERS / 2]; // Each block will need 2 timer queries. +}; + +// all of the information needed by the back end must be +// contained in a backEndData_t. +#define MAX_FRAMES (2) +#define PER_FRAME_MEMORY_BYTES (32 * 1024 * 1024) +class Allocator; +struct Pass; +typedef struct backEndData_s { + unsigned realFrameNumber; + gpuFrame_t frames[MAX_FRAMES]; + gpuFrame_t *currentFrame; + Allocator *perFrameMemory; + Pass *currentPass; + + drawSurf_t drawSurfs[MAX_DRAWSURFS]; + dlight_t dlights[MAX_DLIGHTS]; + trRefEntity_t entities[MAX_REFENTITIES]; + srfPoly_t *polys;//[MAX_POLYS]; + polyVert_t *polyVerts;//[MAX_POLYVERTS]; + pshadow_t pshadows[MAX_CALC_PSHADOWS]; + renderCommandList_t commands; +} backEndData_t; + +extern int max_polys; +extern int max_polyverts; + +extern backEndData_t *backEndData; + + +void *R_GetCommandBuffer( int bytes ); +void RB_ExecuteRenderCommands( const void *data ); + +void R_IssuePendingRenderCommands( void ); + +void R_AddDrawSurfCmd( drawSurf_t *drawSurfs, int numDrawSurfs ); +void R_AddConvolveCubemapCmd(cubemap_t *cubemap, int cubemapId); +void R_AddPostProcessCmd (void); +qhandle_t R_BeginTimedBlockCmd( const char *name ); +void R_EndTimedBlockCmd( qhandle_t timerHandle ); + + +void RE_SetColor( const float *rgba ); +void RE_StretchPic ( float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader ); +void RE_RotatePic ( float x, float y, float w, float h, float s1, float t1, float s2, float t2, float a, qhandle_t hShader ); +void RE_RotatePic2 ( float x, float y, float w, float h, float s1, float t1, float s2, float t2,float a, qhandle_t hShader ); +void RE_BeginFrame( stereoFrame_t stereoFrame ); +void R_NewFrameSync(); +void RE_EndFrame( int *frontEndMsec, int *backEndMsec ); +void RE_TakeVideoFrame( int width, int height, + byte *captureBuffer, byte *encodeBuffer, qboolean motionJpeg ); + +// tr_ghoul2.cpp +void Mat3x4_Multiply(mdxaBone_t *out, const mdxaBone_t *in2, const mdxaBone_t *in); +void Mat3x4_Scale( mdxaBone_t *result, const mdxaBone_t *lhs, const float scale ); +void Mat3x4_Lerp( + mdxaBone_t *result, + const mdxaBone_t *lhs, + const mdxaBone_t *rhs, + const float t ); +const mdxaBone_t operator +( const mdxaBone_t& lhs, const mdxaBone_t& rhs ); +const mdxaBone_t operator -( const mdxaBone_t& lhs, const mdxaBone_t& rhs ); +const mdxaBone_t operator *( const mdxaBone_t& lhs, const mdxaBone_t& rhs ); +const mdxaBone_t operator *( const mdxaBone_t& lhs, const float scale ); +const mdxaBone_t operator *( const float scale, const mdxaBone_t& rhs ); + +qboolean R_LoadMDXM( model_t *mod, void *buffer, const char *name, qboolean &bAlreadyCached ); +qboolean R_LoadMDXA( model_t *mod, void *buffer, const char *name, qboolean &bAlreadyCached ); +void RE_InsertModelIntoHash( const char *name, model_t *mod ); +void ResetGhoul2RenderableSurfaceHeap(); + +void R_InitDecals( void ); +void RE_ClearDecals( void ); +void RE_AddDecalToScene ( qhandle_t shader, const vec3_t origin, const vec3_t dir, float orientation, float r, float g, float b, float a, qboolean alphaFade, float radius, qboolean temporary ); +void R_AddDecals( void ); + +image_t *R_FindImageFile( const char *name, imgType_t type, int flags ); +void R_LoadPackedMaterialImage(shaderStage_t *stage, const char *packedImageName, int flags); +image_t *R_BuildSDRSpecGlossImage(shaderStage_t *stage, const char *specImageName, int flags); +qhandle_t RE_RegisterShader( const char *name ); +qhandle_t RE_RegisterShaderNoMip( const char *name ); +const char *RE_ShaderNameFromIndex(int index); +image_t *R_CreateImage( const char *name, byte *pic, int width, int height, imgType_t type, int flags, int internalFormat ); + +float ProjectRadius( float r, vec3_t location ); +void RE_RegisterModels_StoreShaderRequest(const char *psModelFileName, const char *psShaderName, int *piShaderIndexPoke); +qboolean ShaderHashTableExists(void); +void R_ImageLoader_Init(void); + +class Allocator; +GPUProgramDesc ParseProgramSource( Allocator& allocator, const char *text ); + +struct DepthRange +{ + float minDepth; + float maxDepth; +}; + +struct SamplerBinding +{ + image_t *image; + qhandle_t videoMapHandle; + uint8_t slot; +}; + +struct UniformBlockBinding +{ + GLuint ubo; + int offset; + uniformBlock_t block; +}; + +enum DrawCommandType +{ + DRAW_COMMAND_MULTI_INDEXED, + DRAW_COMMAND_INDEXED, + DRAW_COMMAND_ARRAYS +}; + +struct DrawCommand +{ + DrawCommandType type; + GLenum primitiveType; + int numInstances; + + union DrawParams + { + struct MultiDrawIndexed + { + int numDraws; + GLsizei *numIndices; + glIndex_t **firstIndices; + } multiIndexed; + + struct DrawIndexed + { + GLenum indexType; + GLsizei numIndices; + glIndex_t firstIndex; + glIndex_t baseVertex; + } indexed; + + struct DrawArrays + { + glIndex_t firstVertex; + GLsizei numVertices; + } arrays; + } params; +}; + +struct RenderState +{ + DepthRange depthRange; + uint32_t stateBits; + uint32_t cullType; // this is stupid + + bool transformFeedback; +}; + +struct DrawItem +{ + RenderState renderState; + + IBO_t *ibo; + shaderProgram_t *program; + + uint32_t numAttributes; + vertexAttribute_t *attributes; + + uint32_t numSamplerBindings; + SamplerBinding *samplerBindings; + + uint32_t numUniformBlockBindings; + UniformBlockBinding *uniformBlockBindings; + + bufferBinding_t transformFeedbackBuffer; + + UniformData *uniformData; + + DrawCommand draw; +}; + +void DrawItemSetSamplerBindings( + DrawItem& drawItem, + const SamplerBinding *bindings, + uint32_t count, + Allocator& allocator); +void DrawItemSetUniformBlockBindings( + DrawItem& drawItem, + const UniformBlockBinding *bindings, + uint32_t count, + Allocator& allocator); +void DrawItemSetVertexAttributes( + DrawItem& drawItem, + const vertexAttribute_t *attributes, + uint32_t count, + Allocator& allocator); + +template +void DrawItemSetUniformBlockBindings( + DrawItem& drawItem, + const UniformBlockBinding(&bindings)[N], + Allocator& allocator) +{ + DrawItemSetUniformBlockBindings(drawItem, &bindings[0], N, allocator); +} + +class UniformDataWriter +{ +public: + UniformDataWriter(); + + void Start( shaderProgram_t *sp ); + + UniformDataWriter& SetUniformInt( uniform_t uniform, int value ); + UniformDataWriter& SetUniformFloat( uniform_t uniform, float value ); + UniformDataWriter& SetUniformFloat( uniform_t uniform, float *values, size_t count ); + + UniformDataWriter& SetUniformVec2( uniform_t uniform, float x, float y ); + UniformDataWriter& SetUniformVec2( uniform_t uniform, const float *values, size_t count = 1 ); + + UniformDataWriter& SetUniformVec3( uniform_t uniform, float x, float y, float z ); + UniformDataWriter& SetUniformVec3( uniform_t uniform, const float *values, size_t count = 1 ); + + UniformDataWriter& SetUniformVec4( uniform_t uniform, float x, float y, float z, float w ); + UniformDataWriter& SetUniformVec4( uniform_t uniform, const float *values, size_t count = 1 ); + + UniformDataWriter& SetUniformMatrix4x3( uniform_t uniform, const float *matrix, size_t count = 1 ); + UniformDataWriter& SetUniformMatrix4x4( uniform_t uniform, const float *matrix, size_t count = 1 ); + + UniformData *Finish( Allocator& destHeap ); + +private: + bool failed; + shaderProgram_t *shaderProgram; + char scratchBuffer[2048]; + Allocator scratch; +}; + +class SamplerBindingsWriter +{ +public: + SamplerBindingsWriter(); + + SamplerBindingsWriter( const SamplerBindingsWriter& ) = delete; + SamplerBindingsWriter& operator=( const SamplerBindingsWriter& ) = delete; + + SamplerBindingsWriter& AddStaticImage( image_t *image, int unit ); + + SamplerBindingsWriter& AddAnimatedImage( textureBundle_t *bundle, int unit ); + + SamplerBinding *Finish( Allocator& destHeap, uint32_t* numBindings ); + +private: + SamplerBinding scratch[32]; + bool failed; + int count; +}; + +void RB_FillDrawCommand( + DrawCommand& drawCmd, + GLenum primitiveType, + int numInstances, + const shaderCommands_t *input +); + +uint32_t RB_CreateSortKey( const DrawItem& item, int stage, int layer ); +void RB_AddDrawItem( Pass *pass, uint32_t sortKey, const DrawItem& drawItem ); +DepthRange RB_GetDepthRange( const trRefEntity_t *re, const shader_t *shader ); + +#endif //TR_LOCAL_H diff --git a/codemp/rd-rend2/tr_main.cpp b/codemp/rd-rend2/tr_main.cpp new file mode 100644 index 0000000000..8245479073 --- /dev/null +++ b/codemp/rd-rend2/tr_main.cpp @@ -0,0 +1,3037 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_main.c -- main control flow for each frame + +#include "tr_local.h" +#include "tr_weather.h" + +#include // memcpy + +#include "ghoul2/g2_local.h" + +trGlobals_t tr; + +static float s_flipMatrix[16] = { + // convert from our coordinate system (looking down X) + // to OpenGL's coordinate system (looking down -Z) + 0, 0, -1, 0, + -1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 0, 1 +}; + + +refimport_t ri; + +// entities that will have procedurally generated surfaces will just +// point at this for their sorting surface +surfaceType_t entitySurface = SF_ENTITY; + +/* +================ +R_CompareVert +================ +*/ +qboolean R_CompareVert(srfVert_t * v1, srfVert_t * v2, qboolean checkST) +{ + int i; + + for (i = 0; i < 3; i++) + { + if (floor(v1->xyz[i] + 0.1) != floor(v2->xyz[i] + 0.1)) + { + return qfalse; + } + + if (checkST && ((v1->st[0] != v2->st[0]) || (v1->st[1] != v2->st[1]))) + { + return qfalse; + } + } + + return qtrue; +} + +/* +============= +R_CalcNormalForTriangle +============= +*/ +void R_CalcNormalForTriangle(vec3_t normal, const vec3_t v0, const vec3_t v1, const vec3_t v2) +{ + vec3_t udir, vdir; + + // compute the face normal based on vertex points + VectorSubtract(v2, v0, udir); + VectorSubtract(v1, v0, vdir); + CrossProduct(udir, vdir, normal); + + VectorNormalize(normal); +} + +/* +============= +R_CalcTangentsForTriangle +http://members.rogers.com/deseric/tangentspace.htm +============= +*/ +void R_CalcTangentsForTriangle(vec3_t tangent, vec3_t bitangent, + const vec3_t v0, const vec3_t v1, const vec3_t v2, + const vec2_t t0, const vec2_t t1, const vec2_t t2) +{ + int i; + vec3_t planes[3]; + vec3_t u, v; + + for(i = 0; i < 3; i++) + { + VectorSet(u, v1[i] - v0[i], t1[0] - t0[0], t1[1] - t0[1]); + VectorSet(v, v2[i] - v0[i], t2[0] - t0[0], t2[1] - t0[1]); + + VectorNormalize(u); + VectorNormalize(v); + + CrossProduct(u, v, planes[i]); + } + + //So your tangent space will be defined by this : + //Normal = Normal of the triangle or Tangent X Bitangent (careful with the cross product, + // you have to make sure the normal points in the right direction) + //Tangent = ( dp(Fx(s,t)) / ds, dp(Fy(s,t)) / ds, dp(Fz(s,t)) / ds ) or ( -Bx/Ax, -By/Ay, - Bz/Az ) + //Bitangent = ( dp(Fx(s,t)) / dt, dp(Fy(s,t)) / dt, dp(Fz(s,t)) / dt ) or ( -Cx/Ax, -Cy/Ay, -Cz/Az ) + + // tangent... + tangent[0] = -planes[0][1] / planes[0][0]; + tangent[1] = -planes[1][1] / planes[1][0]; + tangent[2] = -planes[2][1] / planes[2][0]; + VectorNormalize(tangent); + + // bitangent... + bitangent[0] = -planes[0][2] / planes[0][0]; + bitangent[1] = -planes[1][2] / planes[1][0]; + bitangent[2] = -planes[2][2] / planes[2][0]; + VectorNormalize(bitangent); +} + + + + +/* +============= +R_CalcTangentSpace +============= +*/ +void R_CalcTangentSpace(vec3_t tangent, vec3_t bitangent, vec3_t normal, + const vec3_t v0, const vec3_t v1, const vec3_t v2, const vec2_t t0, const vec2_t t1, const vec2_t t2) +{ + vec3_t cp, u, v; + vec3_t faceNormal; + + VectorSet(u, v1[0] - v0[0], t1[0] - t0[0], t1[1] - t0[1]); + VectorSet(v, v2[0] - v0[0], t2[0] - t0[0], t2[1] - t0[1]); + + CrossProduct(u, v, cp); + if(fabs(cp[0]) > 10e-6) + { + tangent[0] = -cp[1] / cp[0]; + bitangent[0] = -cp[2] / cp[0]; + } + + u[0] = v1[1] - v0[1]; + v[0] = v2[1] - v0[1]; + + CrossProduct(u, v, cp); + if(fabs(cp[0]) > 10e-6) + { + tangent[1] = -cp[1] / cp[0]; + bitangent[1] = -cp[2] / cp[0]; + } + + u[0] = v1[2] - v0[2]; + v[0] = v2[2] - v0[2]; + + CrossProduct(u, v, cp); + if(fabs(cp[0]) > 10e-6) + { + tangent[2] = -cp[1] / cp[0]; + bitangent[2] = -cp[2] / cp[0]; + } + + VectorNormalize(tangent); + VectorNormalize(bitangent); + + // compute the face normal based on vertex points + if ( normal[0] == 0.0f && normal[1] == 0.0f && normal[2] == 0.0f ) + { + VectorSubtract(v2, v0, u); + VectorSubtract(v1, v0, v); + CrossProduct(u, v, faceNormal); + } + else + { + VectorCopy(normal, faceNormal); + } + + VectorNormalize(faceNormal); + +#if 1 + // Gram-Schmidt orthogonalize + //tangent[a] = (t - n * Dot(n, t)).Normalize(); + VectorMA(tangent, -DotProduct(faceNormal, tangent), faceNormal, tangent); + VectorNormalize(tangent); + + // compute the cross product B=NxT + //CrossProduct(normal, tangent, bitangent); +#else + // normal, compute the cross product N=TxB + CrossProduct(tangent, bitangent, normal); + VectorNormalize(normal); + + if(DotProduct(normal, faceNormal) < 0) + { + //VectorInverse(normal); + //VectorInverse(tangent); + //VectorInverse(bitangent); + + // compute the cross product T=BxN + CrossProduct(bitangent, faceNormal, tangent); + + // compute the cross product B=NxT + //CrossProduct(normal, tangent, bitangent); + } +#endif + + VectorCopy(faceNormal, normal); +} + +void R_CalcTangentSpaceFast(vec3_t tangent, vec3_t bitangent, vec3_t normal, + const vec3_t v0, const vec3_t v1, const vec3_t v2, const vec2_t t0, const vec2_t t1, const vec2_t t2) +{ + vec3_t cp, u, v; + vec3_t faceNormal; + + VectorSet(u, v1[0] - v0[0], t1[0] - t0[0], t1[1] - t0[1]); + VectorSet(v, v2[0] - v0[0], t2[0] - t0[0], t2[1] - t0[1]); + + CrossProduct(u, v, cp); + if(fabs(cp[0]) > 10e-6) + { + tangent[0] = -cp[1] / cp[0]; + bitangent[0] = -cp[2] / cp[0]; + } + + u[0] = v1[1] - v0[1]; + v[0] = v2[1] - v0[1]; + + CrossProduct(u, v, cp); + if(fabs(cp[0]) > 10e-6) + { + tangent[1] = -cp[1] / cp[0]; + bitangent[1] = -cp[2] / cp[0]; + } + + u[0] = v1[2] - v0[2]; + v[0] = v2[2] - v0[2]; + + CrossProduct(u, v, cp); + if(fabs(cp[0]) > 10e-6) + { + tangent[2] = -cp[1] / cp[0]; + bitangent[2] = -cp[2] / cp[0]; + } + + VectorNormalizeFast(tangent); + VectorNormalizeFast(bitangent); + + // compute the face normal based on vertex points + VectorSubtract(v2, v0, u); + VectorSubtract(v1, v0, v); + CrossProduct(u, v, faceNormal); + + VectorNormalizeFast(faceNormal); + +#if 0 + // normal, compute the cross product N=TxB + CrossProduct(tangent, bitangent, normal); + VectorNormalizeFast(normal); + + if(DotProduct(normal, faceNormal) < 0) + { + VectorInverse(normal); + //VectorInverse(tangent); + //VectorInverse(bitangent); + + CrossProduct(normal, tangent, bitangent); + } + + VectorCopy(faceNormal, normal); +#else + // Gram-Schmidt orthogonalize + //tangent[a] = (t - n * Dot(n, t)).Normalize(); + VectorMA(tangent, -DotProduct(faceNormal, tangent), faceNormal, tangent); + VectorNormalizeFast(tangent); +#endif + + VectorCopy(faceNormal, normal); +} + +/* +http://www.terathon.com/code/tangent.html +*/ +void R_CalcTexDirs(vec3_t sdir, vec3_t tdir, const vec3_t v1, const vec3_t v2, + const vec3_t v3, const vec2_t w1, const vec2_t w2, const vec2_t w3) +{ + float x1, x2, y1, y2, z1, z2; + float s1, s2, t1, t2, r; + + x1 = v2[0] - v1[0]; + x2 = v3[0] - v1[0]; + y1 = v2[1] - v1[1]; + y2 = v3[1] - v1[1]; + z1 = v2[2] - v1[2]; + z2 = v3[2] - v1[2]; + + s1 = w2[0] - w1[0]; + s2 = w3[0] - w1[0]; + t1 = w2[1] - w1[1]; + t2 = w3[1] - w1[1]; + + r = 1.0f / (s1 * t2 - s2 * t1); + + VectorSet(sdir, (t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); + VectorSet(tdir, (s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); +} + +void R_CalcTbnFromNormalAndTexDirs(vec3_t tangent, vec3_t bitangent, vec3_t normal, vec3_t sdir, vec3_t tdir) +{ + vec3_t n_cross_t; + float n_dot_t, handedness; + + // Gram-Schmidt orthogonalize + n_dot_t = DotProduct(normal, sdir); + VectorMA(sdir, -n_dot_t, normal, tangent); + VectorNormalize(tangent); + + // Calculate handedness + CrossProduct(normal, sdir, n_cross_t); + handedness = (DotProduct(n_cross_t, tdir) < 0.0f) ? -1.0f : 1.0f; + + // Calculate bitangent + CrossProduct(normal, tangent, bitangent); + VectorScale(bitangent, handedness, bitangent); +} + +qboolean R_CalcTangentVectors(srfVert_t * dv[3]) +{ + int i; + float bb, s, t; + vec3_t bary; + + + /* calculate barycentric basis for the triangle */ + bb = (dv[1]->st[0] - dv[0]->st[0]) * (dv[2]->st[1] - dv[0]->st[1]) - (dv[2]->st[0] - dv[0]->st[0]) * (dv[1]->st[1] - dv[0]->st[1]); + if(fabs(bb) < 0.00000001f) + return qfalse; + + /* do each vertex */ + for(i = 0; i < 3; i++) + { + vec3_t bitangent, nxt; + + // calculate s tangent vector + s = dv[i]->st[0] + 10.0f; + t = dv[i]->st[1]; + bary[0] = ((dv[1]->st[0] - s) * (dv[2]->st[1] - t) - (dv[2]->st[0] - s) * (dv[1]->st[1] - t)) / bb; + bary[1] = ((dv[2]->st[0] - s) * (dv[0]->st[1] - t) - (dv[0]->st[0] - s) * (dv[2]->st[1] - t)) / bb; + bary[2] = ((dv[0]->st[0] - s) * (dv[1]->st[1] - t) - (dv[1]->st[0] - s) * (dv[0]->st[1] - t)) / bb; + + dv[i]->tangent[0] = bary[0] * dv[0]->xyz[0] + bary[1] * dv[1]->xyz[0] + bary[2] * dv[2]->xyz[0]; + dv[i]->tangent[1] = bary[0] * dv[0]->xyz[1] + bary[1] * dv[1]->xyz[1] + bary[2] * dv[2]->xyz[1]; + dv[i]->tangent[2] = bary[0] * dv[0]->xyz[2] + bary[1] * dv[1]->xyz[2] + bary[2] * dv[2]->xyz[2]; + + VectorSubtract(dv[i]->tangent, dv[i]->xyz, dv[i]->tangent); + VectorNormalize(dv[i]->tangent); + + // calculate t tangent vector + s = dv[i]->st[0]; + t = dv[i]->st[1] + 10.0f; + bary[0] = ((dv[1]->st[0] - s) * (dv[2]->st[1] - t) - (dv[2]->st[0] - s) * (dv[1]->st[1] - t)) / bb; + bary[1] = ((dv[2]->st[0] - s) * (dv[0]->st[1] - t) - (dv[0]->st[0] - s) * (dv[2]->st[1] - t)) / bb; + bary[2] = ((dv[0]->st[0] - s) * (dv[1]->st[1] - t) - (dv[1]->st[0] - s) * (dv[0]->st[1] - t)) / bb; + + bitangent[0] = bary[0] * dv[0]->xyz[0] + bary[1] * dv[1]->xyz[0] + bary[2] * dv[2]->xyz[0]; + bitangent[1] = bary[0] * dv[0]->xyz[1] + bary[1] * dv[1]->xyz[1] + bary[2] * dv[2]->xyz[1]; + bitangent[2] = bary[0] * dv[0]->xyz[2] + bary[1] * dv[1]->xyz[2] + bary[2] * dv[2]->xyz[2]; + + VectorSubtract(bitangent, dv[i]->xyz, bitangent); + VectorNormalize(bitangent); + + // store bitangent handedness + CrossProduct(dv[i]->normal, dv[i]->tangent, nxt); + dv[i]->tangent[3] = (DotProduct(nxt, bitangent) < 0.0f) ? -1.0f : 1.0f; + + // debug code + //% Sys_FPrintf( SYS_VRB, "%d S: (%f %f %f) T: (%f %f %f)\n", i, + //% stv[ i ][ 0 ], stv[ i ][ 1 ], stv[ i ][ 2 ], ttv[ i ][ 0 ], ttv[ i ][ 1 ], ttv[ i ][ 2 ] ); + } + + return qtrue; +} + +/* +================= +R_CullLocalBox + +Returns CULL_IN, CULL_CLIP, or CULL_OUT +================= +*/ +int R_CullLocalBox(vec3_t localBounds[2]) { +#if 0 + int i, j; + vec3_t transformed[8]; + float dists[8]; + vec3_t v; + cplane_t *frust; + int anyBack; + int front, back; + + if ( r_nocull->integer ) { + return CULL_CLIP; + } + + // transform into world space + for (i = 0 ; i < 8 ; i++) { + v[0] = bounds[i&1][0]; + v[1] = bounds[(i>>1)&1][1]; + v[2] = bounds[(i>>2)&1][2]; + + VectorCopy( tr.ori.origin, transformed[i] ); + VectorMA( transformed[i], v[0], tr.ori.axis[0], transformed[i] ); + VectorMA( transformed[i], v[1], tr.ori.axis[1], transformed[i] ); + VectorMA( transformed[i], v[2], tr.ori.axis[2], transformed[i] ); + } + + // check against frustum planes + anyBack = 0; + for (i = 0 ; i < 4 ; i++) { + frust = &tr.viewParms.frustum[i]; + + front = back = 0; + for (j = 0 ; j < 8 ; j++) { + dists[j] = DotProduct(transformed[j], frust->normal); + if ( dists[j] > frust->dist ) { + front = 1; + if ( back ) { + break; // a point is in front + } + } else { + back = 1; + } + } + if ( !front ) { + // all points were behind one of the planes + return CULL_OUT; + } + anyBack |= back; + } + + if ( !anyBack ) { + return CULL_IN; // completely inside frustum + } + + return CULL_CLIP; // partially clipped +#else + int j; + vec3_t transformed; + vec3_t v; + vec3_t worldBounds[2]; + + if(r_nocull->integer) + { + return CULL_CLIP; + } + + // transform into world space + ClearBounds(worldBounds[0], worldBounds[1]); + + for(j = 0; j < 8; j++) + { + v[0] = localBounds[j & 1][0]; + v[1] = localBounds[(j >> 1) & 1][1]; + v[2] = localBounds[(j >> 2) & 1][2]; + + R_LocalPointToWorld(v, transformed); + + AddPointToBounds(transformed, worldBounds[0], worldBounds[1]); + } + + return R_CullBox(worldBounds); +#endif +} + +/* +================= +R_CullBox + +Returns CULL_IN, CULL_CLIP, or CULL_OUT +================= +*/ +int R_CullBox(vec3_t worldBounds[2]) { + int i; + cplane_t *frust; + qboolean anyClip; + int r, numPlanes; + + numPlanes = (tr.viewParms.flags & VPF_FARPLANEFRUSTUM) ? 5 : 4; + + // check against frustum planes + anyClip = qfalse; + for(i = 0; i < numPlanes; i++) + { + frust = &tr.viewParms.frustum[i]; + + r = BoxOnPlaneSide(worldBounds[0], worldBounds[1], frust); + + if(r == 2) + { + // completely outside frustum + return CULL_OUT; + } + if(r == 3) + { + anyClip = qtrue; + } + } + + if(!anyClip) + { + // completely inside frustum + return CULL_IN; + } + + // partially clipped + return CULL_CLIP; +} + +/* +** R_CullLocalPointAndRadius +*/ +int R_CullLocalPointAndRadius( const vec3_t pt, float radius ) +{ + vec3_t transformed; + + R_LocalPointToWorld( pt, transformed ); + + return R_CullPointAndRadius( transformed, radius ); +} + +/* +** R_CullPointAndRadius +*/ +int R_CullPointAndRadiusEx( const vec3_t pt, float radius, const cplane_t* frustum, int numPlanes ) +{ + int i; + float dist; + const cplane_t *frust; + qboolean mightBeClipped = qfalse; + + if ( r_nocull->integer ) { + return CULL_CLIP; + } + + // check against frustum planes + for (i = 0 ; i < numPlanes ; i++) + { + frust = &frustum[i]; + + dist = DotProduct( pt, frust->normal) - frust->dist; + if ( dist < -radius ) + { + return CULL_OUT; + } + else if ( dist <= radius ) + { + mightBeClipped = qtrue; + } + } + + if ( mightBeClipped ) + { + return CULL_CLIP; + } + + return CULL_IN; // completely inside frustum +} + +/* +** R_CullPointAndRadius +*/ +int R_CullPointAndRadius( const vec3_t pt, float radius ) +{ + return R_CullPointAndRadiusEx(pt, radius, tr.viewParms.frustum, (tr.viewParms.flags & VPF_FARPLANEFRUSTUM) ? 5 : 4); +} + +/* +================= +R_LocalNormalToWorld + +================= +*/ +void R_LocalNormalToWorld (const vec3_t local, vec3_t world) { + world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0]; + world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1]; + world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2]; +} + +/* +================= +R_LocalPointToWorld + +================= +*/ +void R_LocalPointToWorld (const vec3_t local, vec3_t world) { + world[0] = local[0] * tr.ori.axis[0][0] + local[1] * tr.ori.axis[1][0] + local[2] * tr.ori.axis[2][0] + tr.ori.origin[0]; + world[1] = local[0] * tr.ori.axis[0][1] + local[1] * tr.ori.axis[1][1] + local[2] * tr.ori.axis[2][1] + tr.ori.origin[1]; + world[2] = local[0] * tr.ori.axis[0][2] + local[1] * tr.ori.axis[1][2] + local[2] * tr.ori.axis[2][2] + tr.ori.origin[2]; +} + +/* +================= +R_WorldToLocal + +================= +*/ +void R_WorldToLocal (const vec3_t world, vec3_t local) { + local[0] = DotProduct(world, tr.ori.axis[0]); + local[1] = DotProduct(world, tr.ori.axis[1]); + local[2] = DotProduct(world, tr.ori.axis[2]); +} + +/* +========================== +R_TransformModelToClip + +========================== +*/ +void R_TransformModelToClip( const vec3_t src, const float *modelViewMatrix, const float *projectionMatrix, + vec4_t eye, vec4_t dst ) { + int i; + + for ( i = 0 ; i < 4 ; i++ ) { + eye[i] = + src[0] * modelViewMatrix[ i + 0 * 4 ] + + src[1] * modelViewMatrix[ i + 1 * 4 ] + + src[2] * modelViewMatrix[ i + 2 * 4 ] + + 1 * modelViewMatrix[ i + 3 * 4 ]; + } + + for ( i = 0 ; i < 4 ; i++ ) { + dst[i] = + eye[0] * projectionMatrix[ i + 0 * 4 ] + + eye[1] * projectionMatrix[ i + 1 * 4 ] + + eye[2] * projectionMatrix[ i + 2 * 4 ] + + eye[3] * projectionMatrix[ i + 3 * 4 ]; + } +} + +/* +========================== +R_TransformClipToWindow + +========================== +*/ +void R_TransformClipToWindow( const vec4_t clip, const viewParms_t *view, vec4_t normalized, vec4_t window ) { + normalized[0] = clip[0] / clip[3]; + normalized[1] = clip[1] / clip[3]; + normalized[2] = ( clip[2] + clip[3] ) / ( 2 * clip[3] ); + + window[0] = 0.5f * ( 1.0f + normalized[0] ) * view->viewportWidth; + window[1] = 0.5f * ( 1.0f + normalized[1] ) * view->viewportHeight; + window[2] = normalized[2]; + + window[0] = (int) ( window[0] + 0.5 ); + window[1] = (int) ( window[1] + 0.5 ); +} + + +/* +========================== +myGlMultMatrix + +========================== +*/ +void myGlMultMatrix( const float *a, const float *b, float *out ) { + int i, j; + + for ( i = 0 ; i < 4 ; i++ ) { + for ( j = 0 ; j < 4 ; j++ ) { + out[ i * 4 + j ] = + a [ i * 4 + 0 ] * b [ 0 * 4 + j ] + + a [ i * 4 + 1 ] * b [ 1 * 4 + j ] + + a [ i * 4 + 2 ] * b [ 2 * 4 + j ] + + a [ i * 4 + 3 ] * b [ 3 * 4 + j ]; + } + } +} + +/* +================= +R_RotateForEntity + +Generates an orientation for an entity and viewParms +Does NOT produce any GL calls +Called by both the front end and the back end +================= +*/ +void R_RotateForEntity( const trRefEntity_t *ent, const viewParms_t *viewParms, + orientationr_t *ori ) +{ + vec3_t delta; + float axisLength; + + if ( ent->e.reType != RT_MODEL || ent == &tr.worldEntity ) { + *ori = viewParms->world; + return; + } + + VectorCopy( ent->e.origin, ori->origin ); + + VectorCopy( ent->e.axis[0], ori->axis[0] ); + VectorCopy( ent->e.axis[1], ori->axis[1] ); + VectorCopy( ent->e.axis[2], ori->axis[2] ); + + ori->modelMatrix[0] = ori->axis[0][0]; + ori->modelMatrix[4] = ori->axis[1][0]; + ori->modelMatrix[8] = ori->axis[2][0]; + ori->modelMatrix[12] = ori->origin[0]; + + ori->modelMatrix[1] = ori->axis[0][1]; + ori->modelMatrix[5] = ori->axis[1][1]; + ori->modelMatrix[9] = ori->axis[2][1]; + ori->modelMatrix[13] = ori->origin[1]; + + ori->modelMatrix[2] = ori->axis[0][2]; + ori->modelMatrix[6] = ori->axis[1][2]; + ori->modelMatrix[10] = ori->axis[2][2]; + ori->modelMatrix[14] = ori->origin[2]; + + ori->modelMatrix[3] = 0; + ori->modelMatrix[7] = 0; + ori->modelMatrix[11] = 0; + ori->modelMatrix[15] = 1; + + // calculate the viewer origin in the model's space + // needed for fog, specular, and environment mapping + VectorSubtract( viewParms->ori.origin, ori->origin, delta ); + + // compensate for scale in the axes if necessary + if ( ent->e.nonNormalizedAxes ) { + axisLength = VectorLength( ent->e.axis[0] ); + if ( !axisLength ) { + axisLength = 0; + } else { + axisLength = 1.0f / axisLength; + } + } else { + axisLength = 1.0f; + } + + ori->viewOrigin[0] = DotProduct( delta, ori->axis[0] ) * axisLength; + ori->viewOrigin[1] = DotProduct( delta, ori->axis[1] ) * axisLength; + ori->viewOrigin[2] = DotProduct( delta, ori->axis[2] ) * axisLength; +} + +/* +================= +R_RotateForViewer + +Sets up the modelview matrix for a given viewParm +================= +*/ +static void R_RotateForViewer(orientationr_t *ori, viewParms_t *viewParms) +{ + float viewerMatrix[16]; + vec3_t origin; + + *ori = {}; + ori->axis[0][0] = 1.0f; + ori->axis[1][1] = 1.0f; + ori->axis[2][2] = 1.0f; + VectorCopy(viewParms->ori.origin, ori->viewOrigin); + + // transform by the camera placement + VectorCopy(viewParms->ori.origin, origin); + + viewerMatrix[0] = viewParms->ori.axis[0][0]; + viewerMatrix[4] = viewParms->ori.axis[0][1]; + viewerMatrix[8] = viewParms->ori.axis[0][2]; + viewerMatrix[12] = -origin[0] * viewerMatrix[0] + -origin[1] * viewerMatrix[4] + -origin[2] * viewerMatrix[8]; + + viewerMatrix[1] = viewParms->ori.axis[1][0]; + viewerMatrix[5] = viewParms->ori.axis[1][1]; + viewerMatrix[9] = viewParms->ori.axis[1][2]; + viewerMatrix[13] = -origin[0] * viewerMatrix[1] + -origin[1] * viewerMatrix[5] + -origin[2] * viewerMatrix[9]; + + viewerMatrix[2] = viewParms->ori.axis[2][0]; + viewerMatrix[6] = viewParms->ori.axis[2][1]; + viewerMatrix[10] = viewParms->ori.axis[2][2]; + viewerMatrix[14] = -origin[0] * viewerMatrix[2] + -origin[1] * viewerMatrix[6] + -origin[2] * viewerMatrix[10]; + + viewerMatrix[3] = 0; + viewerMatrix[7] = 0; + viewerMatrix[11] = 0; + viewerMatrix[15] = 1; + + // convert from our coordinate system (looking down X) + // to OpenGL's coordinate system (looking down -Z) + myGlMultMatrix(viewerMatrix, s_flipMatrix, ori->modelViewMatrix); + Matrix16Identity(ori->modelMatrix); +} + +/* +** SetFarClip +*/ +static void R_SetFarClip( viewParms_t *viewParms, const trRefdef_t *refdef ) +{ + float farthestCornerDistance = 0; + int i; + + // if not rendering the world (icons, menus, etc) + // set a 2k far clip plane + if (refdef != NULL) + { + if (refdef->rdflags & RDF_NOWORLDMODEL) { + // override the zfar then + if (refdef->rdflags & RDF_AUTOMAP) + viewParms->zFar = 32768.0f; + else + viewParms->zFar = 2048.0f; + return; + } + } + + // + // set far clipping planes dynamically + // + for ( i = 0; i < 8; i++ ) + { + vec3_t v; + float distance; + + if ( i & 1 ) + { + v[0] = viewParms->visBounds[0][0]; + } + else + { + v[0] = viewParms->visBounds[1][0]; + } + + if ( i & 2 ) + { + v[1] = viewParms->visBounds[0][1]; + } + else + { + v[1] = viewParms->visBounds[1][1]; + } + + if ( i & 4 ) + { + v[2] = viewParms->visBounds[0][2]; + } + else + { + v[2] = viewParms->visBounds[1][2]; + } + + distance = DistanceSquared( viewParms->ori.origin, v ); + + if ( distance > farthestCornerDistance ) + { + farthestCornerDistance = distance; + } + } + + // Bring in the zFar to the distanceCull distance + // The sky renders at zFar so need to move it out a little + // ...and make sure there is a minimum zfar to prevent problems + viewParms->zFar = Com_Clamp(2048.0f, tr.distanceCull * (1.732), sqrtf( farthestCornerDistance )); +} + +/* +================= +R_SetupFrustum + +Set up the culling frustum planes for the current view using the results we got from computing the first two rows of +the projection matrix. +================= +*/ +void R_SetupFrustum (viewParms_t *dest, float xmin, float xmax, float ymax, float zProj, float zFar, float stereoSep) +{ + vec3_t ofsorigin; + float oppleg, adjleg, length; + int i; + + if(stereoSep == 0 && xmin == -xmax) + { + // symmetric case can be simplified + VectorCopy(dest->ori.origin, ofsorigin); + + length = sqrt(xmax * xmax + zProj * zProj); + oppleg = xmax / length; + adjleg = zProj / length; + + VectorScale(dest->ori.axis[0], oppleg, dest->frustum[0].normal); + VectorMA(dest->frustum[0].normal, adjleg, dest->ori.axis[1], dest->frustum[0].normal); + + VectorScale(dest->ori.axis[0], oppleg, dest->frustum[1].normal); + VectorMA(dest->frustum[1].normal, -adjleg, dest->ori.axis[1], dest->frustum[1].normal); + } + else + { + // In stereo rendering, due to the modification of the projection matrix, dest->ori.origin is not the + // actual origin that we're rendering so offset the tip of the view pyramid. + VectorMA(dest->ori.origin, stereoSep, dest->ori.axis[1], ofsorigin); + + oppleg = xmax + stereoSep; + length = sqrt(oppleg * oppleg + zProj * zProj); + VectorScale(dest->ori.axis[0], oppleg / length, dest->frustum[0].normal); + VectorMA(dest->frustum[0].normal, zProj / length, dest->ori.axis[1], dest->frustum[0].normal); + + oppleg = xmin + stereoSep; + length = sqrt(oppleg * oppleg + zProj * zProj); + VectorScale(dest->ori.axis[0], -oppleg / length, dest->frustum[1].normal); + VectorMA(dest->frustum[1].normal, -zProj / length, dest->ori.axis[1], dest->frustum[1].normal); + } + + length = sqrt(ymax * ymax + zProj * zProj); + oppleg = ymax / length; + adjleg = zProj / length; + + VectorScale(dest->ori.axis[0], oppleg, dest->frustum[2].normal); + VectorMA(dest->frustum[2].normal, adjleg, dest->ori.axis[2], dest->frustum[2].normal); + + VectorScale(dest->ori.axis[0], oppleg, dest->frustum[3].normal); + VectorMA(dest->frustum[3].normal, -adjleg, dest->ori.axis[2], dest->frustum[3].normal); + + for (i=0 ; i<4 ; i++) { + dest->frustum[i].type = PLANE_NON_AXIAL; + dest->frustum[i].dist = DotProduct (ofsorigin, dest->frustum[i].normal); + SetPlaneSignbits( &dest->frustum[i] ); + } + + if (zFar != 0.0f) + { + vec3_t farpoint; + + VectorMA(ofsorigin, zFar, dest->ori.axis[0], farpoint); + VectorScale(dest->ori.axis[0], -1.0f, dest->frustum[4].normal); + + dest->frustum[4].type = PLANE_NON_AXIAL; + dest->frustum[4].dist = DotProduct (farpoint, dest->frustum[4].normal); + SetPlaneSignbits( &dest->frustum[4] ); + dest->flags |= VPF_FARPLANEFRUSTUM; + } +} + +/* +=============== +R_SetupProjection +=============== +*/ +void R_SetupProjection(viewParms_t *dest, float zProj, float zFar, qboolean computeFrustum) +{ + float xmin, xmax, ymin, ymax; + float width, height, stereoSep = r_stereoSeparation->value; + + /* + * offset the view origin of the viewer for stereo rendering + * by setting the projection matrix appropriately. + */ + + if(stereoSep != 0) + { + if(dest->stereoFrame == STEREO_LEFT) + stereoSep = zProj / stereoSep; + else if(dest->stereoFrame == STEREO_RIGHT) + stereoSep = zProj / -stereoSep; + else + stereoSep = 0; + } + + ymax = zProj * tan(dest->fovY * M_PI / 360.0f); + ymin = -ymax; + + xmax = zProj * tan(dest->fovX * M_PI / 360.0f); + xmin = -xmax; + + width = xmax - xmin; + height = ymax - ymin; + + dest->projectionMatrix[0] = 2 * zProj / width; + dest->projectionMatrix[4] = 0; + dest->projectionMatrix[8] = (xmax + xmin + 2 * stereoSep) / width; + dest->projectionMatrix[12] = 2 * zProj * stereoSep / width; + + dest->projectionMatrix[1] = 0; + dest->projectionMatrix[5] = 2 * zProj / height; + dest->projectionMatrix[9] = ( ymax + ymin ) / height; // normally 0 + dest->projectionMatrix[13] = 0; + + dest->projectionMatrix[3] = 0; + dest->projectionMatrix[7] = 0; + dest->projectionMatrix[11] = -1; + dest->projectionMatrix[15] = 0; + + // Now that we have all the data for the projection matrix we can also setup the view frustum. + if(computeFrustum) + R_SetupFrustum(dest, xmin, xmax, ymax, zProj, zFar, stereoSep); +} + +/* +=============== +R_SetupProjectionZ + +Sets the z-component transformation part in the projection matrix +=============== +*/ +void R_SetupProjectionZ(viewParms_t *dest) +{ + float zNear, zFar, depth; + + zNear = dest->zNear * tr.widthRatioCoef; + zFar = dest->zFar; + + depth = zFar - zNear; + + dest->projectionMatrix[2] = 0; + dest->projectionMatrix[6] = 0; + dest->projectionMatrix[10] = -( zFar + zNear ) / depth; + dest->projectionMatrix[14] = -2 * zFar * zNear / depth; + + if (dest->isPortal) + { + float plane[4]; + float plane2[4]; + vec4_t q, c; + + // transform portal plane into camera space + plane[0] = dest->portalPlane.normal[0]; + plane[1] = dest->portalPlane.normal[1]; + plane[2] = dest->portalPlane.normal[2]; + plane[3] = dest->portalPlane.dist; + + plane2[0] = -DotProduct (dest->ori.axis[1], plane); + plane2[1] = DotProduct (dest->ori.axis[2], plane); + plane2[2] = -DotProduct (dest->ori.axis[0], plane); + plane2[3] = DotProduct (plane, dest->ori.origin) - plane[3]; + + // Lengyel, Eric. "Modifying the Projection Matrix to Perform Oblique Near-plane Clipping". + // Terathon Software 3D Graphics Library, 2004. http://www.terathon.com/code/oblique.html + q[0] = (SGN(plane2[0]) + dest->projectionMatrix[8]) / dest->projectionMatrix[0]; + q[1] = (SGN(plane2[1]) + dest->projectionMatrix[9]) / dest->projectionMatrix[5]; + q[2] = -1.0f; + q[3] = (1.0f + dest->projectionMatrix[10]) / dest->projectionMatrix[14]; + + VectorScale4(plane2, 2.0f / DotProduct4(plane2, q), c); + + dest->projectionMatrix[2] = c[0]; + dest->projectionMatrix[6] = c[1]; + dest->projectionMatrix[10] = c[2] + 1.0f; + dest->projectionMatrix[14] = c[3]; + } +} + +/* +=============== +R_SetupProjectionOrtho +=============== +*/ +void R_SetupProjectionOrtho(viewParms_t *dest, const vec3_t viewBounds[2]) +{ + float xmin, xmax, ymin, ymax, znear, zfar; + //viewParms_t *dest = &tr.viewParms; + int i; + vec3_t pop; + + // Quake3: Projection: + // + // Z X Y Z + // | / | / + // |/ |/ + // Y--+ +--X + + xmin = viewBounds[0][1]; + xmax = viewBounds[1][1]; + ymin = -viewBounds[1][2]; + ymax = -viewBounds[0][2]; + znear = viewBounds[0][0]; + zfar = viewBounds[1][0]; + + dest->projectionMatrix[0] = 2 / (xmax - xmin); + dest->projectionMatrix[4] = 0; + dest->projectionMatrix[8] = 0; + dest->projectionMatrix[12] = (xmax + xmin) / (xmax - xmin); + + dest->projectionMatrix[1] = 0; + dest->projectionMatrix[5] = 2 / (ymax - ymin); + dest->projectionMatrix[9] = 0; + dest->projectionMatrix[13] = (ymax + ymin) / (ymax - ymin); + + dest->projectionMatrix[2] = 0; + dest->projectionMatrix[6] = 0; + dest->projectionMatrix[10] = -2 / (zfar - znear); + dest->projectionMatrix[14] = -(zfar + znear) / (zfar - znear); + + dest->projectionMatrix[3] = 0; + dest->projectionMatrix[7] = 0; + dest->projectionMatrix[11] = 0; + dest->projectionMatrix[15] = 1; + + VectorScale(dest->ori.axis[1], 1.0f, dest->frustum[0].normal); + VectorMA(dest->ori.origin, viewBounds[0][1], dest->frustum[0].normal, pop); + dest->frustum[0].dist = DotProduct(pop, dest->frustum[0].normal); + + VectorScale(dest->ori.axis[1], -1.0f, dest->frustum[1].normal); + VectorMA(dest->ori.origin, -viewBounds[1][1], dest->frustum[1].normal, pop); + dest->frustum[1].dist = DotProduct(pop, dest->frustum[1].normal); + + VectorScale(dest->ori.axis[2], 1.0f, dest->frustum[2].normal); + VectorMA(dest->ori.origin, viewBounds[0][2], dest->frustum[2].normal, pop); + dest->frustum[2].dist = DotProduct(pop, dest->frustum[2].normal); + + VectorScale(dest->ori.axis[2], -1.0f, dest->frustum[3].normal); + VectorMA(dest->ori.origin, -viewBounds[1][2], dest->frustum[3].normal, pop); + dest->frustum[3].dist = DotProduct(pop, dest->frustum[3].normal); + + VectorScale(dest->ori.axis[0], -1.0f, dest->frustum[4].normal); + VectorMA(dest->ori.origin, -viewBounds[1][0], dest->frustum[4].normal, pop); + dest->frustum[4].dist = DotProduct(pop, dest->frustum[4].normal); + + for (i = 0; i < 5; i++) + { + dest->frustum[i].type = PLANE_NON_AXIAL; + SetPlaneSignbits (&dest->frustum[i]); + } + + dest->flags |= VPF_FARPLANEFRUSTUM; +} + +/* +================= +R_MirrorPoint +================= +*/ +void R_MirrorPoint (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { + int i; + vec3_t local; + vec3_t transformed; + float d; + + VectorSubtract( in, surface->origin, local ); + + VectorClear( transformed ); + for ( i = 0 ; i < 3 ; i++ ) { + d = DotProduct(local, surface->axis[i]); + VectorMA( transformed, d, camera->axis[i], transformed ); + } + + VectorAdd( transformed, camera->origin, out ); +} + +void R_MirrorVector (vec3_t in, orientation_t *surface, orientation_t *camera, vec3_t out) { + int i; + float d; + + VectorClear( out ); + for ( i = 0 ; i < 3 ; i++ ) { + d = DotProduct(in, surface->axis[i]); + VectorMA( out, d, camera->axis[i], out ); + } +} + + +/* +============= +R_PlaneForSurface +============= +*/ +void R_PlaneForSurface (surfaceType_t *surfType, cplane_t *plane) { + srfBspSurface_t *tri; + srfPoly_t *poly; + srfVert_t *v1, *v2, *v3; + vec4_t plane4; + + if (!surfType) { + Com_Memset (plane, 0, sizeof(*plane)); + plane->normal[0] = 1; + return; + } + switch (*surfType) { + case SF_FACE: + *plane = ((srfBspSurface_t *)surfType)->cullPlane; + return; + case SF_TRIANGLES: + tri = (srfBspSurface_t *)surfType; + v1 = tri->verts + tri->indexes[0]; + v2 = tri->verts + tri->indexes[1]; + v3 = tri->verts + tri->indexes[2]; + PlaneFromPoints( plane4, v1->xyz, v2->xyz, v3->xyz ); + VectorCopy( plane4, plane->normal ); + plane->dist = plane4[3]; + return; + case SF_POLY: + poly = (srfPoly_t *)surfType; + PlaneFromPoints( plane4, poly->verts[0].xyz, poly->verts[1].xyz, poly->verts[2].xyz ); + VectorCopy( plane4, plane->normal ); + plane->dist = plane4[3]; + return; + default: + Com_Memset (plane, 0, sizeof(*plane)); + plane->normal[0] = 1; + return; + } +} + +/* +================= +R_GetPortalOrientation + +entityNum is the entity that the portal surface is a part of, which may +be moving and rotating. + +Returns qtrue if it should be mirrored +================= +*/ +qboolean R_GetPortalOrientations(const msurface_t *surf, int entityNum, + orientation_t *surface, orientation_t *camera, + vec3_t pvsOrigin, qboolean *mirror ) { + int i; + cplane_t originalPlane, plane; + trRefEntity_t *e; + float d; + vec3_t transformed; + + // create plane axis for the portal we are seeing + R_PlaneForSurface( surf->data, &originalPlane ); + + // rotate the plane if necessary + if ( entityNum != REFENTITYNUM_WORLD ) { + const trRefEntity_t *currentEntity = &tr.refdef.entities[entityNum]; + + // get the orientation of the entity + R_RotateForEntity( currentEntity, &tr.viewParms, &tr.ori ); + + // rotate the plane, but keep the non-rotated version for matching + // against the portalSurface entities + R_LocalNormalToWorld( originalPlane.normal, plane.normal ); + plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.ori.origin ); + + // translate the original plane + originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.ori.origin ); + } else { + plane = originalPlane; + } + + VectorCopy( plane.normal, surface->axis[0] ); + PerpendicularVector( surface->axis[1], surface->axis[0] ); + CrossProduct( surface->axis[0], surface->axis[1], surface->axis[2] ); + + // locate the portal entity closest to this plane. + // origin will be the origin of the portal, origin2 will be + // the origin of the camera + for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) { + e = &tr.refdef.entities[i]; + if ( e->e.reType != RT_PORTALSURFACE ) { + continue; + } + + d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist; + if ( d > 64 || d < -64) { + continue; + } + + // get the pvsOrigin from the entity + VectorCopy( e->e.oldorigin, pvsOrigin ); + + // if the entity is just a mirror, don't use as a camera point + if ( e->e.oldorigin[0] == e->e.origin[0] && + e->e.oldorigin[1] == e->e.origin[1] && + e->e.oldorigin[2] == e->e.origin[2] ) { + VectorScale( plane.normal, plane.dist, surface->origin ); + VectorCopy( surface->origin, camera->origin ); + VectorSubtract( vec3_origin, surface->axis[0], camera->axis[0] ); + VectorCopy( surface->axis[1], camera->axis[1] ); + VectorCopy( surface->axis[2], camera->axis[2] ); + + *mirror = qtrue; + return qtrue; + } + + // project the origin onto the surface plane to get + // an origin point we can rotate around + d = DotProduct( e->e.origin, plane.normal ) - plane.dist; + VectorMA( e->e.origin, -d, surface->axis[0], surface->origin ); + + // now get the camera origin and orientation + VectorCopy( e->e.oldorigin, camera->origin ); + AxisCopy( e->e.axis, camera->axis ); + VectorSubtract( vec3_origin, camera->axis[0], camera->axis[0] ); + VectorSubtract( vec3_origin, camera->axis[1], camera->axis[1] ); + + // optionally rotate + if ( e->e.oldframe ) { + // if a speed is specified + if ( e->e.frame ) { + // continuous rotate + d = (tr.refdef.time/1000.0f) * e->e.frame; + VectorCopy( camera->axis[1], transformed ); + RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); + CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + } else { + // bobbing rotate, with skinNum being the rotation offset + d = sin( tr.refdef.time * 0.003f ); + d = e->e.skinNum + d * 4; + VectorCopy( camera->axis[1], transformed ); + RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); + CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + } + } + else if ( e->e.skinNum ) { + d = e->e.skinNum; + VectorCopy( camera->axis[1], transformed ); + RotatePointAroundVector( camera->axis[1], camera->axis[0], transformed, d ); + CrossProduct( camera->axis[0], camera->axis[1], camera->axis[2] ); + } + *mirror = qfalse; + return qtrue; + } + + // if we didn't locate a portal entity, don't render anything. + // We don't want to just treat it as a mirror, because without a + // portal entity the server won't have communicated a proper entity set + // in the snapshot + + // unfortunately, with local movement prediction it is easily possible + // to see a surface before the server has communicated the matching + // portal surface entity, so we don't want to print anything here... + + //ri.Printf( PRINT_ALL, "Portal surface without a portal entity\n" ); + + return qfalse; +} + +static qboolean IsMirror( const msurface_t *surface, int entityNum ) +{ + int i; + cplane_t originalPlane, plane; + trRefEntity_t *e; + float d; + + // create plane axis for the portal we are seeing + R_PlaneForSurface( surface->data, &originalPlane ); + + // rotate the plane if necessary + if ( entityNum != REFENTITYNUM_WORLD ) + { + const trRefEntity_t *currentEntity = &tr.refdef.entities[entityNum]; + + // get the orientation of the entity + R_RotateForEntity( currentEntity, &tr.viewParms, &tr.ori ); + + // rotate the plane, but keep the non-rotated version for matching + // against the portalSurface entities + R_LocalNormalToWorld( originalPlane.normal, plane.normal ); + plane.dist = originalPlane.dist + DotProduct( plane.normal, tr.ori.origin ); + + // translate the original plane + originalPlane.dist = originalPlane.dist + DotProduct( originalPlane.normal, tr.ori.origin ); + } + + // locate the portal entity closest to this plane. + // origin will be the origin of the portal, origin2 will be + // the origin of the camera + for ( i = 0 ; i < tr.refdef.num_entities ; i++ ) + { + e = &tr.refdef.entities[i]; + if ( e->e.reType != RT_PORTALSURFACE ) { + continue; + } + + d = DotProduct( e->e.origin, originalPlane.normal ) - originalPlane.dist; + if ( d > 64 || d < -64) { + continue; + } + + // if the entity is just a mirror, don't use as a camera point + if ( e->e.oldorigin[0] == e->e.origin[0] && + e->e.oldorigin[1] == e->e.origin[1] && + e->e.oldorigin[2] == e->e.origin[2] ) + { + return qtrue; + } + + return qfalse; + } + return qfalse; +} + +/* +** SurfIsOffscreen +** +** Determines if a surface is completely offscreen. +*/ +static qboolean SurfIsOffscreen( const msurface_t *surface, int entityNum, vec4_t clipDest[128], int *numVertices ) { + float shortest = 100000000; + int numTriangles; + vec4_t clip, eye; + int i; + unsigned int pointOr = 0; + unsigned int pointAnd = (unsigned int)~0; + + // TODO: Check if set properly here already + //R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); + + RB_BeginSurface(surface->shader, 0, 0 ); + rb_surfaceTable[ *surface->data ](surface->data); + + if ( tess.numVertexes > 128 ) + { + // Don't bother trying, just assume it's off-screen and make it look bad. Besides, artists + // shouldn't be using this many vertices on a mirror surface anyway :) + return qtrue; + } + + *numVertices = tess.numVertexes; + + for ( i = 0; i < tess.numVertexes; i++ ) + { + int j; + unsigned int pointFlags = 0; + + R_TransformModelToClip( tess.xyz[i], tr.viewParms.world.modelViewMatrix, tr.viewParms.projectionMatrix, eye, clip ); + VectorCopy4(clip, clipDest[i]); + + for ( j = 0; j < 3; j++ ) + { + if ( clip[j] >= clip[3] ) + { + pointFlags |= (1 << (j*2)); + } + else if ( clip[j] <= -clip[3] ) + { + pointFlags |= ( 1 << (j*2+1)); + } + } + pointAnd &= pointFlags; + pointOr |= pointFlags; + } + + // trivially reject + if ( pointAnd ) + { + return qtrue; + } + + // determine if this surface is backfaced and also determine the distance + // to the nearest vertex so we can cull based on portal range. Culling + // based on vertex distance isn't 100% correct (we should be checking for + // range to the surface), but it's good enough for the types of portals + // we have in the game right now. + numTriangles = tess.numIndexes / 3; + + for ( i = 0; i < tess.numIndexes; i += 3 ) + { + vec3_t normal, tNormal; + + float len; + + VectorSubtract( tess.xyz[tess.indexes[i]], tr.viewParms.ori.origin, normal ); + + len = VectorLengthSquared( normal ); // lose the sqrt + if ( len < shortest ) + { + shortest = len; + } + + R_VboUnpackNormal(tNormal, tess.normal[tess.indexes[i]]); + + if ( DotProduct( normal, tNormal ) >= 0 ) + { + numTriangles--; + } + } + if ( !numTriangles ) + { + return qtrue; + } + + // mirrors can early out at this point, since we don't do a fade over distance + // with them (although we could) + if ( IsMirror( surface, entityNum) ) + { + return qfalse; + } + + if ( shortest > (tess.shader->portalRange*tess.shader->portalRange) ) + { + return qtrue; + } + + return qfalse; +} + +/* +======================== +R_MirrorViewBySurface + +Returns qtrue if another view has been rendered +======================== +*/ +qboolean R_MirrorViewBySurface (msurface_t *surface, int entityNum) { + vec4_t clipDest[128]; + int numVertices; + viewParms_t newParms; + viewParms_t oldParms; + orientation_t surfaceOri, camera; + + // don't recursively mirror + if (tr.viewParms.isPortal) { + ri.Printf( PRINT_DEVELOPER, "WARNING: recursive mirror/portal found\n" ); + return qfalse; + } + + if ( r_noportals->integer || (r_fastsky->integer == 1) ) { + return qfalse; + } + + // trivially reject portal/mirror + if ( SurfIsOffscreen(surface, entityNum, clipDest, &numVertices ) ) { + return qfalse; + } + + // save old viewParms so we can return to it after the mirror view + oldParms = tr.viewParms; + + newParms = tr.viewParms; + newParms.isPortal = qtrue; + newParms.zFar = 0.0f; + newParms.zNear = r_znear->value; + newParms.flags &= ~VPF_FARPLANEFRUSTUM; + if ( !R_GetPortalOrientations(surface, entityNum, &surfaceOri, &camera, + newParms.pvsOrigin, &newParms.isMirror ) ) { + return qfalse; // bad portal, no portalentity + } + + if (newParms.isMirror) + newParms.flags |= VPF_NOVIEWMODEL; + + // Calculate window coordinates of this surface to get tight fitting scissor rectangle + int viewportWidth = oldParms.viewportWidth; + int viewportHeight = oldParms.viewportHeight; + float viewportCenterX = oldParms.viewportX + 0.5f * viewportWidth; + float viewportCenterY = oldParms.viewportY + 0.5f * viewportHeight; + + /*int minRectX = INT_MAX; + int minRectY = INT_MAX; + int maxRectX = 0; + int maxRectY = 0; + + for ( int i = 0; i < numVertices; i++ ) + { + float ndcX; + float ndcY; + float wdcX; + float wdcY; + int floorX; + int floorY; + int ceilX; + int ceilY; + + if ( clipDest[i][0] <= -clipDest[i][3] ) + ndcX = -1.0f; + else if ( clipDest[i][0] >= clipDest[i][3] ) + ndcX = 1.0f; + else + ndcX = clipDest[i][0] / clipDest[i][3]; + + if ( clipDest[i][1] <= -clipDest[i][3] ) + ndcY = -1.0f; + else if ( clipDest[i][1] >= clipDest[i][3] ) + ndcY = 1.0f; + else + ndcY = clipDest[i][1] / clipDest[i][3]; + + wdcX = 0.5f * viewportWidth * ndcX + viewportCenterX; + wdcY = 0.5f * viewportHeight * ndcY + viewportCenterY; + + floorX = (int)wdcX; + floorY = (int)wdcY; + + ceilX = (int)(wdcX + 0.5f); + ceilY = (int)(wdcY + 0.5f); + + minRectX = Q_min(minRectX, floorX); + minRectY = Q_min(minRectY, floorY); + maxRectX = Q_max(maxRectX, ceilX); + maxRectY = Q_max(maxRectY, ceilY); + } + + minRectX = Q_max(minRectX, 0); + minRectY = Q_max(minRectY, 0); + maxRectX = Q_min(maxRectX, oldParms.viewportX + viewportWidth); + maxRectY = Q_min(maxRectY, oldParms.viewportY + viewportHeight); + + newParms.scissorX = minRectX; + newParms.scissorY = minRectY; + newParms.scissorWidth = maxRectX - minRectX; + newParms.scissorHeight = maxRectY - minRectY;*/ + + R_MirrorPoint (oldParms.ori.origin, &surfaceOri, &camera, newParms.ori.origin ); + + VectorSubtract( vec3_origin, camera.axis[0], newParms.portalPlane.normal ); + newParms.portalPlane.dist = DotProduct( camera.origin, newParms.portalPlane.normal ); + + R_MirrorVector (oldParms.ori.axis[0], &surfaceOri, &camera, newParms.ori.axis[0]); + R_MirrorVector (oldParms.ori.axis[1], &surfaceOri, &camera, newParms.ori.axis[1]); + R_MirrorVector (oldParms.ori.axis[2], &surfaceOri, &camera, newParms.ori.axis[2]); + + // OPTIMIZE further: restrict the viewport and set up the view and projection + // matrices so they only draw into the tightest screen-space aligned box required + // to fill the restricted viewport. + + tr.viewCount++; + tr.viewParms = newParms; + R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); + R_SetupProjection(&tr.viewParms, tr.viewParms.zNear, tr.viewParms.zFar, qtrue); + + R_MarkLeaves(); + + // clear out the visible min/max + ClearBounds(tr.viewParms.visBounds[0], tr.viewParms.visBounds[1]); + int planeBits = (tr.viewParms.flags & VPF_FARPLANEFRUSTUM) ? 31 : 15; + // set vis bounds + R_RecursiveWorldNode(tr.world->nodes, planeBits, 0, 0); + R_SetFarClip(&tr.viewParms, nullptr); + R_SetupProjectionZ(&tr.viewParms); + + // render the mirror view + tr.viewParms.currentViewParm = tr.numCachedViewParms; + tr.viewParms.viewParmType = VPT_PORTAL; + Com_Memcpy(&tr.cachedViewParms[tr.numCachedViewParms], &tr.viewParms, sizeof(viewParms_t)); + tr.numCachedViewParms++; + + return qtrue; +} + +/* +================= +R_SpriteFogNum + +See if a sprite is inside a fog volume +================= +*/ +int R_SpriteFogNum( trRefEntity_t *ent ) { + int i, j; + fog_t *fog; + + if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + return 0; + } + + for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + fog = &tr.world->fogs[i]; + for ( j = 0 ; j < 3 ; j++ ) { + if ( ent->e.origin[j] - ent->e.radius >= fog->bounds[1][j] ) { + break; + } + if ( ent->e.origin[j] + ent->e.radius <= fog->bounds[0][j] ) { + break; + } + } + if ( j == 3 ) { + return i; + } + } + + return 0; +} + +/* +========================================================================================== + +DRAWSURF SORTING + +========================================================================================== +*/ + +/* +=============== +R_Radix +=============== +*/ +static QINLINE void R_Radix( int byte, int size, drawSurf_t *source, drawSurf_t *dest ) +{ + int count[ 256 ] = { 0 }; + int index[ 256 ]; + int i; + unsigned char *sortKey = NULL; + unsigned char *end = NULL; + + sortKey = ( (unsigned char *)&source[ 0 ].sort ) + byte; + end = sortKey + ( size * sizeof( drawSurf_t ) ); + for( ; sortKey < end; sortKey += sizeof( drawSurf_t ) ) + ++count[ *sortKey ]; + + index[ 0 ] = 0; + + for( i = 1; i < 256; ++i ) + index[ i ] = index[ i - 1 ] + count[ i - 1 ]; + + sortKey = ( (unsigned char *)&source[ 0 ].sort ) + byte; + for( i = 0; i < size; ++i, sortKey += sizeof( drawSurf_t ) ) + dest[ index[ *sortKey ]++ ] = source[ i ]; +} + +/* +=============== +R_RadixSort + +Radix sort with 4 byte size buckets +=============== +*/ +static void R_RadixSort( drawSurf_t *source, int size ) +{ + static drawSurf_t scratch[ MAX_DRAWSURFS ]; +#ifdef Q3_LITTLE_ENDIAN + R_Radix( 0, size, source, scratch ); + R_Radix( 1, size, scratch, source ); + R_Radix( 2, size, source, scratch ); + R_Radix( 3, size, scratch, source ); +#else + R_Radix( 3, size, source, scratch ); + R_Radix( 2, size, scratch, source ); + R_Radix( 1, size, source, scratch ); + R_Radix( 0, size, scratch, source ); +#endif //Q3_LITTLE_ENDIAN +} + +//========================================================================================== + +bool R_IsPostRenderEntity ( const trRefEntity_t *refEntity ) +{ + return (refEntity->e.renderfx & RF_DISTORTION) || + (refEntity->e.renderfx & RF_FORCEPOST) || + (refEntity->e.renderfx & RF_FORCE_ENT_ALPHA); +} + +/* +================= +R_DecomposeSort +================= +*/ +void R_DecomposeSort( uint32_t sort, int *entityNum, shader_t **shader, int *cubemap, int *postRender ) +{ + *shader = tr.sortedShaders[ ( sort >> QSORT_SHADERNUM_SHIFT ) & QSORT_SHADERNUM_MASK ]; + *postRender = (sort >> QSORT_POSTRENDER_SHIFT ) & QSORT_POSTRENDER_MASK; + *entityNum = (sort >> QSORT_ENTITYNUM_SHIFT) & QSORT_ENTITYNUM_MASK; + *cubemap = (sort >> QSORT_CUBEMAP_SHIFT ) & QSORT_CUBEMAP_MASK; +} + +uint32_t R_CreateSortKey(int entityNum, int sortedShaderIndex, int cubemapIndex, int postRender) +{ + uint32_t key = 0; + + key |= (sortedShaderIndex & QSORT_SHADERNUM_MASK) << QSORT_SHADERNUM_SHIFT; + key |= (cubemapIndex & QSORT_CUBEMAP_MASK) << QSORT_CUBEMAP_SHIFT; + key |= (postRender & QSORT_POSTRENDER_MASK) << QSORT_POSTRENDER_SHIFT; + key |= (entityNum & QSORT_ENTITYNUM_MASK) << QSORT_ENTITYNUM_SHIFT; + + return key; +} + +/* +================= +R_AddDrawSurf +================= +*/ +void R_AddDrawSurf( + surfaceType_t *surface, + int entityNum, + shader_t *shader, + int fogIndex, + int dlightMap, + int postRender, + int cubemap) +{ + int index; + drawSurf_t *surf; + + if (tr.refdef.rdflags & RDF_NOFOG) + { + fogIndex = 0; + } + + if ( (shader->surfaceFlags & SURF_FORCESIGHT) && !(tr.refdef.rdflags & RDF_ForceSightOn) ) + { //if shader is only seen with ForceSight and we don't have ForceSight on, then don't draw + return; + } + + if (tr.viewParms.flags & VPF_DEPTHSHADOW && + (postRender == qtrue || shader->sort != SS_OPAQUE)) + { + return; + } + + // instead of checking for overflow, we just mask the index + // so it wraps around + index = tr.refdef.numDrawSurfs & DRAWSURF_MASK; + surf = tr.refdef.drawSurfs + index; + surf->surface = surface; + + if (tr.viewParms.flags & VPF_DEPTHSHADOW && + shader->useSimpleDepthShader == qtrue) + { + surf->sort = R_CreateSortKey(entityNum, tr.defaultShader->sortedIndex, 0, 0); + surf->dlightBits = 0; + surf->fogIndex = 0; + } + else + { + surf->sort = R_CreateSortKey(entityNum, shader->sortedIndex, cubemap, postRender); + surf->dlightBits = dlightMap; + surf->fogIndex = fogIndex; + } + + tr.refdef.numDrawSurfs++; +} + +/* +================= +R_SortAndSubmitDrawSurfs +================= +*/ +void R_SortAndSubmitDrawSurfs( drawSurf_t *drawSurfs, int numDrawSurfs ) { + // it is possible for some views to not have any surfaces + if (numDrawSurfs < 1) + return; + + // if we overflowed MAX_DRAWSURFS, the drawsurfs + // wrapped around in the buffer and we will be missing + // the first surfaces, not the last ones + if ( numDrawSurfs > MAX_DRAWSURFS ) + numDrawSurfs = MAX_DRAWSURFS; + + R_RadixSort( drawSurfs, numDrawSurfs ); + + R_AddDrawSurfCmd( drawSurfs, numDrawSurfs ); +} + +static void R_AddEntitySurface(const trRefdef_t *refdef, trRefEntity_t *ent, int entityNum) +{ + shader_t *shader; + + ent->needDlights = qfalse; + + // + // the weapon model must be handled special -- + // we don't want the hacked weapon position showing in + // mirrors, because the true body position will already be drawn + // + if ( (ent->e.renderfx & RF_FIRST_PERSON) && (tr.viewParms.flags & VPF_NOVIEWMODEL)) { + return; + } + + // simple generated models, like sprites and beams, are not culled + switch ( ent->e.reType ) { + case RT_PORTALSURFACE: + break; // don't draw anything + case RT_SPRITE: + case RT_BEAM: + case RT_ORIENTED_QUAD: + case RT_ELECTRICITY: + case RT_LINE: + case RT_ORIENTEDLINE: + case RT_CYLINDER: + case RT_SABER_GLOW: + // self blood sprites, talk balloons, etc should not be drawn in the primary + // view. We can't just do this check for all entities, because md3 + // entities may still want to cast shadows from them + if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal) { + return; + } + shader = R_GetShaderByHandle( ent->e.customShader ); + R_AddDrawSurf( + &entitySurface, + entityNum, + shader, + R_SpriteFogNum(ent), + 0, + R_IsPostRenderEntity(ent), + 0 /* cubeMap */ ); + break; + + case RT_MODEL: + // we must set up parts of tr.ori for model culling + R_RotateForEntity( ent, &tr.viewParms, &tr.ori ); + + tr.currentModel = R_GetModelByHandle( ent->e.hModel ); + if (!tr.currentModel) { + R_AddDrawSurf( + &entitySurface, + entityNum, + tr.defaultShader, + 0, + 0, + R_IsPostRenderEntity(ent), + 0/* cubeMap */ ); + } else { + switch ( tr.currentModel->type ) { + case MOD_MESH: + R_AddMD3Surfaces( ent, entityNum ); + break; + case MOD_MDR: + R_MDRAddAnimSurfaces( ent, entityNum ); + break; + case MOD_IQM: + R_AddIQMSurfaces( ent, entityNum ); + break; + case MOD_BRUSH: + R_AddBrushModelSurfaces( ent, entityNum ); + break; + case MOD_MDXM: + if (ent->e.ghoul2) + R_AddGhoulSurfaces(ent, entityNum); + break; + case MOD_BAD: // null model axis + if ( (ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal ) { + break; + } + + if ( ent->e.ghoul2 && + G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2)) ) + { + R_AddGhoulSurfaces(ent, entityNum); + break; + } + + // FIX ME: always draw null axis model instead of rejecting the drawcall + if (tr.currentModel->dataSize > 0) + R_AddDrawSurf( + &entitySurface, + entityNum, + tr.defaultShader, + 0, + 0, + R_IsPostRenderEntity(ent), + 0 /* cubeMap */ ); + break; + default: + ri.Error( ERR_DROP, "R_AddEntitySurfaces: Bad modeltype" ); + break; + } + } + break; + case RT_ENT_CHAIN: + shader = R_GetShaderByHandle(ent->e.customShader); + R_AddDrawSurf( + &entitySurface, + entityNum, + shader, + R_SpriteFogNum(ent), + false, + R_IsPostRenderEntity(ent), + 0 /* cubeMap */ ); + break; + default: + ri.Error( ERR_DROP, "R_AddEntitySurfaces: Bad reType" ); + } +} + +/* +============= +R_AddEntitySurfaces +============= +*/ +static void R_AddEntitySurfaces(const trRefdef_t *refdef) +{ + if ( !r_drawentities->integer ) + { + return; + } + + int entityStart = 0; + int numEntities = refdef->num_entities; + if (tr.world && tr.world->skyboxportal) + { + if (tr.viewParms.isSkyPortal) + { + // Stop after skyportal entities + numEntities = tr.skyPortalEntities; + } + else + { + // Skip skyportal entities + entityStart = tr.skyPortalEntities; + } + } + + for (int i = entityStart; i < numEntities; i++) + { + trRefEntity_t *ent = refdef->entities + i; + R_AddEntitySurface(refdef, ent, i); + } +} + + +/* +==================== +R_GenerateDrawSurfs +==================== +*/ +void R_GenerateDrawSurfs( viewParms_t *viewParms, trRefdef_t *refdef ) { + + // TODO: Get rid of this + if (viewParms->viewParmType == VPT_PLAYER_SHADOWS) + { + int entityNum = viewParms->targetFboLayer; + trRefEntity_t *ent = refdef->entities + entityNum; + R_AddEntitySurface(refdef, ent, entityNum); + return; + } + + R_AddWorldSurfaces(viewParms, refdef); + + R_AddEntitySurfaces(refdef); + + R_AddPolygonSurfaces(refdef); + + if ( tr.viewParms.viewParmType > VPT_POINT_SHADOWS && tr.world ) + { + R_AddWeatherSurfaces(); + } +} + +/* +================ +R_DebugPolygon +================ +*/ +void R_DebugPolygon( int color, int numPoints, float *points ) { + // FIXME: implement this +#if 0 + int i; + + GL_State( GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + + // draw solid shade + + qglColor3f( color&1, (color>>1)&1, (color>>2)&1 ); + qglBegin( GL_POLYGON ); + for ( i = 0 ; i < numPoints ; i++ ) { + qglVertex3fv( points + i * 3 ); + } + qglEnd(); + + // draw wireframe outline + GL_State( GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + qglDepthRange( 0, 0 ); + qglColor3f( 1, 1, 1 ); + qglBegin( GL_POLYGON ); + for ( i = 0 ; i < numPoints ; i++ ) { + qglVertex3fv( points + i * 3 ); + } + qglEnd(); + qglDepthRange( 0, 1 ); +#endif +} + +/* +==================== +R_DebugGraphics + +Visualization aid for movement clipping debugging +==================== +*/ +void R_DebugGraphics( void ) { + if ( !r_debugSurface->integer ) { + return; + } + + R_IssuePendingRenderCommands(); + + GL_Bind( tr.whiteImage); + GL_Cull( CT_FRONT_SIDED ); + ri.CM_DrawDebugSurface( R_DebugPolygon ); +} + + +/* +================ +R_RenderView + +A view may be either the actual camera view, +or a mirror / remote location +================ +*/ +void R_RenderView (viewParms_t *parms) { + + if ( parms->viewportWidth <= 0 || parms->viewportHeight <= 0 ) { + return; + } + + tr.viewCount++; + + tr.viewParms = *parms; + tr.viewParms.frameSceneNum = tr.frameSceneNum; + tr.viewParms.frameCount = tr.frameCount; + + tr.refdef.fistDrawSurf = tr.refdef.numDrawSurfs; + + R_GenerateDrawSurfs(&tr.viewParms, &tr.refdef); + + R_SortAndSubmitDrawSurfs( tr.refdef.drawSurfs + tr.refdef.fistDrawSurf, tr.refdef.numDrawSurfs - tr.refdef.fistDrawSurf); + + // draw main system development information (surface outlines, etc) + R_DebugGraphics(); +} + + +void R_RenderDlightCubemaps(const refdef_t *fd) +{ + int i; + + for (i = 0; i < tr.refdef.num_dlights; i++) + { + viewParms_t shadowParms; + int j; + + Com_Memset( &shadowParms, 0, sizeof( shadowParms ) ); + + shadowParms.viewportX = 0; + shadowParms.viewportY = 0; + shadowParms.viewportWidth = DSHADOW_MAP_SIZE; + shadowParms.viewportHeight = DSHADOW_MAP_SIZE; + shadowParms.isPortal = qfalse; + shadowParms.isMirror = qfalse; + + shadowParms.fovX = 90; + shadowParms.fovY = 90; + + shadowParms.flags = VPF_DEPTHSHADOW | VPF_NOVIEWMODEL | VPF_POINTSHADOW; + shadowParms.zFar = tr.refdef.dlights[i].radius; + shadowParms.zNear = 1.0f; + + VectorCopy( tr.refdef.dlights[i].origin, shadowParms.ori.origin ); + + for (j = 0; j < 6; j++) + { + switch(j) + { + case 0: + // -X + VectorSet( shadowParms.ori.axis[0], -1, 0, 0); + VectorSet( shadowParms.ori.axis[1], 0, 0, -1); + VectorSet( shadowParms.ori.axis[2], 0, 1, 0); + break; + case 1: + // +X + VectorSet( shadowParms.ori.axis[0], 1, 0, 0); + VectorSet( shadowParms.ori.axis[1], 0, 0, 1); + VectorSet( shadowParms.ori.axis[2], 0, 1, 0); + break; + case 2: + // -Y + VectorSet( shadowParms.ori.axis[0], 0, -1, 0); + VectorSet( shadowParms.ori.axis[1], 1, 0, 0); + VectorSet( shadowParms.ori.axis[2], 0, 0, -1); + break; + case 3: + // +Y + VectorSet( shadowParms.ori.axis[0], 0, 1, 0); + VectorSet( shadowParms.ori.axis[1], 1, 0, 0); + VectorSet( shadowParms.ori.axis[2], 0, 0, 1); + break; + case 4: + // -Z + VectorSet( shadowParms.ori.axis[0], 0, 0, -1); + VectorSet( shadowParms.ori.axis[1], 1, 0, 0); + VectorSet( shadowParms.ori.axis[2], 0, 1, 0); + break; + case 5: + // +Z + VectorSet( shadowParms.ori.axis[0], 0, 0, 1); + VectorSet( shadowParms.ori.axis[1], -1, 0, 0); + VectorSet( shadowParms.ori.axis[2], 0, 1, 0); + break; + } + + shadowParms.targetFbo = tr.shadowCubeFbo[i*6+j]; + shadowParms.targetFboLayer = 0; + + R_RenderView(&shadowParms); + + R_IssuePendingRenderCommands(); + + tr.refdef.numDrawSurfs = 0; + } + } +} + +void R_SetOrientationOriginAndAxis( + orientationr_t& orientation, + const vec3_t origin, + const vec3_t forward, + const vec3_t left, + const vec3_t up) +{ + VectorCopy(origin, orientation.origin); + VectorCopy(forward, orientation.axis[0]); + VectorCopy(left, orientation.axis[1]); + VectorCopy(up, orientation.axis[2]); +} + +void R_SetOrientationOriginAndAxis( + orientationr_t& orientation, + const vec3_t origin, + const matrix3_t axis) +{ + R_SetOrientationOriginAndAxis(orientation, origin, axis[0], axis[1], axis[2]); +} + +void R_SetupViewParmsForOrthoRendering( + int viewportWidth, + int viewportHeight, + FBO_t *fbo, + viewParmFlags_t viewParmFlags, + const orientationr_t& orientation, + const vec3_t viewBounds[2]) +{ + viewParms_t& viewParms = tr.viewParms; + + viewParms = {}; + viewParms.viewportWidth = viewportWidth; + viewParms.viewportHeight = viewportHeight; + viewParms.flags = viewParmFlags; + viewParms.targetFbo = fbo; + viewParms.zFar = viewBounds[1][0]; + VectorCopy(orientation.origin, viewParms.ori.origin); + for (int i = 0; i < 3; ++i) + VectorCopy(orientation.axis[i], viewParms.ori.axis[i]); + + VectorCopy(orientation.origin, viewParms.pvsOrigin); + + tr.viewCount++; + + viewParms.frameSceneNum = tr.frameSceneNum; + viewParms.frameCount = tr.frameCount; + + R_RotateForViewer(&viewParms.world, &viewParms); + R_SetupProjectionOrtho(&viewParms, viewBounds); +} + +void R_SetupPshadowMaps(trRefdef_t *refdef) +{ + viewParms_t shadowParms; + int i; + + // first, make a list of shadows + for ( i = 0; i < refdef->num_entities; i++) + { + trRefEntity_t *ent = &refdef->entities[i]; + + if((ent->e.renderfx & (RF_FIRST_PERSON | RF_NOSHADOW))) + continue; + + //if((ent->e.renderfx & RF_THIRD_PERSON)) + //continue; + + if (ent->e.reType == RT_MODEL) + { + model_t *model = R_GetModelByHandle( ent->e.hModel ); + pshadow_t shadow; + float radius = 0.0f; + float scale = 1.0f; + vec3_t diff; + int j; + + if (!model) + continue; + + if (ent->e.nonNormalizedAxes) + { + scale = VectorLength( ent->e.axis[0] ); + } + + switch (model->type) + { + case MOD_MDXM: + case MOD_BAD: + { + if (ent->e.ghoul2 && G2API_HaveWeGhoul2Models(*((CGhoul2Info_v *)ent->e.ghoul2))) + { + // scale the radius if needed + float largestScale = ent->e.modelScale[0]; + if (ent->e.modelScale[1] > largestScale) + largestScale = ent->e.modelScale[1]; + if (ent->e.modelScale[2] > largestScale) + largestScale = ent->e.modelScale[2]; + if (!largestScale) + largestScale = 1; + radius = ent->e.radius * largestScale * 1.2; + } + } + break; + + default: + break; + } + + if (!radius) + continue; + + // Cull entities that are behind the viewer by more than lightRadius + VectorSubtract(ent->e.lightingOrigin, refdef->vieworg, diff); + if (DotProduct(diff, refdef->viewaxis[0]) < -r_pshadowDist->value) + continue; + + memset(&shadow, 0, sizeof(shadow)); + + shadow.numEntities = 1; + shadow.entityNums[0] = i; + shadow.viewRadius = radius; + shadow.lightRadius = r_pshadowDist->value; + VectorCopy(ent->e.lightingOrigin, shadow.viewOrigin); + shadow.sort = DotProduct(diff, diff) / (radius * radius); + VectorCopy(ent->e.origin, shadow.entityOrigins[0]); + shadow.entityRadiuses[0] = radius; + + for (j = 0; j < MAX_CALC_PSHADOWS; j++) + { + pshadow_t swap; + + if (j + 1 > refdef->num_pshadows) + { + refdef->num_pshadows = j + 1; + refdef->pshadows[j] = shadow; + break; + } + + // sort shadows by distance from camera divided by radius + // FIXME: sort better + if (refdef->pshadows[j].sort <= shadow.sort) + continue; + + swap = refdef->pshadows[j]; + refdef->pshadows[j] = shadow; + shadow = swap; + } + } + } + + // cap number of drawn pshadows + if (refdef->num_pshadows > MAX_DRAWN_PSHADOWS) + { + refdef->num_pshadows = MAX_DRAWN_PSHADOWS; + } + + // next, fill up the rest of the shadow info + for ( i = 0; i < refdef->num_pshadows; i++) + { + pshadow_t *shadow = &refdef->pshadows[i]; + vec3_t up; + vec3_t ambientLight, directedLight, lightDir; + + VectorSet(lightDir, 0.57735f, 0.57735f, 0.57735f); + + R_LightForPoint(shadow->viewOrigin, ambientLight, directedLight, lightDir); +#if 1 + lightDir[2] = 0.0f; + VectorNormalize(lightDir); + VectorSet(lightDir, lightDir[0] * 0.3f, lightDir[1] * 0.3f, 1.0f); + VectorNormalize(lightDir); +#else + // sometimes there's no light + if (DotProduct(lightDir, lightDir) < 0.9f) + VectorSet(lightDir, 0.0f, 0.0f, 1.0f); +#endif + if (shadow->viewRadius * 3.0f > shadow->lightRadius) + { + shadow->lightRadius = shadow->viewRadius * 3.0f; + } + + VectorMA(shadow->viewOrigin, shadow->viewRadius, lightDir, shadow->lightOrigin); + + // make up a projection, up doesn't matter + VectorScale(lightDir, -1.0f, shadow->lightViewAxis[0]); + VectorSet(up, 0, 0, -1); + + if ( fabs(DotProduct(up, shadow->lightViewAxis[0])) > 0.9f ) + { + VectorSet(up, -1, 0, 0); + } + + CrossProduct(shadow->lightViewAxis[0], up, shadow->lightViewAxis[1]); + VectorNormalize(shadow->lightViewAxis[1]); + CrossProduct(shadow->lightViewAxis[0], shadow->lightViewAxis[1], shadow->lightViewAxis[2]); + + VectorCopy(shadow->lightViewAxis[0], shadow->cullPlane.normal); + shadow->cullPlane.dist = DotProduct(shadow->cullPlane.normal, shadow->lightOrigin); + shadow->cullPlane.type = PLANE_NON_AXIAL; + SetPlaneSignbits(&shadow->cullPlane); + } +} + +void R_RenderCubemapSide(int cubemapIndex, int cubemapSide, bool bounce) +{ + refdef_t refdef = {}; + float oldColorScale = tr.refdef.colorScale; + + VectorCopy(tr.cubemaps[cubemapIndex].origin, refdef.vieworg); + refdef.fov_x = 90; + refdef.fov_y = 90; + refdef.width = tr.renderCubeFbo[cubemapSide]->width; + refdef.height = tr.renderCubeFbo[cubemapSide]->height; + refdef.x = 0; + refdef.y = 0; + + switch (cubemapSide) + { + case 0: + // +X + VectorSet(refdef.viewaxis[0], 1, 0, 0); + VectorSet(refdef.viewaxis[1], 0, 0, 1); + VectorSet(refdef.viewaxis[2], 0, -1, 0); + break; + case 1: + // -X + VectorSet(refdef.viewaxis[0], -1, 0, 0); + VectorSet(refdef.viewaxis[1], 0, 0, -1); + VectorSet(refdef.viewaxis[2], 0, -1, 0); + break; + case 2: + // +Y + VectorSet(refdef.viewaxis[0], 0, 1, 0); + VectorSet(refdef.viewaxis[1], -1, 0, 0); + VectorSet(refdef.viewaxis[2], 0, 0, 1); + break; + case 3: + // -Y + VectorSet(refdef.viewaxis[0], 0, -1, 0); + VectorSet(refdef.viewaxis[1], -1, 0, 0); + VectorSet(refdef.viewaxis[2], 0, 0, -1); + break; + case 4: + // +Z + VectorSet(refdef.viewaxis[0], 0, 0, 1); + VectorSet(refdef.viewaxis[1], -1, 0, 0); + VectorSet(refdef.viewaxis[2], 0, -1, 0); + break; + case 5: + // -Z + VectorSet(refdef.viewaxis[0], 0, 0, -1); + VectorSet(refdef.viewaxis[1], 1, 0, 0); + VectorSet(refdef.viewaxis[2], 0, -1, 0); + break; + } + + RE_BeginFrame(STEREO_CENTER); + + RE_BeginScene(&refdef); + + tr.refdef.colorScale = 1.0f; + + for (int i = 0; i < tr.numCachedViewParms; i++) + { + if (!tr.cachedViewParms[i].targetFbo) + { + tr.cachedViewParms[i].targetFbo = tr.renderCubeFbo[cubemapSide]; + tr.cachedViewParms[i].targetFboLayer = 0; + tr.cachedViewParms[i].flags |= VPF_NOVIEWMODEL; + if (!bounce) + tr.cachedViewParms[i].flags |= VPF_NOCUBEMAPS; + } + R_RenderView(&tr.cachedViewParms[i]); + R_IssuePendingRenderCommands(); + tr.refdef.numDrawSurfs = 0; + } + + RE_EndScene(); + + R_NewFrameSync(); +} + +void R_SetupViewParms(const trRefdef_t *refdef) +{ + tr.viewCount++; + Com_Memset(&tr.viewParms, 0, sizeof(viewParms_t)); + tr.viewParms.viewportX = refdef->x; + + // Shoud be just refef->y but this flips the menu orientation for models, so its actually needed like this + if (!tr.world) + tr.viewParms.viewportY = glConfig.vidHeight - (refdef->y + refdef->height); + else + tr.viewParms.viewportY = refdef->y; + + tr.viewParms.viewportWidth = refdef->width; + tr.viewParms.viewportHeight = refdef->height; + tr.viewParms.zNear = r_znear->value; + + tr.viewParms.fovX = refdef->fov_x; + tr.viewParms.fovY = refdef->fov_y; + + VectorCopy(refdef->vieworg, tr.viewParms.ori.origin); + VectorCopy(refdef->viewaxis[0], tr.viewParms.ori.axis[0]); + VectorCopy(refdef->viewaxis[1], tr.viewParms.ori.axis[1]); + VectorCopy(refdef->viewaxis[2], tr.viewParms.ori.axis[2]); + + VectorCopy(refdef->vieworg, tr.viewParms.pvsOrigin); + + R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); + R_SetupProjection(&tr.viewParms, tr.viewParms.zNear, tr.viewParms.zFar, qtrue); + + if (tr.world) + { + R_MarkLeaves(); + + // clear out the visible min/max + ClearBounds(tr.viewParms.visBounds[0], tr.viewParms.visBounds[1]); + int planeBits = (tr.viewParms.flags & VPF_FARPLANEFRUSTUM) ? 31 : 15; + // set vis bounds + R_RecursiveWorldNode(tr.world->nodes, planeBits, 0, 0); + } + + R_SetFarClip(&tr.viewParms, refdef); + R_SetupProjectionZ(&tr.viewParms); +} + +qboolean R_AddPortalView(const trRefdef_t *refdef) +{ + if (!tr.world) + return qfalse; + + for (int i = 0; i < tr.world->numWorldSurfaces; i++) + { + if (tr.world->surfacesViewCount[i] != tr.viewCount) + continue; + + msurface_t *surface = tr.world->surfaces + i; + if (surface->shader->sort != SS_PORTAL) { + continue; + } + + // if the mirror was completely clipped away, we may need to check another surface + if (R_MirrorViewBySurface(surface, REFENTITYNUM_WORLD)) { + return qtrue; // only one mirror view at a time + } + } + + for (int i = 0; i < tr.world->numMergedSurfaces; i++) + { + if (tr.world->mergedSurfacesViewCount[i] != tr.viewCount) + continue; + + msurface_t *surface = tr.world->mergedSurfaces + i; + if (surface->shader->sort != SS_PORTAL) { + continue; + } + + // if the mirror was completely clipped away, we may need to check another surface + if (R_MirrorViewBySurface(surface, REFENTITYNUM_WORLD)) { + return qtrue; // only one mirror view at a time + } + } + + for (int i = 0; i < refdef->num_entities; i++) + { + trRefEntity_t *ent = &refdef->entities[i]; + switch (ent->e.reType) { + case RT_PORTALSURFACE: + break; // don't draw anything + case RT_SPRITE: + case RT_BEAM: + case RT_ORIENTED_QUAD: + case RT_ELECTRICITY: + case RT_LINE: + case RT_ORIENTEDLINE: + case RT_CYLINDER: + case RT_SABER_GLOW: + break; + + case RT_MODEL: + + // we must set up parts of tr.ori for model culling + R_RotateForEntity(ent, &tr.viewParms, &tr.ori); + + tr.currentModel = R_GetModelByHandle(ent->e.hModel); + if (!tr.currentModel) { + continue; + } + else { + switch (tr.currentModel->type) { + case MOD_BRUSH: + { + //R_AddBrushModelSurfaces(ent, i); + bmodel_t *bmodel = tr.currentModel->data.bmodel; + world_t *world = R_GetWorld(bmodel->worldIndex); + for (int j = 0; j < bmodel->numSurfaces; j++) { + int surf = bmodel->firstSurface + j; + + // TODO: use pvs of misc_bsp models + msurface_t *surface = world->surfaces + surf; + if (surface->shader->sort != SS_PORTAL) { + continue; + } + + // if the mirror was completely clipped away, we may need to check another surface + if (R_MirrorViewBySurface(surface, i)) { + return qtrue; // only one mirror view at a time + } + } + } + break; + case MOD_MESH: + case MOD_MDR: + case MOD_IQM: + case MOD_MDXM: + case MOD_BAD: + default: + break; + } + } + break; + case RT_ENT_CHAIN: + break; + default: + break; + } + } + + return qfalse; +} + +static float CalcSplit(float n, float f, float i, float m) +{ + return (n * pow(f / n, i / m) + (f - n) * i / m) / 2.0f; +} + +void R_GatherFrameViews(trRefdef_t *refdef) +{ + int mainFlags = 0; + // skyportal view + if (tr.world && tr.world->skyboxportal) + { + tr.viewCount++; + tr.viewParms = tr.skyPortalParms; + R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); + R_SetupProjection(&tr.viewParms, tr.viewParms.zNear, tr.viewParms.zFar, qtrue); + + VectorCopy(tr.skyPortalParms.pvsOrigin, tr.viewParms.pvsOrigin); + R_MarkLeaves(); + + // clear out the visible min/max + ClearBounds(tr.viewParms.visBounds[0], tr.viewParms.visBounds[1]); + int planeBits = (tr.viewParms.flags & VPF_FARPLANEFRUSTUM) ? 31 : 15; + // set vis bounds + R_RecursiveWorldNode(tr.world->nodes, planeBits, 0, 0); + R_SetFarClip(&tr.viewParms, refdef); + R_SetupProjectionZ(&tr.viewParms); + + tr.viewParms.currentViewParm = tr.numCachedViewParms; + tr.viewParms.viewParmType = VPT_SKYPORTAL; + Com_Memcpy(&tr.cachedViewParms[tr.numCachedViewParms], &tr.viewParms, sizeof(viewParms_t)); + tr.numCachedViewParms++; + } + + VectorCopy(refdef->vieworg, tr.viewParms.pvsOrigin); + if (tr.world) + R_MarkLeaves(); + + if (!(refdef->rdflags & RDF_NOWORLDMODEL)) + { + // dlight shadowmaps + if (refdef->num_dlights && r_dlightMode->integer >= 2) + { + for (int i = 0; i < refdef->num_dlights; i++) + { + viewParms_t shadowParms; + int j; + + Com_Memset(&shadowParms, 0, sizeof(shadowParms)); + + shadowParms.viewportX = 0; + shadowParms.viewportY = 0; + shadowParms.viewportWidth = DSHADOW_MAP_SIZE; + shadowParms.viewportHeight = DSHADOW_MAP_SIZE; + shadowParms.isPortal = qfalse; + shadowParms.isMirror = qfalse; + + shadowParms.fovX = 90; + shadowParms.fovY = 90; + + shadowParms.flags = VPF_DEPTHSHADOW | VPF_NOVIEWMODEL | VPF_POINTSHADOW; + shadowParms.zFar = refdef->dlights[i].radius; + shadowParms.zNear = 1.0f; + + VectorCopy(refdef->dlights[i].origin, shadowParms.ori.origin); + + for (j = 0; j < 6; j++) + { + switch (j) + { + case 0: + // -X + VectorSet(shadowParms.ori.axis[0], -1, 0, 0); + VectorSet(shadowParms.ori.axis[1], 0, 0, -1); + VectorSet(shadowParms.ori.axis[2], 0, 1, 0); + break; + case 1: + // +X + VectorSet(shadowParms.ori.axis[0], 1, 0, 0); + VectorSet(shadowParms.ori.axis[1], 0, 0, 1); + VectorSet(shadowParms.ori.axis[2], 0, 1, 0); + break; + case 2: + // -Y + VectorSet(shadowParms.ori.axis[0], 0, -1, 0); + VectorSet(shadowParms.ori.axis[1], 1, 0, 0); + VectorSet(shadowParms.ori.axis[2], 0, 0, -1); + break; + case 3: + // +Y + VectorSet(shadowParms.ori.axis[0], 0, 1, 0); + VectorSet(shadowParms.ori.axis[1], 1, 0, 0); + VectorSet(shadowParms.ori.axis[2], 0, 0, 1); + break; + case 4: + // -Z + VectorSet(shadowParms.ori.axis[0], 0, 0, -1); + VectorSet(shadowParms.ori.axis[1], 1, 0, 0); + VectorSet(shadowParms.ori.axis[2], 0, 1, 0); + break; + case 5: + // +Z + VectorSet(shadowParms.ori.axis[0], 0, 0, 1); + VectorSet(shadowParms.ori.axis[1], -1, 0, 0); + VectorSet(shadowParms.ori.axis[2], 0, 1, 0); + break; + } + + shadowParms.targetFbo = tr.shadowCubeFbo[i * 6 + j]; + shadowParms.targetFboLayer = 0; + + shadowParms.currentViewParm = tr.numCachedViewParms; + shadowParms.viewParmType = VPT_POINT_SHADOWS; + + R_RotateForViewer(&shadowParms.world, &shadowParms); + R_SetupProjection(&shadowParms, shadowParms.zNear, shadowParms.zFar, qtrue); + R_SetupProjectionZ(&shadowParms); + + Com_Memcpy(&tr.cachedViewParms[tr.numCachedViewParms], &shadowParms, sizeof(viewParms_t)); + tr.numCachedViewParms++; + } + } + } + + // pshadow shadowmaps + if (r_shadows->integer == 4) + { + R_SetupPshadowMaps(refdef); + + for (int i = 0; i < tr.refdef.num_pshadows; i++) + { + pshadow_t *shadow = &tr.refdef.pshadows[i]; + + tr.viewParms.viewportX = 0; + tr.viewParms.viewportY = 0; + tr.viewParms.viewportWidth = PSHADOW_MAP_SIZE; + tr.viewParms.viewportHeight = PSHADOW_MAP_SIZE; + tr.viewParms.isPortal = qfalse; + tr.viewParms.isMirror = qfalse; + + tr.viewParms.fovX = 90; + tr.viewParms.fovY = 90; + + tr.viewParms.targetFbo = tr.pshadowFbos[i]; + tr.viewParms.targetFboLayer = shadow->entityNums[0]; + + tr.viewParms.flags = (viewParmFlags_t)(VPF_DEPTHSHADOW | VPF_NOVIEWMODEL); + tr.viewParms.viewParmType = VPT_PLAYER_SHADOWS; + tr.viewParms.zFar = shadow->lightRadius; + + VectorCopy(shadow->lightOrigin, tr.viewParms.ori.origin); + + VectorCopy(shadow->lightViewAxis[0], tr.viewParms.ori.axis[0]); + VectorCopy(shadow->lightViewAxis[1], tr.viewParms.ori.axis[1]); + VectorCopy(shadow->lightViewAxis[2], tr.viewParms.ori.axis[2]); + + { + tr.viewCount++; + tr.viewParms.frameSceneNum = tr.frameSceneNum; + tr.viewParms.frameCount = tr.frameCount; + + // set viewParms.world + R_RotateForViewer(&tr.viewParms.world, &tr.viewParms); + + { + float xmin, xmax, ymin, ymax, znear, zfar; + viewParms_t *dest = &tr.viewParms; + vec3_t pop; + + xmin = ymin = -shadow->viewRadius; + xmax = ymax = shadow->viewRadius; + znear = 0; + zfar = shadow->lightRadius; + + dest->projectionMatrix[0] = 2 / (xmax - xmin); + dest->projectionMatrix[4] = 0; + dest->projectionMatrix[8] = (xmax + xmin) / (xmax - xmin); + dest->projectionMatrix[12] = 0; + + dest->projectionMatrix[1] = 0; + dest->projectionMatrix[5] = 2 / (ymax - ymin); + dest->projectionMatrix[9] = (ymax + ymin) / (ymax - ymin); // normally 0 + dest->projectionMatrix[13] = 0; + + dest->projectionMatrix[2] = 0; + dest->projectionMatrix[6] = 0; + dest->projectionMatrix[10] = 2 / (zfar - znear); + dest->projectionMatrix[14] = 0; + + dest->projectionMatrix[3] = 0; + dest->projectionMatrix[7] = 0; + dest->projectionMatrix[11] = 0; + dest->projectionMatrix[15] = 1; + + VectorScale(dest->ori.axis[1], 1.0f, dest->frustum[0].normal); + VectorMA(dest->ori.origin, -shadow->viewRadius, dest->frustum[0].normal, pop); + dest->frustum[0].dist = DotProduct(pop, dest->frustum[0].normal); + + VectorScale(dest->ori.axis[1], -1.0f, dest->frustum[1].normal); + VectorMA(dest->ori.origin, -shadow->viewRadius, dest->frustum[1].normal, pop); + dest->frustum[1].dist = DotProduct(pop, dest->frustum[1].normal); + + VectorScale(dest->ori.axis[2], 1.0f, dest->frustum[2].normal); + VectorMA(dest->ori.origin, -shadow->viewRadius, dest->frustum[2].normal, pop); + dest->frustum[2].dist = DotProduct(pop, dest->frustum[2].normal); + + VectorScale(dest->ori.axis[2], -1.0f, dest->frustum[3].normal); + VectorMA(dest->ori.origin, -shadow->viewRadius, dest->frustum[3].normal, pop); + dest->frustum[3].dist = DotProduct(pop, dest->frustum[3].normal); + + VectorScale(dest->ori.axis[0], -1.0f, dest->frustum[4].normal); + VectorMA(dest->ori.origin, -shadow->lightRadius, dest->frustum[4].normal, pop); + dest->frustum[4].dist = DotProduct(pop, dest->frustum[4].normal); + + for (int j = 0; j < 5; j++) + { + dest->frustum[j].type = PLANE_NON_AXIAL; + SetPlaneSignbits(&dest->frustum[j]); + } + + dest->flags |= VPF_FARPLANEFRUSTUM; + } + + tr.viewParms.currentViewParm = tr.numCachedViewParms; + Com_Memcpy(&tr.cachedViewParms[tr.numCachedViewParms], &tr.viewParms, sizeof(viewParms_t)); + tr.numCachedViewParms++; + } + } + + } + + // sun shadowmaps + if (r_sunlightMode->integer && r_depthPrepass->value && (r_forceSun->integer || tr.sunShadows)) + { + vec3_t lightViewAxis[3]; + vec3_t lightOrigin; + float splitZNear, splitZFar, splitBias; + float viewZNear, viewZFar; + vec3_t lightviewBounds[2]; + + viewZNear = r_shadowCascadeZNear->value; + viewZFar = r_shadowCascadeZFar->value; + splitBias = r_shadowCascadeZBias->value; + + for (int level = 0; level < 3; level++) + { + switch (level) + { + case 0: + default: + splitZNear = viewZNear; + splitZFar = CalcSplit(viewZNear, viewZFar, 1, 3) + splitBias; + break; + case 1: + splitZNear = CalcSplit(viewZNear, viewZFar, 1, 3) + splitBias; + splitZFar = CalcSplit(viewZNear, viewZFar, 2, 3) + splitBias; + break; + case 2: + splitZNear = CalcSplit(viewZNear, viewZFar, 2, 3) + splitBias; + splitZFar = viewZFar; + break; + } + + VectorCopy(refdef->vieworg, lightOrigin); + // Make up a projection + VectorScale(refdef->sunDir, -1.0f, lightViewAxis[0]); + // Use world up as light view up + VectorSet(lightViewAxis[2], 0, 0, 1); + + // Check if too close to parallel to light direction + if (fabs(DotProduct(lightViewAxis[2], lightViewAxis[0])) > 0.9f) + { + // Use world left as light view up + VectorSet(lightViewAxis[2], 0, 1, 0); + } + + // clean axes + CrossProduct(lightViewAxis[2], lightViewAxis[0], lightViewAxis[1]); + VectorNormalize(lightViewAxis[1]); + CrossProduct(lightViewAxis[0], lightViewAxis[1], lightViewAxis[2]); + + // Create bounds for light projection using slice of view projection + { + ClearBounds(lightviewBounds[0], lightviewBounds[1]); + + vec3_t point, base; + float lx, ly, radius; + vec3_t splitCenter, frustrumPoint0, frustrumPoint7; + + VectorSet(splitCenter, 0.f, 0.f, 0.f); + + // add view near plane + lx = splitZNear * tan(refdef->fov_x * M_PI / 360.0f); + ly = splitZNear * tan(refdef->fov_y * M_PI / 360.0f); + VectorMA(refdef->vieworg, splitZNear, refdef->viewaxis[0], base); + + VectorMA(base, lx, refdef->viewaxis[1], point); + VectorMA(point, ly, refdef->viewaxis[2], point); + VectorCopy(point, frustrumPoint0); + VectorAdd(point, splitCenter, splitCenter); + + VectorMA(base, -lx, refdef->viewaxis[1], point); + VectorMA(point, ly, refdef->viewaxis[2], point); + VectorAdd(point, splitCenter, splitCenter); + + VectorMA(base, lx, refdef->viewaxis[1], point); + VectorMA(point, -ly, refdef->viewaxis[2], point); + VectorAdd(point, splitCenter, splitCenter); + + VectorMA(base, -lx, refdef->viewaxis[1], point); + VectorMA(point, -ly, refdef->viewaxis[2], point); + VectorAdd(point, splitCenter, splitCenter); + + // add view far plane + lx = splitZFar * tan(refdef->fov_x * M_PI / 360.0f); + ly = splitZFar * tan(refdef->fov_y * M_PI / 360.0f); + VectorMA(refdef->vieworg, splitZFar, refdef->viewaxis[0], base); + + VectorMA(base, lx, refdef->viewaxis[1], point); + VectorMA(point, ly, refdef->viewaxis[2], point); + VectorAdd(point, splitCenter, splitCenter); + + VectorMA(base, -lx, refdef->viewaxis[1], point); + VectorMA(point, ly, refdef->viewaxis[2], point); + VectorAdd(point, splitCenter, splitCenter); + + VectorMA(base, lx, refdef->viewaxis[1], point); + VectorMA(point, -ly, refdef->viewaxis[2], point); + VectorAdd(point, splitCenter, splitCenter); + + VectorMA(base, -lx, refdef->viewaxis[1], point); + VectorMA(point, -ly, refdef->viewaxis[2], point); + VectorCopy(point, frustrumPoint7); + VectorAdd(point, splitCenter, splitCenter); + + VectorScale(splitCenter, 1.0f / 8.0f, splitCenter); + radius = Distance(frustrumPoint0, frustrumPoint7) / 2.0f; + lightviewBounds[0][0] = -radius; + lightviewBounds[0][1] = -radius; + lightviewBounds[0][2] = -radius; + lightviewBounds[1][0] = radius; + lightviewBounds[1][1] = radius; + lightviewBounds[1][2] = radius; + + VectorCopy(splitCenter, lightOrigin); + } + + orientationr_t orientation = {}; + R_SetOrientationOriginAndAxis(orientation, lightOrigin, lightViewAxis); + + R_SetupViewParmsForOrthoRendering( + tr.sunShadowFbo[level]->width, + tr.sunShadowFbo[level]->height, + tr.sunShadowFbo[level], + VPF_DEPTHSHADOW | VPF_DEPTHCLAMP | VPF_ORTHOGRAPHIC | VPF_NOVIEWMODEL | VPF_SHADOWCASCADES, + orientation, + lightviewBounds); + + // Moving the Light in Texel-Sized Increments + // from http://msdn.microsoft.com/en-us/library/windows/desktop/ee416324%28v=vs.85%29.aspx + static float worldUnitsPerTexel = 2.0f * lightviewBounds[1][0] / (float)tr.sunShadowFbo[level]->width; + static float invWorldUnitsPerTexel = tr.sunShadowFbo[level]->width / (2.0f * lightviewBounds[1][0]); + + tr.viewParms.world.modelViewMatrix[12] = floorf(tr.viewParms.world.modelViewMatrix[12] * invWorldUnitsPerTexel); + tr.viewParms.world.modelViewMatrix[13] = floorf(tr.viewParms.world.modelViewMatrix[13] * invWorldUnitsPerTexel); + tr.viewParms.world.modelViewMatrix[14] = floorf(tr.viewParms.world.modelViewMatrix[14] * invWorldUnitsPerTexel); + + tr.viewParms.world.modelViewMatrix[12] *= worldUnitsPerTexel; + tr.viewParms.world.modelViewMatrix[13] *= worldUnitsPerTexel; + tr.viewParms.world.modelViewMatrix[14] *= worldUnitsPerTexel; + + Matrix16Multiply( + tr.viewParms.projectionMatrix, + tr.viewParms.world.modelViewMatrix, + refdef->sunShadowMvp[level]); + + tr.viewParms.currentViewParm = tr.numCachedViewParms; + tr.viewParms.viewParmType = VPT_SUN_SHADOWS; + Com_Memcpy(&tr.cachedViewParms[tr.numCachedViewParms], &tr.viewParms, sizeof(viewParms_t)); + tr.numCachedViewParms++; + } + mainFlags |= VPF_USESUNLIGHT; + } + } + + // main view + { + R_SetupViewParms(refdef); + if (R_AddPortalView(refdef)) + { + // this is a debug option to see exactly what is being mirrored + if (r_portalOnly->integer) + return; + + R_SetupViewParms(refdef); + } + + tr.viewParms.stereoFrame = STEREO_CENTER; // FIXME + tr.viewParms.flags = mainFlags; + + tr.viewParms.currentViewParm = tr.numCachedViewParms; + tr.viewParms.viewParmType = VPT_MAIN; + Com_Memcpy(&tr.cachedViewParms[tr.numCachedViewParms], &tr.viewParms, sizeof(viewParms_t)); + tr.numCachedViewParms++; + } +} diff --git a/codemp/rd-rend2/tr_marks.cpp b/codemp/rd-rend2/tr_marks.cpp new file mode 100644 index 0000000000..6e12616d13 --- /dev/null +++ b/codemp/rd-rend2/tr_marks.cpp @@ -0,0 +1,466 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_marks.c -- polygon projection on the world polygons + +#include "tr_local.h" +//#include "assert.h" + +#define MAX_VERTS_ON_POLY 64 + +#define MARKER_OFFSET 0 // 1 + +/* +============= +R_ChopPolyBehindPlane + +Out must have space for two more vertexes than in +============= +*/ +#define SIDE_FRONT 0 +#define SIDE_BACK 1 +#define SIDE_ON 2 +static void R_ChopPolyBehindPlane( int numInPoints, vec3_t inPoints[MAX_VERTS_ON_POLY], + int *numOutPoints, vec3_t outPoints[MAX_VERTS_ON_POLY], + vec3_t normal, float dist, float epsilon) { + float dists[MAX_VERTS_ON_POLY+4] = { 0 }; + int sides[MAX_VERTS_ON_POLY+4] = { 0 }; + int counts[3]; + float dot; + int i, j; + float *p1, *p2, *clip; + float d; + + // don't clip if it might overflow + if ( numInPoints >= MAX_VERTS_ON_POLY - 2 ) { + *numOutPoints = 0; + return; + } + + counts[0] = counts[1] = counts[2] = 0; + + // determine sides for each point + for ( i = 0 ; i < numInPoints ; i++ ) { + dot = DotProduct( inPoints[i], normal ); + dot -= dist; + dists[i] = dot; + if ( dot > epsilon ) { + sides[i] = SIDE_FRONT; + } else if ( dot < -epsilon ) { + sides[i] = SIDE_BACK; + } else { + sides[i] = SIDE_ON; + } + counts[sides[i]]++; + } + sides[i] = sides[0]; + dists[i] = dists[0]; + + *numOutPoints = 0; + + if ( !counts[0] ) { + return; + } + if ( !counts[1] ) { + *numOutPoints = numInPoints; + Com_Memcpy( outPoints, inPoints, numInPoints * sizeof(vec3_t) ); + return; + } + + for ( i = 0 ; i < numInPoints ; i++ ) { + p1 = inPoints[i]; + clip = outPoints[ *numOutPoints ]; + + if ( sides[i] == SIDE_ON ) { + VectorCopy( p1, clip ); + (*numOutPoints)++; + continue; + } + + if ( sides[i] == SIDE_FRONT ) { + VectorCopy( p1, clip ); + (*numOutPoints)++; + clip = outPoints[ *numOutPoints ]; + } + + if ( sides[i+1] == SIDE_ON || sides[i+1] == sides[i] ) { + continue; + } + + // generate a split point + p2 = inPoints[ (i+1) % numInPoints ]; + + d = dists[i] - dists[i+1]; + if ( d == 0 ) { + dot = 0; + } else { + dot = dists[i] / d; + } + + // clip xyz + + for (j=0 ; j<3 ; j++) { + clip[j] = p1[j] + dot * ( p2[j] - p1[j] ); + } + + (*numOutPoints)++; + } +} + +/* +================= +R_BoxSurfaces_r + +================= +*/ +void R_BoxSurfaces_r(mnode_t *node, vec3_t mins, vec3_t maxs, surfaceType_t **list, int listsize, int *listlength, vec3_t dir) { + + int s, c; + msurface_t *surf; + int *mark; + + // do the tail recursion in a loop + while ( node->contents == -1 ) { + s = BoxOnPlaneSide( mins, maxs, node->plane ); + if (s == 1) { + node = node->children[0]; + } else if (s == 2) { + node = node->children[1]; + } else { + R_BoxSurfaces_r(node->children[0], mins, maxs, list, listsize, listlength, dir); + node = node->children[1]; + } + } + + // add the individual surfaces + mark = tr.world->marksurfaces + node->firstmarksurface; + c = node->nummarksurfaces; + while (c--) { + int *surfViewCount; + // + if (*listlength >= listsize) break; + // + surfViewCount = &tr.world->surfacesViewCount[*mark]; + surf = tr.world->surfaces + *mark; + // check if the surface has NOIMPACT or NOMARKS set + if ( ( surf->shader->surfaceFlags & ( SURF_NOIMPACT | SURF_NOMARKS ) ) + || ( surf->shader->contentFlags & CONTENTS_FOG ) ) { + *surfViewCount = tr.viewCount; + } + // extra check for surfaces to avoid list overflows + else if (*(surf->data) == SF_FACE) { + // the face plane should go through the box + s = BoxOnPlaneSide( mins, maxs, &surf->cullinfo.plane ); + if (s == 1 || s == 2) { + *surfViewCount = tr.viewCount; + } else if (DotProduct(surf->cullinfo.plane.normal, dir) > -0.5) { + // don't add faces that make sharp angles with the projection direction + *surfViewCount = tr.viewCount; + } + } + else if (*(surf->data) != SF_GRID && + *(surf->data) != SF_TRIANGLES) + *surfViewCount = tr.viewCount; + // check the viewCount because the surface may have + // already been added if it spans multiple leafs + if (*surfViewCount != tr.viewCount) { + *surfViewCount = tr.viewCount; + list[*listlength] = surf->data; + (*listlength)++; + } + mark++; + } +} + +/* +================= +R_AddMarkFragments + +================= +*/ +void R_AddMarkFragments(int numClipPoints, vec3_t clipPoints[2][MAX_VERTS_ON_POLY], + int numPlanes, vec3_t *normals, float *dists, + int maxPoints, vec3_t pointBuffer, + int maxFragments, markFragment_t *fragmentBuffer, + int *returnedPoints, int *returnedFragments, + vec3_t mins, vec3_t maxs) { + int pingPong, i; + markFragment_t *mf; + + // chop the surface by all the bounding planes of the to be projected polygon + pingPong = 0; + + for ( i = 0 ; i < numPlanes ; i++ ) { + + R_ChopPolyBehindPlane( numClipPoints, clipPoints[pingPong], + &numClipPoints, clipPoints[!pingPong], + normals[i], dists[i], 0.5 ); + pingPong ^= 1; + if ( numClipPoints == 0 ) { + break; + } + } + // completely clipped away? + if ( numClipPoints == 0 ) { + return; + } + + // add this fragment to the returned list + if ( numClipPoints + (*returnedPoints) > maxPoints ) { + return; // not enough space for this polygon + } + /* + // all the clip points should be within the bounding box + for ( i = 0 ; i < numClipPoints ; i++ ) { + int j; + for ( j = 0 ; j < 3 ; j++ ) { + if (clipPoints[pingPong][i][j] < mins[j] - 0.5) break; + if (clipPoints[pingPong][i][j] > maxs[j] + 0.5) break; + } + if (j < 3) break; + } + if (i < numClipPoints) return; + */ + + mf = fragmentBuffer + (*returnedFragments); + mf->firstPoint = (*returnedPoints); + mf->numPoints = numClipPoints; + Com_Memcpy( pointBuffer + (*returnedPoints) * 3, clipPoints[pingPong], numClipPoints * sizeof(vec3_t) ); + + (*returnedPoints) += numClipPoints; + (*returnedFragments)++; +} + +/* +================= +R_MarkFragments + +================= +*/ +int R_MarkFragments( int numPoints, const vec3_t *points, const vec3_t projection, + int maxPoints, vec3_t pointBuffer, int maxFragments, markFragment_t *fragmentBuffer ) { + int numsurfaces, numPlanes; + int i, j, k, m, n; + surfaceType_t *surfaces[64]; + vec3_t mins, maxs; + int returnedFragments; + int returnedPoints; + vec3_t normals[MAX_VERTS_ON_POLY+2]; + float dists[MAX_VERTS_ON_POLY+2]; + vec3_t clipPoints[2][MAX_VERTS_ON_POLY]; + int numClipPoints; + float *v; + srfBspSurface_t *cv; + glIndex_t *tri; + srfVert_t *dv; + vec3_t normal; + vec3_t projectionDir; + vec3_t v1, v2; + + if (numPoints <= 0) { + return 0; + } + + //increment view count for double check prevention + tr.viewCount++; + + // + VectorNormalize2( projection, projectionDir ); + // find all the brushes that are to be considered + ClearBounds( mins, maxs ); + for ( i = 0 ; i < numPoints ; i++ ) { + vec3_t temp; + + AddPointToBounds( points[i], mins, maxs ); + VectorAdd( points[i], projection, temp ); + AddPointToBounds( temp, mins, maxs ); + // make sure we get all the leafs (also the one(s) in front of the hit surface) + VectorMA( points[i], -20, projectionDir, temp ); + AddPointToBounds( temp, mins, maxs ); + } + + if (numPoints > MAX_VERTS_ON_POLY) numPoints = MAX_VERTS_ON_POLY; + // create the bounding planes for the to be projected polygon + for ( i = 0 ; i < numPoints ; i++ ) { + VectorSubtract(points[(i+1)%numPoints], points[i], v1); + VectorAdd(points[i], projection, v2); + VectorSubtract(points[i], v2, v2); + CrossProduct(v1, v2, normals[i]); + VectorNormalizeFast(normals[i]); + dists[i] = DotProduct(normals[i], points[i]); + } + // add near and far clipping planes for projection + VectorCopy(projectionDir, normals[numPoints]); + dists[numPoints] = DotProduct(normals[numPoints], points[0]) - 32; + VectorCopy(projectionDir, normals[numPoints+1]); + VectorInverse(normals[numPoints+1]); + dists[numPoints+1] = DotProduct(normals[numPoints+1], points[0]) - 20; + numPlanes = numPoints + 2; + + numsurfaces = 0; + R_BoxSurfaces_r(tr.world->nodes, mins, maxs, surfaces, 64, &numsurfaces, projectionDir); + //assert(numsurfaces <= 64); + //assert(numsurfaces != 64); + + returnedPoints = 0; + returnedFragments = 0; + + for ( i = 0 ; i < numsurfaces ; i++ ) { + + if (*surfaces[i] == SF_GRID) { + + cv = (srfBspSurface_t *) surfaces[i]; + for ( m = 0 ; m < cv->height - 1 ; m++ ) { + for ( n = 0 ; n < cv->width - 1 ; n++ ) { + // We triangulate the grid and chop all triangles within + // the bounding planes of the to be projected polygon. + // LOD is not taken into account, not such a big deal though. + // + // It's probably much nicer to chop the grid itself and deal + // with this grid as a normal SF_GRID surface so LOD will + // be applied. However the LOD of that chopped grid must + // be synced with the LOD of the original curve. + // One way to do this; the chopped grid shares vertices with + // the original curve. When LOD is applied to the original + // curve the unused vertices are flagged. Now the chopped curve + // should skip the flagged vertices. This still leaves the + // problems with the vertices at the chopped grid edges. + // + // To avoid issues when LOD applied to "hollow curves" (like + // the ones around many jump pads) we now just add a 2 unit + // offset to the triangle vertices. + // The offset is added in the vertex normal vector direction + // so all triangles will still fit together. + // The 2 unit offset should avoid pretty much all LOD problems. + + numClipPoints = 3; + + dv = cv->verts + m * cv->width + n; + + VectorCopy(dv[0].xyz, clipPoints[0][0]); + VectorMA(clipPoints[0][0], MARKER_OFFSET, dv[0].normal, clipPoints[0][0]); + VectorCopy(dv[cv->width].xyz, clipPoints[0][1]); + VectorMA(clipPoints[0][1], MARKER_OFFSET, dv[cv->width].normal, clipPoints[0][1]); + VectorCopy(dv[1].xyz, clipPoints[0][2]); + VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[1].normal, clipPoints[0][2]); + // check the normal of this triangle + VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1); + VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2); + CrossProduct(v1, v2, normal); + VectorNormalizeFast(normal); + if (DotProduct(normal, projectionDir) < -0.1) { + // add the fragments of this triangle + R_AddMarkFragments(numClipPoints, clipPoints, + numPlanes, normals, dists, + maxPoints, pointBuffer, + maxFragments, fragmentBuffer, + &returnedPoints, &returnedFragments, mins, maxs); + + if ( returnedFragments == maxFragments ) { + return returnedFragments; // not enough space for more fragments + } + } + + VectorCopy(dv[1].xyz, clipPoints[0][0]); + VectorMA(clipPoints[0][0], MARKER_OFFSET, dv[1].normal, clipPoints[0][0]); + VectorCopy(dv[cv->width].xyz, clipPoints[0][1]); + VectorMA(clipPoints[0][1], MARKER_OFFSET, dv[cv->width].normal, clipPoints[0][1]); + VectorCopy(dv[cv->width+1].xyz, clipPoints[0][2]); + VectorMA(clipPoints[0][2], MARKER_OFFSET, dv[cv->width+1].normal, clipPoints[0][2]); + // check the normal of this triangle + VectorSubtract(clipPoints[0][0], clipPoints[0][1], v1); + VectorSubtract(clipPoints[0][2], clipPoints[0][1], v2); + CrossProduct(v1, v2, normal); + VectorNormalizeFast(normal); + if (DotProduct(normal, projectionDir) < -0.05) { + // add the fragments of this triangle + R_AddMarkFragments(numClipPoints, clipPoints, + numPlanes, normals, dists, + maxPoints, pointBuffer, + maxFragments, fragmentBuffer, + &returnedPoints, &returnedFragments, mins, maxs); + + if ( returnedFragments == maxFragments ) { + return returnedFragments; // not enough space for more fragments + } + } + } + } + } + else if (*surfaces[i] == SF_FACE) { + + srfBspSurface_t *surf = ( srfBspSurface_t * ) surfaces[i]; + + // check the normal of this face + if (DotProduct(surf->cullPlane.normal, projectionDir) > -0.5) { + continue; + } + + for(k = 0, tri = surf->indexes; k < surf->numIndexes; k += 3, tri += 3) + { + for(j = 0; j < 3; j++) + { + v = surf->verts[tri[j]].xyz; + VectorMA(v, MARKER_OFFSET, surf->cullPlane.normal, clipPoints[0][j]); + } + + // add the fragments of this face + R_AddMarkFragments( 3 , clipPoints, + numPlanes, normals, dists, + maxPoints, pointBuffer, + maxFragments, fragmentBuffer, + &returnedPoints, &returnedFragments, mins, maxs); + if ( returnedFragments == maxFragments ) { + return returnedFragments; // not enough space for more fragments + } + } + } + else if(*surfaces[i] == SF_TRIANGLES && r_marksOnTriangleMeshes->integer) { + + srfBspSurface_t *surf = (srfBspSurface_t *) surfaces[i]; + + for(k = 0, tri = surf->indexes; k < surf->numIndexes; k += 3, tri += 3) + { + for(j = 0; j < 3; j++) + { + v = surf->verts[tri[j]].xyz; + VectorMA(v, MARKER_OFFSET, surf->verts[tri[j]].normal, clipPoints[0][j]); + } + + // add the fragments of this face + R_AddMarkFragments(3, clipPoints, + numPlanes, normals, dists, + maxPoints, pointBuffer, + maxFragments, fragmentBuffer, &returnedPoints, &returnedFragments, mins, maxs); + if(returnedFragments == maxFragments) + { + return returnedFragments; // not enough space for more fragments + } + } + } + } + return returnedFragments; +} + + + + + diff --git a/codemp/rd-rend2/tr_mesh.cpp b/codemp/rd-rend2/tr_mesh.cpp new file mode 100644 index 0000000000..e242d79ee0 --- /dev/null +++ b/codemp/rd-rend2/tr_mesh.cpp @@ -0,0 +1,400 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_mesh.c: triangle model functions + +#include "tr_local.h" + +float ProjectRadius( float r, vec3_t location ) +{ + float pr; + float dist; + float c; + vec3_t p; + float projected[4]; + + c = DotProduct( tr.viewParms.ori.axis[0], tr.viewParms.ori.origin ); + dist = DotProduct( tr.viewParms.ori.axis[0], location ) - c; + + if ( dist <= 0 ) + return 0; + + p[0] = 0; + p[1] = fabs( r ); + p[2] = -dist; + + projected[0] = p[0] * tr.viewParms.projectionMatrix[0] + + p[1] * tr.viewParms.projectionMatrix[4] + + p[2] * tr.viewParms.projectionMatrix[8] + + tr.viewParms.projectionMatrix[12]; + + projected[1] = p[0] * tr.viewParms.projectionMatrix[1] + + p[1] * tr.viewParms.projectionMatrix[5] + + p[2] * tr.viewParms.projectionMatrix[9] + + tr.viewParms.projectionMatrix[13]; + + projected[2] = p[0] * tr.viewParms.projectionMatrix[2] + + p[1] * tr.viewParms.projectionMatrix[6] + + p[2] * tr.viewParms.projectionMatrix[10] + + tr.viewParms.projectionMatrix[14]; + + projected[3] = p[0] * tr.viewParms.projectionMatrix[3] + + p[1] * tr.viewParms.projectionMatrix[7] + + p[2] * tr.viewParms.projectionMatrix[11] + + tr.viewParms.projectionMatrix[15]; + + + pr = projected[1] / projected[3]; + + if ( pr > 1.0f ) + pr = 1.0f; + + return pr; +} + +/* +============= +R_CullModel +============= +*/ +static int R_CullModel( mdvModel_t *model, trRefEntity_t *ent ) { + vec3_t bounds[2]; + mdvFrame_t *oldFrame, *newFrame; + int i; + + // compute frame pointers + newFrame = model->frames + ent->e.frame; + oldFrame = model->frames + ent->e.oldframe; + + // cull bounding sphere ONLY if this is not an upscaled entity + if ( !ent->e.nonNormalizedAxes ) + { + if ( ent->e.frame == ent->e.oldframe ) + { + switch ( R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ) ) + { + case CULL_OUT: + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; + + case CULL_IN: + tr.pc.c_sphere_cull_md3_in++; + return CULL_IN; + + case CULL_CLIP: + tr.pc.c_sphere_cull_md3_clip++; + break; + } + } + else + { + int sphereCull, sphereCullB; + + sphereCull = R_CullLocalPointAndRadius( newFrame->localOrigin, newFrame->radius ); + if ( newFrame == oldFrame ) { + sphereCullB = sphereCull; + } else { + sphereCullB = R_CullLocalPointAndRadius( oldFrame->localOrigin, oldFrame->radius ); + } + + if ( sphereCull == sphereCullB ) + { + if ( sphereCull == CULL_OUT ) + { + tr.pc.c_sphere_cull_md3_out++; + return CULL_OUT; + } + else if ( sphereCull == CULL_IN ) + { + tr.pc.c_sphere_cull_md3_in++; + return CULL_IN; + } + else + { + tr.pc.c_sphere_cull_md3_clip++; + } + } + } + } + + // calculate a bounding box in the current coordinate system + for (i = 0 ; i < 3 ; i++) { + bounds[0][i] = oldFrame->bounds[0][i] < newFrame->bounds[0][i] ? oldFrame->bounds[0][i] : newFrame->bounds[0][i]; + bounds[1][i] = oldFrame->bounds[1][i] > newFrame->bounds[1][i] ? oldFrame->bounds[1][i] : newFrame->bounds[1][i]; + } + + switch ( R_CullLocalBox( bounds ) ) + { + case CULL_IN: + tr.pc.c_box_cull_md3_in++; + return CULL_IN; + case CULL_CLIP: + tr.pc.c_box_cull_md3_clip++; + return CULL_CLIP; + case CULL_OUT: + default: + tr.pc.c_box_cull_md3_out++; + return CULL_OUT; + } +} + + +/* +================= +R_ComputeLOD + +================= +*/ +int R_ComputeLOD( trRefEntity_t *ent ) { + float radius; + float flod, lodscale; + float projectedRadius; + mdvFrame_t *frame; + mdrHeader_t *mdr; + mdrFrame_t *mdrframe; + int lod; + + if ( tr.currentModel->numLods < 2 || (ent->e.renderfx & RF_NOLOD) ) + { + // model has only 1 LOD level, skip computations and bias + lod = 0; + } + else + { + // multiple LODs exist, so compute projected bounding sphere + // and use that as a criteria for selecting LOD + + if(tr.currentModel->type == MOD_MDR) + { + int frameSize; + mdr = tr.currentModel->data.mdr; + frameSize = (size_t) (&((mdrFrame_t *)0)->bones[mdr->numBones]); + + mdrframe = (mdrFrame_t *) ((byte *) mdr + mdr->ofsFrames + frameSize * ent->e.frame); + + radius = RadiusFromBounds(mdrframe->bounds[0], mdrframe->bounds[1]); + } + else + { + //frame = ( md3Frame_t * ) ( ( ( unsigned char * ) tr.currentModel->md3[0] ) + tr.currentModel->md3[0]->ofsFrames ); + frame = tr.currentModel->data.mdv[0]->frames; + + frame += ent->e.frame; + + radius = RadiusFromBounds( frame->bounds[0], frame->bounds[1] ); + } + + if ( ( projectedRadius = ProjectRadius( radius, ent->e.origin ) ) != 0 ) + { + lodscale = (r_lodscale->value+r_autolodscalevalue->integer); + if (lodscale > 20) lodscale = 20; + flod = 1.0f - projectedRadius * lodscale; + } + else + { + // object intersects near view plane, e.g. view weapon + flod = 0; + } + + flod *= tr.currentModel->numLods; + lod = Q_ftol(flod); + + if ( lod < 0 ) + { + lod = 0; + } + else if ( lod >= tr.currentModel->numLods ) + { + lod = tr.currentModel->numLods - 1; + } + } + if (!(ent->e.renderfx & RF_NOLOD)) + lod += r_lodbias->integer; + + if ( lod >= tr.currentModel->numLods ) + lod = tr.currentModel->numLods - 1; + if ( lod < 0 ) + lod = 0; + + return lod; +} + +/* +================= +R_ComputeFogNum + +================= +*/ +int R_ComputeFogNum( mdvModel_t *model, trRefEntity_t *ent ) { + int i, j; + fog_t *fog; + mdvFrame_t *mdvFrame; + vec3_t localOrigin; + + if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + return 0; + } + + // FIXME: non-normalized axis issues + mdvFrame = model->frames + ent->e.frame; + VectorAdd( ent->e.origin, mdvFrame->localOrigin, localOrigin ); + for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + fog = &tr.world->fogs[i]; + for ( j = 0 ; j < 3 ; j++ ) { + if ( localOrigin[j] - mdvFrame->radius >= fog->bounds[1][j] ) { + break; + } + if ( localOrigin[j] + mdvFrame->radius <= fog->bounds[0][j] ) { + break; + } + } + if ( j == 3 ) { + return i; + } + } + + return 0; +} + +/* +================= +R_AddMD3Surfaces + +================= +*/ +void R_AddMD3Surfaces( trRefEntity_t *ent, int entityNum ) { + int i; + mdvModel_t *model = NULL; + mdvSurface_t *surface = NULL; + shader_t *shader = NULL; + int cull; + int lod; + int fogNum; + int cubemapIndex; + qboolean personalModel; + + // don't add third_person objects if not in a portal + personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !(tr.viewParms.isPortal + || (tr.viewParms.flags & VPF_DEPTHSHADOW))); + + if ( ent->e.renderfx & RF_WRAP_FRAMES ) { + ent->e.frame %= tr.currentModel->data.mdv[0]->numFrames; + ent->e.oldframe %= tr.currentModel->data.mdv[0]->numFrames; + } + + // + // Validate the frames so there is no chance of a crash. + // This will write directly into the entity structure, so + // when the surfaces are rendered, they don't need to be + // range checked again. + // + if ( (ent->e.frame >= tr.currentModel->data.mdv[0]->numFrames) + || (ent->e.frame < 0) + || (ent->e.oldframe >= tr.currentModel->data.mdv[0]->numFrames) + || (ent->e.oldframe < 0) ) { + ri.Printf( PRINT_DEVELOPER, "R_AddMD3Surfaces: no such frame %d to %d for '%s'\n", + ent->e.oldframe, ent->e.frame, + tr.currentModel->name ); + ent->e.frame = 0; + ent->e.oldframe = 0; + } + + // + // compute LOD + // + lod = R_ComputeLOD( ent ); + + model = tr.currentModel->data.mdv[lod]; + + // + // cull the entire model if merged bounding box of both frames + // is outside the view frustum. + // + cull = R_CullModel ( model, ent ); + if ( cull == CULL_OUT ) { + return; + } + + // + // see if we are in a fog volume + // + fogNum = R_ComputeFogNum( model, ent ); + + cubemapIndex = R_CubemapForPoint(ent->e.origin); + // FIX ME: not tested! Animated models might be handled incorrecly + int dlightBits = R_DLightsForPoint(ent->e.origin, model->frames[ent->e.frame].radius); + + // + // draw all surfaces + // + surface = model->surfaces; + for ( i = 0 ; i < model->numSurfaces ; i++ ) { + + if ( ent->e.customShader ) { + shader = R_GetShaderByHandle( ent->e.customShader ); + } else if ( ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins ) { + skin_t *skin; + int j; + + skin = R_GetSkinByHandle( ent->e.customSkin ); + + // match the surface name to something in the skin file + shader = tr.defaultShader; + for ( j = 0 ; j < skin->numSurfaces ; j++ ) { + // the names have both been lowercased + if ( !strcmp( skin->surfaces[j]->name, surface->name ) ) { + shader = (shader_t *)skin->surfaces[j]->shader; + break; + } + } + if (shader == tr.defaultShader) { + ri.Printf( PRINT_DEVELOPER, "WARNING: no shader for surface %s in skin %s\n", surface->name, skin->name); + } + else if (shader->defaultShader) { + ri.Printf( PRINT_DEVELOPER, "WARNING: shader %s in skin %s not found\n", shader->name, skin->name); + } + //} else if ( surface->numShaders <= 0 ) { + //shader = tr.defaultShader; + } else { + //md3Shader = (md3Shader_t *) ( (byte *)surface + surface->ofsShaders ); + //md3Shader += ent->e.skinNum % surface->numShaders; + //shader = tr.shaders[ md3Shader->shaderIndex ]; + shader = tr.shaders[ surface->shaderIndexes[ ent->e.skinNum % surface->numShaderIndexes ] ]; + } + + // don't add third_person objects if not viewing through a portal + if(!personalModel) + { + srfVBOMDVMesh_t *vboSurface = &model->vboSurfaces[i]; + + R_AddDrawSurf((surfaceType_t *)vboSurface, entityNum, shader, fogNum, dlightBits, R_IsPostRenderEntity(ent), cubemapIndex ); + //R_AddDrawSurf((surfaceType_t *)vboSurface, entityNum, shader, fogNum, qfalse, R_IsPostRenderEntity(ent), cubemapIndex ); + } + + surface++; + } + +} + + + + + diff --git a/codemp/rd-rend2/tr_model.cpp b/codemp/rd-rend2/tr_model.cpp new file mode 100644 index 0000000000..0f9d746110 --- /dev/null +++ b/codemp/rd-rend2/tr_model.cpp @@ -0,0 +1,1838 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_models.c -- model loading and caching + +#include "tr_local.h" +#include "tr_cache.h" +#include + +#define LL(x) x=LittleLong(x) + + +static qboolean R_LoadMD3(model_t *mod, int lod, void *buffer, const char *modName); +static qboolean R_LoadMDR(model_t *mod, void *buffer, int filesize, const char *name ); + +/* +==================== +R_RegisterMD3 +==================== +*/ +qhandle_t R_RegisterMD3(const char *name, model_t *mod) +{ + unsigned *buf; + int lod; + int ident; + qboolean loaded = qfalse; + int numLoaded; + char filename[MAX_QPATH], namebuf[MAX_QPATH+20]; + char *fext, defex[] = "md3"; + + numLoaded = 0; + + strcpy(filename, name); + + fext = strchr(filename, '.'); + if(!fext) + fext = defex; + else + { + *fext = '\0'; + fext++; + } + + for (lod = MD3_MAX_LODS - 1 ; lod >= 0 ; lod--) + { + if(lod) + Com_sprintf(namebuf, sizeof(namebuf), "%s_%d.%s", filename, lod, fext); + else + Com_sprintf(namebuf, sizeof(namebuf), "%s.%s", filename, fext); + + qboolean bAlreadyCached = qfalse; + if( !CModelCache->LoadFile( namebuf, (void**)&buf, &bAlreadyCached ) ) + continue; + + ident = *(unsigned *)buf; + if( !bAlreadyCached ) + LL(ident); + + switch(ident) + { + case MD3_IDENT: + loaded = R_LoadMD3(mod, lod, buf, namebuf); + break; + case MDXA_IDENT: + loaded = R_LoadMDXA(mod, buf, namebuf, bAlreadyCached); + break; + case MDXM_IDENT: + loaded = R_LoadMDXM(mod, buf, name, bAlreadyCached); + break; + default: + ri.Printf(PRINT_WARNING, "R_RegisterMD3: unknown ident for %s\n", name); + break; + } + + if(loaded) + { + mod->numLods++; + numLoaded++; + } + else + break; + } + + if(numLoaded) + { + // duplicate into higher lod spots that weren't + // loaded, in case the user changes r_lodbias on the fly + for(lod--; lod >= 0; lod--) + { + mod->numLods++; + mod->data.mdv[lod] = mod->data.mdv[lod + 1]; + } + + return mod->index; + } + +#ifdef _DEBUG + ri.Printf(PRINT_WARNING,"R_RegisterMD3: couldn't load %s\n", name); +#endif + + mod->type = MOD_BAD; + return 0; +} + +/* +==================== +R_RegisterMDR +==================== +*/ +qhandle_t R_RegisterMDR(const char *name, model_t *mod) +{ + union { + unsigned *u; + void *v; + } buf; + int ident; + qboolean loaded = qfalse; + int filesize; + + filesize = ri.FS_ReadFile(name, (void **) &buf.v); + if(!buf.u) + { + mod->type = MOD_BAD; + return 0; + } + + ident = LittleLong(*(unsigned *)buf.u); + if(ident == MDR_IDENT) + loaded = R_LoadMDR(mod, buf.u, filesize, name); + + ri.FS_FreeFile (buf.v); + + if(!loaded) + { + ri.Printf(PRINT_WARNING,"R_RegisterMDR: couldn't load mdr file %s\n", name); + mod->type = MOD_BAD; + return 0; + } + + return mod->index; +} + +/* +==================== +R_RegisterIQM +==================== +*/ +qhandle_t R_RegisterIQM(const char *name, model_t *mod) +{ + union { + unsigned *u; + void *v; + } buf; + qboolean loaded = qfalse; + int filesize; + + filesize = ri.FS_ReadFile(name, (void **) &buf.v); + if(!buf.u) + { + mod->type = MOD_BAD; + return 0; + } + + loaded = R_LoadIQM(mod, buf.u, filesize, name); + + ri.FS_FreeFile (buf.v); + + if(!loaded) + { + ri.Printf(PRINT_WARNING,"R_RegisterIQM: couldn't load iqm file %s\n", name); + mod->type = MOD_BAD; + return 0; + } + + return mod->index; +} + + +typedef struct +{ + const char *ext; + qhandle_t (*ModelLoader)( const char *, model_t * ); +} modelExtToLoaderMap_t; + +// Note that the ordering indicates the order of preference used +// when there are multiple models of different formats available +static modelExtToLoaderMap_t modelLoaders[ ] = +{ + { "iqm", R_RegisterIQM }, + { "mdr", R_RegisterMDR }, + { "md3", R_RegisterMD3 }, + /* + Ghoul 2 Insert Start + */ + { "glm", R_RegisterMD3 }, + { "gla", R_RegisterMD3 }, + /* + Ghoul 2 Insert End + */ +}; + +static int numModelLoaders = ARRAY_LEN(modelLoaders); + +/* +** R_GetModelByHandle +*/ +model_t *R_GetModelByHandle( qhandle_t index ) { + model_t *mod; + + // out of range gets the defualt model + if ( index < 1 || index >= tr.numModels ) { + return tr.models[0]; + } + + mod = tr.models[index]; + + return mod; +} + +//=============================================================================== + +/* +** R_AllocModel +*/ +model_t *R_AllocModel( void ) { + model_t *mod; + + if ( tr.numModels == MAX_MOD_KNOWN ) { + return NULL; + } + + mod = (model_t *)ri.Hunk_Alloc( sizeof( *tr.models[tr.numModels] ), h_low ); + mod->index = tr.numModels; + tr.models[tr.numModels] = mod; + tr.numModels++; + + return mod; +} + +static qhandle_t RE_RegisterBSP(const char *name) +{ + char bspFilePath[MAX_QPATH]; + Com_sprintf(bspFilePath, sizeof(bspFilePath), "maps/%s.bsp", name + 1); + + int bspIndex; + world_t *world = R_LoadBSP(bspFilePath, &bspIndex); + if (world == nullptr) + { + return 0; + } + + char bspModelIdent[MAX_QPATH]; + Com_sprintf(bspModelIdent, sizeof(bspModelIdent), "*%d-0", bspIndex); + + qhandle_t modelHandle = CModelCache->GetModelHandle(bspModelIdent); + if (modelHandle == -1) + { + return 0; + } + + return modelHandle; +} + +/* +==================== +RE_RegisterModel + +Loads in a model for the given name + +Zero will be returned if the model fails to load. +An entry will be retained for failed models as an +optimization to prevent disk rescanning if they are +asked for again. +==================== +*/ +qhandle_t RE_RegisterModel( const char *name ) { + model_t *mod; + qhandle_t hModel; + qboolean orgNameFailed = qfalse; + int orgLoader = -1; + int i; + char localName[ MAX_QPATH ]; + const char *ext; + char altName[ MAX_QPATH ]; + + if ( !name || !name[0] ) { + ri.Printf( PRINT_ALL, "RE_RegisterModel: NULL name\n" ); + return 0; + } + + if ( strlen( name ) >= MAX_QPATH ) { + ri.Printf( PRINT_ALL, "Model name exceeds MAX_QPATH\n" ); + return 0; + } + + // search the currently loaded models + if( ( hModel = CModelCache->GetModelHandle( name ) ) != -1 ) + return hModel; + + if ( name[0] == '*' ) + { + if ( strcmp (name, "*default.gla") != 0 ) + { + return 0; + } + } + + if( name[0] == '#' ) + { + return RE_RegisterBSP(name); + } + + // allocate a new model_t + if ( ( mod = R_AllocModel() ) == NULL ) { + ri.Printf( PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); + return 0; + } + + // only set the name after the model has been successfully loaded + Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + + R_IssuePendingRenderCommands(); + + mod->type = MOD_BAD; + mod->numLods = 0; + + // + // load the files + // + Q_strncpyz( localName, name, MAX_QPATH ); + + ext = COM_GetExtension( localName ); + + if( *ext ) + { + // Look for the correct loader and use it + for( i = 0; i < numModelLoaders; i++ ) + { + if( !Q_stricmp( ext, modelLoaders[ i ].ext ) ) + { + // Load + hModel = modelLoaders[ i ].ModelLoader( localName, mod ); + break; + } + } + + // A loader was found + if( i < numModelLoaders ) + { + if( !hModel ) + { + // Loader failed, most likely because the file isn't there; + // try again without the extension + orgNameFailed = qtrue; + orgLoader = i; + COM_StripExtension( name, localName, MAX_QPATH ); + } + else + { + // Something loaded + CModelCache->InsertModelHandle( name, hModel ); + return mod->index; + } + } + } + + // Try and find a suitable match using all + // the model formats supported + for( i = 0; i < numModelLoaders; i++ ) + { + if (i == orgLoader) + continue; + + Com_sprintf( altName, sizeof (altName), "%s.%s", localName, modelLoaders[ i ].ext ); + + // Load + hModel = modelLoaders[ i ].ModelLoader( altName, mod ); + + if( hModel ) + { + if( orgNameFailed ) + { + ri.Printf( PRINT_DEVELOPER, "WARNING: %s not present, using %s instead\n", + name, altName ); + } + + break; + } + } + + CModelCache->InsertModelHandle( name, hModel ); + return hModel; +} + +//rww - Please forgive me for all of the below. Feel free to destroy it and replace it with something better. +//You obviously can't touch anything relating to shaders or ri-> functions here in case a dedicated +//server is running, which is the entire point of having these seperate functions. If anything major +//is changed in the non-server-only versions of these functions it would be wise to incorporate it +//here as well. + +/* +================= +R_LoadMDXA_Server - load a Ghoul 2 animation file +================= +*/ +qboolean R_LoadMDXA_Server( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { + + mdxaHeader_t *pinmodel, *mdxa; + int version; + int size; + + pinmodel = (mdxaHeader_t *)buffer; + // + // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... + // + version = (pinmodel->version); + size = (pinmodel->ofsEnd); + + if (!bAlreadyCached) + { + LL(version); + LL(size); + } + + if (version != MDXA_VERSION) { + return qfalse; + } + + mod->type = MOD_MDXA; + mod->dataSize += size; + + qboolean bAlreadyFound = qfalse; + mdxa = (mdxaHeader_t*)CModelCache->Allocate( size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLA ); + mod->data.gla = mdxa; + + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + + if (!bAlreadyFound) + { + // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the + // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since + // we've hijacked that memory block... + // + // Aaaargh. Kill me now... + // + bAlreadyCached = qtrue; + assert( mdxa == buffer ); +// memcpy( mdxa, buffer, size ); // and don't do this now, since it's the same thing + + LL(mdxa->ident); + LL(mdxa->version); + LL(mdxa->numFrames); + LL(mdxa->numBones); + LL(mdxa->ofsFrames); + LL(mdxa->ofsEnd); + } + + if ( mdxa->numFrames < 1 ) { + return qfalse; + } + + if (bAlreadyFound) + { + return qtrue; // All done, stop here, do not LittleLong() etc. Do not pass go... + } + + return qtrue; +} + +/* +================= +R_LoadMDXM_Server - load a Ghoul 2 Mesh file +================= +*/ +qboolean R_LoadMDXM_Server( model_t *mod, void *buffer, const char *mod_name, qboolean &bAlreadyCached ) { + int i,l, j; + mdxmHeader_t *pinmodel, *mdxm; + mdxmLOD_t *lod; + mdxmSurface_t *surf; + int version; + int size; + //shader_t *sh; + mdxmSurfHierarchy_t *surfInfo; + + pinmodel= (mdxmHeader_t *)buffer; + // + // read some fields from the binary, but only LittleLong() them when we know this wasn't an already-cached model... + // + version = (pinmodel->version); + size = (pinmodel->ofsEnd); + + if (!bAlreadyCached) + { + LL(version); + LL(size); + } + + if (version != MDXM_VERSION) { + return qfalse; + } + + mod->type = MOD_MDXM; + mod->dataSize += size; + + qboolean bAlreadyFound = qfalse; + mdxm = (mdxmHeader_t*)CModelCache->Allocate( size, buffer, mod_name, &bAlreadyFound, TAG_MODEL_GLM ); + mod->data.glm = (mdxmData_t *)ri.Hunk_Alloc (sizeof (mdxmData_t), h_low); + mod->data.glm->header = mdxm; + + assert(bAlreadyCached == bAlreadyFound); // I should probably eliminate 'bAlreadyFound', but wtf? + + if (!bAlreadyFound) + { + // horrible new hackery, if !bAlreadyFound then we've just done a tag-morph, so we need to set the + // bool reference passed into this function to true, to tell the caller NOT to do an ri.FS_Freefile since + // we've hijacked that memory block... + // + // Aaaargh. Kill me now... + // + bAlreadyCached = qtrue; + assert( mdxm == buffer ); +// memcpy( mdxm, buffer, size ); // and don't do this now, since it's the same thing + + LL(mdxm->ident); + LL(mdxm->version); + LL(mdxm->numLODs); + LL(mdxm->ofsLODs); + LL(mdxm->numSurfaces); + LL(mdxm->ofsSurfHierarchy); + LL(mdxm->ofsEnd); + } + + // first up, go load in the animation file we need that has the skeletal animation info for this model + mdxm->animIndex = RE_RegisterServerModel(va ("%s.gla",mdxm->animName)); + if (!mdxm->animIndex) + { + return qfalse; + } + + mod->numLods = mdxm->numLODs -1 ; //copy this up to the model for ease of use - it wil get inced after this. + + if (bAlreadyFound) + { + return qtrue; // All done. Stop, go no further, do not LittleLong(), do not pass Go... + } + + surfInfo = (mdxmSurfHierarchy_t *)( (byte *)mdxm + mdxm->ofsSurfHierarchy); + for ( i = 0 ; i < mdxm->numSurfaces ; i++) + { + LL(surfInfo->numChildren); + LL(surfInfo->parentIndex); + + // do all the children indexs + for (j=0; jnumChildren; j++) + { + LL(surfInfo->childIndexes[j]); + } + + // We will not be using shaders on the server. + //sh = 0; + // insert it in the surface list + + surfInfo->shaderIndex = 0; + + CModelCache->StoreShaderRequest(mod_name, &surfInfo->shader[0], &surfInfo->shaderIndex); + + // find the next surface + surfInfo = (mdxmSurfHierarchy_t *)( (byte *)surfInfo + (intptr_t)( &((mdxmSurfHierarchy_t *)0)->childIndexes[ surfInfo->numChildren ] )); + } + + // swap all the LOD's (we need to do the middle part of this even for intel, because of shader reg and err-check) + lod = (mdxmLOD_t *) ( (byte *)mdxm + mdxm->ofsLODs ); + for ( l = 0 ; l < mdxm->numLODs ; l++) + { + int triCount = 0; + + LL(lod->ofsEnd); + // swap all the surfaces + surf = (mdxmSurface_t *) ( (byte *)lod + sizeof (mdxmLOD_t) + (mdxm->numSurfaces * sizeof(mdxmLODSurfOffset_t)) ); + for ( i = 0 ; i < mdxm->numSurfaces ; i++) + { + LL(surf->numTriangles); + LL(surf->ofsTriangles); + LL(surf->numVerts); + LL(surf->ofsVerts); + LL(surf->ofsEnd); + LL(surf->ofsHeader); + LL(surf->numBoneReferences); + LL(surf->ofsBoneReferences); +// LL(surf->maxVertBoneWeights); + + triCount += surf->numTriangles; + + if ( surf->numVerts > SHADER_MAX_VERTEXES ) { + return qfalse; + } + if ( surf->numTriangles*3 > SHADER_MAX_INDEXES ) { + return qfalse; + } + + // change to surface identifier + surf->ident = SF_MDX; + + // register the shaders + + // find the next surface + surf = (mdxmSurface_t *)( (byte *)surf + surf->ofsEnd ); + } + + // find the next LOD + lod = (mdxmLOD_t *)( (byte *)lod + lod->ofsEnd ); + } + + return qtrue; +} + +/* +==================== +R_RegisterMDX_Server +==================== +*/ +qhandle_t R_RegisterMDX_Server(const char *name, model_t *mod) +{ + unsigned *buf; + int lod; + int ident; + qboolean loaded = qfalse; + int numLoaded; + char filename[MAX_QPATH], namebuf[MAX_QPATH+20]; + char *fext, defex[] = "md3"; + + numLoaded = 0; + + strcpy(filename, name); + + fext = strchr(filename, '.'); + if(!fext) + fext = defex; + else + { + *fext = '\0'; + fext++; + } + + for (lod = MD3_MAX_LODS - 1 ; lod >= 0 ; lod--) + { + if(lod) + Com_sprintf(namebuf, sizeof(namebuf), "%s_%d.%s", filename, lod, fext); + else + Com_sprintf(namebuf, sizeof(namebuf), "%s.%s", filename, fext); + + qboolean bAlreadyCached = qfalse; + if( !CModelCache->LoadFile( namebuf, (void**)&buf, &bAlreadyCached ) ) + continue; + + ident = *(unsigned *)buf; + if( !bAlreadyCached ) + LL(ident); + + switch(ident) + { + case MDXA_IDENT: + loaded = R_LoadMDXA_Server(mod, buf, namebuf, bAlreadyCached); + break; + case MDXM_IDENT: + loaded = R_LoadMDXM_Server(mod, buf, namebuf, bAlreadyCached); + break; + default: + //ri.Printf(PRINT_WARNING, "R_RegisterMDX_Server: unknown ident for %s\n", name); + break; + } + + if(loaded) + { + mod->numLods++; + numLoaded++; + } + else + break; + } + + if(numLoaded) + { + // duplicate into higher lod spots that weren't + // loaded, in case the user changes r_lodbias on the fly + for(lod--; lod >= 0; lod--) + { + mod->numLods++; + mod->data.mdv[lod] = mod->data.mdv[lod + 1]; + } + + return mod->index; + } + +/*#ifdef _DEBUG + ri.Printf(PRINT_WARNING,"R_RegisterMDX_Server: couldn't load %s\n", name); +#endif*/ + + mod->type = MOD_BAD; + return 0; +} + +// Note that the ordering indicates the order of preference used +// when there are multiple models of different formats available +static modelExtToLoaderMap_t serverModelLoaders[ ] = +{ + /* + Ghoul 2 Insert Start + */ + { "glm", R_RegisterMDX_Server }, + { "gla", R_RegisterMDX_Server }, + /* + Ghoul 2 Insert End + */ +}; + +static int numServerModelLoaders = ARRAY_LEN(serverModelLoaders); + +qhandle_t RE_RegisterServerModel( const char *name ) { + model_t *mod; + qhandle_t hModel; + int i; + char localName[ MAX_QPATH ]; + const char *ext; + + if (!r_noServerGhoul2) + { //keep it from choking when it gets to these checks in the g2 code. Registering all r_ cvars for the server would be a Bad Thing though. + r_noServerGhoul2 = ri.Cvar_Get( "r_noserverghoul2", "0", 0, ""); + } + + if ( !name || !name[0] ) { + return 0; + } + + if ( strlen( name ) >= MAX_QPATH ) { + return 0; + } + + // search the currently loaded models + if( ( hModel = CModelCache->GetModelHandle( name ) ) != -1 ) + return hModel; + + if ( name[0] == '*' ) + { + if ( strcmp (name, "*default.gla") != 0 ) + { + return 0; + } + } + + // allocate a new model_t + if ( ( mod = R_AllocModel() ) == NULL ) { + ri.Printf( PRINT_WARNING, "RE_RegisterModel: R_AllocModel() failed for '%s'\n", name); + return 0; + } + + // only set the name after the model has been successfully loaded + Q_strncpyz( mod->name, name, sizeof( mod->name ) ); + + R_IssuePendingRenderCommands(); + + mod->type = MOD_BAD; + mod->numLods = 0; + + // + // load the files + // + Q_strncpyz( localName, name, MAX_QPATH ); + + ext = COM_GetExtension( localName ); + + if( *ext ) + { + // Look for the correct loader and use it + for( i = 0; i < numServerModelLoaders; i++ ) + { + if( !Q_stricmp( ext, serverModelLoaders[ i ].ext ) ) + { + // Load + hModel = serverModelLoaders[ i ].ModelLoader( localName, mod ); + break; + } + } + + // A loader was found + if( i < numServerModelLoaders ) + { + if( hModel ) + { + // Something loaded + CModelCache->InsertModelHandle( name, hModel ); + return mod->index; + } + } + } + + CModelCache->InsertModelHandle( name, hModel ); + return hModel; +} + +/* +================= +R_LoadMD3 +================= +*/ +static qboolean R_LoadMD3(model_t * mod, int lod, void *buffer, const char *modName) +{ + int i, j; + + md3Header_t *md3Model; + md3Frame_t *md3Frame; + md3Surface_t *md3Surf; + md3Shader_t *md3Shader; + md3Triangle_t *md3Tri; + md3St_t *md3st; + md3XyzNormal_t *md3xyz; + md3Tag_t *md3Tag; + + mdvModel_t *mdvModel; + mdvFrame_t *frame; + mdvSurface_t *surf;//, *surface; + int *shaderIndex; + glIndex_t *tri; + mdvVertex_t *v; + mdvSt_t *st; + mdvTag_t *tag; + mdvTagName_t *tagName; + + int version; + int size; + + md3Model = (md3Header_t *) buffer; + + version = LittleLong(md3Model->version); + if(version != MD3_VERSION) + { + ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has wrong version (%i should be %i)\n", modName, version, MD3_VERSION); + return qfalse; + } + + mod->type = MOD_MESH; + size = LittleLong(md3Model->ofsEnd); + mod->dataSize += size; + //mdvModel = mod->mdv[lod] = (mdvModel_t *)ri.Hunk_Alloc(sizeof(mdvModel_t), h_low); + qboolean bAlreadyFound = qfalse; + md3Model = (md3Header_t *)CModelCache->Allocate(size, buffer, modName, &bAlreadyFound, TAG_MODEL_MD3); + mdvModel = mod->data.mdv[lod] = (mdvModel_t *)ri.Hunk_Alloc(sizeof(*mdvModel), h_low); + +// Com_Memcpy(mod->md3[lod], buffer, LittleLong(md3Model->ofsEnd)); + if( !bAlreadyFound ) + { // HACK + LL(md3Model->ident); + LL(md3Model->version); + LL(md3Model->numFrames); + LL(md3Model->numTags); + LL(md3Model->numSurfaces); + LL(md3Model->ofsFrames); + LL(md3Model->ofsTags); + LL(md3Model->ofsSurfaces); + LL(md3Model->ofsEnd); + } + else + { + CModelCache->AllocateShaders( modName ); + } + + if(md3Model->numFrames < 1) + { + ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has no frames\n", modName); + return qfalse; + } + + // swap all the frames + mdvModel->numFrames = md3Model->numFrames; + mdvModel->frames = frame = (mdvFrame_t *)ri.Hunk_Alloc(sizeof(*frame) * md3Model->numFrames, h_low); + + md3Frame = (md3Frame_t *) ((byte *) md3Model + md3Model->ofsFrames); + for(i = 0; i < md3Model->numFrames; i++, frame++, md3Frame++) + { + frame->radius = LittleFloat(md3Frame->radius); + for(j = 0; j < 3; j++) + { + frame->bounds[0][j] = LittleFloat(md3Frame->bounds[0][j]); + frame->bounds[1][j] = LittleFloat(md3Frame->bounds[1][j]); + frame->localOrigin[j] = LittleFloat(md3Frame->localOrigin[j]); + } + } + + // swap all the tags + mdvModel->numTags = md3Model->numTags; + mdvModel->tags = tag = (mdvTag_t *)ri.Hunk_Alloc(sizeof(*tag) * (md3Model->numTags * md3Model->numFrames), h_low); + + md3Tag = (md3Tag_t *) ((byte *) md3Model + md3Model->ofsTags); + for(i = 0; i < md3Model->numTags * md3Model->numFrames; i++, tag++, md3Tag++) + { + for(j = 0; j < 3; j++) + { + tag->origin[j] = LittleFloat(md3Tag->origin[j]); + tag->axis[0][j] = LittleFloat(md3Tag->axis[0][j]); + tag->axis[1][j] = LittleFloat(md3Tag->axis[1][j]); + tag->axis[2][j] = LittleFloat(md3Tag->axis[2][j]); + } + } + + + mdvModel->tagNames = tagName = (mdvTagName_t *)ri.Hunk_Alloc(sizeof(*tagName) * (md3Model->numTags), h_low); + + md3Tag = (md3Tag_t *) ((byte *) md3Model + md3Model->ofsTags); + for(i = 0; i < md3Model->numTags; i++, tagName++, md3Tag++) + { + Q_strncpyz(tagName->name, md3Tag->name, sizeof(tagName->name)); + } + + // swap all the surfaces + mdvModel->numSurfaces = md3Model->numSurfaces; + mdvModel->surfaces = surf = (mdvSurface_t *)ri.Hunk_Alloc(sizeof(*surf) * md3Model->numSurfaces, h_low); + + md3Surf = (md3Surface_t *) ((byte *) md3Model + md3Model->ofsSurfaces); + for(i = 0; i < md3Model->numSurfaces; i++) + { + LL(md3Surf->ident); + LL(md3Surf->flags); + LL(md3Surf->numFrames); + LL(md3Surf->numShaders); + LL(md3Surf->numTriangles); + LL(md3Surf->ofsTriangles); + LL(md3Surf->numVerts); + LL(md3Surf->ofsShaders); + LL(md3Surf->ofsSt); + LL(md3Surf->ofsXyzNormals); + LL(md3Surf->ofsEnd); + + if(md3Surf->numVerts >= SHADER_MAX_VERTEXES) + { + ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has more than %i verts on %s (%i).\n", + modName, SHADER_MAX_VERTEXES - 1, md3Surf->name[0] ? md3Surf->name : "a surface", + md3Surf->numVerts ); + return qfalse; + } + if(md3Surf->numTriangles * 3 >= SHADER_MAX_INDEXES) + { + ri.Printf(PRINT_WARNING, "R_LoadMD3: %s has more than %i triangles on %s (%i).\n", + modName, ( SHADER_MAX_INDEXES / 3 ) - 1, md3Surf->name[0] ? md3Surf->name : "a surface", + md3Surf->numTriangles ); + return qfalse; + } + + // change to surface identifier + surf->surfaceType = SF_MDV; + + // give pointer to model for Tess_SurfaceMDX + surf->model = mdvModel; + + // copy surface name + Q_strncpyz(surf->name, md3Surf->name, sizeof(surf->name)); + + // lowercase the surface name so skin compares are faster + Q_strlwr(surf->name); + + // strip off a trailing _1 or _2 + // this is a crutch for q3data being a mess + j = strlen(surf->name); + if(j > 2 && surf->name[j - 2] == '_') + { + surf->name[j - 2] = 0; + } + + // register the shaders + surf->numShaderIndexes = md3Surf->numShaders; + surf->shaderIndexes = shaderIndex = (int *)ri.Hunk_Alloc(sizeof(*shaderIndex) * md3Surf->numShaders, h_low); + + md3Shader = (md3Shader_t *) ((byte *) md3Surf + md3Surf->ofsShaders); + for(j = 0; j < md3Surf->numShaders; j++, shaderIndex++, md3Shader++) + { + shader_t *sh; + + sh = R_FindShader(md3Shader->name, lightmapsNone, stylesDefault, qtrue); + if(sh->defaultShader) + { + *shaderIndex = 0; + } + else + { + *shaderIndex = sh->index; + } + } + + // swap all the triangles + surf->numIndexes = md3Surf->numTriangles * 3; + surf->indexes = tri = (glIndex_t *)ri.Hunk_Alloc(sizeof(*tri) * 3 * md3Surf->numTriangles, h_low); + + md3Tri = (md3Triangle_t *) ((byte *) md3Surf + md3Surf->ofsTriangles); + for(j = 0; j < md3Surf->numTriangles; j++, tri += 3, md3Tri++) + { + tri[0] = LittleLong(md3Tri->indexes[0]); + tri[1] = LittleLong(md3Tri->indexes[1]); + tri[2] = LittleLong(md3Tri->indexes[2]); + } + + // swap all the XyzNormals + surf->numVerts = md3Surf->numVerts; + surf->verts = v = (mdvVertex_t *)ri.Hunk_Alloc(sizeof(*v) * (md3Surf->numVerts * md3Surf->numFrames), h_low); + + md3xyz = (md3XyzNormal_t *) ((byte *) md3Surf + md3Surf->ofsXyzNormals); + for(j = 0; j < md3Surf->numVerts * md3Surf->numFrames; j++, md3xyz++, v++) + { + unsigned lat, lng; + unsigned short normal; + + v->xyz[0] = LittleShort(md3xyz->xyz[0]) * MD3_XYZ_SCALE; + v->xyz[1] = LittleShort(md3xyz->xyz[1]) * MD3_XYZ_SCALE; + v->xyz[2] = LittleShort(md3xyz->xyz[2]) * MD3_XYZ_SCALE; + + normal = LittleShort(md3xyz->normal); + + lat = ( normal >> 8 ) & 0xff; + lng = ( normal & 0xff ); + lat *= (FUNCTABLE_SIZE/256); + lng *= (FUNCTABLE_SIZE/256); + + // decode X as cos( lat ) * sin( long ) + // decode Y as sin( lat ) * sin( long ) + // decode Z as cos( long ) + + v->normal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + v->normal[1] = tr.sinTable[lat] * tr.sinTable[lng]; + v->normal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + } + + // swap all the ST + surf->st = st = (mdvSt_t *)ri.Hunk_Alloc(sizeof(*st) * md3Surf->numVerts, h_low); + + md3st = (md3St_t *) ((byte *) md3Surf + md3Surf->ofsSt); + for(j = 0; j < md3Surf->numVerts; j++, md3st++, st++) + { + st->st[0] = LittleFloat(md3st->st[0]); + st->st[1] = LittleFloat(md3st->st[1]); + } + + // find the next surface + md3Surf = (md3Surface_t *) ((byte *) md3Surf + md3Surf->ofsEnd); + surf++; + } + + { + srfVBOMDVMesh_t *vboSurf; + + mdvModel->numVBOSurfaces = mdvModel->numSurfaces; + mdvModel->vboSurfaces = (srfVBOMDVMesh_t *)ri.Hunk_Alloc(sizeof(*mdvModel->vboSurfaces) * mdvModel->numSurfaces, h_low); + + vboSurf = mdvModel->vboSurfaces; + surf = mdvModel->surfaces; + + vec3_t *verts; + uint32_t *normals; + vec2_t *texcoords; + uint32_t *tangents; + + byte *data; + int dataSize = 0; + int ofsPosition, ofsNormals, ofsTexcoords, ofsTangents; + int stride = 0; + int numVerts = 0; + int numIndexes = 0; + + // +1 to add total vertex count + int *baseVertexes = (int *)ri.Hunk_AllocateTempMemory(sizeof(int) * (mdvModel->numSurfaces + 1)); + int *indexOffsets = (int *)ri.Hunk_AllocateTempMemory(sizeof(int) * mdvModel->numSurfaces); + + // Calculate the required size of the vertex buffer. + for (int n = 0; n < mdvModel->numSurfaces; n++, surf++) + { + baseVertexes[n] = numVerts; + indexOffsets[n] = numIndexes; + + numVerts += surf->numVerts; + numIndexes += surf->numIndexes; + } + baseVertexes[mdvModel->numSurfaces] = numVerts; + + dataSize += numVerts * sizeof(*verts); + dataSize += numVerts * sizeof(*normals); + dataSize += numVerts * sizeof(*texcoords); + dataSize += numVerts * sizeof(*tangents); + + // Allocate and write to memory + data = (byte *)ri.Hunk_AllocateTempMemory(dataSize); + + ofsPosition = stride; + verts = (vec3_t *)(data + ofsPosition); + stride += sizeof(*verts); + + ofsNormals = stride; + normals = (uint32_t *)(data + ofsNormals); + stride += sizeof(*normals); + + ofsTexcoords = stride; + texcoords = (vec2_t *)(data + ofsTexcoords); + stride += sizeof(*texcoords); + + ofsTangents = stride; + tangents = (uint32_t *)(data + ofsTangents); + stride += sizeof(*tangents); + + // Fill in the index buffer and compute tangents + glIndex_t *indices = (glIndex_t *)ri.Hunk_AllocateTempMemory(sizeof(glIndex_t) * numIndexes); + glIndex_t *index = indices; + + surf = mdvModel->surfaces; + for (i = 0; i < mdvModel->numSurfaces; i++, surf++) + { + uint32_t *tangentsf = (uint32_t *)ri.Hunk_AllocateTempMemory(sizeof(uint32_t) * surf->numVerts); + R_CalcMikkTSpaceMD3Surface( + surf->numIndexes / 3, + surf->verts, + tangentsf, + surf->st, + surf->indexes); + + for (int k = 0; k < surf->numIndexes; k++) + { + *index = surf->indexes[k] + baseVertexes[i]; + assert(*index >= 0 && *index < numVerts); + index++; + } + + v = surf->verts; + for (j = 0; j < surf->numVerts; j++, v++) + { + VectorCopy(v->xyz, *verts); + *normals = R_VboPackNormal(v->normal); + *tangents = tangentsf[j]; + + verts = (vec3_t *)((byte *)verts + stride); + normals = (uint32_t *)((byte *)normals + stride); + tangents = (uint32_t *)((byte *)tangents + stride); + } + ri.Hunk_FreeTempMemory(tangentsf); + + st = surf->st; + for (j = 0; j < surf->numVerts; j++, st++) { + (*texcoords)[0] = st->st[0]; + (*texcoords)[1] = st->st[1]; + + texcoords = (vec2_t *)((byte *)texcoords + stride); + } + } + + assert((byte *)verts == (data + dataSize)); + + VBO_t *vbo = R_CreateVBO(data, dataSize, VBO_USAGE_STATIC); + IBO_t *ibo = R_CreateIBO((byte *)indices, sizeof(glIndex_t) * numIndexes, VBO_USAGE_STATIC); + + ri.Hunk_FreeTempMemory(data); + ri.Hunk_FreeTempMemory(indices); + + vbo->offsets[ATTR_INDEX_POSITION] = ofsPosition; + vbo->offsets[ATTR_INDEX_NORMAL] = ofsNormals; + vbo->offsets[ATTR_INDEX_TEXCOORD0] = ofsTexcoords; + vbo->offsets[ATTR_INDEX_TANGENT] = ofsTangents; + + vbo->strides[ATTR_INDEX_POSITION] = stride; + vbo->strides[ATTR_INDEX_NORMAL] = stride; + vbo->strides[ATTR_INDEX_TEXCOORD0] = stride; + vbo->strides[ATTR_INDEX_TANGENT] = stride; + + vbo->sizes[ATTR_INDEX_POSITION] = sizeof(*verts); + vbo->sizes[ATTR_INDEX_NORMAL] = sizeof(*normals); + vbo->sizes[ATTR_INDEX_TEXCOORD0] = sizeof(*texcoords); + vbo->sizes[ATTR_INDEX_TANGENT] = sizeof(*tangents); + + surf = mdvModel->surfaces; + for (i = 0; i < mdvModel->numSurfaces; i++, surf++, vboSurf++) + { + vboSurf->surfaceType = SF_VBO_MDVMESH; + vboSurf->mdvModel = mdvModel; + vboSurf->mdvSurface = surf; + vboSurf->vbo = vbo; + vboSurf->ibo = ibo; + + vboSurf->indexOffset = indexOffsets[i]; + vboSurf->minIndex = baseVertexes[i]; + vboSurf->maxIndex = baseVertexes[i + 1] - 1; + vboSurf->numVerts = surf->numVerts; + vboSurf->numIndexes = surf->numIndexes; + } + + ri.Hunk_FreeTempMemory(indexOffsets); + ri.Hunk_FreeTempMemory(baseVertexes); + } + + return qtrue; +} + + + +/* +================= +R_LoadMDR +================= +*/ +static qboolean R_LoadMDR( model_t *mod, void *buffer, int filesize, const char *mod_name ) +{ + int i, j, k, l; + mdrHeader_t *pinmodel, *mdr; + mdrFrame_t *frame; + mdrLOD_t *lod, *curlod; + mdrSurface_t *surf, *cursurf; + mdrTriangle_t *tri, *curtri; + mdrVertex_t *v, *curv; + mdrWeight_t *weight, *curweight; + mdrTag_t *tag, *curtag; + int size; + shader_t *sh; + + pinmodel = (mdrHeader_t *)buffer; + + pinmodel->version = LittleLong(pinmodel->version); + if (pinmodel->version != MDR_VERSION) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has wrong version (%i should be %i)\n", mod_name, pinmodel->version, MDR_VERSION); + return qfalse; + } + + size = LittleLong(pinmodel->ofsEnd); + + if(size > filesize) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: Header of %s is broken. Wrong filesize declared!\n", mod_name); + return qfalse; + } + + mod->type = MOD_MDR; + + LL(pinmodel->numFrames); + LL(pinmodel->numBones); + LL(pinmodel->ofsFrames); + + // This is a model that uses some type of compressed Bones. We don't want to uncompress every bone for each rendered frame + // over and over again, we'll uncompress it in this function already, so we must adjust the size of the target mdr. + if(pinmodel->ofsFrames < 0) + { + // mdrFrame_t is larger than mdrCompFrame_t: + size += pinmodel->numFrames * sizeof(frame->name); + // now add enough space for the uncompressed bones. + size += pinmodel->numFrames * pinmodel->numBones * ((sizeof(mdrBone_t) - sizeof(mdrCompBone_t))); + } + + // simple bounds check + if(pinmodel->numBones < 0 || + sizeof(*mdr) + pinmodel->numFrames * (sizeof(*frame) + (pinmodel->numBones - 1) * sizeof(*frame->bones)) > size) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); + return qfalse; + } + + mod->dataSize += size; + mod->data.mdr = mdr = (mdrHeader_t*)ri.Hunk_Alloc( size, h_low ); + + // Copy all the values over from the file and fix endian issues in the process, if necessary. + + mdr->ident = LittleLong(pinmodel->ident); + mdr->version = pinmodel->version; // Don't need to swap byte order on this one, we already did above. + Q_strncpyz(mdr->name, pinmodel->name, sizeof(mdr->name)); + mdr->numFrames = pinmodel->numFrames; + mdr->numBones = pinmodel->numBones; + mdr->numLODs = LittleLong(pinmodel->numLODs); + mdr->numTags = LittleLong(pinmodel->numTags); + // We don't care about the other offset values, we'll generate them ourselves while loading. + + mod->numLods = mdr->numLODs; + + if ( mdr->numFrames < 1 ) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has no frames\n", mod_name); + return qfalse; + } + + /* The first frame will be put into the first free space after the header */ + frame = (mdrFrame_t *)(mdr + 1); + mdr->ofsFrames = (int)((byte *) frame - (byte *) mdr); + + if (pinmodel->ofsFrames < 0) + { + mdrCompFrame_t *cframe; + + // compressed model... + cframe = (mdrCompFrame_t *)((byte *) pinmodel - pinmodel->ofsFrames); + + for(i = 0; i < mdr->numFrames; i++) + { + for(j = 0; j < 3; j++) + { + frame->bounds[0][j] = LittleFloat(cframe->bounds[0][j]); + frame->bounds[1][j] = LittleFloat(cframe->bounds[1][j]); + frame->localOrigin[j] = LittleFloat(cframe->localOrigin[j]); + } + + frame->radius = LittleFloat(cframe->radius); + frame->name[0] = '\0'; // No name supplied in the compressed version. + + for(j = 0; j < mdr->numBones; j++) + { + for(k = 0; k < (sizeof(cframe->bones[j].Comp) / 2); k++) + { + // Do swapping for the uncompressing functions. They seem to use shorts + // values only, so I assume this will work. Never tested it on other + // platforms, though. + + ((unsigned short *)(cframe->bones[j].Comp))[k] = + LittleShort( ((unsigned short *)(cframe->bones[j].Comp))[k] ); + } + + /* Now do the actual uncompressing */ + MC_UnCompress(frame->bones[j].matrix, cframe->bones[j].Comp); + } + + // Next Frame... + cframe = (mdrCompFrame_t *) &cframe->bones[j]; + frame = (mdrFrame_t *) &frame->bones[j]; + } + } + else + { + mdrFrame_t *curframe; + + // uncompressed model... + // + + curframe = (mdrFrame_t *)((byte *) pinmodel + pinmodel->ofsFrames); + + // swap all the frames + for ( i = 0 ; i < mdr->numFrames ; i++) + { + for(j = 0; j < 3; j++) + { + frame->bounds[0][j] = LittleFloat(curframe->bounds[0][j]); + frame->bounds[1][j] = LittleFloat(curframe->bounds[1][j]); + frame->localOrigin[j] = LittleFloat(curframe->localOrigin[j]); + } + + frame->radius = LittleFloat(curframe->radius); + Q_strncpyz(frame->name, curframe->name, sizeof(frame->name)); + + for (j = 0; j < (int) (mdr->numBones * sizeof(mdrBone_t) / 4); j++) + { + ((float *)frame->bones)[j] = LittleFloat( ((float *)curframe->bones)[j] ); + } + + curframe = (mdrFrame_t *) &curframe->bones[mdr->numBones]; + frame = (mdrFrame_t *) &frame->bones[mdr->numBones]; + } + } + + // frame should now point to the first free address after all frames. + lod = (mdrLOD_t *) frame; + mdr->ofsLODs = (int) ((byte *) lod - (byte *)mdr); + + curlod = (mdrLOD_t *)((byte *) pinmodel + LittleLong(pinmodel->ofsLODs)); + + // swap all the LOD's + for ( l = 0 ; l < mdr->numLODs ; l++) + { + // simple bounds check + if((byte *) (lod + 1) > (byte *) mdr + size) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); + return qfalse; + } + + lod->numSurfaces = LittleLong(curlod->numSurfaces); + + // swap all the surfaces + surf = (mdrSurface_t *) (lod + 1); + lod->ofsSurfaces = (int)((byte *) surf - (byte *) lod); + cursurf = (mdrSurface_t *) ((byte *)curlod + LittleLong(curlod->ofsSurfaces)); + + for ( i = 0 ; i < lod->numSurfaces ; i++) + { + // simple bounds check + if((byte *) (surf + 1) > (byte *) mdr + size) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); + return qfalse; + } + + // first do some copying stuff + + surf->ident = SF_MDR; + Q_strncpyz(surf->name, cursurf->name, sizeof(surf->name)); + Q_strncpyz(surf->shader, cursurf->shader, sizeof(surf->shader)); + + surf->ofsHeader = (byte *) mdr - (byte *) surf; + + surf->numVerts = LittleLong(cursurf->numVerts); + surf->numTriangles = LittleLong(cursurf->numTriangles); + // numBoneReferences and BoneReferences generally seem to be unused + + // now do the checks that may fail. + if ( surf->numVerts >= SHADER_MAX_VERTEXES ) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has more than %i verts on %s (%i).\n", + mod_name, SHADER_MAX_VERTEXES-1, surf->name[0] ? surf->name : "a surface", + surf->numVerts ); + return qfalse; + } + if ( surf->numTriangles*3 >= SHADER_MAX_INDEXES ) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has more than %i triangles on %s (%i).\n", + mod_name, ( SHADER_MAX_INDEXES / 3 ) - 1, surf->name[0] ? surf->name : "a surface", + surf->numTriangles ); + return qfalse; + } + // lowercase the surface name so skin compares are faster + Q_strlwr( surf->name ); + + // register the shaders + sh = R_FindShader(surf->shader, lightmapsNone, stylesDefault, qtrue); + if ( sh->defaultShader ) { + surf->shaderIndex = 0; + } else { + surf->shaderIndex = sh->index; + } + + // now copy the vertexes. + v = (mdrVertex_t *) (surf + 1); + surf->ofsVerts = (int)((byte *) v - (byte *) surf); + curv = (mdrVertex_t *) ((byte *)cursurf + LittleLong(cursurf->ofsVerts)); + + for(j = 0; j < surf->numVerts; j++) + { + LL(curv->numWeights); + + // simple bounds check + if(curv->numWeights < 0 || (byte *) (v + 1) + (curv->numWeights - 1) * sizeof(*weight) > (byte *) mdr + size) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); + return qfalse; + } + + v->normal[0] = LittleFloat(curv->normal[0]); + v->normal[1] = LittleFloat(curv->normal[1]); + v->normal[2] = LittleFloat(curv->normal[2]); + + v->texCoords[0] = LittleFloat(curv->texCoords[0]); + v->texCoords[1] = LittleFloat(curv->texCoords[1]); + + v->numWeights = curv->numWeights; + weight = &v->weights[0]; + curweight = &curv->weights[0]; + + // Now copy all the weights + for(k = 0; k < v->numWeights; k++) + { + weight->boneIndex = LittleLong(curweight->boneIndex); + weight->boneWeight = LittleFloat(curweight->boneWeight); + + weight->offset[0] = LittleFloat(curweight->offset[0]); + weight->offset[1] = LittleFloat(curweight->offset[1]); + weight->offset[2] = LittleFloat(curweight->offset[2]); + + weight++; + curweight++; + } + + v = (mdrVertex_t *) weight; + curv = (mdrVertex_t *) curweight; + } + + // we know the offset to the triangles now: + tri = (mdrTriangle_t *) v; + surf->ofsTriangles = (int)((byte *) tri - (byte *) surf); + curtri = (mdrTriangle_t *)((byte *) cursurf + LittleLong(cursurf->ofsTriangles)); + + // simple bounds check + if(surf->numTriangles < 0 || (byte *) (tri + surf->numTriangles) > (byte *) mdr + size) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); + return qfalse; + } + + for(j = 0; j < surf->numTriangles; j++) + { + tri->indexes[0] = LittleLong(curtri->indexes[0]); + tri->indexes[1] = LittleLong(curtri->indexes[1]); + tri->indexes[2] = LittleLong(curtri->indexes[2]); + + tri++; + curtri++; + } + + // tri now points to the end of the surface. + surf->ofsEnd = (byte *) tri - (byte *) surf; + surf = (mdrSurface_t *) tri; + + // find the next surface. + cursurf = (mdrSurface_t *) ((byte *) cursurf + LittleLong(cursurf->ofsEnd)); + } + + // surf points to the next lod now. + lod->ofsEnd = (int)((byte *) surf - (byte *) lod); + lod = (mdrLOD_t *) surf; + + // find the next LOD. + curlod = (mdrLOD_t *)((byte *) curlod + LittleLong(curlod->ofsEnd)); + } + + // lod points to the first tag now, so update the offset too. + tag = (mdrTag_t *) lod; + mdr->ofsTags = (int)((byte *) tag - (byte *) mdr); + curtag = (mdrTag_t *) ((byte *)pinmodel + LittleLong(pinmodel->ofsTags)); + + // simple bounds check + if(mdr->numTags < 0 || (byte *) (tag + mdr->numTags) > (byte *) mdr + size) + { + ri.Printf(PRINT_WARNING, "R_LoadMDR: %s has broken structure.\n", mod_name); + return qfalse; + } + + for (i = 0 ; i < mdr->numTags ; i++) + { + tag->boneIndex = LittleLong(curtag->boneIndex); + Q_strncpyz(tag->name, curtag->name, sizeof(tag->name)); + + tag++; + curtag++; + } + + // And finally we know the real offset to the end. + mdr->ofsEnd = (int)((byte *) tag - (byte *) mdr); + + // phew! we're done. + + return qtrue; +} + + + +//============================================================================= + +/* +** RE_BeginRegistration +*/ +void RE_BeginRegistration( glconfig_t *glconfigOut ) { + + R_Init(); + + *glconfigOut = glConfig; + + R_IssuePendingRenderCommands(); + + tr.visIndex = 0; + memset(tr.visClusters, -2, sizeof(tr.visClusters)); // force markleafs to regenerate + + R_ClearFlares(); + RE_ClearScene(); + + tr.registered = qtrue; + + // NOTE: this sucks, for some reason the first stretch pic is never drawn + // without this we'd see a white flash on a level load because the very + // first time the level shot would not be drawn +// RE_StretchPic(0, 0, 0, 0, 0, 0, 1, 1, 0); +} + +//============================================================================= + +void R_SVModelInit() +{ + R_ModelInit(); +} + +/* +=============== +R_ModelInit +=============== +*/ +void R_ModelInit( void ) { + model_t *mod; + + // leave a space for NULL model + tr.numModels = 0; + + CModelCache->DeleteAll(); + + mod = R_AllocModel(); + mod->type = MOD_BAD; +} + +extern void KillTheShaderHashTable(void); +void RE_HunkClearCrap(void) +{ //get your dirty sticky assets off me, you damn dirty hunk! + KillTheShaderHashTable(); + tr.numModels = 0; + CModelCache->DeleteAll(); + tr.numShaders = 0; + tr.numSkins = 0; +} + + +/* +================ +R_Modellist_f +================ +*/ +void R_Modellist_f( void ) { + int i, j; + model_t *mod; + int total; + int lods; + + total = 0; + for ( i = 1 ; i < tr.numModels; i++ ) { + mod = tr.models[i]; + lods = 1; + for ( j = 1 ; j < MD3_MAX_LODS ; j++ ) { + if ( mod->data.mdv[j] && mod->data.mdv[j] != mod->data.mdv[j-1] ) { + lods++; + } + } + ri.Printf( PRINT_ALL, "%8i : (%i) %s\n",mod->dataSize, lods, mod->name ); + total += mod->dataSize; + } + ri.Printf( PRINT_ALL, "%8i : Total models\n", total ); + +#if 0 // not working right with new hunk + if ( tr.world ) { + ri.Printf( PRINT_ALL, "\n%8i : %s\n", tr.world->dataSize, tr.world->name ); + } +#endif +} + + +//============================================================================= + + +/* +================ +R_GetTag +================ +*/ +static mdvTag_t *R_GetTag( mdvModel_t *mod, int frame, const char *_tagName ) { + int i; + mdvTag_t *tag; + mdvTagName_t *tagName; + + if ( frame >= mod->numFrames ) { + // it is possible to have a bad frame while changing models, so don't error + frame = mod->numFrames - 1; + } + + tag = mod->tags + frame * mod->numTags; + tagName = mod->tagNames; + for(i = 0; i < mod->numTags; i++, tag++, tagName++) + { + if(!strcmp(tagName->name, _tagName)) + { + return tag; + } + } + + return NULL; +} + +void R_GetAnimTag( mdrHeader_t *mod, int framenum, const char *tagName, mdvTag_t * dest) +{ + int i, j, k; + int frameSize; + mdrFrame_t *frame; + mdrTag_t *tag; + + if ( framenum >= mod->numFrames ) + { + // it is possible to have a bad frame while changing models, so don't error + framenum = mod->numFrames - 1; + } + + tag = (mdrTag_t *)((byte *)mod + mod->ofsTags); + for ( i = 0 ; i < mod->numTags ; i++, tag++ ) + { + if ( !strcmp( tag->name, tagName ) ) + { + // uncompressed model... + // + frameSize = (intptr_t)( &((mdrFrame_t *)0)->bones[ mod->numBones ] ); + frame = (mdrFrame_t *)((byte *)mod + mod->ofsFrames + framenum * frameSize ); + + for (j = 0; j < 3; j++) + { + for (k = 0; k < 3; k++) + dest->axis[j][k]=frame->bones[tag->boneIndex].matrix[k][j]; + } + + dest->origin[0]=frame->bones[tag->boneIndex].matrix[0][3]; + dest->origin[1]=frame->bones[tag->boneIndex].matrix[1][3]; + dest->origin[2]=frame->bones[tag->boneIndex].matrix[2][3]; + + return; + } + } + + AxisClear( dest->axis ); + VectorClear( dest->origin ); +} + +/* +================ +R_LerpTag +================ +*/ +int R_LerpTag( orientation_t *tag, qhandle_t handle, int startFrame, int endFrame, + float frac, const char *tagName ) { + mdvTag_t *start, *end; + mdvTag_t start_space, end_space; + int i; + float frontLerp, backLerp; + model_t *model; + + model = R_GetModelByHandle( handle ); + if ( !model->data.mdv[0] ) + { + if(model->type == MOD_MDR) + { + start = &start_space; + end = &end_space; + R_GetAnimTag((mdrHeader_t *) model->data.mdr, startFrame, tagName, start); + R_GetAnimTag((mdrHeader_t *) model->data.mdr, endFrame, tagName, end); + } + else if( model->type == MOD_IQM ) { + return R_IQMLerpTag( tag, (iqmData_t *)model->data.iqm, + startFrame, endFrame, + frac, tagName ); + } else { + + AxisClear( tag->axis ); + VectorClear( tag->origin ); + return qfalse; + + } + } + else + { + start = R_GetTag( model->data.mdv[0], startFrame, tagName ); + end = R_GetTag( model->data.mdv[0], endFrame, tagName ); + if ( !start || !end ) { + AxisClear( tag->axis ); + VectorClear( tag->origin ); + return qfalse; + } + } + + frontLerp = frac; + backLerp = 1.0f - frac; + + for ( i = 0 ; i < 3 ; i++ ) { + tag->origin[i] = start->origin[i] * backLerp + end->origin[i] * frontLerp; + tag->axis[0][i] = start->axis[0][i] * backLerp + end->axis[0][i] * frontLerp; + tag->axis[1][i] = start->axis[1][i] * backLerp + end->axis[1][i] * frontLerp; + tag->axis[2][i] = start->axis[2][i] * backLerp + end->axis[2][i] * frontLerp; + } + VectorNormalize( tag->axis[0] ); + VectorNormalize( tag->axis[1] ); + VectorNormalize( tag->axis[2] ); + return qtrue; +} + + +/* +==================== +R_ModelBounds +==================== +*/ +void R_ModelBounds( qhandle_t handle, vec3_t mins, vec3_t maxs ) { + model_t *model; + + model = R_GetModelByHandle( handle ); + + if(model->type == MOD_BRUSH) { + VectorCopy( model->data.bmodel->bounds[0], mins ); + VectorCopy( model->data.bmodel->bounds[1], maxs ); + + return; + } else if (model->type == MOD_MESH) { + mdvModel_t *header; + mdvFrame_t *frame; + + header = model->data.mdv[0]; + frame = header->frames; + + VectorCopy( frame->bounds[0], mins ); + VectorCopy( frame->bounds[1], maxs ); + + return; + } else if (model->type == MOD_MDR) { + mdrHeader_t *header; + mdrFrame_t *frame; + + header = model->data.mdr; + frame = (mdrFrame_t *) ((byte *)header + header->ofsFrames); + + VectorCopy( frame->bounds[0], mins ); + VectorCopy( frame->bounds[1], maxs ); + + return; + } else if(model->type == MOD_IQM) { + iqmData_t *iqmData; + + iqmData = model->data.iqm; + + if(iqmData->bounds) + { + VectorCopy(iqmData->bounds, mins); + VectorCopy(iqmData->bounds + 3, maxs); + return; + } + } + + VectorClear( mins ); + VectorClear( maxs ); +} diff --git a/codemp/rd-rend2/tr_model_iqm.cpp b/codemp/rd-rend2/tr_model_iqm.cpp new file mode 100644 index 0000000000..7639ac1b2d --- /dev/null +++ b/codemp/rd-rend2/tr_model_iqm.cpp @@ -0,0 +1,1187 @@ +/* +=========================================================================== +Copyright (C) 2011 Thilo Schulz +Copyright (C) 2011 Matthias Bentrup + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +#include "tr_local.h" + +#define LL(x) x=LittleLong(x) + +// 3x4 identity matrix +static float identityMatrix[12] = { + 1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0 +}; + +static qboolean IQM_CheckRange( iqmHeader_t *header, int offset, + int count,int size ) { + // return true if the range specified by offset, count and size + // doesn't fit into the file + return (qboolean)( count <= 0 || + offset < 0 || + offset > header->filesize || + offset + count * size < 0 || + offset + count * size > header->filesize ); +} +// "multiply" 3x4 matrices, these are assumed to be the top 3 rows +// of a 4x4 matrix with the last row = (0 0 0 1) +static void Matrix34Multiply( float *a, float *b, float *out ) { + out[ 0] = a[0] * b[0] + a[1] * b[4] + a[ 2] * b[ 8]; + out[ 1] = a[0] * b[1] + a[1] * b[5] + a[ 2] * b[ 9]; + out[ 2] = a[0] * b[2] + a[1] * b[6] + a[ 2] * b[10]; + out[ 3] = a[0] * b[3] + a[1] * b[7] + a[ 2] * b[11] + a[ 3]; + out[ 4] = a[4] * b[0] + a[5] * b[4] + a[ 6] * b[ 8]; + out[ 5] = a[4] * b[1] + a[5] * b[5] + a[ 6] * b[ 9]; + out[ 6] = a[4] * b[2] + a[5] * b[6] + a[ 6] * b[10]; + out[ 7] = a[4] * b[3] + a[5] * b[7] + a[ 6] * b[11] + a[ 7]; + out[ 8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[ 8]; + out[ 9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[ 9]; + out[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10]; + out[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11]; +} +static void Matrix34Multiply_OnlySetOrigin( float *a, float *b, float *out ) { + out[ 3] = a[0] * b[3] + a[1] * b[7] + a[ 2] * b[11] + a[ 3]; + out[ 7] = a[4] * b[3] + a[5] * b[7] + a[ 6] * b[11] + a[ 7]; + out[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11]; +} +static void InterpolateMatrix( float *a, float *b, float lerp, float *mat ) { + float unLerp = 1.0f - lerp; + + mat[ 0] = a[ 0] * unLerp + b[ 0] * lerp; + mat[ 1] = a[ 1] * unLerp + b[ 1] * lerp; + mat[ 2] = a[ 2] * unLerp + b[ 2] * lerp; + mat[ 3] = a[ 3] * unLerp + b[ 3] * lerp; + mat[ 4] = a[ 4] * unLerp + b[ 4] * lerp; + mat[ 5] = a[ 5] * unLerp + b[ 5] * lerp; + mat[ 6] = a[ 6] * unLerp + b[ 6] * lerp; + mat[ 7] = a[ 7] * unLerp + b[ 7] * lerp; + mat[ 8] = a[ 8] * unLerp + b[ 8] * lerp; + mat[ 9] = a[ 9] * unLerp + b[ 9] * lerp; + mat[10] = a[10] * unLerp + b[10] * lerp; + mat[11] = a[11] * unLerp + b[11] * lerp; +} +static void JointToMatrix( vec4_t rot, vec3_t scale, vec3_t trans, + float *mat ) { + float xx = 2.0f * rot[0] * rot[0]; + float yy = 2.0f * rot[1] * rot[1]; + float zz = 2.0f * rot[2] * rot[2]; + float xy = 2.0f * rot[0] * rot[1]; + float xz = 2.0f * rot[0] * rot[2]; + float yz = 2.0f * rot[1] * rot[2]; + float wx = 2.0f * rot[3] * rot[0]; + float wy = 2.0f * rot[3] * rot[1]; + float wz = 2.0f * rot[3] * rot[2]; + + mat[ 0] = scale[0] * (1.0f - (yy + zz)); + mat[ 1] = scale[0] * (xy - wz); + mat[ 2] = scale[0] * (xz + wy); + mat[ 3] = trans[0]; + mat[ 4] = scale[1] * (xy + wz); + mat[ 5] = scale[1] * (1.0f - (xx + zz)); + mat[ 6] = scale[1] * (yz - wx); + mat[ 7] = trans[1]; + mat[ 8] = scale[2] * (xz - wy); + mat[ 9] = scale[2] * (yz + wx); + mat[10] = scale[2] * (1.0f - (xx + yy)); + mat[11] = trans[2]; +} +static void Matrix34Invert( float *inMat, float *outMat ) +{ + vec3_t trans; + float invSqrLen, *v; + + outMat[ 0] = inMat[ 0]; outMat[ 1] = inMat[ 4]; outMat[ 2] = inMat[ 8]; + outMat[ 4] = inMat[ 1]; outMat[ 5] = inMat[ 5]; outMat[ 6] = inMat[ 9]; + outMat[ 8] = inMat[ 2]; outMat[ 9] = inMat[ 6]; outMat[10] = inMat[10]; + + v = outMat + 0; invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); + v = outMat + 4; invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); + v = outMat + 8; invSqrLen = 1.0f / DotProduct(v, v); VectorScale(v, invSqrLen, v); + + trans[0] = inMat[ 3]; + trans[1] = inMat[ 7]; + trans[2] = inMat[11]; + + outMat[ 3] = -DotProduct(outMat + 0, trans); + outMat[ 7] = -DotProduct(outMat + 4, trans); + outMat[11] = -DotProduct(outMat + 8, trans); +} + +/* +================= +R_LoadIQM + +Load an IQM model and compute the joint matrices for every frame. +================= +*/ +qboolean R_LoadIQM( model_t *mod, void *buffer, int filesize, const char *mod_name ) { + iqmHeader_t *header; + iqmVertexArray_t *vertexarray; + iqmTriangle_t *triangle; + iqmMesh_t *mesh; + iqmJoint_t *joint; + iqmPose_t *pose; + iqmBounds_t *bounds; + unsigned short *framedata; + char *str; + int i, j; + float jointInvMats[IQM_MAX_JOINTS * 12]; + float *mat, *matInv; + size_t size, joint_names; + iqmData_t *iqmData; + srfIQModel_t *surface; + char meshName[MAX_QPATH]; + byte blendIndexesType, blendWeightsType; + + if( filesize < sizeof(iqmHeader_t) ) { + return qfalse; + } + + header = (iqmHeader_t *)buffer; + if( Q_strncmp( header->magic, IQM_MAGIC, sizeof(header->magic) ) ) { + return qfalse; + } + + LL( header->version ); + if( header->version != IQM_VERSION ) { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s is a unsupported IQM version (%d), only version %d is supported.\n", + mod_name, header->version, IQM_VERSION); + return qfalse; + } + + LL( header->filesize ); + if( header->filesize > filesize || header->filesize > 16<<20 ) { + return qfalse; + } + + LL( header->flags ); + LL( header->num_text ); + LL( header->ofs_text ); + LL( header->num_meshes ); + LL( header->ofs_meshes ); + LL( header->num_vertexarrays ); + LL( header->num_vertexes ); + LL( header->ofs_vertexarrays ); + LL( header->num_triangles ); + LL( header->ofs_triangles ); + LL( header->ofs_adjacency ); + LL( header->num_joints ); + LL( header->ofs_joints ); + LL( header->num_poses ); + LL( header->ofs_poses ); + LL( header->num_anims ); + LL( header->ofs_anims ); + LL( header->num_frames ); + LL( header->num_framechannels ); + LL( header->ofs_frames ); + LL( header->ofs_bounds ); + LL( header->num_comment ); + LL( header->ofs_comment ); + LL( header->num_extensions ); + LL( header->ofs_extensions ); + + // check ioq3 joint limit + if ( header->num_joints > IQM_MAX_JOINTS ) { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %d joints (%d).\n", + mod_name, IQM_MAX_JOINTS, header->num_joints); + return qfalse; + } + + blendIndexesType = blendWeightsType = IQM_UBYTE; + + // check and swap vertex arrays + if( IQM_CheckRange( header, header->ofs_vertexarrays, + header->num_vertexarrays, + sizeof(iqmVertexArray_t) ) ) { + return qfalse; + } + vertexarray = (iqmVertexArray_t *)((byte *)header + header->ofs_vertexarrays); + for( i = 0; i < header->num_vertexarrays; i++, vertexarray++ ) { + int n, *intPtr; + + if( vertexarray->size <= 0 || vertexarray->size > 4 ) { + return qfalse; + } + + // total number of values + n = header->num_vertexes * vertexarray->size; + + switch( vertexarray->format ) { + case IQM_BYTE: + case IQM_UBYTE: + // 1 byte, no swapping necessary + if( IQM_CheckRange( header, vertexarray->offset, + n, sizeof(byte) ) ) { + return qfalse; + } + break; + case IQM_INT: + case IQM_UINT: + case IQM_FLOAT: + // 4-byte swap + if( IQM_CheckRange( header, vertexarray->offset, + n, sizeof(float) ) ) { + return qfalse; + } + intPtr = (int *)((byte *)header + vertexarray->offset); + for( j = 0; j < n; j++, intPtr++ ) { + LL( *intPtr ); + } + break; + default: + // not supported + return qfalse; + break; + } + + switch( vertexarray->type ) { + case IQM_POSITION: + case IQM_NORMAL: + if( vertexarray->format != IQM_FLOAT || + vertexarray->size != 3 ) { + return qfalse; + } + break; + case IQM_TANGENT: + if( vertexarray->format != IQM_FLOAT || + vertexarray->size != 4 ) { + return qfalse; + } + break; + case IQM_TEXCOORD: + if( vertexarray->format != IQM_FLOAT || + vertexarray->size != 2 ) { + return qfalse; + } + break; + case IQM_BLENDINDEXES: + if( (vertexarray->format != IQM_INT && + vertexarray->format != IQM_UBYTE) || + vertexarray->size != 4 ) { + return qfalse; + } + blendIndexesType = vertexarray->format; + break; + case IQM_BLENDWEIGHTS: + if( (vertexarray->format != IQM_FLOAT && + vertexarray->format != IQM_UBYTE) || + vertexarray->size != 4 ) { + return qfalse; + } + blendWeightsType = vertexarray->format; + break; + case IQM_COLOR: + if( vertexarray->format != IQM_UBYTE || + vertexarray->size != 4 ) { + return qfalse; + } + break; + } + } + + // check and swap triangles + if( IQM_CheckRange( header, header->ofs_triangles, + header->num_triangles, sizeof(iqmTriangle_t) ) ) { + return qfalse; + } + triangle = (iqmTriangle_t *)((byte *)header + header->ofs_triangles); + for( i = 0; i < header->num_triangles; i++, triangle++ ) { + LL( triangle->vertex[0] ); + LL( triangle->vertex[1] ); + LL( triangle->vertex[2] ); + + if( triangle->vertex[0] > header->num_vertexes || + triangle->vertex[1] > header->num_vertexes || + triangle->vertex[2] > header->num_vertexes ) { + return qfalse; + } + } + + // check and swap meshes + if( IQM_CheckRange( header, header->ofs_meshes, + header->num_meshes, sizeof(iqmMesh_t) ) ) { + return qfalse; + } + mesh = (iqmMesh_t *)((byte *)header + header->ofs_meshes); + for( i = 0; i < header->num_meshes; i++, mesh++) { + LL( mesh->name ); + LL( mesh->material ); + LL( mesh->first_vertex ); + LL( mesh->num_vertexes ); + LL( mesh->first_triangle ); + LL( mesh->num_triangles ); + + if ( mesh->name < header->num_text ) { + Q_strncpyz( meshName, (char*)header + header->ofs_text + mesh->name, sizeof (meshName) ); + } else { + meshName[0] = '\0'; + } + + // check ioq3 limits + if ( mesh->num_vertexes >= SHADER_MAX_VERTEXES ) + { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %i verts on %s (%i).\n", + mod_name, SHADER_MAX_VERTEXES-1, meshName[0] ? meshName : "a surface", + mesh->num_vertexes ); + return qfalse; + } + if ( mesh->num_triangles*3 >= SHADER_MAX_INDEXES ) + { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has more than %i triangles on %s (%i).\n", + mod_name, ( SHADER_MAX_INDEXES / 3 ) - 1, meshName[0] ? meshName : "a surface", + mesh->num_triangles ); + return qfalse; + } + + if( mesh->first_vertex >= header->num_vertexes || + mesh->first_vertex + mesh->num_vertexes > header->num_vertexes || + mesh->first_triangle >= header->num_triangles || + mesh->first_triangle + mesh->num_triangles > header->num_triangles || + mesh->name >= header->num_text || + mesh->material >= header->num_text ) { + return qfalse; + } + } + + if( header->num_poses != header->num_joints && header->num_poses != 0 ) { + ri.Printf(PRINT_WARNING, "R_LoadIQM: %s has %d poses and %d joints, must have the same number or 0 poses\n", + mod_name, header->num_poses, header->num_joints ); + return qfalse; + } + + joint_names = 0; + + if ( header->num_joints ) + { + // check and swap joints + if( IQM_CheckRange( header, header->ofs_joints, + header->num_joints, sizeof(iqmJoint_t) ) ) { + return qfalse; + } + joint = (iqmJoint_t *)((byte *)header + header->ofs_joints); + for( i = 0; i < header->num_joints; i++, joint++ ) { + LL( joint->name ); + LL( joint->parent ); + LL( joint->translate[0] ); + LL( joint->translate[1] ); + LL( joint->translate[2] ); + LL( joint->rotate[0] ); + LL( joint->rotate[1] ); + LL( joint->rotate[2] ); + LL( joint->rotate[3] ); + LL( joint->scale[0] ); + LL( joint->scale[1] ); + LL( joint->scale[2] ); + + if( joint->parent < -1 || + joint->parent >= (int)header->num_joints || + joint->name >= (int)header->num_text ) { + return qfalse; + } + joint_names += strlen( (char *)header + header->ofs_text + + joint->name ) + 1; + } + } + + if ( header->num_poses ) + { + // check and swap poses + if( IQM_CheckRange( header, header->ofs_poses, + header->num_poses, sizeof(iqmPose_t) ) ) { + return qfalse; + } + pose = (iqmPose_t *)((byte *)header + header->ofs_poses); + for( i = 0; i < header->num_poses; i++, pose++ ) { + LL( pose->parent ); + LL( pose->mask ); + LL( pose->channeloffset[0] ); + LL( pose->channeloffset[1] ); + LL( pose->channeloffset[2] ); + LL( pose->channeloffset[3] ); + LL( pose->channeloffset[4] ); + LL( pose->channeloffset[5] ); + LL( pose->channeloffset[6] ); + LL( pose->channeloffset[7] ); + LL( pose->channeloffset[8] ); + LL( pose->channeloffset[9] ); + LL( pose->channelscale[0] ); + LL( pose->channelscale[1] ); + LL( pose->channelscale[2] ); + LL( pose->channelscale[3] ); + LL( pose->channelscale[4] ); + LL( pose->channelscale[5] ); + LL( pose->channelscale[6] ); + LL( pose->channelscale[7] ); + LL( pose->channelscale[8] ); + LL( pose->channelscale[9] ); + } + } + + if (header->ofs_bounds) + { + // check and swap model bounds + if(IQM_CheckRange(header, header->ofs_bounds, + header->num_frames, sizeof(*bounds))) + { + return qfalse; + } + bounds = (iqmBounds_t *) ((byte *) header + header->ofs_bounds); + for(i = 0; i < header->num_frames; i++) + { + LL(bounds->bbmin[0]); + LL(bounds->bbmin[1]); + LL(bounds->bbmin[2]); + LL(bounds->bbmax[0]); + LL(bounds->bbmax[1]); + LL(bounds->bbmax[2]); + + bounds++; + } + } + + // allocate the model and copy the data + size = sizeof(iqmData_t); + size += header->num_meshes * sizeof( srfIQModel_t ); + size += header->num_joints * 12 * sizeof( float ); // joint mats + size += header->num_poses * header->num_frames * 12 * sizeof( float ); // pose mats + if(header->ofs_bounds) + size += header->num_frames * 6 * sizeof(float); // model bounds + size += header->num_vertexes * 3 * sizeof(float); // positions + size += header->num_vertexes * 2 * sizeof(float); // texcoords + size += header->num_vertexes * 3 * sizeof(float); // normals + size += header->num_vertexes * 4 * sizeof(float); // tangents + size += header->num_vertexes * 4 * sizeof(byte); // blendIndexes + size += header->num_vertexes * 4 * sizeof(byte); // colors + size += header->num_joints * sizeof(int); // parents + size += header->num_triangles * 3 * sizeof(int); // triangles + size += joint_names; // joint names + + // blendWeights + if (blendWeightsType == IQM_FLOAT) { + size += header->num_vertexes * 4 * sizeof(float); + } else { + size += header->num_vertexes * 4 * sizeof(byte); + } + + mod->type = MOD_IQM; + iqmData = (iqmData_t *)ri.Hunk_Alloc( size, h_low ); + mod->data.iqm = iqmData; + + // fill header + iqmData->num_vertexes = header->num_vertexes; + iqmData->num_triangles = header->num_triangles; + iqmData->num_frames = header->num_frames; + iqmData->num_surfaces = header->num_meshes; + iqmData->num_joints = header->num_joints; + iqmData->num_poses = header->num_poses; + iqmData->blendWeightsType = blendWeightsType; + iqmData->surfaces = (srfIQModel_t *)(iqmData + 1); + iqmData->jointMats = (float *) (iqmData->surfaces + iqmData->num_surfaces); + iqmData->poseMats = iqmData->jointMats + 12 * header->num_joints; + if(header->ofs_bounds) + { + iqmData->bounds = iqmData->poseMats + 12 * header->num_poses * header->num_frames; + iqmData->positions = iqmData->bounds + 6 * header->num_frames; + } + else + iqmData->positions = iqmData->poseMats + 12 * header->num_poses * header->num_frames; + iqmData->texcoords = iqmData->positions + 3 * header->num_vertexes; + iqmData->normals = iqmData->texcoords + 2 * header->num_vertexes; + iqmData->tangents = iqmData->normals + 3 * header->num_vertexes; + iqmData->blendIndexes = (byte *)(iqmData->tangents + 4 * header->num_vertexes); + + if(blendWeightsType == IQM_FLOAT) { + iqmData->blendWeights.f = (float *)(iqmData->blendIndexes + 4 * header->num_vertexes); + iqmData->colors = (byte *)(iqmData->blendWeights.f + 4 * header->num_vertexes); + } else { + iqmData->blendWeights.b = iqmData->blendIndexes + 4 * header->num_vertexes; + iqmData->colors = iqmData->blendWeights.b + 4 * header->num_vertexes; + } + + iqmData->jointParents = (int *)(iqmData->colors + 4 * header->num_vertexes); + iqmData->triangles = iqmData->jointParents + header->num_joints; + iqmData->names = (char *)(iqmData->triangles + 3 * header->num_triangles); + + if ( header->num_joints == 0 ) + iqmData->jointMats = NULL; + + if ( header->num_poses == 0 ) + iqmData->poseMats = NULL; + + // calculate joint matrices and their inverses + // joint inverses are needed only until the pose matrices are calculated + mat = iqmData->jointMats; + matInv = jointInvMats; + joint = (iqmJoint_t *)((byte *)header + header->ofs_joints); + for( i = 0; i < header->num_joints; i++, joint++ ) { + float baseFrame[12], invBaseFrame[12]; + + JointToMatrix( joint->rotate, joint->scale, joint->translate, baseFrame ); + Matrix34Invert( baseFrame, invBaseFrame ); + + if ( joint->parent >= 0 ) + { + Matrix34Multiply( iqmData->jointMats + 12 * joint->parent, baseFrame, mat ); + mat += 12; + Matrix34Multiply( invBaseFrame, jointInvMats + 12 * joint->parent, matInv ); + matInv += 12; + } + else + { + Com_Memcpy( mat, baseFrame, sizeof(baseFrame) ); + mat += 12; + Com_Memcpy( matInv, invBaseFrame, sizeof(invBaseFrame) ); + matInv += 12; + } + } + + // calculate pose matrices + framedata = (unsigned short *)((byte *)header + header->ofs_frames); + mat = iqmData->poseMats; + for( i = 0; i < header->num_frames; i++ ) { + pose = (iqmPose_t *)((byte *)header + header->ofs_poses); + for( j = 0; j < header->num_poses; j++, pose++ ) { + vec3_t translate; + vec4_t rotate; + vec3_t scale; + float mat1[12], mat2[12]; + + translate[0] = pose->channeloffset[0]; + if( pose->mask & 0x001) + translate[0] += *framedata++ * pose->channelscale[0]; + translate[1] = pose->channeloffset[1]; + if( pose->mask & 0x002) + translate[1] += *framedata++ * pose->channelscale[1]; + translate[2] = pose->channeloffset[2]; + if( pose->mask & 0x004) + translate[2] += *framedata++ * pose->channelscale[2]; + + rotate[0] = pose->channeloffset[3]; + if( pose->mask & 0x008) + rotate[0] += *framedata++ * pose->channelscale[3]; + rotate[1] = pose->channeloffset[4]; + if( pose->mask & 0x010) + rotate[1] += *framedata++ * pose->channelscale[4]; + rotate[2] = pose->channeloffset[5]; + if( pose->mask & 0x020) + rotate[2] += *framedata++ * pose->channelscale[5]; + rotate[3] = pose->channeloffset[6]; + if( pose->mask & 0x040) + rotate[3] += *framedata++ * pose->channelscale[6]; + + scale[0] = pose->channeloffset[7]; + if( pose->mask & 0x080) + scale[0] += *framedata++ * pose->channelscale[7]; + scale[1] = pose->channeloffset[8]; + if( pose->mask & 0x100) + scale[1] += *framedata++ * pose->channelscale[8]; + scale[2] = pose->channeloffset[9]; + if( pose->mask & 0x200) + scale[2] += *framedata++ * pose->channelscale[9]; + + // construct transformation matrix + JointToMatrix( rotate, scale, translate, mat1 ); + + if( pose->parent >= 0 ) { + Matrix34Multiply( iqmData->jointMats + 12 * pose->parent, + mat1, mat2 ); + } else { + Com_Memcpy( mat2, mat1, sizeof(mat1) ); + } + + Matrix34Multiply( mat2, jointInvMats + 12 * j, mat ); + mat += 12; + } + } + + // register shaders + // overwrite the material offset with the shader index + mesh = (iqmMesh_t *)((byte *)header + header->ofs_meshes); + surface = iqmData->surfaces; + str = (char *)header + header->ofs_text; + for( i = 0; i < header->num_meshes; i++, mesh++, surface++ ) { + surface->surfaceType = SF_IQM; + Q_strncpyz(surface->name, str + mesh->name, sizeof (surface->name)); + Q_strlwr(surface->name); // lowercase the surface name so skin compares are faster + surface->shader = R_FindShader( str + mesh->material, lightmapsNone, stylesDefault, qtrue ); + if( surface->shader->defaultShader ) + surface->shader = tr.defaultShader; + surface->data = iqmData; + surface->first_vertex = mesh->first_vertex; + surface->num_vertexes = mesh->num_vertexes; + surface->first_triangle = mesh->first_triangle; + surface->num_triangles = mesh->num_triangles; + } + + // copy vertexarrays and indexes + vertexarray = (iqmVertexArray_t *)((byte *)header + header->ofs_vertexarrays); + for( i = 0; i < header->num_vertexarrays; i++, vertexarray++ ) { + int n; + + // total number of values + n = header->num_vertexes * vertexarray->size; + + switch( vertexarray->type ) { + case IQM_POSITION: + Com_Memcpy( iqmData->positions, + (byte *)header + vertexarray->offset, + n * sizeof(float) ); + break; + case IQM_NORMAL: + Com_Memcpy( iqmData->normals, + (byte *)header + vertexarray->offset, + n * sizeof(float) ); + break; + case IQM_TANGENT: + Com_Memcpy( iqmData->tangents, + (byte *)header + vertexarray->offset, + n * sizeof(float) ); + break; + case IQM_TEXCOORD: + Com_Memcpy( iqmData->texcoords, + (byte *)header + vertexarray->offset, + n * sizeof(float) ); + break; + case IQM_BLENDINDEXES: + if( blendIndexesType == IQM_INT ) { + int *data = (int*)((byte*)header + vertexarray->offset); + for ( j = 0; j < n; j++ ) { + iqmData->blendIndexes[j] = (byte)data[j]; + } + } else { + Com_Memcpy( iqmData->blendIndexes, + (byte *)header + vertexarray->offset, + n * sizeof(byte) ); + } + break; + case IQM_BLENDWEIGHTS: + if( blendWeightsType == IQM_FLOAT ) { + Com_Memcpy( iqmData->blendWeights.f, + (byte *)header + vertexarray->offset, + n * sizeof(float) ); + } else { + Com_Memcpy( iqmData->blendWeights.b, + (byte *)header + vertexarray->offset, + n * sizeof(byte) ); + } + break; + case IQM_COLOR: + Com_Memcpy( iqmData->colors, + (byte *)header + vertexarray->offset, + n * sizeof(byte) ); + break; + } + } + + // copy joint parents + joint = (iqmJoint_t *)((byte *)header + header->ofs_joints); + for( i = 0; i < header->num_joints; i++, joint++ ) { + iqmData->jointParents[i] = joint->parent; + } + + // copy triangles + triangle = (iqmTriangle_t *)((byte *)header + header->ofs_triangles); + for( i = 0; i < header->num_triangles; i++, triangle++ ) { + iqmData->triangles[3*i+0] = triangle->vertex[0]; + iqmData->triangles[3*i+1] = triangle->vertex[1]; + iqmData->triangles[3*i+2] = triangle->vertex[2]; + } + + // copy joint names + str = iqmData->names; + joint = (iqmJoint_t *)((byte *)header + header->ofs_joints); + for( i = 0; i < header->num_joints; i++, joint++ ) { + char *name = (char *)header + header->ofs_text + + joint->name; + int len = strlen( name ) + 1; + Com_Memcpy( str, name, len ); + str += len; + } + + // copy model bounds + if(header->ofs_bounds) + { + mat = iqmData->bounds; + bounds = (iqmBounds_t *) ((byte *) header + header->ofs_bounds); + for(i = 0; i < header->num_frames; i++) + { + mat[0] = bounds->bbmin[0]; + mat[1] = bounds->bbmin[1]; + mat[2] = bounds->bbmin[2]; + mat[3] = bounds->bbmax[0]; + mat[4] = bounds->bbmax[1]; + mat[5] = bounds->bbmax[2]; + + mat += 6; + bounds++; + } + } + + return qtrue; +} + +/* +============= +R_CullIQM +============= +*/ +static int R_CullIQM( iqmData_t *data, trRefEntity_t *ent ) { + vec3_t bounds[2]; + float *oldBounds, *newBounds; + int i; + + if (!data->bounds) { + tr.pc.c_box_cull_md3_clip++; + return CULL_CLIP; + } + + // compute bounds pointers + oldBounds = data->bounds + 6*ent->e.oldframe; + newBounds = data->bounds + 6*ent->e.frame; + + // calculate a bounding box in the current coordinate system + for (i = 0 ; i < 3 ; i++) { + bounds[0][i] = oldBounds[i] < newBounds[i] ? oldBounds[i] : newBounds[i]; + bounds[1][i] = oldBounds[i+3] > newBounds[i+3] ? oldBounds[i+3] : newBounds[i+3]; + } + + switch ( R_CullLocalBox( bounds ) ) + { + case CULL_IN: + tr.pc.c_box_cull_md3_in++; + return CULL_IN; + case CULL_CLIP: + tr.pc.c_box_cull_md3_clip++; + return CULL_CLIP; + case CULL_OUT: + default: + tr.pc.c_box_cull_md3_out++; + return CULL_OUT; + } +} + +/* +================= +R_ComputeIQMFogNum + +================= +*/ +int R_ComputeIQMFogNum( iqmData_t *data, trRefEntity_t *ent ) { + int i, j; + fog_t *fog; + const float *bounds; + const float defaultBounds[6] = { -8, -8, -8, 8, 8, 8 }; + vec3_t diag, center; + vec3_t localOrigin; + float radius; + + if ( tr.refdef.rdflags & RDF_NOWORLDMODEL ) { + return 0; + } + + // FIXME: non-normalized axis issues + if (data->bounds) { + bounds = data->bounds + 6*ent->e.frame; + } else { + bounds = defaultBounds; + } + VectorSubtract( bounds+3, bounds, diag ); + VectorMA( bounds, 0.5f, diag, center ); + VectorAdd( ent->e.origin, center, localOrigin ); + radius = 0.5f * VectorLength( diag ); + + for ( i = 1 ; i < tr.world->numfogs ; i++ ) { + fog = &tr.world->fogs[i]; + for ( j = 0 ; j < 3 ; j++ ) { + if ( localOrigin[j] - radius >= fog->bounds[1][j] ) { + break; + } + if ( localOrigin[j] + radius <= fog->bounds[0][j] ) { + break; + } + } + if ( j == 3 ) { + return i; + } + } + + return 0; +} + +/* +================= +R_AddIQMSurfaces + +Add all surfaces of this model +================= +*/ +void R_AddIQMSurfaces( trRefEntity_t *ent, int entityNum ) { + iqmData_t *data; + srfIQModel_t *surface; + int i, j; + qboolean personalModel; + int cull; + int fogNum; + int cubemapIndex; + shader_t *shader; + skin_t *skin; + + data = tr.currentModel->data.iqm; + surface = data->surfaces; + + // don't add third_person objects if not in a portal + personalModel = (qboolean)((ent->e.renderfx & RF_THIRD_PERSON) && !tr.viewParms.isPortal); + + if ( ent->e.renderfx & RF_WRAP_FRAMES ) { + ent->e.frame %= data->num_frames; + ent->e.oldframe %= data->num_frames; + } + + // + // Validate the frames so there is no chance of a crash. + // This will write directly into the entity structure, so + // when the surfaces are rendered, they don't need to be + // range checked again. + // + if ( (ent->e.frame >= data->num_frames) + || (ent->e.frame < 0) + || (ent->e.oldframe >= data->num_frames) + || (ent->e.oldframe < 0) ) { + ri.Printf( PRINT_DEVELOPER, "R_AddIQMSurfaces: no such frame %d to %d for '%s'\n", + ent->e.oldframe, ent->e.frame, + tr.currentModel->name ); + ent->e.frame = 0; + ent->e.oldframe = 0; + } + + // + // cull the entire model if merged bounding box of both frames + // is outside the view frustum. + // + cull = R_CullIQM ( data, ent ); + if ( cull == CULL_OUT ) { + return; + } + + // + // see if we are in a fog volume + // + fogNum = R_ComputeIQMFogNum( data, ent ); + + cubemapIndex = R_CubemapForPoint(ent->e.origin); + + for ( i = 0 ; i < data->num_surfaces ; i++ ) { + if(ent->e.customShader) + shader = R_GetShaderByHandle( ent->e.customShader ); + else if(ent->e.customSkin > 0 && ent->e.customSkin < tr.numSkins) + { + skin = R_GetSkinByHandle(ent->e.customSkin); + shader = tr.defaultShader; + + for(j = 0; j < skin->numSurfaces; j++) + { + if (!strcmp(skin->surfaces[j]->name, surface->name)) + { + shader = (shader_t *)skin->surfaces[j]->shader; + break; + } + } + } else { + shader = surface->shader; + } + + // we will add shadows even if the main object isn't visible in the view + + // stencil shadows can't do personal models unless I polyhedron clip + if ( !personalModel + && r_shadows->integer == 2 + && fogNum == 0 + && !(ent->e.renderfx & ( RF_NOSHADOW | RF_DEPTHHACK ) ) + && shader->sort == SS_OPAQUE ) { + R_AddDrawSurf( (surfaceType_t *)surface, entityNum, tr.shadowShader, 0, 0, R_IsPostRenderEntity(ent), 0 ); + } + + // projection shadows work fine with personal models + if ( r_shadows->integer == 3 + && fogNum == 0 + && (ent->e.renderfx & RF_SHADOW_PLANE ) + && shader->sort == SS_OPAQUE ) { + R_AddDrawSurf( (surfaceType_t *)surface, entityNum, tr.projectionShadowShader, 0, 0, R_IsPostRenderEntity(ent), 0 ); + } + + if( !personalModel ) { + R_AddDrawSurf( (surfaceType_t *)surface, entityNum, shader, fogNum, 0, R_IsPostRenderEntity(ent), cubemapIndex ); + } + + surface++; + } +} + + +static void ComputePoseMats( iqmData_t *data, int frame, int oldframe, + float backlerp, float *mat ) { + float *mat1, *mat2; + int *joint = data->jointParents; + int i; + + if ( data->num_poses == 0 ) { + for( i = 0; i < data->num_joints; i++, joint++ ) { + if( *joint >= 0 ) { + Matrix34Multiply( mat + 12 * *joint, + identityMatrix, mat + 12*i ); + } else { + Com_Memcpy( mat + 12*i, identityMatrix, 12 * sizeof(float) ); + } + } + return; + } + + if ( oldframe == frame ) { + mat1 = data->poseMats + 12 * data->num_poses * frame; + for( i = 0; i < data->num_poses; i++, joint++ ) { + if( *joint >= 0 ) { + Matrix34Multiply( mat + 12 * *joint, + mat1 + 12*i, mat + 12*i ); + } else { + Com_Memcpy( mat + 12*i, mat1 + 12*i, 12 * sizeof(float) ); + } + } + } else { + mat1 = data->poseMats + 12 * data->num_poses * frame; + mat2 = data->poseMats + 12 * data->num_poses * oldframe; + + for( i = 0; i < data->num_poses; i++, joint++ ) { + if( *joint >= 0 ) { + float tmpMat[12]; + InterpolateMatrix( mat1 + 12*i, mat2 + 12*i, + backlerp, tmpMat ); + Matrix34Multiply( mat + 12 * *joint, + tmpMat, mat + 12*i ); + + } else { + InterpolateMatrix( mat1 + 12*i, mat2 + 12*i, + backlerp, mat ); + } + } + } +} + +static void ComputeJointMats( iqmData_t *data, int frame, int oldframe, + float backlerp, float *mat ) { + float *mat1; + int i; + + ComputePoseMats( data, frame, oldframe, backlerp, mat ); + + for( i = 0; i < data->num_joints; i++ ) { + float outmat[12]; + mat1 = mat + 12 * i; + + Com_Memcpy(outmat, mat1, sizeof(outmat)); + + Matrix34Multiply_OnlySetOrigin( outmat, data->jointMats + 12 * i, mat1 ); + } +} + + +/* +================= +RB_AddIQMSurfaces + +Compute vertices for this model surface +================= +*/ +void RB_IQMSurfaceAnim( surfaceType_t *surface ) { + srfIQModel_t *surf = (srfIQModel_t *)surface; + iqmData_t *data = surf->data; + float jointMats[IQM_MAX_JOINTS * 12]; + int i; + + vec4_t *outXYZ; + uint32_t *outNormal; + uint32_t *outTangent; + vec2_t (*outTexCoord)[NUM_TESS_TEXCOORDS]; + vec4_t *outColor; + + int frame = data->num_frames ? backEnd.currentEntity->e.frame % data->num_frames : 0; + int oldframe = data->num_frames ? backEnd.currentEntity->e.oldframe % data->num_frames : 0; + float backlerp = backEnd.currentEntity->e.backlerp; + + int *tri; + glIndex_t *ptr; + glIndex_t base; + + RB_CHECKOVERFLOW( surf->num_vertexes, surf->num_triangles * 3 ); + + outXYZ = &tess.xyz[tess.numVertexes]; + outNormal = &tess.normal[tess.numVertexes]; + outTangent = &tess.tangent[tess.numVertexes]; + outTexCoord = &tess.texCoords[tess.numVertexes]; + outColor = &tess.vertexColors[tess.numVertexes]; + + // compute interpolated joint matrices + if ( data->num_poses > 0 ) { + ComputePoseMats( data, frame, oldframe, backlerp, jointMats ); + } + + // transform vertexes and fill other data + for( i = 0; i < surf->num_vertexes; + i++, outXYZ++, outNormal++, outTexCoord++, outColor++ ) { + int j, k; + float vtxMat[12]; + float nrmMat[9]; + int vtx = i + surf->first_vertex; + float blendWeights[4]; + int numWeights; + + for ( numWeights = 0; numWeights < 4; numWeights++ ) { + if ( data->blendWeightsType == IQM_FLOAT ) + blendWeights[numWeights] = data->blendWeights.f[4*vtx + numWeights]; + else + blendWeights[numWeights] = (float)data->blendWeights.b[4*vtx + numWeights] / 255.0f; + + if ( blendWeights[numWeights] <= 0 ) + break; + } + + if ( data->num_poses == 0 || numWeights == 0 ) { + // no blend joint, use identity matrix. + Com_Memcpy( vtxMat, identityMatrix, 12 * sizeof (float) ); + } else { + // compute the vertex matrix by blending the up to + // four blend weights + Com_Memset( vtxMat, 0, 12 * sizeof (float) ); + for( j = 0; j < numWeights; j++ ) { + for( k = 0; k < 12; k++ ) { + vtxMat[k] += blendWeights[j] * jointMats[12*data->blendIndexes[4*vtx + j] + k]; + } + } + } + + // compute the normal matrix as transpose of the adjoint + // of the vertex matrix + nrmMat[ 0] = vtxMat[ 5]*vtxMat[10] - vtxMat[ 6]*vtxMat[ 9]; + nrmMat[ 1] = vtxMat[ 6]*vtxMat[ 8] - vtxMat[ 4]*vtxMat[10]; + nrmMat[ 2] = vtxMat[ 4]*vtxMat[ 9] - vtxMat[ 5]*vtxMat[ 8]; + nrmMat[ 3] = vtxMat[ 2]*vtxMat[ 9] - vtxMat[ 1]*vtxMat[10]; + nrmMat[ 4] = vtxMat[ 0]*vtxMat[10] - vtxMat[ 2]*vtxMat[ 8]; + nrmMat[ 5] = vtxMat[ 1]*vtxMat[ 8] - vtxMat[ 0]*vtxMat[ 9]; + nrmMat[ 6] = vtxMat[ 1]*vtxMat[ 6] - vtxMat[ 2]*vtxMat[ 5]; + nrmMat[ 7] = vtxMat[ 2]*vtxMat[ 4] - vtxMat[ 0]*vtxMat[ 6]; + nrmMat[ 8] = vtxMat[ 0]*vtxMat[ 5] - vtxMat[ 1]*vtxMat[ 4]; + + (*outTexCoord)[0][0] = data->texcoords[2*vtx + 0]; + (*outTexCoord)[0][1] = data->texcoords[2*vtx + 1]; + (*outTexCoord)[1][0] = (*outTexCoord)[0][0]; + (*outTexCoord)[1][1] = (*outTexCoord)[0][1]; + + (*outXYZ)[0] = + vtxMat[ 0] * data->positions[3*vtx+0] + + vtxMat[ 1] * data->positions[3*vtx+1] + + vtxMat[ 2] * data->positions[3*vtx+2] + + vtxMat[ 3]; + (*outXYZ)[1] = + vtxMat[ 4] * data->positions[3*vtx+0] + + vtxMat[ 5] * data->positions[3*vtx+1] + + vtxMat[ 6] * data->positions[3*vtx+2] + + vtxMat[ 7]; + (*outXYZ)[2] = + vtxMat[ 8] * data->positions[3*vtx+0] + + vtxMat[ 9] * data->positions[3*vtx+1] + + vtxMat[10] * data->positions[3*vtx+2] + + vtxMat[11]; + (*outXYZ)[3] = 1.0f; + + { + vec3_t normal; + vec4_t tangent; + + normal[0] = DotProduct(&nrmMat[0], &data->normals[3*vtx]); + normal[1] = DotProduct(&nrmMat[3], &data->normals[3*vtx]); + normal[2] = DotProduct(&nrmMat[6], &data->normals[3*vtx]); + + *outNormal = R_VboPackNormal(normal); + + tangent[0] = DotProduct(&nrmMat[0], &data->tangents[4*vtx]); + tangent[1] = DotProduct(&nrmMat[3], &data->tangents[4*vtx]); + tangent[2] = DotProduct(&nrmMat[6], &data->tangents[4*vtx]); + tangent[3] = data->tangents[4*vtx+3]; + + *outTangent++ = R_VboPackTangent(tangent); + } + + (*outColor)[0] = data->colors[4*vtx+0] / 255.0f; + (*outColor)[1] = data->colors[4*vtx+1] / 255.0f; + (*outColor)[2] = data->colors[4*vtx+2] / 255.0f; + (*outColor)[3] = data->colors[4*vtx+3] / 255.0f; + } + + tri = data->triangles + 3 * surf->first_triangle; + ptr = &tess.indexes[tess.numIndexes]; + base = tess.numVertexes; + + for( i = 0; i < surf->num_triangles; i++ ) { + *ptr++ = base + (*tri++ - surf->first_vertex); + *ptr++ = base + (*tri++ - surf->first_vertex); + *ptr++ = base + (*tri++ - surf->first_vertex); + } + + tess.numIndexes += 3 * surf->num_triangles; + tess.numVertexes += surf->num_vertexes; +} + +int R_IQMLerpTag( orientation_t *tag, iqmData_t *data, + int startFrame, int endFrame, + float frac, const char *tagName ) { + float jointMats[IQM_MAX_JOINTS * 12]; + int joint; + char *names = data->names; + + // get joint number by reading the joint names + for( joint = 0; joint < data->num_joints; joint++ ) { + if( !strcmp( tagName, names ) ) + break; + names += strlen( names ) + 1; + } + if( joint >= data->num_joints ) { + AxisClear( tag->axis ); + VectorClear( tag->origin ); + return qfalse; + } + + ComputeJointMats( data, startFrame, endFrame, frac, jointMats ); + + tag->axis[0][0] = jointMats[12 * joint + 0]; + tag->axis[1][0] = jointMats[12 * joint + 1]; + tag->axis[2][0] = jointMats[12 * joint + 2]; + tag->origin[0] = jointMats[12 * joint + 3]; + tag->axis[0][1] = jointMats[12 * joint + 4]; + tag->axis[1][1] = jointMats[12 * joint + 5]; + tag->axis[2][1] = jointMats[12 * joint + 6]; + tag->origin[1] = jointMats[12 * joint + 7]; + tag->axis[0][2] = jointMats[12 * joint + 8]; + tag->axis[1][2] = jointMats[12 * joint + 9]; + tag->axis[2][2] = jointMats[12 * joint + 10]; + tag->origin[2] = jointMats[12 * joint + 11]; + + return qtrue; +} diff --git a/codemp/rd-rend2/tr_postprocess.cpp b/codemp/rd-rend2/tr_postprocess.cpp new file mode 100644 index 0000000000..9502cb50e7 --- /dev/null +++ b/codemp/rd-rend2/tr_postprocess.cpp @@ -0,0 +1,528 @@ +/* +=========================================================================== +Copyright (C) 2011 Andrei Drexler, Richard Allen, James Canete + +This file is part of Reaction source code. + +Reaction source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Reaction source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Reaction source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +#include "tr_local.h" + +void RB_ToneMap(FBO_t *hdrFbo, vec4i_t hdrBox, FBO_t *ldrFbo, vec4i_t ldrBox, int autoExposure) +{ + vec4i_t srcBox, dstBox; + vec4_t color; + static int lastFrameCount = 0; + + if (autoExposure) + { + if (lastFrameCount == 0 || tr.frameCount < lastFrameCount || tr.frameCount - lastFrameCount > 5) + { + // determine average log luminance + FBO_t *srcFbo, *dstFbo, *tmp; + int size = 256; + + lastFrameCount = tr.frameCount; + + VectorSet4(dstBox, 0, 0, size, size); + + FBO_Blit(hdrFbo, hdrBox, NULL, tr.textureScratchFbo[0], dstBox, &tr.calclevels4xShader[0], NULL, 0); + + srcFbo = tr.textureScratchFbo[0]; + dstFbo = tr.textureScratchFbo[1]; + + // downscale to 1x1 texture + while (size > 1) + { + VectorSet4(srcBox, 0, 0, size, size); + size >>= 1; + VectorSet4(dstBox, 0, 0, size, size); + + if (size == 1) + dstFbo = tr.targetLevelsFbo; + + FBO_Blit(srcFbo, srcBox, NULL, dstFbo, dstBox, &tr.calclevels4xShader[1], NULL, 0); + + tmp = srcFbo; + srcFbo = dstFbo; + dstFbo = tmp; + } + } + + // blend with old log luminance for gradual change + VectorSet4(srcBox, 0, 0, 0, 0); + + color[0] = + color[1] = + color[2] = 1.0f; + + color[3] = Com_Clamp(0.0f, 1.0f, 0.001f * backEnd.refdef.frameTime); + FBO_Blit(tr.targetLevelsFbo, srcBox, NULL, tr.calcLevelsFbo, NULL, NULL, color, GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); + } + + // tonemap + color[0] = + color[1] = + color[2] = powf(2.0f, r_cameraExposure->value); //exp2(r_cameraExposure->value); + color[3] = 1.0f; + + if (autoExposure) + GL_BindToTMU(tr.calcLevelsImage, TB_LEVELSMAP); + else + GL_BindToTMU(tr.fixedLevelsImage, TB_LEVELSMAP); + + bool srgbTransform = tr.hdrLighting == qtrue; + shaderProgram_t *shader = srgbTransform ? &tr.tonemapShader[1] : &tr.tonemapShader[0]; + FBO_Blit(hdrFbo, hdrBox, NULL, ldrFbo, ldrBox, shader, color, 0); +} + +/* +============= +RB_BokehBlur + + +Blurs a part of one framebuffer to another. + +Framebuffers can be identical. +============= +*/ +void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float blur) +{ +// vec4i_t srcBox, dstBox; + vec4_t color; + + blur *= 10.0f; + + if (blur < 0.004f) + return; + + // bokeh blur + if (blur > 0.0f) + { + vec4i_t quarterBox; + + quarterBox[0] = 0; + quarterBox[1] = tr.quarterFbo[0]->height; + quarterBox[2] = tr.quarterFbo[0]->width; + quarterBox[3] = -tr.quarterFbo[0]->height; + + // create a quarter texture + //FBO_Blit(NULL, NULL, NULL, tr.quarterFbo[0], NULL, NULL, NULL, 0); + FBO_FastBlit(src, srcBox, tr.quarterFbo[0], quarterBox, GL_COLOR_BUFFER_BIT, GL_LINEAR); + } + +#ifndef HQ_BLUR + if (blur > 1.0f) + { + // create a 1/16th texture + //FBO_Blit(tr.quarterFbo[0], NULL, NULL, tr.textureScratchFbo[0], NULL, NULL, NULL, 0); + FBO_FastBlit(tr.quarterFbo[0], NULL, tr.textureScratchFbo[0], NULL, GL_COLOR_BUFFER_BIT, GL_LINEAR); + } +#endif + + if (blur > 0.0f && blur <= 1.0f) + { + // Crossfade original with quarter texture + VectorSet4(color, 1, 1, 1, blur); + + FBO_Blit(tr.quarterFbo[0], NULL, NULL, dst, dstBox, NULL, color, GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); + } +#ifndef HQ_BLUR + // ok blur, but can see some pixelization + else if (blur > 1.0f && blur <= 2.0f) + { + // crossfade quarter texture with 1/16th texture + FBO_Blit(tr.quarterFbo[0], NULL, NULL, dst, dstBox, NULL, NULL, 0); + + VectorSet4(color, 1, 1, 1, blur - 1.0f); + + FBO_Blit(tr.textureScratchFbo[0], NULL, NULL, dst, dstBox, NULL, color, GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); + } + else if (blur > 2.0f) + { + // blur 1/16th texture then replace + int i; + + for (i = 0; i < 2; i++) + { + vec2_t blurTexScale; + float subblur; + + subblur = ((blur - 2.0f) / 2.0f) / 3.0f * (float)(i + 1); + + blurTexScale[0] = + blurTexScale[1] = subblur; + + color[0] = + color[1] = + color[2] = 0.5f; + color[3] = 1.0f; + + if (i != 0) + FBO_Blit(tr.textureScratchFbo[0], NULL, blurTexScale, tr.textureScratchFbo[1], NULL, &tr.bokehShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); + else + FBO_Blit(tr.textureScratchFbo[0], NULL, blurTexScale, tr.textureScratchFbo[1], NULL, &tr.bokehShader, color, 0); + } + + FBO_Blit(tr.textureScratchFbo[1], NULL, NULL, dst, dstBox, &tr.textureColorShader, NULL, 0); + } +#else // higher quality blur, but slower + else if (blur > 1.0f) + { + // blur quarter texture then replace + int i; + + src = tr.quarterFbo[0]; + dst = tr.quarterFbo[1]; + + VectorSet4(color, 0.5f, 0.5f, 0.5f, 1); + + for (i = 0; i < 2; i++) + { + vec2_t blurTexScale; + float subblur; + + subblur = (blur - 1.0f) / 2.0f * (float)(i + 1); + + blurTexScale[0] = + blurTexScale[1] = subblur; + + color[0] = + color[1] = + color[2] = 1.0f; + if (i != 0) + color[3] = 1.0f; + else + color[3] = 0.5f; + + FBO_Blit(tr.quarterFbo[0], NULL, blurTexScale, tr.quarterFbo[1], NULL, &tr.bokehShader, color, GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA); + } + + FBO_Blit(tr.quarterFbo[1], NULL, NULL, dst, dstBox, &tr.textureColorShader, NULL, 0); + } +#endif +} + + +static void RB_RadialBlur(FBO_t *srcFbo, FBO_t *dstFbo, int passes, float stretch, float x, float y, float w, float h, float xcenter, float ycenter, float alpha) +{ + vec4i_t srcBox, dstBox; + vec4_t color; + const float inc = 1.f / passes; + const float mul = powf(stretch, inc); + float scale; + + { + vec2_t texScale; + + texScale[0] = + texScale[1] = 1.0f; + + alpha *= inc; + VectorSet4(color, alpha, alpha, alpha, 1.0f); + + VectorSet4(srcBox, 0, 0, srcFbo->width, srcFbo->height); + VectorSet4(dstBox, x, y, w, h); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, 0); + + --passes; + scale = mul; + while (passes > 0) + { + float iscale = 1.f / scale; + float s0 = xcenter * (1.f - iscale); + float t0 = (1.0f - ycenter) * (1.f - iscale); + float s1 = iscale + s0; + float t1 = iscale + t0; + + if (srcFbo) + { + srcBox[0] = s0 * srcFbo->width; + srcBox[1] = t0 * srcFbo->height; + srcBox[2] = (s1 - s0) * srcFbo->width; + srcBox[3] = (t1 - t0) * srcFbo->height; + } + else + { + srcBox[0] = s0 * glConfig.vidWidth; + srcBox[1] = t0 * glConfig.vidHeight; + srcBox[2] = (s1 - s0) * glConfig.vidWidth; + srcBox[3] = (t1 - t0) * glConfig.vidHeight; + } + + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + + scale *= mul; + --passes; + } + } +} + + +static qboolean RB_UpdateSunFlareVis(void) +{ + GLuint sampleCount = 0; + + tr.sunFlareQueryIndex ^= 1; + if (!tr.sunFlareQueryActive[tr.sunFlareQueryIndex]) + return qtrue; + + /* debug code */ + if (0) + { + int iter; + for (iter=0 ; ; ++iter) + { + GLint available = 0; + qglGetQueryObjectiv(tr.sunFlareQuery[tr.sunFlareQueryIndex], GL_QUERY_RESULT_AVAILABLE, &available); + if (available) + break; + } + + ri.Printf(PRINT_DEVELOPER, "Waited %d iterations\n", iter); + } + + qglGetQueryObjectuiv(tr.sunFlareQuery[tr.sunFlareQueryIndex], GL_QUERY_RESULT, &sampleCount); + return (qboolean)(sampleCount > 0); +} + +void RB_SunRays(FBO_t *srcFbo, vec4i_t srcBox, FBO_t *dstFbo, vec4i_t dstBox) +{ + vec4_t color; + float dot; + const float cutoff = 0.25f; + qboolean colorize = qtrue; + +// float w, h, w2, h2; + matrix_t mvp; + vec4_t pos, hpos; + + dot = DotProduct(tr.sunDirection, backEnd.viewParms.ori.axis[0]); + if (dot < cutoff) + return; + + if (!RB_UpdateSunFlareVis()) + return; + + // From RB_DrawSun() + { + float dist; + matrix_t trans, model; + + Matrix16Translation( backEnd.viewParms.ori.origin, trans ); + Matrix16Multiply( backEnd.viewParms.world.modelViewMatrix, trans, model ); + Matrix16Multiply(backEnd.viewParms.projectionMatrix, model, mvp); + + dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + + VectorScale( tr.sunDirection, dist, pos ); + } + + // project sun point + //Matrix16Multiply(backEnd.viewParms.projectionMatrix, backEnd.viewParms.world.modelViewMatrix, mvp); + Matrix16Transform(mvp, pos, hpos); + + // transform to UV coords + hpos[3] = 0.5f / hpos[3]; + + pos[0] = 0.5f + hpos[0] * hpos[3]; + pos[1] = 0.5f + hpos[1] * hpos[3]; + + // initialize quarter buffers + { + float mul = 1.f; + vec2_t texScale; + vec4i_t rayBox, quarterBox; + + texScale[0] = + texScale[1] = 1.0f; + + VectorSet4(color, mul, mul, mul, 1); + + if (srcFbo) + { + rayBox[0] = srcBox[0] * tr.sunRaysFbo->width / srcFbo->width; + rayBox[1] = srcBox[1] * tr.sunRaysFbo->height / srcFbo->height; + rayBox[2] = srcBox[2] * tr.sunRaysFbo->width / srcFbo->width; + rayBox[3] = srcBox[3] * tr.sunRaysFbo->height / srcFbo->height; + } + else + { + rayBox[0] = srcBox[0] * tr.sunRaysFbo->width / glConfig.vidWidth; + rayBox[1] = srcBox[1] * tr.sunRaysFbo->height / glConfig.vidHeight; + rayBox[2] = srcBox[2] * tr.sunRaysFbo->width / glConfig.vidWidth; + rayBox[3] = srcBox[3] * tr.sunRaysFbo->height / glConfig.vidHeight; + } + + quarterBox[0] = 0; + quarterBox[1] = tr.quarterFbo[0]->height; + quarterBox[2] = tr.quarterFbo[0]->width; + quarterBox[3] = -tr.quarterFbo[0]->height; + + // first, downsample the framebuffer + if (colorize) + { + FBO_FastBlit(srcFbo, srcBox, tr.quarterFbo[0], quarterBox, GL_COLOR_BUFFER_BIT, GL_LINEAR); + FBO_Blit(tr.sunRaysFbo, rayBox, NULL, tr.quarterFbo[0], quarterBox, NULL, color, GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO); + } + else + { + FBO_FastBlit(tr.sunRaysFbo, rayBox, tr.quarterFbo[0], quarterBox, GL_COLOR_BUFFER_BIT, GL_LINEAR); + } + } + + // radial blur passes, ping-ponging between the two quarter-size buffers + { + const float stretch_add = 2.f/3.f; + float stretch = 1.f + stretch_add; + int i; + for (i=0; i<2; ++i) + { + RB_RadialBlur(tr.quarterFbo[i&1], tr.quarterFbo[(~i) & 1], 5, stretch, 0.f, 0.f, tr.quarterFbo[0]->width, tr.quarterFbo[0]->height, pos[0], pos[1], 1.125f); + stretch += stretch_add; + } + } + + // add result back on top of the main buffer + { + float mul = 1.f; + vec2_t texScale; + + texScale[0] = + texScale[1] = 1.0f; + + VectorSet4(color, mul, mul, mul, 1); + + FBO_Blit(tr.quarterFbo[0], NULL, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE); + } +} + +static void RB_BlurAxis(FBO_t *srcFbo, FBO_t *dstFbo, float strength, qboolean horizontal) +{ + float dx, dy; + float xmul, ymul; + float weights[3] = { + 0.227027027f, + 0.316216216f, + 0.070270270f, + }; + float offsets[3] = { + 0.f, + 1.3846153846f, + 3.2307692308f, + }; + + xmul = horizontal; + ymul = 1.f - xmul; + + xmul *= strength; + ymul *= strength; + + { + vec4i_t srcBox, dstBox; + vec4_t color; + vec2_t texScale; + + texScale[0] = + texScale[1] = 1.0f; + + VectorSet4(color, weights[0], weights[0], weights[0], 1.0f); + VectorSet4(srcBox, 0, 0, srcFbo->width, srcFbo->height); + VectorSet4(dstBox, 0, 0, dstFbo->width, dstFbo->height); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, 0 ); + + VectorSet4(color, weights[1], weights[1], weights[1], 1.0f); + dx = offsets[1] * xmul; + dy = offsets[1] * ymul; + VectorSet4(srcBox, dx, dy, srcFbo->width, srcFbo->height); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + VectorSet4(srcBox, -dx, -dy, srcFbo->width, srcFbo->height); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + + VectorSet4(color, weights[2], weights[2], weights[2], 1.0f); + dx = offsets[2] * xmul; + dy = offsets[2] * ymul; + VectorSet4(srcBox, dx, dy, srcFbo->width, srcFbo->height); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + VectorSet4(srcBox, -dx, -dy, srcFbo->width, srcFbo->height); + FBO_Blit(srcFbo, srcBox, texScale, dstFbo, dstBox, &tr.textureColorShader, color, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + } +} + +void RB_HBlur(FBO_t *srcFbo, FBO_t *dstFbo, float strength) +{ + RB_BlurAxis(srcFbo, dstFbo, strength, qtrue); +} + +void RB_VBlur(FBO_t *srcFbo, FBO_t *dstFbo, float strength) +{ + RB_BlurAxis(srcFbo, dstFbo, strength, qfalse); +} + +void RB_GaussianBlur(FBO_t *srcFbo, FBO_t *intermediateFbo, FBO_t *dstFbo, float spread) +{ + // Blur X + vec2_t scale; + VectorSet2 (scale, spread, spread); + + FBO_Blit (srcFbo, NULL, scale, intermediateFbo, NULL, &tr.gaussianBlurShader[0], NULL, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); + + // Blur Y + FBO_Blit (intermediateFbo, NULL, scale, dstFbo, NULL, &tr.gaussianBlurShader[1], NULL, GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); +} + +void RB_BloomDownscale(image_t *sourceImage, FBO_t *destFBO) +{ + vec2_t invTexRes = { 1.0f / sourceImage->width, 1.0f / sourceImage->height }; + + FBO_Bind(destFBO); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); + + qglViewport(0, 0, destFBO->width, destFBO->height); + qglClearBufferfv(GL_COLOR, 0, colorBlack); + + GLSL_BindProgram(&tr.dglowDownsample); + GLSL_SetUniformVec2(&tr.dglowDownsample, UNIFORM_INVTEXRES, invTexRes); + GL_BindToTMU(sourceImage, 0); + + // Draw fullscreen triangle + qglDrawArrays(GL_TRIANGLES, 0, 3); +} + +void RB_BloomDownscale(FBO_t *sourceFBO, FBO_t *destFBO) +{ + RB_BloomDownscale(sourceFBO->colorImage[0], destFBO); +} + +void RB_BloomUpscale(FBO_t *sourceFBO, FBO_t *destFBO) +{ + image_t *sourceImage = sourceFBO->colorImage[0]; + vec2_t invTexRes = { 1.0f / sourceImage->width, 1.0f / sourceImage->height }; + + FBO_Bind(destFBO); + GL_State(GLS_SRCBLEND_ONE | GLS_DSTBLEND_ZERO); + + glViewport(0, 0, destFBO->width, destFBO->height); + qglClearBufferfv(GL_COLOR, 0, colorBlack); + + GLSL_BindProgram(&tr.dglowUpsample); + GLSL_SetUniformVec2(&tr.dglowUpsample, UNIFORM_INVTEXRES, invTexRes); + GL_BindToTMU(sourceImage, 0); + + // Draw fullscreen triangle + qglDrawArrays(GL_TRIANGLES, 0, 3); +} diff --git a/codemp/rd-rend2/tr_postprocess.h b/codemp/rd-rend2/tr_postprocess.h new file mode 100644 index 0000000000..0aba4b564a --- /dev/null +++ b/codemp/rd-rend2/tr_postprocess.h @@ -0,0 +1,39 @@ +/* +=========================================================================== +Copyright (C) 2011 Andrei Drexler, Richard Allen, James Canete + +This file is part of Reaction source code. + +Reaction source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Reaction source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Reaction source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +#ifndef TR_POSTPROCESS_H +#define TR_POSTPROCESS_H + +typedef struct FBO_s FBO_t; +typedef struct image_s image_t; + +void RB_ToneMap(FBO_t *hdrFbo, vec4i_t hdrBox, FBO_t *ldrFbo, vec4i_t ldrBox, int autoExposure); +void RB_BokehBlur(FBO_t *src, vec4i_t srcBox, FBO_t *dst, vec4i_t dstBox, float blur); +void RB_SunRays(FBO_t *srcFbo, vec4i_t srcBox, FBO_t *dstFbo, vec4i_t dstBox); +void RB_GaussianBlur(FBO_t *srcFbo, FBO_t *intermediateFbo, FBO_t *dstFbo, float spread); +void RB_HBlur(FBO_t *srcFbo, FBO_t *dstFbo, float strength); +void RB_VBlur(FBO_t *srcFbo, FBO_t *dstFbo, float strength); +void RB_BloomDownscale(image_t *sourceImage, FBO_t *destFBO); +void RB_BloomDownscale(FBO_t *sourceFBO, FBO_t *destFBO); +void RB_BloomUpscale(FBO_t *sourceFBO, FBO_t *destFBO); + +#endif diff --git a/codemp/rd-rend2/tr_scene.cpp b/codemp/rd-rend2/tr_scene.cpp new file mode 100644 index 0000000000..b62dca2004 --- /dev/null +++ b/codemp/rd-rend2/tr_scene.cpp @@ -0,0 +1,596 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +#include "tr_local.h" + +int r_firstSceneDrawSurf; + +int r_numdlights; +int r_firstSceneDlight; + +int r_numentities; +int r_firstSceneEntity; + +int r_numpolys; +int r_firstScenePoly; + +int r_numpolyverts; + + +/* +==================== +R_InitNextFrame + +==================== +*/ +void R_InitNextFrame( void ) { + backEndData->commands.used = 0; + + tr.numTimedBlocks = 0; + + r_firstSceneDrawSurf = 0; + + r_numdlights = 0; + r_firstSceneDlight = 0; + + r_numentities = 0; + r_firstSceneEntity = 0; + + r_numpolys = 0; + r_firstScenePoly = 0; + + r_numpolyverts = 0; +} + + +/* +==================== +RE_ClearScene + +==================== +*/ +void RE_ClearScene( void ) { + r_firstSceneDlight = r_numdlights; + r_firstSceneEntity = r_numentities; + r_firstScenePoly = r_numpolys; +} + +/* +=========================================================================== + +DISCRETE POLYS + +=========================================================================== +*/ + +/* +===================== +R_AddPolygonSurfaces + +Adds all the scene's polys into this view's drawsurf list +===================== +*/ +void R_AddPolygonSurfaces( const trRefdef_t *refdef ) { + srfPoly_t *poly; + int fogMask = -((refdef->rdflags & RDF_NOFOG) == 0); + + int i; + for ( i = 0, poly = refdef->polys; i < refdef->numPolys ; i++, poly++ ) { + shader_t *sh = R_GetShaderByHandle( poly->hShader ); + R_AddDrawSurf( + (surfaceType_t *)poly, + REFENTITYNUM_WORLD, + sh, + poly->fogIndex & fogMask, + qfalse, + qfalse, + 0 /* cubemapIndex */ ); + } +} + +/* +===================== +RE_AddPolyToScene + +===================== +*/ +void RE_AddPolyToScene( qhandle_t hShader, int numVerts, const polyVert_t *verts, int numPolys ) { + srfPoly_t *poly; + int i, j; + int fogIndex; + fog_t *fog; + vec3_t bounds[2]; + + if ( !tr.registered ) { + return; + } + + for ( j = 0; j < numPolys; j++ ) { + if ( (r_numpolyverts + numVerts) > max_polyverts || r_numpolys >= max_polys ) { + ri.Printf( + PRINT_DEVELOPER, + S_COLOR_YELLOW "WARNING: RE_AddPolyToScene: r_max_polys or r_max_polyverts reached\n"); + return; + } + + poly = &backEndData->polys[r_numpolys]; + poly->surfaceType = SF_POLY; + poly->hShader = hShader; + poly->numVerts = numVerts; + poly->verts = &backEndData->polyVerts[r_numpolyverts]; + + Com_Memcpy( poly->verts, &verts[numVerts*j], numVerts * sizeof( *verts ) ); + + // done. + r_numpolys++; + r_numpolyverts += numVerts; + + // if no world is loaded + if ( tr.world == NULL ) { + fogIndex = 0; + } + // see if it is in a fog volume + else if ( tr.world->numfogs == 1 ) { + fogIndex = 0; + } else { + // find which fog volume the poly is in + VectorCopy( poly->verts[0].xyz, bounds[0] ); + VectorCopy( poly->verts[0].xyz, bounds[1] ); + for ( i = 1 ; i < poly->numVerts ; i++ ) { + AddPointToBounds( poly->verts[i].xyz, bounds[0], bounds[1] ); + } + for ( fogIndex = 1 ; fogIndex < tr.world->numfogs ; fogIndex++ ) { + fog = &tr.world->fogs[fogIndex]; + if ( bounds[1][0] >= fog->bounds[0][0] + && bounds[1][1] >= fog->bounds[0][1] + && bounds[1][2] >= fog->bounds[0][2] + && bounds[0][0] <= fog->bounds[1][0] + && bounds[0][1] <= fog->bounds[1][1] + && bounds[0][2] <= fog->bounds[1][2] ) { + break; + } + } + if ( fogIndex == tr.world->numfogs ) { + fogIndex = 0; + } + } + poly->fogIndex = fogIndex; + } +} + + +//================================================================================= + + +/* +===================== +RE_AddRefEntityToScene + +===================== +*/ +void RE_AddRefEntityToScene( const refEntity_t *ent ) { + vec3_t cross; + + if ( !tr.registered ) { + return; + } + if ( r_numentities >= MAX_REFENTITIES ) { + ri.Printf(PRINT_DEVELOPER, "RE_AddRefEntityToScene: Dropping refEntity, reached MAX_REFENTITIES\n"); + return; + } + if ( Q_isnan(ent->origin[0]) || Q_isnan(ent->origin[1]) || Q_isnan(ent->origin[2]) ) { + static qboolean firstTime = qtrue; + if (firstTime) { + firstTime = qfalse; + ri.Printf( PRINT_WARNING, "RE_AddRefEntityToScene passed a refEntity which has an origin with a NaN component\n"); + } + return; + } + if ( (int)ent->reType < 0 || ent->reType >= RT_MAX_REF_ENTITY_TYPE ) { + ri.Error( ERR_DROP, "RE_AddRefEntityToScene: bad reType %i", ent->reType ); + } + + backEndData->entities[r_numentities].e = *ent; + backEndData->entities[r_numentities].lightingCalculated = qfalse; + + CrossProduct(ent->axis[0], ent->axis[1], cross); + backEndData->entities[r_numentities].mirrored = (qboolean)(DotProduct(ent->axis[2], cross) < 0.f); + + r_numentities++; +} + +/* +===================== +RE_AddMiniRefEntityToScene + +1:1 with how vanilla does it --eez +===================== +*/ +void RE_AddMiniRefEntityToScene( const miniRefEntity_t *miniRefEnt ) { + refEntity_t entity; + if(!tr.registered) + return; + if(!miniRefEnt) + return; + memset(&entity, 0, sizeof(entity)); + memcpy(&entity, miniRefEnt, sizeof(*miniRefEnt)); + RE_AddRefEntityToScene(&entity); +} + + +/* +===================== +RE_AddDynamicLightToScene + +===================== +*/ +void RE_AddDynamicLightToScene( const vec3_t org, float intensity, float r, float g, float b, int additive ) { + dlight_t *dl; + + if ( !tr.registered ) { + return; + } + if ( r_numdlights >= MAX_DLIGHTS ) { + return; + } + if ( intensity <= 0 ) { + return; + } + dl = &backEndData->dlights[r_numdlights++]; + VectorCopy (org, dl->origin); + dl->radius = intensity; + dl->color[0] = r; + dl->color[1] = g; + dl->color[2] = b; + + if (r_hdr->integer) + { + float maxValue = MAX(r, MAX(g, b)); + if (maxValue > 1.0f) + { + VectorScale(dl->color, 1.0f / maxValue, dl->color); + dl->radius *= maxValue; + } + dl->radius = MIN(dl->radius, 65535.0f); + } + + dl->additive = additive; +} + +/* +===================== +RE_AddLightToScene + +===================== +*/ +void RE_AddLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { + RE_AddDynamicLightToScene( org, intensity, r, g, b, qfalse ); +} + +/* +===================== +RE_AddAdditiveLightToScene + +===================== +*/ +void RE_AddAdditiveLightToScene( const vec3_t org, float intensity, float r, float g, float b ) { + RE_AddDynamicLightToScene( org, intensity, r, g, b, qtrue ); +} + +void RE_BeginScene(const refdef_t *fd) +{ + Com_Memcpy( tr.refdef.text, fd->text, sizeof( tr.refdef.text ) ); + + tr.refdef.x = fd->x; + tr.refdef.y = fd->y; + tr.refdef.width = fd->width; + tr.refdef.height = fd->height; + tr.refdef.fov_x = fd->fov_x; + tr.refdef.fov_y = fd->fov_y; + + VectorCopy( fd->vieworg, tr.refdef.vieworg ); + VectorCopy( fd->viewaxis[0], tr.refdef.viewaxis[0] ); + VectorCopy( fd->viewaxis[1], tr.refdef.viewaxis[1] ); + VectorCopy( fd->viewaxis[2], tr.refdef.viewaxis[2] ); + + tr.refdef.time = fd->time; + tr.refdef.rdflags = fd->rdflags; + tr.refdef.frameTime = fd->time - tr.refdef.lastTime; + + // copy the areamask data over and note if it has changed, which + // will force a reset of the visible leafs even if the view hasn't moved + tr.refdef.areamaskModified = qfalse; + if ( ! (tr.refdef.rdflags & RDF_NOWORLDMODEL) ) { + int areaDiff; + int i; + + // compare the area bits + areaDiff = 0; + for (i = 0 ; i < MAX_MAP_AREA_BYTES/4 ; i++) { + areaDiff |= ((int *)tr.refdef.areamask)[i] ^ ((int *)fd->areamask)[i]; + ((int *)tr.refdef.areamask)[i] = ((int *)fd->areamask)[i]; + } + + if ( areaDiff ) { + // a door just opened or something + tr.refdef.areamaskModified = qtrue; + } + } + + tr.refdef.sunDir[3] = 0.0f; + tr.refdef.sunCol[3] = 1.0f; + tr.refdef.sunAmbCol[3] = 1.0f; + + VectorCopy(tr.sunDirection, tr.refdef.sunDir); + if ( (fd->rdflags & RDF_NOWORLDMODEL) || !(r_depthPrepass->value) ){ + tr.refdef.colorScale = 1.0f; + VectorSet(tr.refdef.sunCol, 0, 0, 0); + VectorSet(tr.refdef.sunAmbCol, 0, 0, 0); + } + else + { + tr.refdef.colorScale = r_forceSun->integer ? r_forceSunMapLightScale->value : tr.mapLightScale; + + if (r_sunlightMode->integer == 1) + { + tr.refdef.sunCol[0] = + tr.refdef.sunCol[1] = + tr.refdef.sunCol[2] = 1.0f; + + tr.refdef.sunAmbCol[0] = + tr.refdef.sunAmbCol[1] = + tr.refdef.sunAmbCol[2] = r_forceSun->integer ? r_forceSunAmbientScale->value : tr.sunShadowScale; + } + else + { + float scale = pow(2.0f, r_mapOverBrightBits->integer - tr.overbrightBits - 8); + if (r_forceSun->integer) + { + VectorScale(tr.sunLight, scale * r_forceSunLightScale->value, tr.refdef.sunCol); + VectorScale(tr.sunLight, scale * r_forceSunAmbientScale->value, tr.refdef.sunAmbCol); + } + else + { + VectorScale(tr.sunLight, scale, tr.refdef.sunCol); + VectorScale(tr.sunLight, scale * tr.sunShadowScale, tr.refdef.sunAmbCol); + } + } + + if (r_forceSun->integer == 2) + { + vec4_t lightDir, lightCol; + int scale = 32768; + float angle = (fd->time % scale) / (float)scale * M_PI; + lightDir[0] = cos(angle); + lightDir[1] = sin(35.0f * M_PI / 180.0f); + lightDir[2] = sin(angle) * cos(35.0f * M_PI / 180.0f); + lightDir[3] = 0.0f; + + lightCol[0] = + lightCol[1] = + lightCol[2] = CLAMP(sin(angle) * 2.0f, 0.0f, 1.0f) * 2.0f; + lightCol[3] = 1.0f; + + VectorCopy4(lightDir, tr.refdef.sunDir); + VectorCopy4(lightCol, tr.refdef.sunCol); + VectorScale4(lightCol, 0.2f, tr.refdef.sunAmbCol); + } + } + + if (r_forceAutoExposure->integer) + { + tr.refdef.autoExposureMinMax[0] = r_forceAutoExposureMin->value; + tr.refdef.autoExposureMinMax[1] = r_forceAutoExposureMax->value; + } + else + { + tr.refdef.autoExposureMinMax[0] = tr.autoExposureMinMax[0]; + tr.refdef.autoExposureMinMax[1] = tr.autoExposureMinMax[1]; + } + + if (r_forceToneMap->integer) + { + tr.refdef.toneMinAvgMaxLinear[0] = pow(2, r_forceToneMapMin->value); + tr.refdef.toneMinAvgMaxLinear[1] = pow(2, r_forceToneMapAvg->value); + tr.refdef.toneMinAvgMaxLinear[2] = pow(2, r_forceToneMapMax->value); + } + else + { + tr.refdef.toneMinAvgMaxLinear[0] = pow(2, tr.toneMinAvgMaxLevel[0]); + tr.refdef.toneMinAvgMaxLinear[1] = pow(2, tr.toneMinAvgMaxLevel[1]); + tr.refdef.toneMinAvgMaxLinear[2] = pow(2, tr.toneMinAvgMaxLevel[2]); + } + + // Makro - copy exta info if present + if (fd->rdflags & RDF_EXTRA) { + const refdefex_t* extra = (const refdefex_t*) (fd+1); + + tr.refdef.blurFactor = extra->blurFactor; + + if (fd->rdflags & RDF_SUNLIGHT) + { + VectorCopy(extra->sunDir, tr.refdef.sunDir); + VectorCopy(extra->sunCol, tr.refdef.sunCol); + VectorCopy(extra->sunAmbCol, tr.refdef.sunAmbCol); + } + } + else + { + tr.refdef.blurFactor = 0.0f; + } + + // derived info + + tr.refdef.floatTime = tr.refdef.time * 0.001f; + + tr.refdef.numDrawSurfs = r_firstSceneDrawSurf; + tr.refdef.drawSurfs = backEndData->drawSurfs; + + tr.refdef.num_entities = r_numentities - r_firstSceneEntity; + tr.refdef.entities = &backEndData->entities[r_firstSceneEntity]; + + tr.refdef.num_dlights = r_numdlights - r_firstSceneDlight; + tr.refdef.dlights = &backEndData->dlights[r_firstSceneDlight]; + + // Add the decals here because decals add polys and we need to ensure + // that the polys are added before the the renderer is prepared + if ( !(fd->rdflags & RDF_NOWORLDMODEL) ) + R_AddDecals(); + + tr.refdef.numPolys = r_numpolys - r_firstScenePoly; + tr.refdef.polys = &backEndData->polys[r_firstScenePoly]; + + tr.refdef.num_pshadows = 0; + tr.refdef.pshadows = &backEndData->pshadows[0]; + + // turn off dynamic lighting globally by clearing all the + // dlights if it needs to be disabled or if vertex lighting is enabled + if ( r_dynamiclight->integer == 0 || + r_vertexLight->integer == 1 ) { + tr.refdef.num_dlights = 0; + } + + if (fd->rdflags & RDF_SKYBOXPORTAL) + { + tr.world->skyboxportal = 1; + + // Don't update constants yet. Store everything and render everything next scene + return; + } + else + { + // pasted this from SP + // cdr - only change last time for the real render, not the portal + tr.refdef.lastTime = fd->time; + } + + // a single frame may have multiple scenes draw inside it -- + // a 3D game view, 3D status bar renderings, 3D menus, etc. + // They need to be distinguished by the light flare code, because + // the visibility state for a given surface may be different in + // each scene / view. + tr.frameSceneNum++; + tr.sceneCount++; + + //ri.Printf(PRINT_ALL, "RE_BeginScene Frame: %i, skyportal: %i, entities: %i\n", backEndData->realFrameNumber, int(tr.world->skyboxportal && (tr.refdef.rdflags & RDF_SKYBOXPORTAL)), tr.refdef.num_entities); + R_GatherFrameViews(&tr.refdef); + RB_UpdateConstants(&tr.refdef); +} + +void RE_EndScene() +{ + // the next scene rendered in this frame will tack on after this one + r_firstSceneDrawSurf = tr.refdef.numDrawSurfs; + r_firstSceneEntity = r_numentities; + r_firstSceneDlight = r_numdlights; + r_firstScenePoly = r_numpolys; + tr.skyPortalEntities = 0; + tr.numCachedViewParms = 0; +} + +/* +@@@@@@@@@@@@@@@@@@@@@ +RE_RenderScene + +Draw a 3D view into a part of the window, then return +to 2D drawing. + +Rendering a scene may require multiple views to be rendered +to handle mirrors, +@@@@@@@@@@@@@@@@@@@@@ +*/ +void RE_RenderScene( const refdef_t *fd ) +{ + int startTime; + + if ( !tr.registered ) { + return; + } + GLimp_LogComment( "====== RE_RenderScene =====\n" ); + + if ( r_norefresh->integer ) { + return; + } + + startTime = ri.Milliseconds(); + + if (!tr.world && !( fd->rdflags & RDF_NOWORLDMODEL ) ) { + ri.Error (ERR_DROP, "R_RenderScene: NULL worldmodel"); + } + + RE_BeginScene(fd); + + // Store skyportal info and don't render yet + if (tr.refdef.rdflags & RDF_SKYBOXPORTAL) + { + viewParms_t parms; + Com_Memset(&parms, 0, sizeof(parms)); + parms.viewportX = fd->x; + parms.viewportY = glConfig.vidHeight - (fd->y + fd->height); + parms.viewportWidth = fd->width; + parms.viewportHeight = fd->height; + parms.isPortal = qfalse; + parms.isSkyPortal = qfalse; + parms.zNear = r_znear->value; + + parms.fovX = fd->fov_x; + parms.fovY = fd->fov_y; + + parms.stereoFrame = tr.refdef.stereoFrame; + + VectorCopy(fd->vieworg, parms.ori.origin); + VectorCopy(fd->viewaxis[0], parms.ori.axis[0]); + VectorCopy(fd->viewaxis[1], parms.ori.axis[1]); + VectorCopy(fd->viewaxis[2], parms.ori.axis[2]); + + VectorCopy(fd->vieworg, parms.pvsOrigin); + + parms.isSkyPortal = qtrue; + Com_Memcpy(&tr.skyPortalParms, &parms, sizeof(viewParms_t)); + Com_Memcpy(tr.skyPortalAreaMask, tr.refdef.areamask, sizeof(tr.refdef.areamask)); + tr.skyPortalEntities = tr.refdef.num_entities; + return; + } + + // Render all the passes + for (int i = 0; i < tr.numCachedViewParms; i++) + { + qhandle_t timer = R_BeginTimedBlockCmd(va("Render Pass %i", i)); + tr.refdef.numDrawSurfs = 0; + R_RenderView(&tr.cachedViewParms[i]); + R_IssuePendingRenderCommands(); + R_EndTimedBlockCmd(timer); + } + + if(!( fd->rdflags & RDF_NOWORLDMODEL )) + { + qhandle_t timer = R_BeginTimedBlockCmd( "Post processing" ); + R_AddPostProcessCmd(); + R_EndTimedBlockCmd( timer ); + } + + R_IssuePendingRenderCommands(); + + RE_EndScene(); + + tr.frontEndMsec += ri.Milliseconds() - startTime; +} diff --git a/codemp/rd-rend2/tr_shade.cpp b/codemp/rd-rend2/tr_shade.cpp new file mode 100644 index 0000000000..bc65a71cb7 --- /dev/null +++ b/codemp/rd-rend2/tr_shade.cpp @@ -0,0 +1,2037 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_shade.c + +#include "tr_local.h" +#include "tr_allocator.h" + +/* + + THIS ENTIRE FILE IS BACK END + + This file deals with applying shaders to surface data in the tess struct. +*/ + +color4ub_t styleColors[MAX_LIGHT_STYLES]; + +void RB_BinTriangleCounts( void ); + + +/* +================== +R_DrawElements + +================== +*/ + +void R_DrawElementsVBO( int numIndexes, glIndex_t firstIndex, glIndex_t minIndex, glIndex_t maxIndex ) +{ + int offset = firstIndex * sizeof(glIndex_t) + + (tess.useInternalVBO ? backEndData->currentFrame->dynamicIboCommitOffset : 0); + + GL_DrawIndexed(GL_TRIANGLES, numIndexes, GL_INDEX_TYPE, offset, 1, 0); +} + + +static void R_DrawMultiElementsVBO( int multiDrawPrimitives, glIndex_t *multiDrawMinIndex, glIndex_t *multiDrawMaxIndex, + GLsizei *multiDrawNumIndexes, glIndex_t **multiDrawFirstIndex) +{ + GL_MultiDrawIndexed( + GL_TRIANGLES, + multiDrawNumIndexes, + multiDrawFirstIndex, + multiDrawPrimitives); +} + + +/* +============================================================= + +SURFACE SHADERS + +============================================================= +*/ + +shaderCommands_t tess; + + +/* +================= +R_BindAnimatedImageToTMU + +================= +*/ +void R_BindAnimatedImageToTMU( textureBundle_t *bundle, int tmu ) { + int index; + + if ( bundle->isVideoMap ) { + int oldtmu = glState.currenttmu; + GL_SelectTexture(tmu); + ri.CIN_RunCinematic(bundle->videoMapHandle); + ri.CIN_UploadCinematic(bundle->videoMapHandle); + GL_SelectTexture(oldtmu); + return; + } + + if ( bundle->numImageAnimations <= 1 ) { + GL_BindToTMU( bundle->image[0], tmu); + return; + } + + if (backEnd.currentEntity->e.renderfx & RF_SETANIMINDEX ) + { + index = backEnd.currentEntity->e.skinNum; + } + else + { + // it is necessary to do this messy calc to make sure animations line up + // exactly with waveforms of the same frequency + index = Q_ftol( tess.shaderTime * bundle->imageAnimationSpeed * FUNCTABLE_SIZE ); + index >>= FUNCTABLE_SIZE2; + + if ( index < 0 ) { + index = 0; // may happen with shader time offsets + } + } + + if ( bundle->oneShotAnimMap ) + { + if ( index >= bundle->numImageAnimations ) + { + // stick on last frame + index = bundle->numImageAnimations - 1; + } + } + else + { + // loop + index %= bundle->numImageAnimations; + } + + GL_BindToTMU( bundle->image[ index ], tmu ); +} + +/* +============== +RB_BeginSurface + +We must set some things up before beginning any tesselation, +because a surface may be forced to perform a RB_End due +to overflow. +============== +*/ +void RB_BeginSurface( shader_t *shader, int fogNum, int cubemapIndex ) { + + shader_t *state = (shader->remappedShader) ? shader->remappedShader : shader; + + tess.numIndexes = 0; + tess.firstIndex = 0; + tess.numVertexes = 0; + tess.multiDrawPrimitives = 0; + tess.shader = state; + tess.fogNum = fogNum; + tess.cubemapIndex = cubemapIndex; + tess.dlightBits = 0; // will be OR'd in by surface functions + tess.pshadowBits = 0; // will be OR'd in by surface functions + tess.xstages = state->stages; + tess.numPasses = state->numUnfoggedPasses; + tess.currentStageIteratorFunc = state->optimalStageIteratorFunc; + tess.externalIBO = nullptr; + tess.useInternalVBO = qtrue; + + tess.shaderTime = backEnd.refdef.floatTime - tess.shader->timeOffset; + if (tess.shader->clampTime && tess.shaderTime >= tess.shader->clampTime) { + tess.shaderTime = tess.shader->clampTime; + } + + if (backEnd.viewParms.flags & VPF_DEPTHSHADOW) + { + tess.currentStageIteratorFunc = RB_StageIteratorGeneric; + } +} + + + +extern float EvalWaveForm( const waveForm_t *wf ); +extern float EvalWaveFormClamped( const waveForm_t *wf ); + + +static void ComputeTexMods( shaderStage_t *pStage, int bundleNum, float *outMatrix, float *outOffTurb) +{ + int tm; + float matrix[6], currentmatrix[6]; + textureBundle_t *bundle = &pStage->bundle[bundleNum]; + + matrix[0] = 1.0f; matrix[2] = 0.0f; matrix[4] = 0.0f; + matrix[1] = 0.0f; matrix[3] = 1.0f; matrix[5] = 0.0f; + + currentmatrix[0] = 1.0f; currentmatrix[2] = 0.0f; currentmatrix[4] = 0.0f; + currentmatrix[1] = 0.0f; currentmatrix[3] = 1.0f; currentmatrix[5] = 0.0f; + + outMatrix[0] = 1.0f; outMatrix[2] = 0.0f; + outMatrix[1] = 0.0f; outMatrix[3] = 1.0f; + + outOffTurb[0] = 0.0f; outOffTurb[1] = 0.0f; outOffTurb[2] = 0.0f; outOffTurb[3] = 0.0f; + + for ( tm = 0; tm < bundle->numTexMods ; tm++ ) { + switch ( bundle->texMods[tm].type ) + { + + case TMOD_NONE: + tm = TR_MAX_TEXMODS; // break out of for loop + break; + + case TMOD_TURBULENT: + RB_CalcTurbulentFactors(&bundle->texMods[tm].wave, &outOffTurb[2], &outOffTurb[3]); + break; + + case TMOD_ENTITY_TRANSLATE: + RB_CalcScrollTexMatrix( backEnd.currentEntity->e.shaderTexCoord, matrix ); + break; + + case TMOD_SCROLL: + RB_CalcScrollTexMatrix( bundle->texMods[tm].scroll, + matrix ); + break; + + case TMOD_SCALE: + RB_CalcScaleTexMatrix( bundle->texMods[tm].scale, + matrix ); + break; + + case TMOD_STRETCH: + RB_CalcStretchTexMatrix( &bundle->texMods[tm].wave, + matrix ); + break; + + case TMOD_TRANSFORM: + RB_CalcTransformTexMatrix( &bundle->texMods[tm], + matrix ); + break; + + case TMOD_ROTATE: + RB_CalcRotateTexMatrix( bundle->texMods[tm].rotateSpeed, + matrix ); + break; + + default: + ri.Error( ERR_DROP, "ERROR: unknown texmod '%d' in shader '%s'", bundle->texMods[tm].type, tess.shader->name ); + break; + } + + switch ( bundle->texMods[tm].type ) + { + case TMOD_NONE: + case TMOD_TURBULENT: + default: + break; + + case TMOD_ENTITY_TRANSLATE: + case TMOD_SCROLL: + case TMOD_SCALE: + case TMOD_STRETCH: + case TMOD_TRANSFORM: + case TMOD_ROTATE: + outMatrix[0] = matrix[0] * currentmatrix[0] + matrix[2] * currentmatrix[1]; + outMatrix[1] = matrix[1] * currentmatrix[0] + matrix[3] * currentmatrix[1]; + + outMatrix[2] = matrix[0] * currentmatrix[2] + matrix[2] * currentmatrix[3]; + outMatrix[3] = matrix[1] * currentmatrix[2] + matrix[3] * currentmatrix[3]; + + outOffTurb[0] = matrix[0] * currentmatrix[4] + matrix[2] * currentmatrix[5] + matrix[4]; + outOffTurb[1] = matrix[1] * currentmatrix[4] + matrix[3] * currentmatrix[5] + matrix[5]; + + currentmatrix[0] = outMatrix[0]; + currentmatrix[1] = outMatrix[1]; + currentmatrix[2] = outMatrix[2]; + currentmatrix[3] = outMatrix[3]; + currentmatrix[4] = outOffTurb[0]; + currentmatrix[5] = outOffTurb[1]; + break; + } + } +} + +static void ComputeShaderColors( shaderStage_t *pStage, vec4_t baseColor, vec4_t vertColor, int blend, colorGen_t *forceRGBGen, alphaGen_t *forceAlphaGen ) +{ + colorGen_t rgbGen = pStage->rgbGen; + alphaGen_t alphaGen = pStage->alphaGen; + + baseColor[0] = + baseColor[1] = + baseColor[2] = + baseColor[3] = 1.0f; + + vertColor[0] = + vertColor[1] = + vertColor[2] = + vertColor[3] = 0.0f; + + if ( forceRGBGen != NULL && *forceRGBGen != CGEN_BAD ) + { + rgbGen = *forceRGBGen; + } + + if ( forceAlphaGen != NULL && *forceAlphaGen != AGEN_IDENTITY ) + { + alphaGen = *forceAlphaGen; + } + + switch ( rgbGen ) + { + case CGEN_IDENTITY_LIGHTING: + baseColor[0] = + baseColor[1] = + baseColor[2] = tr.identityLight; + break; + case CGEN_EXACT_VERTEX: + case CGEN_EXACT_VERTEX_LIT: + baseColor[0] = + baseColor[1] = + baseColor[2] = + baseColor[3] = 0.0f; + + vertColor[0] = + vertColor[1] = + vertColor[2] = + vertColor[3] = 1.0f; + break; + case CGEN_CONST: + baseColor[0] = pStage->constantColor[0]; + baseColor[1] = pStage->constantColor[1]; + baseColor[2] = pStage->constantColor[2]; + baseColor[3] = pStage->constantColor[3]; + break; + case CGEN_VERTEX: + baseColor[0] = + baseColor[1] = + baseColor[2] = + baseColor[3] = 0.0f; + + vertColor[0] = + vertColor[1] = + vertColor[2] = tr.identityLight; + vertColor[3] = 1.0f; + break; + case CGEN_VERTEX_LIT: + baseColor[0] = + baseColor[1] = + baseColor[2] = + baseColor[3] = 0.0f; + + vertColor[0] = + vertColor[1] = + vertColor[2] = + vertColor[3] = tr.identityLight; + break; + case CGEN_ONE_MINUS_VERTEX: + baseColor[0] = + baseColor[1] = + baseColor[2] = tr.identityLight; + + vertColor[0] = + vertColor[1] = + vertColor[2] = -tr.identityLight; + break; + case CGEN_FOG: + { + fog_t *fog = tr.world->fogs + tess.fogNum; + VectorCopy4(fog->color, baseColor); + } + break; + case CGEN_WAVEFORM: + baseColor[0] = + baseColor[1] = + baseColor[2] = RB_CalcWaveColorSingle( &pStage->rgbWave ); + break; + case CGEN_ENTITY: + case CGEN_LIGHTING_DIFFUSE_ENTITY: + if (backEnd.currentEntity) + { + baseColor[0] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[0] / 255.0f; + baseColor[1] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[1] / 255.0f; + baseColor[2] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[2] / 255.0f; + baseColor[3] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + + if ( alphaGen == AGEN_IDENTITY && + backEnd.currentEntity->e.shaderRGBA[3] == 255 ) + { + alphaGen = AGEN_SKIP; + } + } + break; + case CGEN_ONE_MINUS_ENTITY: + if (backEnd.currentEntity) + { + baseColor[0] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[0] / 255.0f; + baseColor[1] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[1] / 255.0f; + baseColor[2] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[2] / 255.0f; + baseColor[3] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + } + break; + case CGEN_LIGHTMAPSTYLE: + VectorScale4 (styleColors[pStage->lightmapStyle], 1.0f / 255.0f, baseColor); + break; + case CGEN_IDENTITY: + case CGEN_LIGHTING_DIFFUSE: + case CGEN_BAD: + break; + default: + break; + } + + // + // alphaGen + // + switch ( alphaGen ) + { + case AGEN_SKIP: + break; + case AGEN_CONST: + if ( rgbGen != CGEN_CONST ) { + baseColor[3] = pStage->constantColor[3]; + vertColor[3] = 0.0f; + } + break; + case AGEN_WAVEFORM: + baseColor[3] = RB_CalcWaveAlphaSingle( &pStage->alphaWave ); + vertColor[3] = 0.0f; + break; + case AGEN_ENTITY: + if (backEnd.currentEntity) + { + baseColor[3] = ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + } + vertColor[3] = 0.0f; + break; + case AGEN_ONE_MINUS_ENTITY: + if (backEnd.currentEntity) + { + baseColor[3] = 1.0f - ((unsigned char *)backEnd.currentEntity->e.shaderRGBA)[3] / 255.0f; + } + vertColor[3] = 0.0f; + break; + case AGEN_VERTEX: + if ( rgbGen != CGEN_VERTEX ) { + baseColor[3] = 0.0f; + vertColor[3] = 1.0f; + } + break; + case AGEN_ONE_MINUS_VERTEX: + baseColor[3] = 1.0f; + vertColor[3] = -1.0f; + break; + case AGEN_IDENTITY: + case AGEN_LIGHTING_SPECULAR: + case AGEN_PORTAL: + // Done entirely in vertex program + baseColor[3] = 1.0f; + vertColor[3] = 0.0f; + break; + default: + break; + } + + if ( forceAlphaGen != NULL ) + { + *forceAlphaGen = alphaGen; + } + + if ( forceRGBGen != NULL ) + { + *forceRGBGen = rgbGen; + } + + // multiply color by overbrightbits if this isn't a blend + if (tr.overbrightBits + && !((blend & GLS_SRCBLEND_BITS) == GLS_SRCBLEND_DST_COLOR) + && !((blend & GLS_SRCBLEND_BITS) == GLS_SRCBLEND_ONE_MINUS_DST_COLOR) + && !((blend & GLS_DSTBLEND_BITS) == GLS_DSTBLEND_SRC_COLOR) + && !((blend & GLS_DSTBLEND_BITS) == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR)) + { + float scale = 1 << tr.overbrightBits; + + baseColor[0] *= scale; + baseColor[1] *= scale; + baseColor[2] *= scale; + vertColor[0] *= scale; + vertColor[1] *= scale; + vertColor[2] *= scale; + } + + // FIXME: find some way to implement this. +#if 0 + // if in greyscale rendering mode turn all color values into greyscale. + if(r_greyscale->integer) + { + int scale; + + for(i = 0; i < tess.numVertexes; i++) + { + scale = (tess.svars.colors[i][0] + tess.svars.colors[i][1] + tess.svars.colors[i][2]) / 3; + tess.svars.colors[i][0] = tess.svars.colors[i][1] = tess.svars.colors[i][2] = scale; + } + } +#endif +} + +static void ComputeFogColorMask( shaderStage_t *pStage, vec4_t fogColorMask ) +{ + switch(pStage->adjustColorsForFog) + { + case ACFF_MODULATE_RGB: + fogColorMask[0] = + fogColorMask[1] = + fogColorMask[2] = 1.0f; + fogColorMask[3] = 0.0f; + break; + case ACFF_MODULATE_ALPHA: + fogColorMask[0] = + fogColorMask[1] = + fogColorMask[2] = 0.0f; + fogColorMask[3] = 1.0f; + break; + case ACFF_MODULATE_RGBA: + fogColorMask[0] = + fogColorMask[1] = + fogColorMask[2] = + fogColorMask[3] = 1.0f; + break; + default: + fogColorMask[0] = + fogColorMask[1] = + fogColorMask[2] = + fogColorMask[3] = 0.0f; + break; + } +} + +static void CaptureDrawData(const shaderCommands_t *input, shaderStage_t *stage, int glslShaderIndex, int stageIndex ) +{ + if ( !tr.numFramesToCapture ) + return; + + if ( input->multiDrawPrimitives ) + { + int numIndexes = 0; + for ( int i = 0; i < input->multiDrawPrimitives; i++ ) + numIndexes += input->multiDrawNumIndexes[i]; + + const char *data = va("%d,%d,%s,%d,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,Y\n", + tr.frameCount, + backEnd.currentEntity == &tr.worldEntity ? -1 : (backEnd.currentEntity - tr.refdef.entities), + stage->glslShaderGroup ? "lightall" : "generic", glslShaderIndex, + input->shader->name, stageIndex, input->shader->sortedIndex, (int)input->shader->sort, + input->fogNum, + input->cubemapIndex, + glState.vertexAttribsState, + glState.glStateBits, + glState.currentVBO->vertexesVBO, + glState.currentIBO->indexesVBO, + numIndexes / 3); + ri.FS_Write(data, strlen(data), tr.debugFile); + } + else + { + const char *data = va("%d,%d,%s,%d,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,N\n", + tr.frameCount, + backEnd.currentEntity == &tr.worldEntity ? -1 : (backEnd.currentEntity - tr.refdef.entities), + stage->glslShaderGroup ? "lightall" : "generic", glslShaderIndex, + input->shader->name, stageIndex, input->shader->sortedIndex, (int)input->shader->sort, + input->fogNum, + input->cubemapIndex, + glState.vertexAttribsState, + glState.glStateBits, + glState.currentVBO->vertexesVBO, + glState.currentIBO->indexesVBO, + input->numIndexes / 3); + ri.FS_Write(data, strlen(data), tr.debugFile); + } +} + +uint32_t RB_CreateSortKey( const DrawItem& item, int stage, int layer ) +{ + uint32_t key = 0; + uintptr_t shaderProgram = (uintptr_t)item.program; + + assert(stage < 16); + layer = Q_min(layer, 15); + + key |= (layer & 0xf) << 28; + key |= (stage & 0xf) << 24; + key |= shaderProgram & 0x00ffffff; + return key; +} + +static cullType_t RB_GetCullType( const viewParms_t *viewParms, const trRefEntity_t *refEntity, cullType_t shaderCullType ) +{ + assert(refEntity); + + cullType_t cullType = CT_TWO_SIDED; + if ( !backEnd.projection2D ) + { + if ( shaderCullType != CT_TWO_SIDED ) + { + bool cullFront = (shaderCullType == CT_FRONT_SIDED); + if ( viewParms->isMirror ) + cullFront = !cullFront; + + if ( refEntity->mirrored ) + cullFront = !cullFront; + + if ( viewParms->flags & VPF_DEPTHSHADOW ) + cullFront = !cullFront; + + cullType = (cullFront ? CT_FRONT_SIDED : CT_BACK_SIDED); + } + } + + return cullType; +} + +DepthRange RB_GetDepthRange( const trRefEntity_t *re, const shader_t *shader ) +{ + DepthRange range = {0.0f, 1.0f}; + if ( shader->isSky ) + { + // r_showsky will let all the sky blocks be drawn in + // front of everything to allow developers to see how + // much sky is getting sucked in + if ( !r_showsky->integer ) + { + range.minDepth = 1.0f; + range.maxDepth = 1.0f; + } + else + { + range.maxDepth = 0.0f; + } + } + else if ( re->e.renderfx & RF_NODEPTH ) + { + range.maxDepth = 0.0f; + } + else if ( re->e.renderfx & RF_DEPTHHACK ) + { + range.maxDepth = 0.3f; + } + + return range; +} + +void RB_FillDrawCommand( + DrawCommand& drawCmd, + GLenum primitiveType, + int numInstances, + const shaderCommands_t *input +) +{ + drawCmd.primitiveType = primitiveType; + drawCmd.numInstances = numInstances; + + if ( input->multiDrawPrimitives ) + { + if ( input->multiDrawPrimitives == 1 ) + { + drawCmd.type = DRAW_COMMAND_INDEXED; + drawCmd.params.indexed.indexType = GL_INDEX_TYPE; + drawCmd.params.indexed.firstIndex = (glIndex_t)(size_t)(input->multiDrawFirstIndex[0]); + drawCmd.params.indexed.numIndices = input->multiDrawNumIndexes[0]; + drawCmd.params.indexed.baseVertex = 0; + } + else + { + drawCmd.type = DRAW_COMMAND_MULTI_INDEXED; + drawCmd.params.multiIndexed.numDraws = input->multiDrawPrimitives; + + drawCmd.params.multiIndexed.firstIndices = + ojkAllocArray(*backEndData->perFrameMemory, input->multiDrawPrimitives); + memcpy(drawCmd.params.multiIndexed.firstIndices, + input->multiDrawFirstIndex, + sizeof(glIndex_t *) * input->multiDrawPrimitives); + + drawCmd.params.multiIndexed.numIndices = + ojkAllocArray(*backEndData->perFrameMemory, input->multiDrawPrimitives); + memcpy(drawCmd.params.multiIndexed.numIndices, + input->multiDrawNumIndexes, + sizeof(GLsizei *) * input->multiDrawPrimitives); + } + } + else + { + int offset = input->firstIndex * sizeof(glIndex_t) + + (input->useInternalVBO ? backEndData->currentFrame->dynamicIboCommitOffset : 0); + + drawCmd.type = DRAW_COMMAND_INDEXED; + drawCmd.params.indexed.indexType = GL_INDEX_TYPE; + drawCmd.params.indexed.firstIndex = offset; + drawCmd.params.indexed.numIndices = input->numIndexes; + drawCmd.params.indexed.baseVertex = 0; + } +} + +static UniformBlockBinding GetCameraBlockUniformBinding( + const trRefEntity_t *refEntity) +{ + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + UniformBlockBinding binding = {}; + binding.block = UNIFORM_BLOCK_CAMERA; + + if (refEntity == &backEnd.entity2D) + { + binding.ubo = tr.staticUbo; + binding.offset = tr.camera2DUboOffset; + } + else if (refEntity == &backEnd.entityFlare) + { + binding.ubo = tr.staticUbo; + binding.offset = tr.cameraFlareUboOffset; + } + else + { + binding.ubo = currentFrameUbo; + binding.offset = tr.cameraUboOffsets[backEnd.viewParms.currentViewParm]; + } + return binding; +} + +static UniformBlockBinding GetLightsBlockUniformBinding() +{ + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + UniformBlockBinding binding = {}; + binding.block = UNIFORM_BLOCK_LIGHTS; + + if (tr.lightsUboOffset == -1) + { + binding.ubo = tr.staticUbo; + binding.offset = tr.defaultLightsUboOffset; + } + else + { + binding.ubo = currentFrameUbo; + binding.offset = tr.lightsUboOffset; + } + return binding; +} + +static UniformBlockBinding GetSceneBlockUniformBinding() +{ + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + UniformBlockBinding binding = {}; + binding.block = UNIFORM_BLOCK_SCENE; + + if (tr.sceneUboOffset == -1) + { + binding.ubo = tr.staticUbo; + binding.offset = tr.defaultSceneUboOffset; + } + else + { + binding.ubo = currentFrameUbo; + binding.offset = tr.sceneUboOffset; + } + return binding; +} + +static UniformBlockBinding GetFogsBlockUniformBinding() +{ + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + UniformBlockBinding binding = {}; + binding.block = UNIFORM_BLOCK_FOGS; + + if (tr.fogsUboOffset == -1) + { + binding.ubo = tr.staticUbo; + binding.offset = tr.defaultFogsUboOffset; + } + else + { + binding.ubo = currentFrameUbo; + binding.offset = tr.fogsUboOffset; + } + return binding; +} + +static UniformBlockBinding GetEntityBlockUniformBinding( + const trRefEntity_t *refEntity) +{ + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + UniformBlockBinding binding = {}; + binding.block = UNIFORM_BLOCK_ENTITY; + + if (refEntity == &backEnd.entity2D) + { + binding.ubo = tr.staticUbo; + binding.offset = tr.entity2DUboOffset; + } + else if (refEntity == &backEnd.entityFlare) + { + binding.ubo = tr.staticUbo; + binding.offset = tr.entityFlareUboOffset; + } + else + { + binding.ubo = currentFrameUbo; + if (!refEntity || refEntity == &tr.worldEntity) + { + binding.offset = tr.entityUboOffsets[REFENTITYNUM_WORLD]; + } + else + { + const int refEntityNum = refEntity - backEnd.refdef.entities; + binding.offset = tr.entityUboOffsets[refEntityNum]; + } + } + + return binding; +} + +static UniformBlockBinding GetBonesBlockUniformBinding( + const trRefEntity_t *refEntity) +{ + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + UniformBlockBinding binding = {}; + binding.ubo = currentFrameUbo; + binding.block = UNIFORM_BLOCK_BONES; + + if (refEntity == &tr.worldEntity) + binding.offset = 0; + else if (refEntity == &backEnd.entity2D) + binding.offset = 0; + else + { + binding.offset = tr.animationBoneUboOffset; + } + + return binding; +} + +static UniformBlockBinding GetShaderInstanceBlockUniformBinding( + const trRefEntity_t *refEntity, const shader_t *shader) +{ + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + UniformBlockBinding binding = {}; + binding.ubo = tr.shaderInstanceUbo; + binding.block = UNIFORM_BLOCK_SHADER_INSTANCE; + + if (shader->ShaderInstanceUboOffset == -1) + { + binding.ubo = tr.staticUbo; + binding.offset = tr.defaultShaderInstanceUboOffset; + return binding; + } + + binding.offset = shader->ShaderInstanceUboOffset; + + return binding; +} + +/* +================ +DrawTris + +Draws triangle outlines for debugging +================ +*/ +static void DrawTris(shaderCommands_t *input, const VertexArraysProperties *vertexArrays) { + + Allocator& frameAllocator = *backEndData->perFrameMemory; + vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; + GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); + { + int index = 0; + + if (input->shader->numDeforms && !ShaderRequiresCPUDeforms(input->shader)) + { + index |= GENERICDEF_USE_DEFORM_VERTEXES; + } +#ifdef REND2_SP + if (glState.vertexAnimation) + { + index |= GENERICDEF_USE_VERTEX_ANIMATION; + } +#endif // REND2_SP + else if (glState.skeletalAnimation) + { + index |= GENERICDEF_USE_SKELETAL_ANIMATION; + } + + shaderProgram_t *sp = &tr.genericShader[index]; + assert(sp); + UniformDataWriter uniformDataWriter; + SamplerBindingsWriter samplerBindingsWriter; + uniformDataWriter.Start(sp); + + const UniformBlockBinding uniformBlockBindings[] = { + GetCameraBlockUniformBinding(backEnd.currentEntity), + GetSceneBlockUniformBinding(), + GetEntityBlockUniformBinding(backEnd.currentEntity), + GetShaderInstanceBlockUniformBinding( + backEnd.currentEntity, input->shader), + GetBonesBlockUniformBinding(backEnd.currentEntity) + }; + + samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_DIFFUSEMAP); + const vec4_t baseColor = { 1.0f, 1.0f, 1.0f, 1.0f }; + const vec4_t vertColor = { 0.0f, 0.0f, 0.0f, 0.0f }; + uniformDataWriter.SetUniformVec4(UNIFORM_BASECOLOR, baseColor); + uniformDataWriter.SetUniformVec4(UNIFORM_VERTCOLOR, vertColor); + + DrawItem item = {}; + item.renderState.stateBits = GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE | GLS_POLYGON_OFFSET_FILL; + item.renderState.cullType = RB_GetCullType(&backEnd.viewParms, backEnd.currentEntity, input->shader->cullType); + item.renderState.depthRange = RB_GetDepthRange(backEnd.currentEntity, input->shader); + item.program = sp; + item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; + item.uniformData = uniformDataWriter.Finish(frameAllocator); + item.samplerBindings = samplerBindingsWriter.Finish( + frameAllocator, &item.numSamplerBindings); + + DrawItemSetVertexAttributes( + item, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings( + item, uniformBlockBindings, frameAllocator); + + RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); + + uint32_t key = RB_CreateSortKey(item, 15, 15); + + RB_AddDrawItem(backEndData->currentPass, key, item); + } +} + +/* +================ +DrawNormals + +Draws vertex normals for debugging +================ +*/ +static void DrawNormals(shaderCommands_t *input) { + //FIXME: implement this +} + +static void ProjectPshadowVBOGLSL( const shaderCommands_t *input, const VertexArraysProperties *vertexArrays ) { + int l; + vec3_t origin; + float radius; + + if ( !backEnd.refdef.num_pshadows ) { + return; + } + + cullType_t cullType = RB_GetCullType(&backEnd.viewParms, backEnd.currentEntity, input->shader->cullType); + + UniformDataWriter uniformDataWriter; + SamplerBindingsWriter samplerBindingsWriter; + shaderStage_t *pStage = tess.xstages[0]; + + vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; + GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); + + for ( l = 0; l < backEnd.refdef.num_pshadows; l++ ) { + pshadow_t *ps; + shaderProgram_t *sp; + vec4_t vector; + + if ( !( tess.pshadowBits & ( 1 << l ) ) ) { + continue; // this surface definately doesn't have any of this shadow + } + + ps = &backEnd.refdef.pshadows[l]; + VectorCopy( ps->lightOrigin, origin ); + radius = ps->lightRadius; + + sp = &tr.pshadowShader; + + uniformDataWriter.Start(sp); + + uniformDataWriter.SetUniformMatrix4x4(UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); + + VectorCopy(origin, vector); + vector[3] = (float)l; + uniformDataWriter.SetUniformVec4(UNIFORM_LIGHTORIGIN, vector); + + VectorScale(ps->lightViewAxis[0], 1.0f, vector); + uniformDataWriter.SetUniformVec3(UNIFORM_LIGHTFORWARD, vector); + + VectorScale(ps->lightViewAxis[1], 1.0f / ps->viewRadius, vector); + uniformDataWriter.SetUniformVec3(UNIFORM_LIGHTRIGHT, vector); + + VectorScale(ps->lightViewAxis[2], 1.0f / ps->viewRadius, vector); + uniformDataWriter.SetUniformVec3(UNIFORM_LIGHTUP, vector); + + uniformDataWriter.SetUniformFloat(UNIFORM_LIGHTRADIUS, radius); + + // include GLS_DEPTHFUNC_EQUAL so alpha tested surfaces don't add light + // where they aren't rendered + uint32_t stateBits = 0; + stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHFUNC_EQUAL; + + samplerBindingsWriter.AddStaticImage(tr.pshadowArrayImage, TB_DIFFUSEMAP); + + CaptureDrawData(input, pStage, 0, 0); + + DrawItem item = {}; + item.renderState.stateBits = stateBits; + item.renderState.cullType = cullType; + item.program = sp; + item.renderState.depthRange = RB_GetDepthRange(backEnd.currentEntity, input->shader); + item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; + + item.numAttributes = vertexArrays->numVertexArrays; + item.attributes = ojkAllocArray( + *backEndData->perFrameMemory, vertexArrays->numVertexArrays); + memcpy(item.attributes, attribs, sizeof(*item.attributes)*vertexArrays->numVertexArrays); + + item.uniformData = uniformDataWriter.Finish(*backEndData->perFrameMemory); + // FIXME: This is a bit ugly with the casting + item.samplerBindings = samplerBindingsWriter.Finish( + *backEndData->perFrameMemory, &item.numSamplerBindings); + + RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); + + uint32_t key = RB_CreateSortKey(item, 13, input->shader->sort); + RB_AddDrawItem(backEndData->currentPass, key, item); + + backEnd.pc.c_totalIndexes += tess.numIndexes; + + RB_BinTriangleCounts(); + } +} + +/* +=================== +RB_FogPass + +Blends a fog texture on top of everything else +=================== +*/ +static void RB_FogPass( shaderCommands_t *input, const VertexArraysProperties *vertexArrays ) +{ + cullType_t cullType = RB_GetCullType(&backEnd.viewParms, backEnd.currentEntity, input->shader->cullType); + + vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; + GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); + + int shaderBits = 0; + + if (input->shader->numDeforms && !ShaderRequiresCPUDeforms(input->shader)) + shaderBits |= FOGDEF_USE_DEFORM_VERTEXES; +#ifdef REND2_SP + if (glState.vertexAnimation) + shaderBits |= FOGDEF_USE_VERTEX_ANIMATION; +#endif // REND2_SP + else if (glState.skeletalAnimation) + shaderBits |= FOGDEF_USE_SKELETAL_ANIMATION; + + if (tr.world && tr.world->globalFog && + input->fogNum != tr.world->globalFogIndex && + input->shader->sort != SS_FOG) + shaderBits |= FOGDEF_USE_FALLBACK_GLOBAL_FOG; + + if (input->numPasses > 0) + if (input->xstages[0]->alphaTestType != ALPHA_TEST_NONE) + shaderBits |= FOGDEF_USE_ALPHA_TEST; + + shaderProgram_t *sp = tr.fogShader + shaderBits; + + backEnd.pc.c_fogDraws++; + + UniformDataWriter uniformDataWriter; + uniformDataWriter.Start(sp); + uniformDataWriter.SetUniformInt(UNIFORM_FOGINDEX, input->fogNum - 1); + if (input->numPasses > 0) + uniformDataWriter.SetUniformInt(UNIFORM_ALPHA_TEST_TYPE, input->xstages[0]->alphaTestType); + + uint32_t stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + if ( tess.shader->fogPass == FP_EQUAL ) + stateBits |= GLS_DEPTHFUNC_EQUAL; + + if (input->shader->polygonOffset == qtrue) + stateBits |= GLS_POLYGON_OFFSET_FILL; + + const UniformBlockBinding uniformBlockBindings[] = { + GetCameraBlockUniformBinding(backEnd.currentEntity), + GetFogsBlockUniformBinding(), + GetEntityBlockUniformBinding(backEnd.currentEntity), + GetShaderInstanceBlockUniformBinding( + backEnd.currentEntity, input->shader), + GetBonesBlockUniformBinding(backEnd.currentEntity) + }; + + SamplerBindingsWriter samplerBindingsWriter; + if (input->numPasses > 0) + if (input->xstages[0]->alphaTestType != ALPHA_TEST_NONE) + samplerBindingsWriter.AddStaticImage(input->xstages[0]->bundle[0].image[0], 0); + + Allocator& frameAllocator = *backEndData->perFrameMemory; + DrawItem item = {}; + item.renderState.stateBits = stateBits; + item.renderState.cullType = cullType; + item.renderState.depthRange = RB_GetDepthRange(backEnd.currentEntity, input->shader); + item.program = sp; + item.uniformData = uniformDataWriter.Finish(frameAllocator); + item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; + item.samplerBindings = samplerBindingsWriter.Finish( + frameAllocator, &item.numSamplerBindings); + + DrawItemSetVertexAttributes( + item, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings( + item, uniformBlockBindings, frameAllocator); + + RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); + + const uint32_t key = RB_CreateSortKey(item, 14, input->shader->sort); + RB_AddDrawItem(backEndData->currentPass, key, item); + + // invert fog planes and render global fog into them + if (input->fogNum != tr.world->globalFogIndex && tr.world->globalFogIndex != -1) + { + // only invert render fog planes + if (input->shader->sort != SS_FOG) + return; + if (backEnd.currentEntity && backEnd.currentEntity != &tr.worldEntity) + return; + // well, no idea how to handle this case, it's actually wrong + if (cullType == CT_TWO_SIDED) + return; + if (cullType == CT_FRONT_SIDED) + cullType = CT_BACK_SIDED; + else + cullType = CT_FRONT_SIDED; + UniformDataWriter uniformDataWriterBack; + uniformDataWriterBack.Start(sp); + uniformDataWriterBack.SetUniformInt(UNIFORM_FOGINDEX, tr.world->globalFogIndex - 1); + if (input->numPasses > 0) + { + uniformDataWriterBack.SetUniformInt(UNIFORM_ALPHA_TEST_TYPE, input->xstages[0]->alphaTestType); + SamplerBindingsWriter samplerBindingsWriter; + if (input->xstages[0]->alphaTestType != ALPHA_TEST_NONE) + samplerBindingsWriter.AddStaticImage(input->xstages[0]->bundle[0].image[0], 0); + } + + DrawItem backItem = {}; + memcpy(&backItem, &item, sizeof(item)); + backItem.renderState.cullType = cullType; + backItem.uniformData = uniformDataWriterBack.Finish(frameAllocator); + backItem.samplerBindings = samplerBindingsWriter.Finish( + frameAllocator, &item.numSamplerBindings); + + DrawItemSetVertexAttributes( + backItem, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings( + backItem, uniformBlockBindings, frameAllocator); + + RB_FillDrawCommand(backItem.draw, GL_TRIANGLES, 1, input); + + const uint32_t key = RB_CreateSortKey(backItem, 14, input->shader->sort); + RB_AddDrawItem(backEndData->currentPass, key, backItem); + } +} + +static unsigned int RB_CalcShaderVertexAttribs( const shader_t *shader ) +{ + unsigned int vertexAttribs = shader->vertexAttribs; +#ifdef REND2_SP + if(glState.vertexAnimation) + { + //vertexAttribs &= ~ATTR_COLOR; + vertexAttribs |= ATTR_POSITION2; + if (vertexAttribs & ATTR_NORMAL) + { + vertexAttribs |= ATTR_NORMAL2; + vertexAttribs |= ATTR_TANGENT2; + } + } +#endif // REND2_SP + if (glState.skeletalAnimation) + { + vertexAttribs |= ATTR_BONE_WEIGHTS; + vertexAttribs |= ATTR_BONE_INDEXES; + } + + return vertexAttribs; +} + +static shaderProgram_t *SelectShaderProgram( int stageIndex, shaderStage_t *stage, shaderProgram_t *glslShaderGroup, bool useAlphaTestGE192, bool forceRefraction ) +{ + uint32_t index; + shaderProgram_t *result = nullptr; + + if (forceRefraction) + { + index = 0; + if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) + { + index |= REFRACTIONDEF_USE_DEFORM_VERTEXES; + } +#ifdef REND2_SP + if (glState.vertexAnimation) + { + index |= REFRACTIONDEF_USE_VERTEX_ANIMATION; + } +#endif // REND2_SP + else if (glState.skeletalAnimation) + { + index |= REFRACTIONDEF_USE_SKELETAL_ANIMATION; + } + + if (stage->bundle[0].tcGen != TCGEN_TEXTURE || (stage->bundle[0].numTexMods)) + index |= REFRACTIONDEF_USE_TCGEN_AND_TCMOD; + + if (!useAlphaTestGE192) + { + if (stage->alphaTestType != ALPHA_TEST_NONE) + index |= REFRACTIONDEF_USE_TCGEN_AND_TCMOD | REFRACTIONDEF_USE_ALPHA_TEST; + } + else + { + index |= REFRACTIONDEF_USE_ALPHA_TEST; + } + + if (tr.hdrLighting == qtrue) + index |= REFRACTIONDEF_USE_SRGB_TRANSFORM; + + return &tr.refractionShader[index]; + } + + if (backEnd.depthFill) + { + if (glslShaderGroup == tr.lightallShader) + { + index = 0; + + if (backEnd.currentEntity && backEnd.currentEntity != &tr.worldEntity) + { +#ifdef REND2_SP + if (glState.vertexAnimation) + { + index |= LIGHTDEF_USE_VERTEX_ANIMATION; + } + else +#endif // REND2_SP + if (glState.skeletalAnimation) + { + index |= LIGHTDEF_USE_SKELETAL_ANIMATION; + } + } + + if ( !useAlphaTestGE192 ) + { + if (stage->alphaTestType != ALPHA_TEST_NONE) + index |= LIGHTDEF_USE_ALPHA_TEST; + } + else + { + index |= LIGHTDEF_USE_ALPHA_TEST; + } + + result = &stage->glslShaderGroup[index]; + backEnd.pc.c_lightallDraws++; + } + else + { + index = 0; + + if (tess.shader->numDeforms && !ShaderRequiresCPUDeforms(tess.shader)) + { + index |= GENERICDEF_USE_DEFORM_VERTEXES; + } +#ifdef REND2_SP + if (glState.vertexAnimation) + { + index |= GENERICDEF_USE_VERTEX_ANIMATION; + } +#endif // REND2_SP + else if (glState.skeletalAnimation) + { + index |= GENERICDEF_USE_SKELETAL_ANIMATION; + } + + if ( !useAlphaTestGE192 ) + { + if (stage->alphaTestType != ALPHA_TEST_NONE) + index |= GENERICDEF_USE_TCGEN_AND_TCMOD | GENERICDEF_USE_ALPHA_TEST; + } + else + { + index |= GENERICDEF_USE_ALPHA_TEST; + } + + if (backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1 | RF_DISINTEGRATE2)) + index |= GENERICDEF_USE_RGBAGEN; + + if (backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE2) + index |= GENERICDEF_USE_DEFORM_VERTEXES; + + result = &tr.genericShader[index]; + backEnd.pc.c_genericDraws++; + } + } + else if (stage->glslShaderGroup == tr.lightallShader) + { + index = stage->glslShaderIndex; + + if (r_lightmap->integer && (index & LIGHTDEF_USE_LIGHTMAP) && !(index & LIGHTDEF_USE_LIGHT_VERTEX)) + { + index = LIGHTDEF_USE_LIGHTMAP; + } + else + { + if (backEnd.currentEntity && backEnd.currentEntity != &tr.worldEntity) + { +#ifdef REND2_SP + if (glState.vertexAnimation) + { + index |= LIGHTDEF_USE_VERTEX_ANIMATION; + } +#endif // REND2_SP + if (glState.skeletalAnimation) + { + index |= LIGHTDEF_USE_SKELETAL_ANIMATION; + } + } + + if ( !useAlphaTestGE192 ) + { + if (stage->alphaTestType != ALPHA_TEST_NONE) + index |= LIGHTDEF_USE_TCGEN_AND_TCMOD | LIGHTDEF_USE_ALPHA_TEST; + } + else + { + index |= LIGHTDEF_USE_ALPHA_TEST; + } + } + + result = &stage->glslShaderGroup[index]; + backEnd.pc.c_lightallDraws++; + } + else + { + result = GLSL_GetGenericShaderProgram(stageIndex); + backEnd.pc.c_genericDraws++; + } + + return result; +} + +/* +================= +RB_ShadowTessEnd + +================= +*/ +void RB_ShadowTessEnd(shaderCommands_t *input, const VertexArraysProperties *vertexArrays) { + if (glConfig.stencilBits < 4) { + ri.Printf(PRINT_ALL, "no stencil bits for stencil writing\n"); + return; + } + + if (!input->numVertexes || !input->numIndexes || input->useInternalVBO) + { + return; + } + + vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; + GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); + GL_VertexAttribPointers(vertexArrays->numVertexArrays, attribs); + + Allocator& frameAllocator = *backEndData->perFrameMemory; + + cullType_t cullType = CT_TWO_SIDED; + + int stateBits = GLS_DEPTHFUNC_LESS | GLS_STENCILTEST_ENABLE | GLS_COLORMASK_BITS; + + const UniformBlockBinding uniformBlockBindings[] = { + GetCameraBlockUniformBinding(backEnd.currentEntity), + GetEntityBlockUniformBinding(backEnd.currentEntity), + GetBonesBlockUniformBinding(backEnd.currentEntity) + }; + + DrawItem item = {}; + item.renderState.stateBits = stateBits; + item.renderState.cullType = cullType; + DepthRange range = { 0.0f, 1.0f }; + item.renderState.depthRange = range; + item.program = &tr.volumeShadowShader; + item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; + + DrawItemSetVertexAttributes( + item, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings( + item, uniformBlockBindings, frameAllocator); + + RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); + + const uint32_t key = RB_CreateSortKey(item, 13, 15); + RB_AddDrawItem(backEndData->currentPass, key, item); +} + +static void RB_IterateStagesGeneric( shaderCommands_t *input, const VertexArraysProperties *vertexArrays ) +{ + Allocator& frameAllocator = *backEndData->perFrameMemory; + cullType_t cullType = RB_GetCullType(&backEnd.viewParms, backEnd.currentEntity, input->shader->cullType); + + vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; + GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), vertexArrays); + + UniformDataWriter uniformDataWriter; + SamplerBindingsWriter samplerBindingsWriter; + + for ( int stage = 0; stage < MAX_SHADER_STAGES; stage++ ) + { + shaderStage_t *pStage = input->xstages[stage]; + shaderProgram_t *sp; + vec4_t texMatrix; + vec4_t texOffTurb; + int stateBits; + colorGen_t forceRGBGen = CGEN_BAD; + alphaGen_t forceAlphaGen = AGEN_IDENTITY; + int index = 0; + bool useAlphaTestGE192 = false; + bool forceRefraction = false; + vec4_t disintegrationInfo; + + if ( !pStage ) + { + break; + } + + if ( pStage->ss ) + { + continue; + } + + stateBits = pStage->stateBits; + + if (backEnd.currentEntity) + { + assert(backEnd.currentEntity->e.renderfx >= 0); + + if ( backEnd.currentEntity->e.renderfx & ( RF_DISINTEGRATE1 | RF_DISINTEGRATE2 )) + { + if ( backEnd.currentEntity->e.renderfx & RF_DISINTEGRATE1 ) + { + // we want to be able to rip a hole in the thing being + // disintegrated, and by doing the depth-testing it avoids some + // kinds of artefacts, but will probably introduce others? + stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA | GLS_DEPTHMASK_TRUE; + forceRGBGen = CGEN_DISINTEGRATION_1; + useAlphaTestGE192 = true; + } + else + forceRGBGen = CGEN_DISINTEGRATION_2; + + disintegrationInfo[0] = backEnd.currentEntity->e.oldorigin[0]; + disintegrationInfo[1] = backEnd.currentEntity->e.oldorigin[1]; + disintegrationInfo[2] = backEnd.currentEntity->e.oldorigin[2]; + disintegrationInfo[3] = (backEnd.refdef.time - backEnd.currentEntity->e.endTime) * 0.045f; + disintegrationInfo[3] *= disintegrationInfo[3]; + } + else if ( backEnd.currentEntity->e.renderfx & RF_RGB_TINT ) + {//want to use RGBGen from ent + forceRGBGen = CGEN_ENTITY; + } + + // only force blend on the internal distortion shader + if (input->shader == tr.distortionShader) + stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + + if (input->shader->useDistortion == qtrue || backEnd.currentEntity->e.renderfx & RF_DISTORTION) + forceRefraction = true; + + if ( backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA ) + { + stateBits = GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + if ( backEnd.currentEntity->e.renderfx & RF_ALPHA_DEPTH ) + { + // depth write, so faces through the model will be stomped + // over by nearer ones. this works because we draw + // RF_FORCE_ENT_ALPHA stuff after everything else, including + // standard alpha surfs. + stateBits |= GLS_DEPTHMASK_TRUE; + } + } + } + + if (backEnd.viewParms.flags & VPF_POINTSHADOW) + stateBits |= GLS_POLYGON_OFFSET_FILL; + + sp = SelectShaderProgram(stage, pStage, pStage->glslShaderGroup, useAlphaTestGE192, forceRefraction); + assert(sp); + + uniformDataWriter.Start(sp); + + if ( input->fogNum ) { + vec4_t fogColorMask; + ComputeFogColorMask(pStage, fogColorMask); + uniformDataWriter.SetUniformVec4(UNIFORM_FOGCOLORMASK, fogColorMask); + uniformDataWriter.SetUniformInt(UNIFORM_FOGINDEX, input->fogNum - 1); + } + + float volumetricBaseValue = -1.0f; + if ( backEnd.currentEntity->e.renderfx & RF_VOLUMETRIC ) + { + volumetricBaseValue = backEnd.currentEntity->e.shaderRGBA[0] / 255.0f; + } + else + { + vec4_t baseColor; + vec4_t vertColor; + +#ifdef REND2_SP_MAYBE + // Fade will be set true when rendering some gore surfaces + if (input->fade) + { + VectorCopy4(input->svars.colors[input->firstIndex], baseColor); + VectorScale4(baseColor, 1.0f / 255.0f, baseColor); + VectorSet4(vertColor, 0.0f, 0.0f, 0.0f, 0.0f); + } + else +#endif + ComputeShaderColors(pStage, baseColor, vertColor, stateBits, &forceRGBGen, &forceAlphaGen); + + if ((backEnd.refdef.colorScale != 1.0f) && !(backEnd.refdef.rdflags & RDF_NOWORLDMODEL)) + { + // use VectorScale to only scale first three values, not alpha + VectorScale(baseColor, backEnd.refdef.colorScale, baseColor); + VectorScale(vertColor, backEnd.refdef.colorScale, vertColor); + } + + if (backEnd.currentEntity->e.renderfx & RF_FORCE_ENT_ALPHA) + { + baseColor[3] = backEnd.currentEntity->e.shaderRGBA[3] / 255.0f; + vertColor[3] = 0.0f; + } + + if (backEnd.currentEntity->e.hModel != NULL) + { + model_t *model = R_GetModelByHandle(backEnd.currentEntity->e.hModel); + if (model->type != MOD_BRUSH) + { + switch (forceRGBGen) + { + case CGEN_EXACT_VERTEX: + case CGEN_EXACT_VERTEX_LIT: + case CGEN_VERTEX: + case CGEN_VERTEX_LIT: + baseColor[0] = + baseColor[1] = + baseColor[2] = + baseColor[3] = 0.0f; + + vertColor[0] = + vertColor[1] = + vertColor[2] = + vertColor[3] = tr.identityLight; + break; + default: + break; + } + } + } + + uniformDataWriter.SetUniformVec4(UNIFORM_BASECOLOR, baseColor); + uniformDataWriter.SetUniformVec4(UNIFORM_VERTCOLOR, vertColor); + } + +#if 0 // TODO: Revisit this, isn't it just a alphaGen? + if (pStage->alphaGen == AGEN_PORTAL) + { + uniformDataWriter.SetUniformFloat(UNIFORM_PORTALRANGE, tess.shader->portalRange); + } +#endif + uniformDataWriter.SetUniformInt(UNIFORM_COLORGEN, forceRGBGen); + uniformDataWriter.SetUniformInt(UNIFORM_ALPHAGEN, forceAlphaGen); + + if (backEnd.currentEntity->e.renderfx & (RF_DISINTEGRATE1 | RF_DISINTEGRATE2)) + uniformDataWriter.SetUniformVec4(UNIFORM_DISINTEGRATION, disintegrationInfo); + + if (forceRefraction) + { + vec4_t color; + color[0] = + color[1] = + color[2] = powf(2.0f, r_cameraExposure->value); + color[3] = 10.0f; + uniformDataWriter.SetUniformVec4(UNIFORM_COLOR, color); + uniformDataWriter.SetUniformVec2(UNIFORM_AUTOEXPOSUREMINMAX, tr.refdef.autoExposureMinMax); + uniformDataWriter.SetUniformVec3(UNIFORM_TONEMINAVGMAXLINEAR, tr.refdef.toneMinAvgMaxLinear); + } + +#ifdef REND2_SP_MAYBE + // tess scale will be set true only when theres scaled gore + if (!input->scale) + texMatrix[0] = texMatrix[3] = input->texCoords[input->firstIndex][0][0]; + else +#endif + ComputeTexMods(pStage, TB_DIFFUSEMAP, texMatrix, texOffTurb); + + uniformDataWriter.SetUniformVec4(UNIFORM_DIFFUSETEXMATRIX, texMatrix); + uniformDataWriter.SetUniformVec4(UNIFORM_DIFFUSETEXOFFTURB, texOffTurb); + + uniformDataWriter.SetUniformInt(UNIFORM_TCGEN0, pStage->bundle[0].tcGen); + uniformDataWriter.SetUniformInt(UNIFORM_TCGEN1, pStage->bundle[1].tcGen); + if (pStage->bundle[0].tcGen == TCGEN_VECTOR) + { + uniformDataWriter.SetUniformVec3(UNIFORM_TCGEN0VECTOR0, pStage->bundle[0].tcGenVectors[0]); + uniformDataWriter.SetUniformVec3(UNIFORM_TCGEN0VECTOR1, pStage->bundle[0].tcGenVectors[1]); + } + + vec4_t normalScale = { + pStage->normalScale[0], + pStage->normalScale[1], + backEnd.viewParms.isPortal ? -1.0f : 1.0f, + pStage->normalScale[3] + }; + + uniformDataWriter.SetUniformVec4(UNIFORM_NORMALSCALE, normalScale); + uniformDataWriter.SetUniformVec4(UNIFORM_SPECULARSCALE, pStage->specularScale); + + const float parallaxBias = r_forceParallaxBias->value > 0.0f ? r_forceParallaxBias->value : pStage->parallaxBias; + uniformDataWriter.SetUniformFloat(UNIFORM_PARALLAXBIAS, parallaxBias); + + const AlphaTestType alphaTestType = + useAlphaTestGE192 ? ALPHA_TEST_GE192 : pStage->alphaTestType; + uniformDataWriter.SetUniformInt(UNIFORM_ALPHA_TEST_TYPE, alphaTestType); + + // + // do multitexture + // + bool enableCubeMaps = ( r_cubeMapping->integer + && !(tr.viewParms.flags & VPF_NOCUBEMAPS) + && input->cubemapIndex > 0 + && pStage->rgbGen != CGEN_LIGHTMAPSTYLE ); + bool enableDLights = ( tess.dlightBits + && tess.shader->sort <= SS_OPAQUE + && !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY)) + && pStage->rgbGen != CGEN_LIGHTMAPSTYLE ); + + if (forceRefraction) + { + FBO_t *srcFbo = tr.renderFbo; + if (tr.msaaResolveFbo) + srcFbo = tr.msaaResolveFbo; + + samplerBindingsWriter.AddStaticImage(srcFbo->colorImage[0], TB_COLORMAP); + samplerBindingsWriter.AddStaticImage(tr.renderDepthImage, TB_SHADOWMAP); + qboolean autoExposure = (qboolean)(r_autoExposure->integer || r_forceAutoExposure->integer); + + if (autoExposure) + samplerBindingsWriter.AddStaticImage(tr.calcLevelsImage, TB_LEVELSMAP); + else + samplerBindingsWriter.AddStaticImage(tr.fixedLevelsImage, TB_LEVELSMAP); + } + else if ( backEnd.depthFill ) + { + if (pStage->alphaTestType == ALPHA_TEST_NONE) + samplerBindingsWriter.AddStaticImage(tr.whiteImage, 0); + else if ( pStage->bundle[TB_COLORMAP].image[0] != 0 ) + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_COLORMAP], TB_COLORMAP); + } + else if ( pStage->glslShaderGroup == tr.lightallShader ) + { + int i; + vec4_t enableTextures = {}; + + if (r_sunlightMode->integer && + (backEnd.viewParms.flags & VPF_USESUNLIGHT) && + (pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK)) + { + samplerBindingsWriter.AddStaticImage(tr.sunShadowArrayImage, TB_SHADOWMAP); + enableTextures[2] = 1.0f; + } + else + samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_SHADOWMAP); + + if ((r_lightmap->integer == 1 || r_lightmap->integer == 2) && + (pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap)) + { + for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) + { + if (i == TB_DIFFUSEMAP) + samplerBindingsWriter.AddStaticImage(tr.whiteImage, i); + else + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[i], i); + } + } + else if (r_lightmap->integer == 3 && pStage->bundle[TB_DELUXEMAP].image[0]) + { + for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) + { + if (i == TB_LIGHTMAP) + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_DELUXEMAP], i); + else if (i == TB_DIFFUSEMAP) + samplerBindingsWriter.AddStaticImage(tr.whiteImage, i); + else + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[i], i); + } + } + else + { + qboolean light = (qboolean)((pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK) != 0); + qboolean allowVertexLighting = (qboolean)!(r_normalMapping->integer || r_specularMapping->integer); + + if (pStage->bundle[TB_DIFFUSEMAP].image[0]) + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_DIFFUSEMAP], TB_DIFFUSEMAP); + + if (pStage->bundle[TB_LIGHTMAP].image[0]) + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_LIGHTMAP], TB_LIGHTMAP); + + // bind textures that are sampled and used in the glsl shader, and + // bind whiteImage to textures that are sampled but zeroed in the glsl shader + // + // alternatives: + // - use the last bound texture + // -> costs more to sample a higher res texture then throw out the result + // - disable texture sampling in glsl shader with #ifdefs, as before + // -> increases the number of shaders that must be compiled + // + if (light && !allowVertexLighting) + { + if (pStage->bundle[TB_NORMALMAP].image[0]) + { + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_NORMALMAP], TB_NORMALMAP); + enableTextures[0] = 1.0f; + } + else if (r_normalMapping->integer) + { + samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_NORMALMAP); + } + + if (pStage->bundle[TB_DELUXEMAP].image[0]) + { + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_DELUXEMAP], TB_DELUXEMAP); + enableTextures[1] = 1.0f; + } + else if (r_deluxeMapping->integer) + { + samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_DELUXEMAP); + } + + if (pStage->bundle[TB_SPECULARMAP].image[0]) + { + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[TB_SPECULARMAP], TB_SPECULARMAP); + } + else if (r_specularMapping->integer) + { + samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_SPECULARMAP); + } + + if (r_ssao->integer && tr.world && backEnd.framePostProcessed == qfalse) + samplerBindingsWriter.AddStaticImage(tr.screenSsaoImage, TB_SSAOMAP); + else if (r_ssao->integer) + samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_SSAOMAP); + + } + + if ( enableCubeMaps ) + { + enableTextures[3] = 1.0f; + } + } + + uniformDataWriter.SetUniformVec4(UNIFORM_ENABLETEXTURES, enableTextures); + } + else if ( pStage->bundle[1].image[0] != 0 ) + { + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[0], 0); + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[1], 1); + } + else + { + // + // set state + // + samplerBindingsWriter.AddAnimatedImage(&pStage->bundle[0], 0); + } + + // + // testing cube map + // + if ( enableCubeMaps ) + { + vec4_t vec; + cubemap_t *cubemap = &tr.cubemaps[input->cubemapIndex - 1]; + + samplerBindingsWriter.AddStaticImage(cubemap->image, TB_CUBEMAP); + samplerBindingsWriter.AddStaticImage(tr.envBrdfImage, TB_ENVBRDFMAP); + + VectorSubtract(cubemap->origin, backEnd.viewParms.ori.origin, vec); + vec[3] = 1.0f; + + VectorScale4(vec, 1.0f / cubemap->parallaxRadius, vec); + + uniformDataWriter.SetUniformVec4(UNIFORM_CUBEMAPINFO, vec); + } + + if (enableDLights) + { + uniformDataWriter.SetUniformInt(UNIFORM_LIGHTMASK, tess.dlightBits); + if (r_dlightMode->integer > 1) + samplerBindingsWriter.AddStaticImage(tr.pointShadowArrayImage, TB_SHADOWMAPARRAY); + } + else + uniformDataWriter.SetUniformInt(UNIFORM_LIGHTMASK, 0); + + CaptureDrawData(input, pStage, index, stage); + + const UniformBlockBinding uniformBlockBindings[] = { + GetCameraBlockUniformBinding(backEnd.currentEntity), + GetLightsBlockUniformBinding(), + GetSceneBlockUniformBinding(), + GetFogsBlockUniformBinding(), + GetEntityBlockUniformBinding(backEnd.currentEntity), + GetShaderInstanceBlockUniformBinding( + backEnd.currentEntity, input->shader), + GetBonesBlockUniformBinding(backEnd.currentEntity) + }; + + DrawItem item = {}; + item.renderState.stateBits = stateBits; + item.renderState.cullType = forceRefraction ? CT_TWO_SIDED : cullType; + item.renderState.depthRange = RB_GetDepthRange(backEnd.currentEntity, input->shader); + item.program = sp; + item.ibo = input->externalIBO ? input->externalIBO : backEndData->currentFrame->dynamicIbo; + item.uniformData = uniformDataWriter.Finish(frameAllocator); + item.samplerBindings = samplerBindingsWriter.Finish( + frameAllocator, &item.numSamplerBindings); + + DrawItemSetVertexAttributes( + item, attribs, vertexArrays->numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings( + item, uniformBlockBindings, frameAllocator); + + RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, input); + + uint32_t key = RB_CreateSortKey(item, stage, input->shader->sort); + + RB_AddDrawItem(backEndData->currentPass, key, item); + + // allow skipping out to show just lightmaps during development + if ( r_lightmap->integer && ( pStage->bundle[0].isLightmap || pStage->bundle[1].isLightmap ) ) + { + break; + } + + if (backEnd.depthFill) + break; + } +} + +/* +** RB_StageIteratorGeneric +*/ +void RB_StageIteratorGeneric( void ) +{ + shaderCommands_t *input = &tess; + if (!input->numVertexes || !input->numIndexes) + { + return; + } + + // + // log this call + // + if ( r_logFile->integer ) + { + // don't just call LogComment, or we will get + // a call to va() every frame! + GLimp_LogComment( va("--- RB_StageIteratorGeneric( %s ) ---\n", tess.shader->name) ); + } + + // + // update vertex buffer data + // + uint32_t vertexAttribs = RB_CalcShaderVertexAttribs( input->shader ); + if (tess.useInternalVBO) + { + RB_DeformTessGeometry(); + RB_UpdateVBOs(vertexAttribs); + } + else + { + backEnd.pc.c_staticVboDraws++; + } + + // + // vertex arrays + // + VertexArraysProperties vertexArrays; + if ( tess.useInternalVBO ) + { + CalculateVertexArraysProperties(vertexAttribs, &vertexArrays); + for ( int i = 0; i < vertexArrays.numVertexArrays; i++ ) + { + int attributeIndex = vertexArrays.enabledAttributes[i]; + vertexArrays.offsets[attributeIndex] += backEndData->currentFrame->dynamicVboCommitOffset; + } + } + else + { + CalculateVertexArraysFromVBO(vertexAttribs, glState.currentVBO, &vertexArrays); + } + + if ( backEnd.depthFill ) + { + RB_IterateStagesGeneric( input, &vertexArrays ); + } + else + { + RB_IterateStagesGeneric( input, &vertexArrays ); + + // + // pshadows! + // + if (r_shadows->integer == 4 && + tess.pshadowBits && + tess.shader->sort <= SS_OPAQUE && + !(tess.shader->surfaceFlags & (SURF_NODLIGHT | SURF_SKY))) + { + ProjectPshadowVBOGLSL( input, &vertexArrays ); + } + + // + // volumeshadows! + // + if (glState.genShadows && r_shadows->integer == 2) + { + RB_ShadowTessEnd( input, &vertexArrays ); + } + + // + // now do fog + // + const fog_t *fog = nullptr; + if ( tr.world && input->fogNum != 0) + { + fog = tr.world->fogs + input->fogNum; + } + if (fog && tess.shader->fogPass && r_drawfog->integer) + RB_FogPass(input, &vertexArrays); + + // + // draw debugging stuff + // + if ( r_showtris->integer ) { + DrawTris( input, &vertexArrays ); + } + if ( r_shownormals->integer ) { + DrawNormals( input ); + } + } + + RB_CommitInternalBufferData(); +} + +void RB_BinTriangleCounts( void ) +{ + int numTriangles = tess.numIndexes / 3; + if ( numTriangles < 20 ) + backEnd.pc.c_triangleCountBins[TRI_BIN_0_19]++; + else if ( numTriangles < 50 ) + backEnd.pc.c_triangleCountBins[TRI_BIN_20_49]++; + else if ( numTriangles < 100 ) + backEnd.pc.c_triangleCountBins[TRI_BIN_50_99]++; + else if ( numTriangles < 300 ) + backEnd.pc.c_triangleCountBins[TRI_BIN_100_299]++; + else if ( numTriangles < 600 ) + backEnd.pc.c_triangleCountBins[TRI_BIN_300_599]++; + else if ( numTriangles < 1000 ) + backEnd.pc.c_triangleCountBins[TRI_BIN_1000_1499]++; + else if ( numTriangles < 1500 ) + backEnd.pc.c_triangleCountBins[TRI_BIN_1500_1999]++; + else if ( numTriangles < 2000 ) + backEnd.pc.c_triangleCountBins[TRI_BIN_2000_2999]++; + else + backEnd.pc.c_triangleCountBins[TRI_BIN_3000_PLUS]++; +} + +/* +** RB_EndSurface +*/ +void RB_EndSurface( void ) { + shaderCommands_t *input; + + input = &tess; + + if (input->numIndexes == 0 || input->numVertexes == 0) { + return; + } + + if (input->indexes[SHADER_MAX_INDEXES-1] != 0) { + ri.Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_INDEXES hit"); + } + if (input->xyz[SHADER_MAX_VERTEXES-1][0] != 0) { + ri.Error (ERR_DROP, "RB_EndSurface() - SHADER_MAX_VERTEXES hit"); + } + + // for debugging of sort order issues, stop rendering after a given sort value + if ( r_debugSort->integer && r_debugSort->integer < tess.shader->sort ) { + return; + } + + if (tr.world && !backEnd.framePostProcessed) { + if (tr.world->skyboxportal) + { + // world + if (!(tr.viewParms.isSkyPortal) && (tess.currentStageIteratorFunc == RB_StageIteratorSky)) + { // don't process these tris at all + return; + } + // portal sky + else if (!(backEnd.refdef.rdflags & RDF_DRAWSKYBOX) && (tess.currentStageIteratorFunc != RB_StageIteratorSky)) + { // /only/ process sky tris + return; + } + } + } + + // + // update performance counters + // + backEnd.pc.c_shaders++; + backEnd.pc.c_vertexes += tess.numVertexes; + backEnd.pc.c_indexes += tess.numIndexes; + backEnd.pc.c_totalIndexes += tess.numIndexes * tess.numPasses; + + RB_BinTriangleCounts(); + + // + // call off to shader specific tess end function + // + tess.currentStageIteratorFunc(); + + // clear shader so we can tell we don't have any unclosed surfaces + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + tess.multiDrawPrimitives = 0; + tess.externalIBO = nullptr; + glState.vertexAnimation = qfalse; + glState.skeletalAnimation = qfalse; + glState.genShadows = qfalse; + + GLimp_LogComment( "----------\n" ); +} diff --git a/codemp/rd-rend2/tr_shade_calc.cpp b/codemp/rd-rend2/tr_shade_calc.cpp new file mode 100644 index 0000000000..840bc8087a --- /dev/null +++ b/codemp/rd-rend2/tr_shade_calc.cpp @@ -0,0 +1,825 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_shade_calc.c + +#include "tr_local.h" + + +#define WAVEVALUE( table, base, amplitude, phase, freq ) ((base) + table[ Q_ftol( ( ( (phase) + tess.shaderTime * (freq) ) * FUNCTABLE_SIZE ) ) & FUNCTABLE_MASK ] * (amplitude)) + +static float *TableForFunc( genFunc_t func ) +{ + switch ( func ) + { + case GF_SIN: + return tr.sinTable; + case GF_TRIANGLE: + return tr.triangleTable; + case GF_SQUARE: + return tr.squareTable; + case GF_SAWTOOTH: + return tr.sawToothTable; + case GF_INVERSE_SAWTOOTH: + return tr.inverseSawToothTable; + case GF_NONE: + default: + break; + } + + ri.Error( ERR_DROP, "TableForFunc called with invalid function '%d' in shader '%s'", func, tess.shader->name ); + return NULL; +} + +/* +** EvalWaveForm +** +** Evaluates a given waveForm_t, referencing backEnd.refdef.time directly +*/ +static float EvalWaveForm( const waveForm_t *wf ) +{ + float *table; + + if ( wf->func == GF_NOISE ) { + return ( wf->base + R_NoiseGet4f( 0, 0, 0, ( backEnd.refdef.floatTime + wf->phase ) * wf->frequency ) * wf->amplitude ); + } else if (wf->func == GF_RAND) { + if( GetNoiseTime( backEnd.refdef.time + wf->phase ) <= wf->frequency ) { + return (wf->base + wf->amplitude); + } else { + return wf->base; + } + } + + table = TableForFunc( wf->func ); + + return WAVEVALUE( table, wf->base, wf->amplitude, wf->phase, wf->frequency ); +} + +static float EvalWaveFormClamped( const waveForm_t *wf ) +{ + float glow = EvalWaveForm( wf ); + + if ( glow < 0 ) + { + return 0; + } + + if ( glow > 1 ) + { + return 1; + } + + return glow; +} + +/* +** RB_CalcStretchTexMatrix +*/ +void RB_CalcStretchTexMatrix( const waveForm_t *wf, float *matrix ) +{ + float p; + + p = 1.0f / EvalWaveForm( wf ); + + matrix[0] = p; matrix[2] = 0; matrix[4] = 0.5f - 0.5f * p; + matrix[1] = 0; matrix[3] = p; matrix[5] = 0.5f - 0.5f * p; +} + +/* +==================================================================== + +DEFORMATIONS + +==================================================================== +*/ + +/* +======================== +RB_CalcDeformVertexes + +======================== +*/ +void RB_CalcDeformVertexes( deformStage_t *ds ) +{ + int i; + vec3_t offset; + float scale; + float *xyz = ( float * ) tess.xyz; + uint32_t *normal = ( uint32_t * ) tess.normal; + float *table; + + if ( ds->deformationWave.frequency == 0 ) + { + scale = EvalWaveForm( &ds->deformationWave ); + + for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal++ ) + { + R_VboUnpackNormal(offset, *normal); + + xyz[0] += offset[0] * scale; + xyz[1] += offset[1] * scale; + xyz[2] += offset[2] * scale; + } + } + else + { + table = TableForFunc( ds->deformationWave.func ); + + for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal++ ) + { + float off = ( xyz[0] + xyz[1] + xyz[2] ) * ds->deformationSpread; + + scale = WAVEVALUE( table, ds->deformationWave.base, + ds->deformationWave.amplitude, + ds->deformationWave.phase + off, + ds->deformationWave.frequency ); + + R_VboUnpackNormal(offset, *normal); + + xyz[0] += offset[0] * scale; + xyz[1] += offset[1] * scale; + xyz[2] += offset[2] * scale; + } + } +} + +/* +========================= +RB_CalcDeformNormals + +Wiggle the normals for wavy environment mapping +========================= +*/ +void RB_CalcDeformNormals( deformStage_t *ds ) { + int i; + float scale; + float *xyz = ( float * ) tess.xyz; + uint32_t *normal = ( uint32_t * ) tess.normal; + + for ( i = 0; i < tess.numVertexes; i++, xyz += 4, normal++ ) { + vec3_t fNormal; + + R_VboUnpackNormal(fNormal, *normal); + + scale = 0.98f; + scale = R_NoiseGet4f( xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, + tess.shaderTime * ds->deformationWave.frequency ); + fNormal[ 0 ] += ds->deformationWave.amplitude * scale; + + scale = 0.98f; + scale = R_NoiseGet4f( 100 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, + tess.shaderTime * ds->deformationWave.frequency ); + fNormal[ 1 ] += ds->deformationWave.amplitude * scale; + + scale = 0.98f; + scale = R_NoiseGet4f( 200 + xyz[0] * scale, xyz[1] * scale, xyz[2] * scale, + tess.shaderTime * ds->deformationWave.frequency ); + fNormal[ 2 ] += ds->deformationWave.amplitude * scale; + + VectorNormalizeFast( fNormal ); + + *normal = R_VboPackNormal(fNormal); + } +} + +/* +======================== +RB_CalcBulgeVertexes + +======================== +*/ +void RB_CalcBulgeVertexes( deformStage_t *ds ) { + int i; + const float *st = ( const float * ) tess.texCoords[0]; + float *xyz = ( float * ) tess.xyz; + uint32_t *normal = ( uint32_t * ) tess.normal; + float now; + + now = backEnd.refdef.time * ds->bulgeSpeed * 0.001f; + + for ( i = 0; i < tess.numVertexes; i++, xyz += 4, st += NUM_TESS_TEXCOORDS*2, normal++ ) { + int off; + float scale; + vec3_t fNormal; + + R_VboUnpackNormal(fNormal, *normal); + + off = (float)( FUNCTABLE_SIZE / (M_PI*2) ) * ( st[0] * ds->bulgeWidth + now ); + + scale = tr.sinTable[ off & FUNCTABLE_MASK ] * ds->bulgeHeight; + + xyz[0] += fNormal[0] * scale; + xyz[1] += fNormal[1] * scale; + xyz[2] += fNormal[2] * scale; + } +} + + +/* +====================== +RB_CalcMoveVertexes + +A deformation that can move an entire surface along a wave path +====================== +*/ +void RB_CalcMoveVertexes( deformStage_t *ds ) { + int i; + float *xyz; + float *table; + float scale; + vec3_t offset; + + table = TableForFunc( ds->deformationWave.func ); + + scale = WAVEVALUE( table, ds->deformationWave.base, + ds->deformationWave.amplitude, + ds->deformationWave.phase, + ds->deformationWave.frequency ); + + VectorScale( ds->moveVector, scale, offset ); + + xyz = ( float * ) tess.xyz; + for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) { + VectorAdd( xyz, offset, xyz ); + } +} + + +/* +============= +DeformText + +Change a polygon into a bunch of text polygons +============= +*/ +void DeformText( const char *text ) { + int i; + vec3_t origin, width, height; + int len; + int ch; + float color[4]; + float bottom, top; + vec3_t mid; + vec3_t fNormal; + + height[0] = 0; + height[1] = 0; + height[2] = -1; + + R_VboUnpackNormal(fNormal, tess.normal[0]); + CrossProduct( fNormal, height, width ); + + // find the midpoint of the box + VectorClear( mid ); + bottom = 999999; + top = -999999; + for ( i = 0 ; i < 4 ; i++ ) { + VectorAdd( tess.xyz[i], mid, mid ); + if ( tess.xyz[i][2] < bottom ) { + bottom = tess.xyz[i][2]; + } + if ( tess.xyz[i][2] > top ) { + top = tess.xyz[i][2]; + } + } + VectorScale( mid, 0.25f, origin ); + + // determine the individual character size + height[0] = 0; + height[1] = 0; + height[2] = ( top - bottom ) * 0.5f; + + VectorScale( width, height[2] * -0.75f, width ); + + // determine the starting position + len = strlen( text ); + VectorMA( origin, (len-1), width, origin ); + + // clear the shader indexes + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + + color[0] = color[1] = color[2] = color[3] = 1.0f; + + // draw each character + for ( i = 0 ; i < len ; i++ ) { + ch = text[i]; + ch &= 255; + + if ( ch != ' ' ) { + int row, col; + float frow, fcol, size; + + row = ch>>4; + col = ch&15; + + frow = row*0.0625f; + fcol = col*0.0625f; + size = 0.0625f; + + RB_AddQuadStampExt( origin, width, height, color, fcol, frow, fcol + size, frow + size ); + } + VectorMA( origin, -2, width, origin ); + } +} + +/* +================== +GlobalVectorToLocal +================== +*/ +static void GlobalVectorToLocal( const vec3_t in, vec3_t out ) { + out[0] = DotProduct( in, backEnd.ori.axis[0] ); + out[1] = DotProduct( in, backEnd.ori.axis[1] ); + out[2] = DotProduct( in, backEnd.ori.axis[2] ); +} + +/* +===================== +AutospriteDeform + +Assuming all the triangles for this shader are independant +quads, rebuild them as forward facing sprites +===================== +*/ +static void AutospriteDeform( void ) { + int i; + int oldVerts; + float *xyz; + vec3_t mid, delta; + float radius; + vec3_t left, up; + vec3_t leftDir, upDir; + + if ( tess.numVertexes & 3 ) { + ri.Printf( PRINT_WARNING, "Autosprite shader %s had odd vertex count\n", tess.shader->name ); + } + if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) { + ri.Printf( PRINT_WARNING, "Autosprite shader %s had odd index count\n", tess.shader->name ); + } + + oldVerts = tess.numVertexes; + tess.numVertexes = 0; + tess.numIndexes = 0; + tess.firstIndex = 0; + + if ( backEnd.currentEntity != &tr.worldEntity ) { + GlobalVectorToLocal( backEnd.viewParms.ori.axis[1], leftDir ); + GlobalVectorToLocal( backEnd.viewParms.ori.axis[2], upDir ); + } else { + VectorCopy( backEnd.viewParms.ori.axis[1], leftDir ); + VectorCopy( backEnd.viewParms.ori.axis[2], upDir ); + } + + for ( i = 0 ; i < oldVerts ; i+=4 ) { + // find the midpoint + xyz = tess.xyz[i]; + + mid[0] = 0.25f * (xyz[0] + xyz[4] + xyz[8] + xyz[12]); + mid[1] = 0.25f * (xyz[1] + xyz[5] + xyz[9] + xyz[13]); + mid[2] = 0.25f * (xyz[2] + xyz[6] + xyz[10] + xyz[14]); + + VectorSubtract( xyz, mid, delta ); + radius = VectorLength( delta ) * 0.707f; // / sqrt(2) + + VectorScale( leftDir, radius, left ); + VectorScale( upDir, radius, up ); + + if ( backEnd.viewParms.isMirror ) { + VectorSubtract( vec3_origin, left, left ); + } + + // compensate for scale in the axes if necessary + if ( backEnd.currentEntity->e.nonNormalizedAxes ) { + float axisLength; + axisLength = VectorLength( backEnd.currentEntity->e.axis[0] ); + if ( !axisLength ) { + axisLength = 0; + } else { + axisLength = 1.0f / axisLength; + } + VectorScale(left, axisLength, left); + VectorScale(up, axisLength, up); + } + + RB_AddQuadStamp( mid, left, up, tess.vertexColors[i] ); + } +} + + +/* +===================== +Autosprite2Deform + +Autosprite2 will pivot a rectangular quad along the center of its long axis +===================== +*/ +int edgeVerts[6][2] = { + { 0, 1 }, + { 0, 2 }, + { 0, 3 }, + { 1, 2 }, + { 1, 3 }, + { 2, 3 } +}; + +static void Autosprite2Deform( void ) { + int i, j, k; + int indexes; + float *xyz; + vec3_t forward; + + if ( tess.numVertexes & 3 ) { + ri.Printf( PRINT_WARNING, "Autosprite2 shader %s had odd vertex count\n", tess.shader->name ); + } + if ( tess.numIndexes != ( tess.numVertexes >> 2 ) * 6 ) { + ri.Printf( PRINT_WARNING, "Autosprite2 shader %s had odd index count\n", tess.shader->name ); + } + + if ( backEnd.currentEntity != &tr.worldEntity ) { + GlobalVectorToLocal( backEnd.viewParms.ori.axis[0], forward ); + } else { + VectorCopy( backEnd.viewParms.ori.axis[0], forward ); + } + + // this is a lot of work for two triangles... + // we could precalculate a lot of it is an issue, but it would mess up + // the shader abstraction + for ( i = 0, indexes = 0 ; i < tess.numVertexes ; i+=4, indexes+=6 ) { + float lengths[2]; + int nums[2]; + vec3_t mid[2]; + vec3_t major, minor; + float *v1, *v2; + + // find the midpoint + xyz = tess.xyz[i]; + + // identify the two shortest edges + nums[0] = nums[1] = 0; + lengths[0] = lengths[1] = 999999; + + for ( j = 0 ; j < 6 ; j++ ) { + float l; + vec3_t temp; + + v1 = xyz + 4 * edgeVerts[j][0]; + v2 = xyz + 4 * edgeVerts[j][1]; + + VectorSubtract( v1, v2, temp ); + + l = DotProduct( temp, temp ); + if ( l < lengths[0] ) { + nums[1] = nums[0]; + lengths[1] = lengths[0]; + nums[0] = j; + lengths[0] = l; + } else if ( l < lengths[1] ) { + nums[1] = j; + lengths[1] = l; + } + } + + for ( j = 0 ; j < 2 ; j++ ) { + v1 = xyz + 4 * edgeVerts[nums[j]][0]; + v2 = xyz + 4 * edgeVerts[nums[j]][1]; + + mid[j][0] = 0.5f * (v1[0] + v2[0]); + mid[j][1] = 0.5f * (v1[1] + v2[1]); + mid[j][2] = 0.5f * (v1[2] + v2[2]); + } + + // find the vector of the major axis + VectorSubtract( mid[1], mid[0], major ); + + // cross this with the view direction to get minor axis + CrossProduct( major, forward, minor ); + VectorNormalize( minor ); + + // re-project the points + for ( j = 0 ; j < 2 ; j++ ) { + float l; + + v1 = xyz + 4 * edgeVerts[nums[j]][0]; + v2 = xyz + 4 * edgeVerts[nums[j]][1]; + + l = 0.5 * sqrt( lengths[j] ); + + // we need to see which direction this edge + // is used to determine direction of projection + for ( k = 0 ; k < 5 ; k++ ) { + if ( tess.indexes[ indexes + k ] == i + edgeVerts[nums[j]][0] + && tess.indexes[ indexes + k + 1 ] == i + edgeVerts[nums[j]][1] ) { + break; + } + } + + if ( k == 5 ) { + VectorMA( mid[j], l, minor, v1 ); + VectorMA( mid[j], -l, minor, v2 ); + } else { + VectorMA( mid[j], -l, minor, v1 ); + VectorMA( mid[j], l, minor, v2 ); + } + } + } +} + + +/* +===================== +RB_DeformTessGeometry + +===================== +*/ +void RB_DeformTessGeometry( void ) { + int i; + deformStage_t *ds; + + if(!ShaderRequiresCPUDeforms(tess.shader)) + { + // we don't need the following CPU deforms + return; + } + + for ( i = 0 ; i < tess.shader->numDeforms ; i++ ) { + ds = &tess.shader->deforms[ i ]; + + switch ( ds->deformation ) { + case DEFORM_NONE: + break; + case DEFORM_NORMALS: + RB_CalcDeformNormals( ds ); + break; + case DEFORM_WAVE: + RB_CalcDeformVertexes( ds ); + break; + case DEFORM_BULGE: + RB_CalcBulgeVertexes( ds ); + break; + case DEFORM_MOVE: + RB_CalcMoveVertexes( ds ); + break; + case DEFORM_PROJECTION_SHADOW: + RB_ProjectionShadowDeform(); + break; + case DEFORM_AUTOSPRITE: + AutospriteDeform(); + break; + case DEFORM_AUTOSPRITE2: + Autosprite2Deform(); + break; + case DEFORM_TEXT0: + case DEFORM_TEXT1: + case DEFORM_TEXT2: + case DEFORM_TEXT3: + case DEFORM_TEXT4: + case DEFORM_TEXT5: + case DEFORM_TEXT6: + case DEFORM_TEXT7: + DeformText( backEnd.refdef.text[ds->deformation - DEFORM_TEXT0] ); + break; + } + } +} + +/* +==================================================================== + +COLORS + +==================================================================== +*/ + + +/* +** RB_CalcWaveColorSingle +*/ +float RB_CalcWaveColorSingle( const waveForm_t *wf ) +{ + float glow; + + if ( wf->func == GF_NOISE ) { + glow = wf->base + R_NoiseGet4f( 0, 0, 0, ( tess.shaderTime + wf->phase ) * wf->frequency ) * wf->amplitude; + } else { + glow = EvalWaveForm( wf ) * tr.identityLight; + } + + if ( glow < 0 ) { + glow = 0; + } + else if ( glow > 1 ) { + glow = 1; + } + + return glow; +} + +/* +** RB_CalcWaveAlphaSingle +*/ +float RB_CalcWaveAlphaSingle( const waveForm_t *wf ) +{ + return EvalWaveFormClamped( wf ); +} + +/* +** RB_CalcModulateColorsByFog +*/ +void RB_CalcModulateColorsByFog( unsigned char *colors ) { + int i; + float texCoords[SHADER_MAX_VERTEXES][2]; + + // calculate texcoords so we can derive density + // this is not wasted, because it would only have + // been previously called if the surface was opaque + RB_CalcFogTexCoords( texCoords[0] ); + + for ( i = 0; i < tess.numVertexes; i++, colors += 4 ) { + float f = 1.0 - R_FogFactor( texCoords[i][0], texCoords[i][1] ); + colors[0] *= f; + colors[1] *= f; + colors[2] *= f; + } +} + +/* +==================================================================== + +TEX COORDS + +==================================================================== +*/ + +/* +======================== +RB_CalcFogTexCoords + +To do the clipped fog plane really correctly, we should use +projected textures, but I don't trust the drivers and it +doesn't fit our shader data. +======================== +*/ +void RB_CalcFogTexCoords( float *st ) { + int i; + float *v; + float s, t; + float eyeT; + qboolean eyeOutside; + fog_t *fog; + vec3_t local; + vec4_t fogDistanceVector, fogDepthVector = {0, 0, 0, 0}; + + fog = tr.world->fogs + tess.fogNum; + + // all fogging distance is based on world Z units + VectorSubtract( backEnd.ori.origin, backEnd.viewParms.ori.origin, local ); + fogDistanceVector[0] = -backEnd.ori.modelViewMatrix[2]; + fogDistanceVector[1] = -backEnd.ori.modelViewMatrix[6]; + fogDistanceVector[2] = -backEnd.ori.modelViewMatrix[10]; + fogDistanceVector[3] = DotProduct( local, backEnd.viewParms.ori.axis[0] ); + + // scale the fog vectors based on the fog's thickness + fogDistanceVector[0] *= fog->tcScale; + fogDistanceVector[1] *= fog->tcScale; + fogDistanceVector[2] *= fog->tcScale; + fogDistanceVector[3] *= fog->tcScale; + + // rotate the gradient vector for this orientation + if ( fog->hasSurface ) { + fogDepthVector[0] = fog->surface[0] * backEnd.ori.axis[0][0] + + fog->surface[1] * backEnd.ori.axis[0][1] + fog->surface[2] * backEnd.ori.axis[0][2]; + fogDepthVector[1] = fog->surface[0] * backEnd.ori.axis[1][0] + + fog->surface[1] * backEnd.ori.axis[1][1] + fog->surface[2] * backEnd.ori.axis[1][2]; + fogDepthVector[2] = fog->surface[0] * backEnd.ori.axis[2][0] + + fog->surface[1] * backEnd.ori.axis[2][1] + fog->surface[2] * backEnd.ori.axis[2][2]; + fogDepthVector[3] = -fog->surface[3] + DotProduct( backEnd.ori.origin, fog->surface ); + + eyeT = DotProduct( backEnd.ori.viewOrigin, fogDepthVector ) + fogDepthVector[3]; + } else { + eyeT = 1; // non-surface fog always has eye inside + } + + // see if the viewpoint is outside + // this is needed for clipping distance even for constant fog + + if ( eyeT < 0 ) { + eyeOutside = qtrue; + } else { + eyeOutside = qfalse; + } + + fogDistanceVector[3] += 1.0/512; + + // calculate density for each point + for (i = 0, v = tess.xyz[0] ; i < tess.numVertexes ; i++, v += 4) { + // calculate the length in fog + s = DotProduct( v, fogDistanceVector ) + fogDistanceVector[3]; + t = DotProduct( v, fogDepthVector ) + fogDepthVector[3]; + + // partially clipped fogs use the T axis + if ( eyeOutside ) { + if ( t < 1.0 ) { + t = 1.0/32; // point is outside, so no fogging + } else { + t = 1.0/32 + 30.0/32 * t / ( t - eyeT ); // cut the distance at the fog plane + } + } else { + if ( t < 0 ) { + t = 1.0/32; // point is outside, so no fogging + } else { + t = 31.0/32; + } + } + + st[0] = s; + st[1] = t; + st += 2; + } +} + +/* +** RB_CalcTurbulentFactors +*/ +void RB_CalcTurbulentFactors( const waveForm_t *wf, float *amplitude, float *now ) +{ + *now = wf->phase + tess.shaderTime * wf->frequency; + *amplitude = wf->amplitude; +} + +/* +** RB_CalcScaleTexMatrix +*/ +void RB_CalcScaleTexMatrix( const float scale[2], float *matrix ) +{ + matrix[0] = scale[0]; matrix[2] = 0.0f; matrix[4] = 0.0f; + matrix[1] = 0.0f; matrix[3] = scale[1]; matrix[5] = 0.0f; +} + +/* +** RB_CalcScrollTexMatrix +*/ +void RB_CalcScrollTexMatrix( const float scrollSpeed[2], float *matrix ) +{ + float timeScale = tess.shaderTime; + float adjustedScrollS, adjustedScrollT; + + adjustedScrollS = scrollSpeed[0] * timeScale; + adjustedScrollT = scrollSpeed[1] * timeScale; + + // clamp so coordinates don't continuously get larger, causing problems + // with hardware limits + adjustedScrollS = adjustedScrollS - floor( adjustedScrollS ); + adjustedScrollT = adjustedScrollT - floor( adjustedScrollT ); + + matrix[0] = 1.0f; matrix[2] = 0.0f; matrix[4] = adjustedScrollS; + matrix[1] = 0.0f; matrix[3] = 1.0f; matrix[5] = adjustedScrollT; +} + +/* +** RB_CalcTransformTexMatrix +*/ +void RB_CalcTransformTexMatrix( const texModInfo_t *tmi, float *matrix ) +{ + matrix[0] = tmi->matrix[0][0]; matrix[2] = tmi->matrix[1][0]; matrix[4] = tmi->translate[0]; + matrix[1] = tmi->matrix[0][1]; matrix[3] = tmi->matrix[1][1]; matrix[5] = tmi->translate[1]; +} + +/* +** RB_CalcRotateTexMatrix +*/ +void RB_CalcRotateTexMatrix( float degsPerSecond, float *matrix ) +{ + float timeScale = tess.shaderTime; + float degs; + int index; + float sinValue, cosValue; + + degs = -degsPerSecond * timeScale; + index = degs * ( FUNCTABLE_SIZE / 360.0f ); + + sinValue = tr.sinTable[ index & FUNCTABLE_MASK ]; + cosValue = tr.sinTable[ ( index + FUNCTABLE_SIZE / 4 ) & FUNCTABLE_MASK ]; + + matrix[0] = cosValue; matrix[2] = -sinValue; matrix[4] = 0.5 - 0.5 * cosValue + 0.5 * sinValue; + matrix[1] = sinValue; matrix[3] = cosValue; matrix[5] = 0.5 - 0.5 * sinValue - 0.5 * cosValue; +} diff --git a/codemp/rd-rend2/tr_shader.cpp b/codemp/rd-rend2/tr_shader.cpp new file mode 100644 index 0000000000..92933dd7f9 --- /dev/null +++ b/codemp/rd-rend2/tr_shader.cpp @@ -0,0 +1,5070 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +#include "tr_local.h" + +// tr_shader.c -- this file deals with the parsing and definition of shaders + +static char *s_shaderText; + +// the shader is parsed into these global variables, then copied into +// dynamically allocated memory if it is valid. +static shaderStage_t stages[MAX_SHADER_STAGES]; +static shader_t shader; +static texModInfo_t texMods[MAX_SHADER_STAGES][TR_MAX_TEXMODS]; + +// Hash value (generated using the generateHashValueForText function) for the original +// retail JKA shader for gfx/2d/wedge. +#define RETAIL_ROCKET_WEDGE_SHADER_HASH (1217042) + +#define FILE_HASH_SIZE 1024 +static shader_t* hashTable[FILE_HASH_SIZE]; + +#define MAX_SHADERTEXT_HASH 2048 +static const char **shaderTextHashTable[MAX_SHADERTEXT_HASH] = { 0 }; + +const int lightmapsNone[MAXLIGHTMAPS] = +{ + LIGHTMAP_NONE, + LIGHTMAP_NONE, + LIGHTMAP_NONE, + LIGHTMAP_NONE +}; + +const int lightmaps2d[MAXLIGHTMAPS] = +{ + LIGHTMAP_2D, + LIGHTMAP_2D, + LIGHTMAP_2D, + LIGHTMAP_2D +}; + +const int lightmapsVertex[MAXLIGHTMAPS] = +{ + LIGHTMAP_BY_VERTEX, + LIGHTMAP_BY_VERTEX, + LIGHTMAP_BY_VERTEX, + LIGHTMAP_BY_VERTEX +}; + +const int lightmapsFullBright[MAXLIGHTMAPS] = +{ + LIGHTMAP_WHITEIMAGE, + LIGHTMAP_WHITEIMAGE, + LIGHTMAP_WHITEIMAGE, + LIGHTMAP_WHITEIMAGE +}; + +const byte stylesDefault[MAXLIGHTMAPS] = +{ + LS_NORMAL, + LS_LSNONE, + LS_LSNONE, + LS_LSNONE +}; + +qhandle_t RE_RegisterShaderLightMap( const char *name, const int *lightmapIndexes, const byte *styles ); + +void KillTheShaderHashTable(void) +{ + memset(shaderTextHashTable, 0, sizeof(shaderTextHashTable)); +} + +qboolean ShaderHashTableExists(void) +{ + if (shaderTextHashTable[0]) + { + return qtrue; + } + return qfalse; +} + +static void ClearGlobalShader(void) +{ + int i; + + memset( &shader, 0, sizeof( shader ) ); + memset( &stages, 0, sizeof( stages ) ); + for ( i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + stages[i].bundle[0].texMods = texMods[i]; + //stages[i].mGLFogColorOverride = GLFOGOVERRIDE_NONE; + + // default normal/specular + VectorSet4(stages[i].normalScale, 0.0f, 0.0f, 0.0f, 0.0f); + stages[i].specularScale[0] = + stages[i].specularScale[1] = + stages[i].specularScale[2] = r_baseSpecular->value; + stages[i].specularScale[3] = 0.99f; + } + + shader.contentFlags = CONTENTS_SOLID | CONTENTS_OPAQUE; +} + +static uint32_t generateHashValueForText( const char *string, size_t length ) +{ + int i = 0; + uint32_t hash = 0; + + while ( length-- ) + { + hash += string[i] * (i + 119); + i++; + } + + return (hash ^ (hash >> 10) ^ (hash >> 20)); +} + +/* +================ +return a hash value for the filename +================ +*/ +static long generateHashValue( const char *fname, const int size ) { + int i; + long hash; + char letter; + + hash = 0; + i = 0; + while (fname[i] != '\0') { + letter = tolower((unsigned char)fname[i]); + if (letter =='.') break; // don't include extension + if (letter =='\\') letter = '/'; // damn path names + if (letter == PATH_SEP) letter = '/'; // damn path names + hash+=(long)(letter)*(i+119); + i++; + } + hash = (hash ^ (hash >> 10) ^ (hash >> 20)); + hash &= (size-1); + return hash; +} + +void R_RemapShader(const char *shaderName, const char *newShaderName, const char *timeOffset) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh, *sh2; + qhandle_t h; + + sh = R_FindShaderByName( shaderName ); + if (sh == NULL || sh == tr.defaultShader) { + h = RE_RegisterShaderLightMap (shaderName, lightmapsNone, stylesDefault); + sh = R_GetShaderByHandle(h); + } + if (sh == NULL || sh == tr.defaultShader) { + ri.Printf( PRINT_WARNING, "WARNING: R_RemapShader: shader %s not found\n", shaderName ); + return; + } + + sh2 = R_FindShaderByName( newShaderName ); + if (sh2 == NULL || sh2 == tr.defaultShader) { + h = RE_RegisterShaderLightMap (newShaderName, lightmapsNone, stylesDefault); + sh2 = R_GetShaderByHandle(h); + } + + if (sh2 == NULL || sh2 == tr.defaultShader) { + ri.Printf( PRINT_WARNING, "WARNING: R_RemapShader: new shader %s not found\n", newShaderName ); + return; + } + + // remap all the shaders with the given name + // even tho they might have different lightmaps + COM_StripExtension(shaderName, strippedName, sizeof(strippedName)); + hash = generateHashValue(strippedName, FILE_HASH_SIZE); + for (sh = hashTable[hash]; sh; sh = sh->next) { + if (Q_stricmp(sh->name, strippedName) == 0) { + if (sh != sh2) { + sh->remappedShader = sh2; + } else { + sh->remappedShader = NULL; + } + } + } + if (timeOffset) { + sh2->timeOffset = atof(timeOffset); + } +} + +/* +=============== +ParseVector +=============== +*/ +static qboolean ParseVector( const char **text, int count, float *v ) { + char *token; + int i; + + // FIXME: spaces are currently required after parens, should change parseext... + token = COM_ParseExt( text, qfalse ); + if ( strcmp( token, "(" ) ) { + ri.Printf( PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + return qfalse; + } + + for ( i = 0 ; i < count ; i++ ) { + token = COM_ParseExt( text, qfalse ); + if ( !token[0] ) { + ri.Printf( PRINT_WARNING, "WARNING: missing vector element in shader '%s'\n", shader.name ); + return qfalse; + } + v[i] = atof( token ); + } + + token = COM_ParseExt( text, qfalse ); + if ( strcmp( token, ")" ) ) { + ri.Printf( PRINT_WARNING, "WARNING: missing parenthesis in shader '%s'\n", shader.name ); + return qfalse; + } + + return qtrue; +} + + +/* +=============== +ParseAlphaTestFunc +=============== +*/ +static void ParseAlphaTestFunc( shaderStage_t *stage, const char *funcname ) +{ + stage->alphaTestType = ALPHA_TEST_NONE; + + if ( !Q_stricmp( funcname, "GT0" ) ) + stage->alphaTestType = ALPHA_TEST_GT0; + else if ( !Q_stricmp( funcname, "LT128" ) ) + stage->alphaTestType = ALPHA_TEST_LT128; + else if ( !Q_stricmp( funcname, "GE128" ) ) + stage->alphaTestType = ALPHA_TEST_GE128; + else if ( !Q_stricmp( funcname, "GE192" ) ) + stage->alphaTestType = ALPHA_TEST_GE192; + else + ri.Printf( PRINT_WARNING, + "WARNING: invalid alphaFunc name '%s' in shader '%s'\n", + funcname, shader.name ); +} + + +/* +=============== +NameToSrcBlendMode +=============== +*/ +static int NameToSrcBlendMode( const char *name ) +{ + if ( !Q_stricmp( name, "GL_ONE" ) ) + { + return GLS_SRCBLEND_ONE; + } + else if ( !Q_stricmp( name, "GL_ZERO" ) ) + { + return GLS_SRCBLEND_ZERO; + } + else if ( !Q_stricmp( name, "GL_DST_COLOR" ) ) + { + return GLS_SRCBLEND_DST_COLOR; + } + else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_COLOR" ) ) + { + return GLS_SRCBLEND_ONE_MINUS_DST_COLOR; + } + else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) + { + return GLS_SRCBLEND_SRC_ALPHA; + } + else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) + { + return GLS_SRCBLEND_ONE_MINUS_SRC_ALPHA; + } + else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) + { + if ( r_ignoreDstAlpha->integer ) + { + return GLS_SRCBLEND_ONE; + } + + return GLS_SRCBLEND_DST_ALPHA; + } + else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) + { + if ( r_ignoreDstAlpha->integer ) + { + return GLS_SRCBLEND_ZERO; + } + + return GLS_SRCBLEND_ONE_MINUS_DST_ALPHA; + } + else if ( !Q_stricmp( name, "GL_SRC_ALPHA_SATURATE" ) ) + { + return GLS_SRCBLEND_ALPHA_SATURATE; + } + + ri.Printf( PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + return GLS_SRCBLEND_ONE; +} + +/* +=============== +NameToDstBlendMode +=============== +*/ +static int NameToDstBlendMode( const char *name ) +{ + if ( !Q_stricmp( name, "GL_ONE" ) ) + { + return GLS_DSTBLEND_ONE; + } + else if ( !Q_stricmp( name, "GL_ZERO" ) ) + { + return GLS_DSTBLEND_ZERO; + } + else if ( !Q_stricmp( name, "GL_SRC_ALPHA" ) ) + { + return GLS_DSTBLEND_SRC_ALPHA; + } + else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_ALPHA" ) ) + { + return GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } + else if ( !Q_stricmp( name, "GL_DST_ALPHA" ) ) + { + if ( r_ignoreDstAlpha->integer ) + { + return GLS_DSTBLEND_ONE; + } + + return GLS_DSTBLEND_DST_ALPHA; + } + else if ( !Q_stricmp( name, "GL_ONE_MINUS_DST_ALPHA" ) ) + { + if ( r_ignoreDstAlpha->integer ) + { + return GLS_DSTBLEND_ZERO; + } + + return GLS_DSTBLEND_ONE_MINUS_DST_ALPHA; + } + else if ( !Q_stricmp( name, "GL_SRC_COLOR" ) ) + { + return GLS_DSTBLEND_SRC_COLOR; + } + else if ( !Q_stricmp( name, "GL_ONE_MINUS_SRC_COLOR" ) ) + { + return GLS_DSTBLEND_ONE_MINUS_SRC_COLOR; + } + + ri.Printf( PRINT_WARNING, "WARNING: unknown blend mode '%s' in shader '%s', substituting GL_ONE\n", name, shader.name ); + return GLS_DSTBLEND_ONE; +} + +/* +=============== +NameToGenFunc +=============== +*/ +static genFunc_t NameToGenFunc( const char *funcname ) +{ + if ( !Q_stricmp( funcname, "sin" ) ) + { + return GF_SIN; + } + else if ( !Q_stricmp( funcname, "square" ) ) + { + return GF_SQUARE; + } + else if ( !Q_stricmp( funcname, "triangle" ) ) + { + return GF_TRIANGLE; + } + else if ( !Q_stricmp( funcname, "sawtooth" ) ) + { + return GF_SAWTOOTH; + } + else if ( !Q_stricmp( funcname, "inversesawtooth" ) ) + { + return GF_INVERSE_SAWTOOTH; + } + else if ( !Q_stricmp( funcname, "noise" ) ) + { + return GF_NOISE; + } + else if ( !Q_stricmp( funcname, "random" ) ) + { + return GF_RAND; + } + + ri.Printf( PRINT_WARNING, "WARNING: invalid genfunc name '%s' in shader '%s'\n", funcname, shader.name ); + return GF_SIN; +} + + +/* +=================== +ParseWaveForm +=================== +*/ +static void ParseWaveForm( const char **text, waveForm_t *wave ) +{ + char *token; + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + return; + } + wave->func = NameToGenFunc( token ); + + // BASE, AMP, PHASE, FREQ + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + return; + } + wave->base = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + return; + } + wave->amplitude = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + return; + } + wave->phase = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing waveform parm in shader '%s'\n", shader.name ); + return; + } + wave->frequency = atof( token ); +} + + +/* +=================== +ParseTexMod +=================== +*/ +static void ParseTexMod( const char *_text, shaderStage_t *stage ) +{ + const char *token; + const char **text = &_text; + texModInfo_t *tmi; + + if ( stage->bundle[0].numTexMods == TR_MAX_TEXMODS ) { + ri.Error( ERR_DROP, "ERROR: too many tcMod stages in shader '%s'", shader.name ); + return; + } + + tmi = &stage->bundle[0].texMods[stage->bundle[0].numTexMods]; + stage->bundle[0].numTexMods++; + + token = COM_ParseExt( text, qfalse ); + + // + // turb + // + if ( !Q_stricmp( token, "turb" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb parms in shader '%s'\n", shader.name ); + return; + } + tmi->wave.base = atof( token ); + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + return; + } + tmi->wave.amplitude = atof( token ); + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + return; + } + tmi->wave.phase = atof( token ); + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing tcMod turb in shader '%s'\n", shader.name ); + return; + } + tmi->wave.frequency = atof( token ); + + tmi->type = TMOD_TURBULENT; + } + // + // scale + // + else if ( !Q_stricmp( token, "scale" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name ); + return; + } + tmi->scale[0] = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing scale parms in shader '%s'\n", shader.name ); + return; + } + tmi->scale[1] = atof( token ); + tmi->type = TMOD_SCALE; + } + // + // scroll + // + else if ( !Q_stricmp( token, "scroll" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + return; + } + tmi->scroll[0] = atof( token ); + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing scale scroll parms in shader '%s'\n", shader.name ); + return; + } + tmi->scroll[1] = atof( token ); + tmi->type = TMOD_SCROLL; + } + // + // stretch + // + else if ( !Q_stricmp( token, "stretch" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + return; + } + tmi->wave.func = NameToGenFunc( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + return; + } + tmi->wave.base = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + return; + } + tmi->wave.amplitude = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + return; + } + tmi->wave.phase = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing stretch parms in shader '%s'\n", shader.name ); + return; + } + tmi->wave.frequency = atof( token ); + + tmi->type = TMOD_STRETCH; + } + // + // transform + // + else if ( !Q_stricmp( token, "transform" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + return; + } + tmi->matrix[0][0] = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + return; + } + tmi->matrix[0][1] = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + return; + } + tmi->matrix[1][0] = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + return; + } + tmi->matrix[1][1] = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + return; + } + tmi->translate[0] = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing transform parms in shader '%s'\n", shader.name ); + return; + } + tmi->translate[1] = atof( token ); + + tmi->type = TMOD_TRANSFORM; + } + // + // rotate + // + else if ( !Q_stricmp( token, "rotate" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing tcMod rotate parms in shader '%s'\n", shader.name ); + return; + } + tmi->rotateSpeed = atof( token ); + tmi->type = TMOD_ROTATE; + } + // + // entityTranslate + // + else if ( !Q_stricmp( token, "entityTranslate" ) ) + { + tmi->type = TMOD_ENTITY_TRANSLATE; + } + else + { + ri.Printf( PRINT_WARNING, "WARNING: unknown tcMod '%s' in shader '%s'\n", token, shader.name ); + } +} + +static animMapType_t AnimMapType( const char *token ) +{ + if ( !Q_stricmp( token, "clampanimMap" ) ) { return ANIMMAP_CLAMP; } + else if ( !Q_stricmp( token, "oneshotanimMap" ) ) { return ANIMMAP_ONESHOT; } + else { return ANIMMAP_NORMAL; } +} + +static const char *animMapNames[] = { + "animMap", + "clapanimMap", + "oneshotanimMap" +}; + +static bool ParseSurfaceSprites( const char *buffer, shaderStage_t *stage ) +{ + const char *token; + const char **text = &buffer; + surfaceSpriteType_t sstype = SURFSPRITE_NONE; + + // spritetype + token = COM_ParseExt( text, qfalse ); + if ( token[0] == '\0' ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", + shader.name); + return false; + } + + if ( !Q_stricmp(token, "vertical") ) + { + sstype = SURFSPRITE_VERTICAL; + } + else if ( !Q_stricmp(token, "oriented") ) + { + sstype = SURFSPRITE_ORIENTED; + } + else if ( !Q_stricmp(token, "effect") ) + { + sstype = SURFSPRITE_EFFECT; + } + else if ( !Q_stricmp(token, "flattened") ) + { + sstype = SURFSPRITE_FLATTENED; + } + else + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: invalid type in shader '%s'\n", + shader.name); + return false; + } + + // width + token = COM_ParseExt( text, qfalse ); + if ( token[0] == '\0' ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", + shader.name); + return false; + } + + float width = atof(token); + if ( width <= 0.0f ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: invalid width in shader '%s'\n", + shader.name); + return false; + } + + // height + token = COM_ParseExt( text, qfalse ); + if ( token[0] == '\0' ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", + shader.name); + return false; + } + + float height = atof(token); + if ( height <= 0.0f ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: invalid height in shader '%s'\n", + shader.name); + return false; + } + + // density + token = COM_ParseExt( text, qfalse ); + if ( token[0] == '\0' ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", + shader.name); + return false; + } + + float density = atof(token); + if ( density <= 0.0f ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: invalid density in shader '%s'\n", + shader.name); + return false; + } + + // fadedist + token = COM_ParseExt( text, qfalse ); + if ( token[0] == '\0' ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: missing surfaceSprites params in shader '%s'\n", + shader.name); + return false; + } + + float fadedist = atof(token); + if ( fadedist < 32.0f ) + { + ri.Printf(PRINT_ALL, + S_COLOR_YELLOW "WARNING: invalid fadedist (%.2f < 32) in shader '%s'\n", + fadedist, shader.name); + return false; + } + + if ( !stage->ss ) + { + stage->ss = (surfaceSprite_t *)Hunk_Alloc( sizeof( surfaceSprite_t ), h_low ); + + } + + // These are all set by the command lines. + stage->ss->type = sstype; + stage->ss->width = width; + stage->ss->height = height; + stage->ss->density = density; + stage->ss->fadeDist = fadedist; + + // These are defaults that can be overwritten. + stage->ss->fadeMax = fadedist * 1.33f; + stage->ss->fadeScale = 0.0f; + stage->ss->wind = 0.0f; + stage->ss->windIdle = 0.0f; + stage->ss->variance[0] = 0.0f; + stage->ss->variance[1] = 0.0f; + stage->ss->facing = SURFSPRITE_FACING_NORMAL; + + // A vertical parameter that needs a default regardless + stage->ss->vertSkew = 0.0f; + + // These are effect parameters that need defaults nonetheless. + stage->ss->fxDuration = 1000; // 1 second + stage->ss->fxGrow[0] = 0.0f; + stage->ss->fxGrow[1] = 0.0f; + stage->ss->fxAlphaStart = 1.0f; + stage->ss->fxAlphaEnd = 0.0f; + + return true; +} + +// Parses the following keywords in a shader stage: +// +// ssFademax +// ssFadescale +// ssVariance +// ssHangdown +// ssAnyangle +// ssFaceup +// ssWind +// ssWindIdle +// ssVertSkew +// ssFXDuration +// ssFXGrow +// ssFXAlphaRange +// ssFXWeather +static bool ParseSurfaceSpritesOptional( + const char *param, + const char *buffer, + shaderStage_t *stage +) +{ + const char *token; + const char **text = &buffer; + float value; + + if (!stage->ss) + { + stage->ss = (surfaceSprite_t *)Hunk_Alloc( sizeof( surfaceSprite_t ), h_low ); + } + + // TODO: Tidy this up some how. There's a lot of repeated code + + // + // fademax + // + if (!Q_stricmp(param, "ssFademax")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fademax in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value <= stage->ss->fadeDist) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fademax (%.2f <= fadeDist(%.2f)) in shader '%s'\n", value, stage->ss->fadeDist, shader.name ); + return false; + } + stage->ss->fadeMax=value; + return true; + } + + // + // fadescale + // + if (!Q_stricmp(param, "ssFadescale")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fadescale in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + stage->ss->fadeScale=value; + return true; + } + + // + // variance + // + if (!Q_stricmp(param, "ssVariance")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance width in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance width in shader '%s'\n", shader.name ); + return false; + } + stage->ss->variance[0]=value; + + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite variance height in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite variance height in shader '%s'\n", shader.name ); + return false; + } + stage->ss->variance[1]=value; + return true; + } + + // + // hangdown + // + if (!Q_stricmp(param, "ssHangdown")) + { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Hangdown facing overrides previous facing in shader '%s'\n", shader.name ); + return false; + } + stage->ss->facing=SURFSPRITE_FACING_DOWN; + return true; + } + + // + // anyangle + // + if (!Q_stricmp(param, "ssAnyangle")) + { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Anyangle facing overrides previous facing in shader '%s'\n", shader.name ); + return false; + } + stage->ss->facing=SURFSPRITE_FACING_ANY; + return true; + } + + // + // faceup + // + if (!Q_stricmp(param, "ssFaceup")) + { + if (stage->ss->facing != SURFSPRITE_FACING_NORMAL) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: Faceup facing overrides previous facing in shader '%s'\n", shader.name ); + return false; + } + stage->ss->facing=SURFSPRITE_FACING_UP; + return true; + } + + // + // wind + // + if (!Q_stricmp(param, "ssWind")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite wind in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0.0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite wind in shader '%s'\n", shader.name ); + return false; + } + stage->ss->wind=value; + if (stage->ss->windIdle <= 0) + { // Also override the windidle, it usually is the same as wind + stage->ss->windIdle = value; + } + return true; + } + + // + // windidle + // + if (!Q_stricmp(param, "ssWindidle")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite windidle in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0.0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite windidle in shader '%s'\n", shader.name ); + return false; + } + stage->ss->windIdle=value; + return true; + } + + // + // vertskew + // + if (!Q_stricmp(param, "ssVertskew")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite vertskew in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0.0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite vertskew in shader '%s'\n", shader.name ); + return false; + } + stage->ss->vertSkew=value; + return true; + } + + // + // fxduration + // + if (!Q_stricmp(param, "ssFXDuration")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite duration in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value <= 0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite duration in shader '%s'\n", shader.name ); + return false; + } + stage->ss->fxDuration=value; + return true; + } + + // + // fxgrow + // + if (!Q_stricmp(param, "ssFXGrow")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow width in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow width in shader '%s'\n", shader.name ); + return false; + } + stage->ss->fxGrow[0]=value; + + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite grow height in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite grow height in shader '%s'\n", shader.name ); + return false; + } + stage->ss->fxGrow[1]=value; + return true; + } + + // + // fxalpharange + // + if (!Q_stricmp(param, "ssFXAlphaRange")) + { + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha start in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0 || value > 1.0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha start in shader '%s'\n", shader.name ); + return false; + } + stage->ss->fxAlphaStart=value; + + token = COM_ParseExt( text, qfalse); + if (token[0]==0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: missing surfacesprite fxalpha end in shader '%s'\n", shader.name ); + return false; + } + value = atof(token); + if (value < 0 || value > 1.0) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid surfacesprite fxalpha end in shader '%s'\n", shader.name ); + return false; + } + stage->ss->fxAlphaEnd=value; + return true; + } + + // + // fxweather + // + if (!Q_stricmp(param, "ssFXWeather")) + { + if (stage->ss->type != SURFSPRITE_EFFECT) + { + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: weather applied to non-effect surfacesprite in shader '%s'\n", shader.name ); + return false; + } + stage->ss->type = SURFSPRITE_WEATHERFX; + return true; + } + + // + // invalid ss command. + // + ri.Printf( PRINT_ALL, S_COLOR_YELLOW "WARNING: invalid optional surfacesprite param '%s' in shader '%s'\n", param, shader.name ); + return false; +} + +/* +=================== +ParseStage +=================== +*/ +static qboolean ParseStage( shaderStage_t *stage, const char **text ) +{ + char *token; + unsigned depthMaskBits = GLS_DEPTHMASK_TRUE; + unsigned blendSrcBits = 0; + unsigned blendDstBits = 0; + unsigned depthFuncBits = 0; + qboolean depthMaskExplicit = qfalse; + char bufferPackedTextureName[MAX_QPATH]; + char bufferBaseColorTextureName[MAX_QPATH]; + + stage->active = qtrue; + stage->specularType = SPEC_NONE; + + while ( 1 ) + { + token = COM_ParseExt( text, qtrue ); + if ( !token[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: no matching '}' found\n" ); + return qfalse; + } + + if ( token[0] == '}' ) + { + break; + } + // + // map or clampmap + // + else if ( !Q_stricmp( token, "map" ) || (!Q_stricmp(token, "clampmap"))) + { + int flags = !Q_stricmp(token, "clampmap") ? IMGFLAG_CLAMPTOEDGE : IMGFLAG_NONE; + + token = COM_ParseExt( text, qfalse ); + if ( !token[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'map' keyword in shader '%s'\n", shader.name); + return qfalse; + } + + if ( !Q_stricmp( token, "$whiteimage" ) ) + { + stage->bundle[0].image[0] = tr.whiteImage; + continue; + } + else if ( !Q_stricmp( token, "$lightmap" ) ) + { + stage->bundle[0].isLightmap = qtrue; + if ( shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps ) { +#ifndef FINAL_BUILD + ri.Printf (PRINT_ALL, S_COLOR_RED "Lightmap requested but none avilable for shader '%s'\n", shader.name); +#endif + stage->bundle[0].image[0] = tr.whiteImage; + } else { + stage->bundle[0].image[0] = tr.lightmaps[shader.lightmapIndex[0]]; + if (r_deluxeMapping->integer && tr.worldDeluxeMapping) + stage->bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[0]]; + } + continue; + } + else if ( !Q_stricmp( token, "$deluxemap" ) ) + { + if (!tr.worldDeluxeMapping) + { + ri.Printf( PRINT_WARNING, "WARNING: shader '%s' wants a deluxe map in a map compiled without them\n", shader.name ); + return qfalse; + } + + stage->bundle[0].isLightmap = qtrue; + if ( shader.lightmapIndex[0] < 0 || shader.lightmapIndex[0] >= tr.numLightmaps ) { + stage->bundle[0].image[0] = tr.whiteImage; + } else { + stage->bundle[0].image[0] = tr.deluxemaps[shader.lightmapIndex[0]]; + } + continue; + } + else + { + imgType_t type = IMGTYPE_COLORALPHA; + + if (!shader.noMipMaps) + flags |= IMGFLAG_MIPMAP; + + if (!shader.noPicMip) + flags |= IMGFLAG_PICMIP; + + if (shader.noTC) + flags |= IMGFLAG_NO_COMPRESSION; + + if (r_genNormalMaps->integer) + flags |= IMGFLAG_GENNORMALMAP; + + if (shader.isHDRLit == qtrue) + flags |= IMGFLAG_SRGB; + + Q_strncpyz(bufferBaseColorTextureName, token, sizeof(bufferBaseColorTextureName)); + stage->bundle[0].image[0] = R_FindImageFile(bufferBaseColorTextureName, type, flags); + + if ( !stage->bundle[0].image[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + return qfalse; + } + } + } + // + // normalMap or normalHeightMap + // + else if (!Q_stricmp(token, "normalMap") || !Q_stricmp(token, "normalHeightMap")) + { + imgType_t type = !Q_stricmp(token, "normalHeightMap") ? IMGTYPE_NORMALHEIGHT : IMGTYPE_NORMAL; + + token = COM_ParseExt(text, qfalse); + if (!token[0]) + { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'normalMap' keyword in shader '%s'\n", shader.name); + return qfalse; + } + + int flags = IMGFLAG_NONE; + + if (!shader.noMipMaps) + flags |= IMGFLAG_MIPMAP; + + if (!shader.noPicMip) + flags |= IMGFLAG_PICMIP; + + if (shader.noTC) + flags |= IMGFLAG_NO_COMPRESSION; + + flags |= IMGFLAG_NOLIGHTSCALE; + stage->bundle[TB_NORMALMAP].image[0] = R_FindImageFile(token, type, flags); + + if (!stage->bundle[TB_NORMALMAP].image[0]) + { + ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find normalMap '%s' in shader '%s'\n", token, shader.name); + return qfalse; + } + + VectorSet4(stage->normalScale, r_baseNormalX->value, r_baseNormalY->value, 1.0f, r_baseParallax->value); + } + // + // specMap || specularMap + // + else if (!Q_stricmp(token, "specMap") || !Q_stricmp(token, "specularMap")) + { + imgType_t type = IMGTYPE_COLORALPHA; + + token = COM_ParseExt(text, qfalse); + if (!token[0]) + { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'specularMap' keyword in shader '%s'\n", shader.name); + return qfalse; + } + + stage->specularType = SPEC_SPECGLOSS; + VectorSet4(stage->specularScale, 1.0f, 1.0f, 1.0f, 0.0f); + if (!Q_stricmp(token, "$whiteimage")) + { + stage->bundle[TB_SPECULARMAP].image[0] = tr.whiteImage; + continue; + } + + int flags = IMGFLAG_NONE; + + if (!shader.noMipMaps) + flags |= IMGFLAG_MIPMAP; + + if (!shader.noPicMip) + flags |= IMGFLAG_PICMIP; + + if (shader.noTC) + flags |= IMGFLAG_NO_COMPRESSION; + + // Always srgb to have correct reflectivity + if (shader.isHDRLit == qtrue) + stage->bundle[TB_SPECULARMAP].image[0] = R_FindImageFile(token, type, flags | IMGFLAG_SRGB); + else + stage->bundle[TB_SPECULARMAP].image[0] = R_BuildSDRSpecGlossImage(stage, token, flags); + + if (!stage->bundle[TB_SPECULARMAP].image[0]) + { + ri.Printf(PRINT_WARNING, "WARNING: R_FindImageFile could not find specMap '%s' in shader '%s'\n", token, shader.name); + return qfalse; + } + + } + // + // rmoMap || rmosMap + // + else if (!Q_stricmp(token, "rmoMap") || !Q_stricmp(token, "rmosMap")) + { + token = COM_ParseExt(text, qfalse); + if (!token[0]) + { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'rmoMap' keyword in shader '%s'\n", shader.name); + return qfalse; + } + stage->specularType = !Q_stricmp(token, "rmosMap") ? SPEC_RMOS : SPEC_RMO; + if (!Q_stricmp(token, "$whiteimage")) + { + stage->bundle[TB_SPECULARMAP].image[0] = tr.whiteImage; + continue; + } + Q_strncpyz(bufferPackedTextureName, token, sizeof(bufferPackedTextureName)); + } + // + // moxrMap || mosrMap + // + else if (!Q_stricmp(token, "moxrMap") || !Q_stricmp(token, "mosrMap")) + { + token = COM_ParseExt(text, qfalse); + if (!token[0]) + { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'moxrMap' keyword in shader '%s'\n", shader.name); + return qfalse; + } + stage->specularType = !Q_stricmp(token, "mosrMap") ? SPEC_MOSR : SPEC_MOXR; + if (!Q_stricmp(token, "$whiteimage")) + { + stage->bundle[TB_SPECULARMAP].image[0] = tr.whiteImage; + continue; + } + Q_strncpyz(bufferPackedTextureName, token, sizeof(bufferPackedTextureName)); + } + // + // ormMap || ormsMap + // + else if (!Q_stricmp(token, "ormMap") || !Q_stricmp(token, "ormsMap")) + { + token = COM_ParseExt(text, qfalse); + if (!token[0]) + { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for 'ormMap' keyword in shader '%s'\n", shader.name); + return qfalse; + } + stage->specularType = !Q_stricmp(token, "ormsMap") ? SPEC_ORMS : SPEC_ORM; + if (!Q_stricmp(token, "$whiteimage")) + { + stage->bundle[TB_SPECULARMAP].image[0] = tr.whiteImage; + continue; + } + Q_strncpyz(bufferPackedTextureName, token, sizeof(bufferPackedTextureName)); + } + // + // animMap .... + // + else if ( !Q_stricmp( token, "animMap" ) || !Q_stricmp( token, "clampanimMap" ) || !Q_stricmp( token, "oneshotanimMap" ) ) + { + animMapType_t type = AnimMapType( token ); + token = COM_ParseExt( text, qfalse ); + if ( !token[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for '%s' keyword in shader '%s'\n", animMapNames[type], shader.name ); + return qfalse; + } + stage->bundle[0].imageAnimationSpeed = atof( token ); + stage->bundle[0].oneShotAnimMap = (qboolean)(type == ANIMMAP_ONESHOT); + + // parse up to MAX_IMAGE_ANIMATIONS animations + while ( 1 ) { + int num; + + token = COM_ParseExt( text, qfalse ); + if ( !token[0] ) { + break; + } + num = stage->bundle[0].numImageAnimations; + if ( num < MAX_IMAGE_ANIMATIONS ) { + imgType_t imgtype = IMGTYPE_COLORALPHA; + int flags = type == ANIMMAP_CLAMP ? IMGFLAG_CLAMPTOEDGE : IMGFLAG_NONE; + + if (!shader.noMipMaps) + flags |= IMGFLAG_MIPMAP; + + if (!shader.noPicMip) + flags |= IMGFLAG_PICMIP; + + if (shader.isHDRLit == qtrue) + flags |= IMGFLAG_SRGB; + + if (shader.noTC) + flags |= IMGFLAG_NO_COMPRESSION; + + if (r_genNormalMaps->integer) + flags |= IMGFLAG_GENNORMALMAP; + + stage->bundle[0].image[num] = R_FindImageFile( token, imgtype, flags ); + if ( !stage->bundle[0].image[num] ) + { + ri.Printf( PRINT_WARNING, "WARNING: R_FindImageFile could not find '%s' in shader '%s'\n", token, shader.name ); + return qfalse; + } + stage->bundle[0].numImageAnimations++; + } + } + } + else if ( !Q_stricmp( token, "videoMap" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( !token[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'videoMap' keyword in shader '%s'\n", shader.name ); + return qfalse; + } + stage->bundle[0].videoMapHandle = ri.CIN_PlayCinematic( token, 0, 0, 256, 256, (CIN_loop | CIN_silent | CIN_shader)); + if (stage->bundle[0].videoMapHandle != -1) { + stage->bundle[0].isVideoMap = qtrue; + stage->bundle[0].image[0] = tr.scratchImage[stage->bundle[0].videoMapHandle]; + } + } + // + // alphafunc + // + else if ( !Q_stricmp( token, "alphaFunc" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( !token[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'alphaFunc' keyword in shader '%s'\n", shader.name ); + return qfalse; + } + + ParseAlphaTestFunc( stage, token ); + } + // + // depthFunc + // + else if ( !Q_stricmp( token, "depthfunc" ) ) + { + token = COM_ParseExt( text, qfalse ); + + if ( !token[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for 'depthfunc' keyword in shader '%s'\n", shader.name ); + return qfalse; + } + + if ( !Q_stricmp( token, "lequal" ) ) + { + depthFuncBits = 0; + } + else if ( !Q_stricmp( token, "equal" ) ) + { + depthFuncBits = GLS_DEPTHFUNC_EQUAL; + } + else if ( !Q_stricmp( token, "disable" ) ) + { + depthFuncBits = GLS_DEPTHTEST_DISABLE; + } + else + { + ri.Printf( PRINT_WARNING, "WARNING: unknown depthfunc '%s' in shader '%s'\n", token, shader.name ); + continue; + } + } + // + // detail + // + else if ( !Q_stricmp( token, "detail" ) ) + { + stage->isDetail = qtrue; + } + // + // blendfunc + // or blendfunc + // + else if ( !Q_stricmp( token, "blendfunc" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + continue; + } + // check for "simple" blends first + if ( !Q_stricmp( token, "add" ) ) { + blendSrcBits = GLS_SRCBLEND_ONE; + blendDstBits = GLS_DSTBLEND_ONE; + } else if ( !Q_stricmp( token, "filter" ) ) { + blendSrcBits = GLS_SRCBLEND_DST_COLOR; + blendDstBits = GLS_DSTBLEND_ZERO; + } else if ( !Q_stricmp( token, "blend" ) ) { + blendSrcBits = GLS_SRCBLEND_SRC_ALPHA; + blendDstBits = GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } else { + // complex double blends + blendSrcBits = NameToSrcBlendMode( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parm for blendFunc in shader '%s'\n", shader.name ); + continue; + } + blendDstBits = NameToDstBlendMode( token ); + } + + // clear depth mask for blended surfaces + if ( !depthMaskExplicit ) + { + depthMaskBits = 0; + } + } + // + // specularReflectance + // + else if (!Q_stricmp(token, "specularreflectance")) + { + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for specular reflectance in shader '%s'\n", shader.name ); + continue; + } + stage->specularScale[0] = + stage->specularScale[1] = + stage->specularScale[2] = Com_Clamp( 0.0f, 1.0f, atof( token ) ); + } + // + // specularExponent + // + else if (!Q_stricmp(token, "specularexponent")) + { + float exponent; + + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for specular exponent in shader '%s'\n", shader.name ); + continue; + } + exponent = atof( token ); + + // Change shininess to gloss + // FIXME: assumes max exponent of 8192 and min of 1, must change here if altered in lightall_fp.glsl + exponent = CLAMP(exponent, 1.0, 8192.0); + stage->specularScale[3] = 1.0f - (log(exponent) / log(8192.0)); + } + // + // gloss + // + else if ( !Q_stricmp( token, "gloss" ) ) + { + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for gloss in shader '%s'\n", shader.name ); + continue; + } + + stage->specularScale[3] = 1.0 - atof( token ); + } + // + // roughness + // + else if (!Q_stricmp(token, "roughness")) + { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) + { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for roughness in shader '%s'\n", shader.name); + continue; + } + + stage->specularScale[3] = atof(token); + } + // + // parallaxDepth + // + else if (!Q_stricmp(token, "parallaxdepth")) + { + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for parallaxDepth in shader '%s'\n", shader.name ); + continue; + } + + stage->normalScale[3] = atof( token ); + } + // + // parallaxBias + // + else if (!Q_stricmp(token, "parallaxbias")) + { + token = COM_ParseExt(text, qfalse); + if (token[0] == 0) + { + ri.Printf(PRINT_WARNING, "WARNING: missing parameter for parallaxBias in shader '%s'\n", shader.name); + continue; + } + + stage->parallaxBias = atof(token); + } + // + // normalScale + // or normalScale + // or normalScale + // + else if (!Q_stricmp(token, "normalscale")) + { + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for normalScale in shader '%s'\n", shader.name ); + continue; + } + + stage->normalScale[0] = atof( token ); + + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + // one value, applies to X/Y + stage->normalScale[1] = stage->normalScale[0]; + continue; + } + + stage->normalScale[1] = atof( token ); + + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + // two values, no height + continue; + } + + stage->normalScale[3] = atof( token ); + } + // + // specularScale + // or specularScale + // or specularScale + // or specularScale when metal roughness workflow is used + // + else if (!Q_stricmp(token, "specularscale")) + { + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for specularScale in shader '%s'\n", shader.name ); + continue; + } + + stage->specularScale[0] = atof( token ); + + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameter for specularScale in shader '%s'\n", shader.name ); + continue; + } + + stage->specularScale[1] = atof( token ); + + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + // two values, rgb then gloss + stage->specularScale[3] = 1.0 - stage->specularScale[1]; + stage->specularScale[1] = + stage->specularScale[2] = stage->specularScale[0]; + continue; + } + + stage->specularScale[2] = atof( token ); + + token = COM_ParseExt(text, qfalse); + if ( token[0] == 0 ) + { + // three values, rgb + continue; + } + + stage->specularScale[3] = 1.0 - atof( token ); + } + // + // rgbGen + // + else if ( !Q_stricmp( token, "rgbGen" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameters for rgbGen in shader '%s'\n", shader.name ); + continue; + } + + if ( !Q_stricmp( token, "wave" ) ) + { + ParseWaveForm( text, &stage->rgbWave ); + stage->rgbGen = CGEN_WAVEFORM; + } + else if ( !Q_stricmp( token, "const" ) ) + { + vec3_t color; + + ParseVector( text, 3, color ); + stage->constantColor[0] = color[0]; + stage->constantColor[1] = color[1]; + stage->constantColor[2] = color[2]; + if (tr.hdrLighting == qfalse) + { + stage->constantColor[0] = MIN(color[0], 1.0f); + stage->constantColor[1] = MIN(color[1], 1.0f); + stage->constantColor[2] = MIN(color[2], 1.0f); + } + + stage->rgbGen = CGEN_CONST; + } + else if ( !Q_stricmp( token, "identity" ) ) + { + stage->rgbGen = CGEN_IDENTITY; + } + else if ( !Q_stricmp( token, "identityLighting" ) ) + { + stage->rgbGen = CGEN_IDENTITY_LIGHTING; + } + else if ( !Q_stricmp( token, "entity" ) ) + { + stage->rgbGen = CGEN_ENTITY; + } + else if ( !Q_stricmp( token, "oneMinusEntity" ) ) + { + stage->rgbGen = CGEN_ONE_MINUS_ENTITY; + } + else if ( !Q_stricmp( token, "vertex" ) ) + { + stage->rgbGen = CGEN_VERTEX; + if ( stage->alphaGen == 0 ) { + stage->alphaGen = AGEN_VERTEX; + } + } + else if ( !Q_stricmp( token, "exactVertex" ) ) + { + stage->rgbGen = CGEN_EXACT_VERTEX; + } + else if ( !Q_stricmp( token, "vertexLit" ) ) + { + stage->rgbGen = CGEN_VERTEX_LIT; + if ( stage->alphaGen == 0 ) { + stage->alphaGen = AGEN_VERTEX; + } + } + else if ( !Q_stricmp( token, "exactVertexLit" ) ) + { + stage->rgbGen = CGEN_EXACT_VERTEX_LIT; + } + else if ( !Q_stricmp( token, "lightingDiffuse" ) ) + { + stage->rgbGen = CGEN_LIGHTING_DIFFUSE; + } + else if ( !Q_stricmp( token, "lightingDiffuseEntity" ) ) + { + if (shader.lightmapIndex[0] != LIGHTMAP_NONE) + { + Com_Printf( S_COLOR_RED "ERROR: rgbGen lightingDiffuseEntity used on a misc_model! in shader '%s'\n", shader.name ); + } + stage->rgbGen = CGEN_LIGHTING_DIFFUSE_ENTITY; + } + else if ( !Q_stricmp( token, "oneMinusVertex" ) ) + { + stage->rgbGen = CGEN_ONE_MINUS_VERTEX; + } + else + { + ri.Printf( PRINT_WARNING, "WARNING: unknown rgbGen parameter '%s' in shader '%s'\n", token, shader.name ); + continue; + } + } + // + // alphaGen + // + else if ( !Q_stricmp( token, "alphaGen" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parameters for alphaGen in shader '%s'\n", shader.name ); + continue; + } + + if ( !Q_stricmp( token, "wave" ) ) + { + ParseWaveForm( text, &stage->alphaWave ); + stage->alphaGen = AGEN_WAVEFORM; + } + else if ( !Q_stricmp( token, "const" ) ) + { + token = COM_ParseExt( text, qfalse ); + stage->constantColor[3] = atof( token ); + stage->alphaGen = AGEN_CONST; + } + else if ( !Q_stricmp( token, "identity" ) ) + { + stage->alphaGen = AGEN_IDENTITY; + } + else if ( !Q_stricmp( token, "entity" ) ) + { + stage->alphaGen = AGEN_ENTITY; + } + else if ( !Q_stricmp( token, "oneMinusEntity" ) ) + { + stage->alphaGen = AGEN_ONE_MINUS_ENTITY; + } + else if ( !Q_stricmp( token, "vertex" ) ) + { + stage->alphaGen = AGEN_VERTEX; + } + else if ( !Q_stricmp( token, "lightingSpecular" ) ) + { + stage->alphaGen = AGEN_LIGHTING_SPECULAR; + } + else if ( !Q_stricmp( token, "oneMinusVertex" ) ) + { + stage->alphaGen = AGEN_ONE_MINUS_VERTEX; + } + else if ( !Q_stricmp( token, "dot" ) ) + { + //stage->alphaGen = AGEN_DOT; + } + else if ( !Q_stricmp( token, "oneMinusDot" ) ) + { + //stage->alphaGen = AGEN_ONE_MINUS_DOT; + } + else if ( !Q_stricmp( token, "portal" ) ) + { + stage->alphaGen = AGEN_PORTAL; + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + shader.portalRange = 256; + ri.Printf( PRINT_WARNING, "WARNING: missing range parameter for alphaGen portal in shader '%s', defaulting to 256\n", shader.name ); + } + else + { + shader.portalRange = atof( token ); + } + } + else + { + ri.Printf( PRINT_WARNING, "WARNING: unknown alphaGen parameter '%s' in shader '%s'\n", token, shader.name ); + continue; + } + } + // + // tcGen + // + else if ( !Q_stricmp(token, "texgen") || !Q_stricmp( token, "tcGen" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing texgen parm in shader '%s'\n", shader.name ); + continue; + } + + if ( !Q_stricmp( token, "environment" ) ) + { + stage->bundle[0].tcGen = TCGEN_ENVIRONMENT_MAPPED; + } + else if ( !Q_stricmp( token, "lightmap" ) ) + { + stage->bundle[0].tcGen = TCGEN_LIGHTMAP; + } + else if ( !Q_stricmp( token, "texture" ) || !Q_stricmp( token, "base" ) ) + { + stage->bundle[0].tcGen = TCGEN_TEXTURE; + } + else if ( !Q_stricmp( token, "vector" ) ) + { + ParseVector( text, 3, stage->bundle[0].tcGenVectors[0] ); + ParseVector( text, 3, stage->bundle[0].tcGenVectors[1] ); + + stage->bundle[0].tcGen = TCGEN_VECTOR; + } + else + { + ri.Printf( PRINT_WARNING, "WARNING: unknown texgen parm in shader '%s'\n", shader.name ); + } + } + // + // tcMod <...> + // + else if ( !Q_stricmp( token, "tcMod" ) ) + { + char buffer[1024] = ""; + + while ( 1 ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + break; + Q_strcat( buffer, sizeof( buffer ), token ); + Q_strcat( buffer, sizeof( buffer ), " " ); + } + + ParseTexMod( buffer, stage ); + + continue; + } + // + // depthmask + // + else if ( !Q_stricmp( token, "depthwrite" ) ) + { + depthMaskBits = GLS_DEPTHMASK_TRUE; + depthMaskExplicit = qtrue; + + continue; + } + // If this stage has glow... GLOWXXX + else if ( Q_stricmp( token, "glow" ) == 0 ) + { + stage->glow = qtrue; + + continue; + } + // + // If this stage is cloth + else if (Q_stricmp(token, "cloth") == 0) + { + stage->cloth = qtrue; + + continue; + } + // surfaceSprites ... + // + else if ( !Q_stricmp( token, "surfacesprites" ) ) + { + char buffer[1024] = {}; + + while ( 1 ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + break; + Q_strcat( buffer, sizeof( buffer ), token ); + Q_strcat( buffer, sizeof( buffer ), " " ); + } + + bool hasSS = (stage->ss != nullptr); + if ( ParseSurfaceSprites( buffer, stage ) && !hasSS ) + { + ++shader.numSurfaceSpriteStages; + } + + continue; + } + // + // ssFademax + // ssFadescale + // ssVariance + // ssHangdown + // ssAnyangle + // ssFaceup + // ssWind + // ssWindIdle + // ssDuration + // ssGrow + // ssWeather + // + else if (!Q_stricmpn(token, "ss", 2)) + { + char buffer[1024] = {}; + char param[128] = {}; + Q_strncpyz( param, token, sizeof( param ) ); + + while ( 1 ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == '\0' ) + break; + Q_strcat( buffer, sizeof( buffer ), token ); + Q_strcat( buffer, sizeof( buffer ), " " ); + } + + bool hasSS = (stage->ss != nullptr); + if ( ParseSurfaceSpritesOptional( param, buffer, stage ) && !hasSS ) + { + ++shader.numSurfaceSpriteStages; + } + + continue; + } + else + { + ri.Printf( PRINT_WARNING, "WARNING: unknown parameter '%s' in shader '%s'\n", token, shader.name ); + return qfalse; + } + } + + // + // load packed textures + // + if (stage->specularType != SPEC_SPECGLOSS && stage->specularType != SPEC_NONE) + { + int flags = IMGFLAG_NOLIGHTSCALE; + + if (!shader.noMipMaps) + flags |= IMGFLAG_MIPMAP; + + if (!shader.noPicMip) + flags |= IMGFLAG_PICMIP; + + if (shader.noTC) + flags |= IMGFLAG_NO_COMPRESSION; + + R_LoadPackedMaterialImage(stage, bufferPackedTextureName, flags); + } + + // + // search for shader based external lightmaps that were created by q3map2 + // + if (stage->bundle[0].tcGen == TCGEN_LIGHTMAP && stage->bundle[0].isLightmap == qfalse) + { + const char *filename = { va("%s/lm_", tr.worldName) }; + if (!Q_strncmp(filename, bufferBaseColorTextureName, sizeof(filename))) + { + if (shader.isHDRLit) + { + image_t *hdrImage = R_FindImageFile(bufferBaseColorTextureName, IMGTYPE_COLORALPHA, IMGFLAG_NOLIGHTSCALE | IMGFLAG_HDR_LIGHTMAP | IMGFLAG_NO_COMPRESSION | IMGFLAG_CLAMPTOEDGE); + if (hdrImage) + stage->bundle[0].image[0] = hdrImage; + } + + stage->bundle[0].isLightmap = qtrue; + shader.lightmapIndex[0] = LIGHTMAP_EXTERNAL; + + // shader based external lightmaps can't utilize lightstyles + shader.styles[0] = 0; + shader.styles[1] = 255; + shader.styles[2] = 255; + shader.styles[3] = 255; + + // it obviously receives light, so receive dlights too + shader.surfaceFlags &= ~SURF_NODLIGHT; + } + } + + // + // if cgen isn't explicitly specified, use either identity or identitylighting + // + if ( stage->rgbGen == CGEN_BAD ) { + if ( blendSrcBits == 0 || + blendSrcBits == GLS_SRCBLEND_ONE || + blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) { + stage->rgbGen = CGEN_IDENTITY_LIGHTING; + } else { + stage->rgbGen = CGEN_IDENTITY; + } + } + + + // + // implicitly assume that a GL_ONE GL_ZERO blend mask disables blending + // + if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && + ( blendDstBits == GLS_DSTBLEND_ZERO ) ) + { + blendDstBits = blendSrcBits = 0; + depthMaskBits = GLS_DEPTHMASK_TRUE; + } + + // decide which agens we can skip + if ( stage->alphaGen == AGEN_IDENTITY ) { + if ( stage->rgbGen == CGEN_IDENTITY + || stage->rgbGen == CGEN_LIGHTING_DIFFUSE ) { + stage->alphaGen = AGEN_SKIP; + } + } + + // + // compute state bits + // + stage->stateBits = depthMaskBits | + blendSrcBits | blendDstBits | + depthFuncBits; + + return qtrue; +} + +/* +=============== +ParseDeform + +deformVertexes wave +deformVertexes normal +deformVertexes move +deformVertexes bulge +deformVertexes projectionShadow +deformVertexes autoSprite +deformVertexes autoSprite2 +deformVertexes text[0-7] +=============== +*/ +static void ParseDeform( const char **text ) { + char *token; + deformStage_t *ds; + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing deform parm in shader '%s'\n", shader.name ); + return; + } + + if ( shader.numDeforms == MAX_SHADER_DEFORMS ) { + ri.Printf( PRINT_WARNING, "WARNING: MAX_SHADER_DEFORMS in '%s'\n", shader.name ); + return; + } + + ds = &shader.deforms[ shader.numDeforms ]; + shader.numDeforms++; + + if ( !Q_stricmp( token, "projectionShadow" ) ) { + ds->deformation = DEFORM_PROJECTION_SHADOW; + return; + } + + if ( !Q_stricmp( token, "autosprite" ) ) { + ds->deformation = DEFORM_AUTOSPRITE; + return; + } + + if ( !Q_stricmp( token, "autosprite2" ) ) { + ds->deformation = DEFORM_AUTOSPRITE2; + return; + } + + if ( !Q_stricmpn( token, "text", 4 ) ) { + int n; + + n = token[4] - '0'; + if ( n < 0 || n > 7 ) { + n = 0; + } + ds->deformation = (deform_t)(DEFORM_TEXT0 + n); + return; + } + + if ( !Q_stricmp( token, "bulge" ) ) { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + return; + } + ds->bulgeWidth = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + return; + } + ds->bulgeHeight = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes bulge parm in shader '%s'\n", shader.name ); + return; + } + ds->bulgeSpeed = atof( token ); + + ds->deformation = DEFORM_BULGE; + return; + } + + if ( !Q_stricmp( token, "wave" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + return; + } + + if ( atof( token ) != 0 ) + { + ds->deformationSpread = 1.0f / atof( token ); + } + else + { + ds->deformationSpread = 100.0f; + ri.Printf( PRINT_WARNING, "WARNING: illegal div value of 0 in deformVertexes command for shader '%s'\n", shader.name ); + } + + ParseWaveForm( text, &ds->deformationWave ); + ds->deformation = DEFORM_WAVE; + return; + } + + if ( !Q_stricmp( token, "normal" ) ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + return; + } + ds->deformationWave.amplitude = atof( token ); + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + return; + } + ds->deformationWave.frequency = atof( token ); + + ds->deformation = DEFORM_NORMALS; + return; + } + + if ( !Q_stricmp( token, "move" ) ) { + int i; + + for ( i = 0 ; i < 3 ; i++ ) { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) { + ri.Printf( PRINT_WARNING, "WARNING: missing deformVertexes parm in shader '%s'\n", shader.name ); + return; + } + ds->moveVector[i] = atof( token ); + } + + ParseWaveForm( text, &ds->deformationWave ); + ds->deformation = DEFORM_MOVE; + return; + } + + ri.Printf( PRINT_WARNING, "WARNING: unknown deformVertexes subtype '%s' found in shader '%s'\n", token, shader.name ); +} + + +/* +=============== +ParseSkyParms + +skyParms +=============== +*/ +static void ParseSkyParms( const char **text ) { + char *token; + static const char *suf[6] = {"rt", "lf", "bk", "ft", "up", "dn"}; + char pathname[MAX_QPATH]; + int i; + int imgFlags = IMGFLAG_MIPMAP | IMGFLAG_PICMIP | IMGFLAG_CLAMPTOEDGE; + + if (shader.noTC) + imgFlags |= IMGFLAG_NO_COMPRESSION; + + if (tr.hdrLighting == qtrue) + imgFlags |= IMGFLAG_SRGB | IMGFLAG_HDR | IMGFLAG_NOLIGHTSCALE; // srgb or hdr are requested. If hdr is found, the srgb flag will be ignored + + // outerbox + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) { + ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing parameter in shader '%s'\n", shader.name ); + return; + } + if ( strcmp( token, "-" ) ) { + for (i=0 ; i<6 ; i++) { + Com_sprintf( pathname, sizeof(pathname), "%s_%s", token, suf[i] ); + shader.sky.outerbox[i] = R_FindImageFile( ( char * ) pathname, IMGTYPE_COLORALPHA, imgFlags ); + + if ( !shader.sky.outerbox[i] ) { + if ( i ) + shader.sky.outerbox[i] = shader.sky.outerbox[i-1]; //not found, so let's use the previous image + else + shader.sky.outerbox[i] = tr.defaultImage; + } + } + } + + // cloudheight + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) { + ri.Printf( PRINT_WARNING, "WARNING: 'skyParms' missing cloudheight in shader '%s'\n", shader.name ); + return; + } + shader.sky.cloudHeight = atof( token ); + if ( !shader.sky.cloudHeight ) { + shader.sky.cloudHeight = 512; + } + R_InitSkyTexCoords( shader.sky.cloudHeight ); + + // innerbox + token = COM_ParseExt( text, qfalse ); + if ( strcmp( token, "-" ) ) { + ri.Printf( PRINT_WARNING, "WARNING: in shader '%s' 'skyParms', innerbox is not supported!", shader.name ); + } + + shader.isSky = qtrue; +} + + +/* +================= +ParseSort +================= +*/ +void ParseSort( const char **text ) { + char *token; + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) { + ri.Printf( PRINT_WARNING, "WARNING: missing sort parameter in shader '%s'\n", shader.name ); + return; + } + + if ( !Q_stricmp( token, "portal" ) ) { + shader.sort = SS_PORTAL; + } else if ( !Q_stricmp( token, "sky" ) ) { + shader.sort = SS_ENVIRONMENT; + } else if ( !Q_stricmp( token, "opaque" ) ) { + shader.sort = SS_OPAQUE; + } else if ( !Q_stricmp( token, "decal" ) ) { + shader.sort = SS_DECAL; + } else if ( !Q_stricmp( token, "seeThrough" ) ) { + shader.sort = SS_SEE_THROUGH; + } else if ( !Q_stricmp( token, "banner" ) ) { + shader.sort = SS_BANNER; + } else if ( !Q_stricmp( token, "additive" ) ) { + shader.sort = SS_BLEND1; + } else if ( !Q_stricmp( token, "nearest" ) ) { + shader.sort = SS_NEAREST; + } else if ( !Q_stricmp( token, "underwater" ) ) { + shader.sort = SS_UNDERWATER; + } else if ( !Q_stricmp( token, "inside" ) ) { + shader.sort = SS_INSIDE; + } else if ( !Q_stricmp( token, "mid_inside" ) ) { + shader.sort = SS_MID_INSIDE; + } else if ( !Q_stricmp( token, "middle" ) ) { + shader.sort = SS_MIDDLE; + } else if ( !Q_stricmp( token, "mid_outside" ) ) { + shader.sort = SS_MID_OUTSIDE; + } else if ( !Q_stricmp( token, "outside" ) ) { + shader.sort = SS_OUTSIDE; + } + else { + shader.sort = atof( token ); + } +} + +/* +================= +ParseMaterial +================= +*/ +const char *materialNames[MATERIAL_LAST] = +{ + MATERIALS +}; + +void ParseMaterial( const char **text ) +{ + char *token; + int i; + + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + Com_Printf (S_COLOR_YELLOW "WARNING: missing material in shader '%s'\n", shader.name ); + return; + } + for(i = 0; i < MATERIAL_LAST; i++) + { + if ( !Q_stricmp( token, materialNames[i] ) ) + { + shader.surfaceFlags |= i; + break; + } + } +} + + +// this table is also present in q3map + +typedef struct infoParm_s { + const char *name; + uint32_t clearSolid, surfaceFlags, contents; +} infoParm_t; + +infoParm_t infoParms[] = { + // Game content Flags + { "nonsolid", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_NONE }, // special hack to clear solid flag + { "nonopaque", ~CONTENTS_OPAQUE, SURF_NONE, CONTENTS_NONE }, // special hack to clear opaque flag + { "lava", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_LAVA }, // very damaging + { "slime", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SLIME }, // mildly damaging + { "water", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_WATER }, // + { "fog", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_FOG}, // carves surfaces entering + { "shotclip", ~CONTENTS_SOLID, SURF_NONE, CONTENTS_SHOTCLIP }, // block shots, but not people + { "playerclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_PLAYERCLIP }, // block only the player + { "monsterclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_MONSTERCLIP }, // + { "botclip", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_BOTCLIP }, // for bots + { "trigger", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TRIGGER }, // + { "nodrop", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_NODROP }, // don't drop items or leave bodies (death fog, lava, etc) + { "terrain", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_TERRAIN }, // use special terrain collsion + { "ladder", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_LADDER }, // climb up in it like water + { "abseil", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_ABSEIL }, // can abseil down this brush + { "outside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_OUTSIDE }, // volume is considered to be in the outside (i.e. not indoors) + { "inside", ~(CONTENTS_SOLID|CONTENTS_OPAQUE), SURF_NONE, CONTENTS_INSIDE }, // volume is considered to be inside (i.e. indoors) + + { "detail", CONTENTS_ALL, SURF_NONE, CONTENTS_DETAIL }, // don't include in structural bsp + { "trans", CONTENTS_ALL, SURF_NONE, CONTENTS_TRANSLUCENT }, // surface has an alpha component + + /* Game surface flags */ + { "sky", CONTENTS_ALL, SURF_SKY, CONTENTS_NONE }, // emit light from an environment map + { "slick", CONTENTS_ALL, SURF_SLICK, CONTENTS_NONE }, // + + { "nodamage", CONTENTS_ALL, SURF_NODAMAGE, CONTENTS_NONE }, // + { "noimpact", CONTENTS_ALL, SURF_NOIMPACT, CONTENTS_NONE }, // don't make impact explosions or marks + { "nomarks", CONTENTS_ALL, SURF_NOMARKS, CONTENTS_NONE }, // don't make impact marks, but still explode + { "nodraw", CONTENTS_ALL, SURF_NODRAW, CONTENTS_NONE }, // don't generate a drawsurface (or a lightmap) + { "nosteps", CONTENTS_ALL, SURF_NOSTEPS, CONTENTS_NONE }, // + { "nodlight", CONTENTS_ALL, SURF_NODLIGHT, CONTENTS_NONE }, // don't ever add dynamic lights + { "metalsteps", CONTENTS_ALL, SURF_METALSTEPS, CONTENTS_NONE }, // + { "nomiscents", CONTENTS_ALL, SURF_NOMISCENTS, CONTENTS_NONE }, // No misc ents on this surface + { "forcefield", CONTENTS_ALL, SURF_FORCEFIELD, CONTENTS_NONE }, // + { "forcesight", CONTENTS_ALL, SURF_FORCESIGHT, CONTENTS_NONE }, // only visible with force sight +}; + + +/* +=============== +ParseSurfaceParm + +surfaceparm +=============== +*/ +static void ParseSurfaceParm( const char **text ) { + char *token; + int numInfoParms = ARRAY_LEN( infoParms ); + int i; + + token = COM_ParseExt( text, qfalse ); + for ( i = 0 ; i < numInfoParms ; i++ ) { + if ( !Q_stricmp( token, infoParms[i].name ) ) { + shader.surfaceFlags |= infoParms[i].surfaceFlags; + shader.contentFlags |= infoParms[i].contents; + shader.contentFlags &= infoParms[i].clearSolid; + break; + } + } +} + +/* +================= +ParseShader + +The current text pointer is at the explicit text definition of the +shader. Parse it into the global shader variable. Later functions +will optimize it. +================= +*/ +static qboolean ParseShader( const char **text ) +{ + char *token; + const char *begin = *text; + int s; + + s = 0; + + token = COM_ParseExt( text, qtrue ); + if ( token[0] != '{' ) + { + ri.Printf( PRINT_WARNING, "WARNING: expecting '{', found '%s' instead in shader '%s'\n", token, shader.name ); + return qfalse; + } + + while ( 1 ) + { + token = COM_ParseExt( text, qtrue ); + if ( !token[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: no concluding '}' in shader %s\n", shader.name ); + return qfalse; + } + + // end of shader definition + if ( token[0] == '}' ) + { + break; + } + // stage definition + else if ( token[0] == '{' ) + { + if ( s >= MAX_SHADER_STAGES ) { + ri.Printf( PRINT_WARNING, "WARNING: too many stages in shader %s\n", shader.name ); + return qfalse; + } + + if ( !ParseStage( &stages[s], text ) ) + { + return qfalse; + } + stages[s].active = qtrue; + s++; + + continue; + } + // skip stuff that only the QuakeEdRadient needs + else if ( !Q_stricmpn( token, "qer", 3 ) ) { + SkipRestOfLine( text ); + continue; + } + // material deprecated as of 11 Jan 01 + // material undeprecated as of 7 May 01 - q3map_material deprecated + else if ( !Q_stricmp( token, "material" ) || !Q_stricmp( token, "q3map_material" ) ) + { + ParseMaterial( text ); + } + // sun parms + else if ( !Q_stricmp( token, "sun" ) || !Q_stricmp( token, "q3map_sun" ) || !Q_stricmp( token, "q3map_sunExt" ) || !Q_stricmp( token, "q3gl2_sun" ) ) { + float a, b; + qboolean isGL2Sun = qfalse; + + if (!Q_stricmp( token, "q3gl2_sun" ) && r_sunShadows->integer ) + { + isGL2Sun = qtrue; + tr.sunShadows = qtrue; + } + + token = COM_ParseExt( text, qfalse ); + tr.sunLight[0] = atof( token ); + token = COM_ParseExt( text, qfalse ); + tr.sunLight[1] = atof( token ); + token = COM_ParseExt( text, qfalse ); + tr.sunLight[2] = atof( token ); + + VectorNormalize( tr.sunLight ); + + token = COM_ParseExt( text, qfalse ); + a = atof( token ); + VectorScale( tr.sunLight, a, tr.sunLight); + + token = COM_ParseExt( text, qfalse ); + a = atof( token ); + a = a / 180 * M_PI; + + token = COM_ParseExt( text, qfalse ); + b = atof( token ); + b = b / 180 * M_PI; + + tr.sunDirection[0] = cos( a ) * cos( b ); + tr.sunDirection[1] = sin( a ) * cos( b ); + tr.sunDirection[2] = sin( b ); + + if (isGL2Sun) + { + token = COM_ParseExt( text, qfalse ); + tr.mapLightScale = atof(token); + + token = COM_ParseExt( text, qfalse ); + tr.sunShadowScale = atof(token); + + if (tr.sunShadowScale < 0.0f) + { + ri.Printf (PRINT_WARNING, "WARNING: q3gl2_sun's 'shadow scale' value must be between 0 and 1. Clamping to 0.0.\n"); + tr.sunShadowScale = 0.0f; + } + else if (tr.sunShadowScale > 1.0f) + { + ri.Printf (PRINT_WARNING, "WARNING: q3gl2_sun's 'shadow scale' value must be between 0 and 1. Clamping to 1.0.\n"); + tr.sunShadowScale = 1.0f; + } + } + + SkipRestOfLine( text ); + continue; + } + // tonemap parms + else if ( !Q_stricmp( token, "q3gl2_tonemap" ) ) { + token = COM_ParseExt( text, qfalse ); + tr.toneMinAvgMaxLevel[0] = atof( token ); + token = COM_ParseExt( text, qfalse ); + tr.toneMinAvgMaxLevel[1] = atof( token ); + token = COM_ParseExt( text, qfalse ); + tr.toneMinAvgMaxLevel[2] = atof( token ); + + token = COM_ParseExt( text, qfalse ); + tr.autoExposureMinMax[0] = atof( token ); + token = COM_ParseExt( text, qfalse ); + tr.autoExposureMinMax[1] = atof( token ); + + tr.explicitToneMap = true; + + SkipRestOfLine( text ); + continue; + } + // q3map_surfacelight deprecated as of 16 Jul 01 + else if ( !Q_stricmp( token, "surfacelight" ) || !Q_stricmp( token, "q3map_surfacelight" ) ) + { + SkipRestOfLine( text ); + continue; + } + else if ( !Q_stricmp( token, "lightColor" ) ) + { + SkipRestOfLine( text ); + continue; + } + else if ( !Q_stricmp( token, "deformvertexes" ) || !Q_stricmp( token, "deform" ) ) { + ParseDeform( text ); + continue; + } + else if ( !Q_stricmp( token, "tesssize" ) ) { + SkipRestOfLine( text ); + continue; + } + else if ( !Q_stricmp( token, "clampTime" ) ) { + token = COM_ParseExt( text, qfalse ); + if (token[0]) { + shader.clampTime = atof(token); + } + } + // skip stuff that only the q3map needs + else if ( !Q_stricmpn( token, "q3map", 5 ) ) { + SkipRestOfLine( text ); + continue; + } + // skip stuff that only q3map or the server needs + else if ( !Q_stricmp( token, "surfaceParm" ) ) { + ParseSurfaceParm( text ); + continue; + } + // no mip maps + else if ( !Q_stricmp( token, "nomipmaps" ) ) + { + shader.noMipMaps = qtrue; + shader.noPicMip = qtrue; + continue; + } + // refractive surface + else if ( !Q_stricmp(token, "refractive" ) ) + { + shader.useDistortion = qtrue; + continue; + } + // no picmip adjustment + else if ( !Q_stricmp( token, "nopicmip" ) ) + { + shader.noPicMip = qtrue; + continue; + } + else if ( !Q_stricmp( token, "noglfog" ) ) + { + //shader.fogPass = FP_NONE; + continue; + } + // polygonOffset + else if ( !Q_stricmp( token, "polygonOffset" ) ) + { + shader.polygonOffset = qtrue; + continue; + } + else if ( !Q_stricmp( token, "noTC" ) ) + { + shader.noTC = qtrue; + continue; + } + // entityMergable, allowing sprite surfaces from multiple entities + // to be merged into one batch. This is a savings for smoke + // puffs and blood, but can't be used for anything where the + // shader calcs (not the surface function) reference the entity color or scroll + else if ( !Q_stricmp( token, "entityMergable" ) ) + { + shader.entityMergable = qtrue; + continue; + } + // fogParms + else if ( !Q_stricmp( token, "fogParms" ) ) + { + if ( !ParseVector( text, 3, shader.fogParms.color ) ) { + return qfalse; + } + + token = COM_ParseExt( text, qfalse ); + if ( !token[0] ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing parm for 'fogParms' keyword in shader '%s'\n", shader.name ); + continue; + } + shader.fogParms.depthForOpaque = atof( token ); + + // skip any old gradient directions + SkipRestOfLine( text ); + continue; + } + // portal + else if ( !Q_stricmp(token, "portal") ) + { + shader.sort = SS_PORTAL; + shader.isPortal = qtrue; + continue; + } + // skyparms + else if ( !Q_stricmp( token, "skyparms" ) ) + { + ParseSkyParms( text ); + continue; + } + // light determines flaring in q3map, not needed here + else if ( !Q_stricmp(token, "light") ) + { + COM_ParseExt( text, qfalse ); + continue; + } + // cull + else if ( !Q_stricmp( token, "cull") ) + { + token = COM_ParseExt( text, qfalse ); + if ( token[0] == 0 ) + { + ri.Printf( PRINT_WARNING, "WARNING: missing cull parms in shader '%s'\n", shader.name ); + continue; + } + + if ( !Q_stricmp( token, "none" ) || !Q_stricmp( token, "twosided" ) || !Q_stricmp( token, "disable" ) ) + { + shader.cullType = CT_TWO_SIDED; + } + else if ( !Q_stricmp( token, "back" ) || !Q_stricmp( token, "backside" ) || !Q_stricmp( token, "backsided" ) ) + { + shader.cullType = CT_BACK_SIDED; + } + else + { + ri.Printf( PRINT_WARNING, "WARNING: invalid cull parm '%s' in shader '%s'\n", token, shader.name ); + } + continue; + } + // sort + else if ( !Q_stricmp( token, "sort" ) ) + { + ParseSort( text ); + continue; + } + else + { + ri.Printf( PRINT_WARNING, "WARNING: unknown general shader parameter '%s' in '%s'\n", token, shader.name ); + return qfalse; + } + } + + // + // ignore shaders that don't have any stages, unless it is a sky or fog + // + if ( s == 0 && !shader.isSky && !(shader.contentFlags & CONTENTS_FOG ) ) { + return qfalse; + } + + shader.explicitlyDefined = qtrue; + + // The basejka rocket lock wedge shader uses the incorrect blending mode. + // It only worked because the shader state was not being set, and relied + // on previous state to be multiplied by alpha. Since fixing RB_RotatePic, + // the shader needs to be fixed here to render correctly. + // + // We match against the retail version of gfx/2d/wedge by calculating the + // hash value of the shader text, and comparing it against a precalculated + // value. + uint32_t shaderHash = generateHashValueForText( begin, *text - begin ); + if ( shaderHash == RETAIL_ROCKET_WEDGE_SHADER_HASH && + Q_stricmp( shader.name, "gfx/2d/wedge" ) == 0 ) + { + stages[0].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); + stages[0].stateBits |= GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } + + return qtrue; +} + +/* +======================================================================================== + +SHADER OPTIMIZATION AND FOGGING + +======================================================================================== +*/ + +/* +=================== +ComputeStageIteratorFunc + +See if we can use on of the simple fastpath stage functions, +otherwise set to the generic stage function +=================== +*/ +static void ComputeStageIteratorFunc( void ) +{ + shader.optimalStageIteratorFunc = RB_StageIteratorGeneric; + + // + // see if this should go into the sky path + // + if ( shader.isSky ) + { + shader.optimalStageIteratorFunc = RB_StageIteratorSky; + return; + } +} + +/* +=================== +ComputeVertexAttribs + +Check which vertex attributes we only need, so we +don't need to submit/copy all of them. +=================== +*/ +static void ComputeVertexAttribs(void) +{ + int i, stage; + + // dlights always need ATTR_NORMAL + shader.vertexAttribs = ATTR_POSITION | ATTR_NORMAL | ATTR_COLOR; + + if (shader.defaultShader) + { + shader.vertexAttribs |= ATTR_TEXCOORD0; + return; + } + + if(shader.numDeforms) + { + for ( i = 0; i < shader.numDeforms; i++) + { + deformStage_t *ds = &shader.deforms[i]; + + switch (ds->deformation) + { + case DEFORM_BULGE: + shader.vertexAttribs |= ATTR_NORMAL | ATTR_TEXCOORD0; + break; + + case DEFORM_AUTOSPRITE: + shader.vertexAttribs |= ATTR_NORMAL | ATTR_COLOR; + break; + + case DEFORM_WAVE: + case DEFORM_NORMALS: + case DEFORM_TEXT0: + case DEFORM_TEXT1: + case DEFORM_TEXT2: + case DEFORM_TEXT3: + case DEFORM_TEXT4: + case DEFORM_TEXT5: + case DEFORM_TEXT6: + case DEFORM_TEXT7: + shader.vertexAttribs |= ATTR_NORMAL; + break; + + default: + case DEFORM_NONE: + case DEFORM_MOVE: + case DEFORM_PROJECTION_SHADOW: + case DEFORM_AUTOSPRITE2: + break; + } + } + } + + for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ ) + { + shaderStage_t *pStage = &stages[stage]; + + if ( !pStage->active ) + { + break; + } + + if (pStage->glslShaderGroup == tr.lightallShader) + { + shader.vertexAttribs |= ATTR_NORMAL; + + if ((pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK) && + (r_normalMapping->integer != 0 || + r_specularMapping->integer != 0)) + { + shader.vertexAttribs |= ATTR_TANGENT; + } + + switch (pStage->glslShaderIndex & LIGHTDEF_LIGHTTYPE_MASK) + { + case LIGHTDEF_USE_LIGHTMAP: + case LIGHTDEF_USE_LIGHT_VERTEX: + shader.vertexAttribs |= ATTR_LIGHTDIRECTION; + break; + default: + break; + } + } + + for (i = 0; i < NUM_TEXTURE_BUNDLES; i++) + { + if ( pStage->bundle[i].image[0] == 0 ) + { + continue; + } + + switch(pStage->bundle[i].tcGen) + { + case TCGEN_TEXTURE: + shader.vertexAttribs |= ATTR_TEXCOORD0; + break; + case TCGEN_LIGHTMAP: + case TCGEN_LIGHTMAP1: + case TCGEN_LIGHTMAP2: + case TCGEN_LIGHTMAP3: + shader.vertexAttribs |= (ATTR_TEXCOORD1 | ATTR_TEXCOORD2 | + ATTR_TEXCOORD3 | ATTR_TEXCOORD4); + break; + case TCGEN_ENVIRONMENT_MAPPED: + shader.vertexAttribs |= ATTR_NORMAL; + break; + + default: + break; + } + } + + switch(pStage->rgbGen) + { + case CGEN_EXACT_VERTEX: + case CGEN_VERTEX: + case CGEN_EXACT_VERTEX_LIT: + case CGEN_VERTEX_LIT: + case CGEN_ONE_MINUS_VERTEX: + shader.vertexAttribs |= ATTR_COLOR; + break; + + case CGEN_LIGHTING_DIFFUSE: + case CGEN_LIGHTING_DIFFUSE_ENTITY: + shader.vertexAttribs |= ATTR_NORMAL; + break; + + default: + break; + } + + switch(pStage->alphaGen) + { + case AGEN_LIGHTING_SPECULAR: + shader.vertexAttribs |= ATTR_NORMAL; + break; + + case AGEN_VERTEX: + case AGEN_ONE_MINUS_VERTEX: + shader.vertexAttribs |= ATTR_COLOR; + break; + + default: + break; + } + } +} + +static void CollapseStagesToLightall(shaderStage_t *stage, shaderStage_t *lightmap, + qboolean useLightVector, qboolean useLightVertex, qboolean tcgen) +{ + int defs = 0; + + //ri.Printf(PRINT_ALL, "shader %s has diffuse %s", shader.name, stage->bundle[0].image[0]->imgName); + + // reuse diffuse, mark others inactive + stage->type = ST_GLSL; + + if (lightmap) + { + //ri.Printf(PRINT_ALL, ", lightmap"); + stage->bundle[TB_LIGHTMAP] = lightmap->bundle[0]; + defs |= LIGHTDEF_USE_LIGHTMAP; + } + else if (useLightVector) + { + defs |= LIGHTDEF_USE_LIGHT_VECTOR; + } + else if (useLightVertex) + { + defs |= LIGHTDEF_USE_LIGHT_VERTEX; + } + + if (r_deluxeMapping->integer && tr.worldDeluxeMapping && lightmap) + { + //ri.Printf(PRINT_ALL, ", deluxemap"); + stage->bundle[TB_DELUXEMAP] = lightmap->bundle[TB_DELUXEMAP]; + } + + if (r_normalMapping->integer) + { + image_t *diffuseImg; + if (stage->bundle[TB_NORMALMAP].image[0]) + { + if (stage->bundle[TB_NORMALMAP].image[0]->type == IMGTYPE_NORMALHEIGHT && + r_parallaxMapping->integer && + defs & LIGHTDEF_LIGHTTYPE_MASK) + defs |= LIGHTDEF_USE_PARALLAXMAP; + //ri.Printf(PRINT_ALL, ", normalmap %s", stage->bundle[TB_NORMALMAP].image[0]->imgName); + } + else if ((lightmap || useLightVector || useLightVertex) && (diffuseImg = stage->bundle[TB_DIFFUSEMAP].image[0]) != NULL) + { + char normalName[MAX_QPATH]; + image_t *normalImg; + int normalFlags = (diffuseImg->flags & ~(IMGFLAG_GENNORMALMAP | IMGFLAG_SRGB)) | IMGFLAG_NOLIGHTSCALE; + qboolean parallax = qfalse; + // try a normalheight image first + COM_StripExtension(diffuseImg->imgName, normalName, sizeof(normalName)); + Q_strcat(normalName, sizeof(normalName), "_nh"); + + normalImg = R_FindImageFile(normalName, IMGTYPE_NORMALHEIGHT, normalFlags); + + if (normalImg) + { + parallax = qtrue; + } + else + { + // try a normal image ("_n" suffix) + normalName[strlen(normalName) - 1] = '\0'; + normalImg = R_FindImageFile(normalName, IMGTYPE_NORMAL, normalFlags); + } + + if (normalImg) + { + stage->bundle[TB_NORMALMAP] = stage->bundle[0]; + stage->bundle[TB_NORMALMAP].numImageAnimations = 0; + stage->bundle[TB_NORMALMAP].image[0] = normalImg; + + if (parallax && r_parallaxMapping->integer) + defs |= LIGHTDEF_USE_PARALLAXMAP; + + VectorSet4(stage->normalScale, r_baseNormalX->value, r_baseNormalY->value, 1.0f, r_baseParallax->value); + } + } + } + + if (r_specularMapping->integer) + { + image_t *diffuseImg; + if (stage->bundle[TB_SPECULARMAP].image[0]) + { + if (stage->specularType == SPEC_SPECGLOSS) + defs |= LIGHTDEF_USE_SPEC_GLOSS; + } + else if ((lightmap || useLightVector || useLightVertex) && (diffuseImg = stage->bundle[TB_DIFFUSEMAP].image[0]) != NULL) + { + char imageName[MAX_QPATH]; + image_t *specularImg; + int specularFlags = diffuseImg->flags & ~(IMGFLAG_GENNORMALMAP); + + COM_StripExtension(diffuseImg->imgName, imageName, MAX_QPATH); + Q_strcat(imageName, MAX_QPATH, "_specGloss"); + + if (diffuseImg->flags & IMGFLAG_SRGB) + specularImg = R_FindImageFile(imageName, IMGTYPE_COLORALPHA, specularFlags); + else + specularImg = R_BuildSDRSpecGlossImage(stage, imageName, specularFlags); + + if (specularImg) + { + stage->bundle[TB_SPECULARMAP] = stage->bundle[0]; + stage->bundle[TB_SPECULARMAP].numImageAnimations = 0; + stage->bundle[TB_SPECULARMAP].image[0] = specularImg; + stage->specularType = SPEC_SPECGLOSS; + defs |= LIGHTDEF_USE_SPEC_GLOSS; + VectorSet4(stage->specularScale, 1.0f, 1.0f, 1.0f, 0.0f); + } + else + { + // Data images shouldn't be lightscaled + specularFlags |= IMGFLAG_NOLIGHTSCALE; + COM_StripExtension(diffuseImg->imgName, imageName, MAX_QPATH); + Q_strcat(imageName, MAX_QPATH, "_rmo"); + stage->specularType = SPEC_RMO; + R_LoadPackedMaterialImage(stage, imageName, specularFlags); + + if (!stage->bundle[TB_ORMSMAP].image[0]) + { + COM_StripExtension(diffuseImg->imgName, imageName, MAX_QPATH); + Q_strcat(imageName, MAX_QPATH, "_orm"); + stage->specularType = SPEC_ORM; + R_LoadPackedMaterialImage(stage, imageName, specularFlags); + if (!stage->bundle[TB_ORMSMAP].image[0]) + { + stage->specularScale[0] = 0.0f; + stage->specularScale[2] = + stage->specularScale[3] = 1.0f; + stage->specularScale[1] = 0.5f; + } + } + } + } + } + + if (tcgen || stage->bundle[0].numTexMods) + { + defs |= LIGHTDEF_USE_TCGEN_AND_TCMOD; + } + + if (stage->glow) + defs |= LIGHTDEF_USE_GLOW_BUFFER; + + if (stage->cloth) + defs |= LIGHTDEF_USE_CLOTH_BRDF; + + if (stage->alphaTestType != ALPHA_TEST_NONE) + defs |= LIGHTDEF_USE_ALPHA_TEST; + + //ri.Printf(PRINT_ALL, ".\n"); + + stage->glslShaderGroup = tr.lightallShader; + stage->glslShaderIndex = defs; +} + + +static qboolean CollapseStagesToGLSL(void) +{ + int i, j, numStages; + qboolean skip = qfalse; + + ri.Printf (PRINT_DEVELOPER, "Collapsing stages for shader '%s'\n", shader.name); + + // skip shaders with deforms + if (shader.numDeforms == 1) + { + skip = qtrue; + ri.Printf (PRINT_DEVELOPER, "> Shader has vertex deformations. Aborting stage collapsing\n"); + } + + ri.Printf (PRINT_DEVELOPER, "> Original shader stage order:\n"); + + for ( int i = 0; i < MAX_SHADER_STAGES; i++ ) + { + shaderStage_t *stage = &stages[i]; + + if ( !stage->active ) + { + continue; + } + + ri.Printf (PRINT_DEVELOPER, "-> %s\n", stage->bundle[0].image[0]->imgName); + } + + if (!skip) + { + // scan for shaders that aren't supported + for (i = 0; i < MAX_SHADER_STAGES; i++) + { + shaderStage_t *pStage = &stages[i]; + + if (!pStage->active) + continue; + + if (pStage->adjustColorsForFog) + { + skip = qtrue; + break; + } + + if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && + pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3) + { + int blendBits = pStage->stateBits & ( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); + + if (blendBits != (GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO) + && blendBits != (GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR) + && blendBits != (GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE)) //lightstyle lightmap stages + { + skip = qtrue; + break; + } + } + + switch(pStage->bundle[0].tcGen) + { + case TCGEN_TEXTURE: + case TCGEN_LIGHTMAP: + case TCGEN_LIGHTMAP1: + case TCGEN_LIGHTMAP2: + case TCGEN_LIGHTMAP3: + case TCGEN_ENVIRONMENT_MAPPED: + case TCGEN_VECTOR: + break; + default: + skip = qtrue; + break; + } + + switch(pStage->alphaGen) + { + case AGEN_PORTAL: + case AGEN_LIGHTING_SPECULAR: + skip = qtrue; + break; + default: + break; + } + } + } + + if (!skip) + { + shaderStage_t *lightmaps[MAX_SHADER_STAGES] = {}; + + for (i = 0; i < MAX_SHADER_STAGES; i++) + { + shaderStage_t *pStage = &stages[i]; + + if (!pStage->active) + continue; + + if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3) + { + lightmaps[i] = pStage; + } + } + + for (i = 0; i < MAX_SHADER_STAGES; i++) + { + shaderStage_t *pStage = &stages[i]; + shaderStage_t *diffuse, *lightmap; + qboolean parallax, tcgen, diffuselit, vertexlit; + + if (!pStage->active) + continue; + + // skip normal and specular maps + if (pStage->type != ST_COLORMAP) + continue; + + // skip lightmaps + if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3) + continue; + + diffuse = pStage; + parallax = qfalse; + lightmap = NULL; + + // we have a diffuse map, find matching lightmap + for (j = i + 1; j < MAX_SHADER_STAGES; j++) + { + shaderStage_t *pStage2 = &stages[j]; + + if (!pStage2->active) + continue; + + if (pStage2->glow) + continue; + + if (pStage2->bundle[0].tcGen >= TCGEN_LIGHTMAP && + pStage2->bundle[0].tcGen <= TCGEN_LIGHTMAP3 && + pStage2->rgbGen != CGEN_EXACT_VERTEX) + { + ri.Printf (PRINT_DEVELOPER, "> Setting lightmap for %s to %s\n", pStage->bundle[0].image[0]->imgName, pStage2->bundle[0].image[0]->imgName); + lightmap = pStage2; + lightmaps[j] = NULL; + break; + } + } + + tcgen = qfalse; + if (diffuse->bundle[0].tcGen == TCGEN_ENVIRONMENT_MAPPED + || (diffuse->bundle[0].tcGen >= TCGEN_LIGHTMAP && diffuse->bundle[0].tcGen <= TCGEN_LIGHTMAP3) + || diffuse->bundle[0].tcGen == TCGEN_VECTOR) + { + tcgen = qtrue; + } + + diffuselit = qfalse; + if (diffuse->rgbGen == CGEN_LIGHTING_DIFFUSE || + diffuse->rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) + { + diffuselit = qtrue; + } + + vertexlit = qfalse; + if (diffuse->rgbGen == CGEN_VERTEX_LIT || diffuse->rgbGen == CGEN_EXACT_VERTEX_LIT || diffuse->rgbGen == CGEN_VERTEX || diffuse->rgbGen == CGEN_EXACT_VERTEX) + { + vertexlit = qtrue; + } + + CollapseStagesToLightall(diffuse, lightmap, diffuselit, vertexlit, tcgen); + + //find lightstyle stages + if (lightmap != NULL) + { + for (j = i + 2; j < MAX_SHADER_STAGES; j++) + { + shaderStage_t *pStage2 = &stages[j]; + + int blendBits = pStage2->stateBits & (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); + + if (blendBits != (GLS_DSTBLEND_ONE | GLS_SRCBLEND_ONE) + || (pStage2->bundle[0].tcGen < TCGEN_LIGHTMAP && pStage2->bundle[0].tcGen > TCGEN_LIGHTMAP3) + || pStage2->rgbGen != CGEN_LIGHTMAPSTYLE) + break; + + //style stage is the previous lightmap stage which is not used anymore + shaderStage_t *styleStage = &stages[j - 1]; + + int style = pStage2->lightmapStyle; + int stateBits = pStage2->stateBits; + textureBundle_t tbLightmap = pStage2->bundle[0]; + textureBundle_t tbDeluxemap = pStage2->bundle[TB_DELUXEMAP]; + + memcpy(styleStage, diffuse, sizeof(shaderStage_t)); + styleStage->lightmapStyle = style; + styleStage->stateBits = stateBits; + styleStage->rgbGen = CGEN_LIGHTMAPSTYLE; + + styleStage->bundle[TB_LIGHTMAP] = tbLightmap; + styleStage->bundle[TB_DELUXEMAP] = tbDeluxemap; + + lightmaps[j] = NULL; + } + } + } + + // deactivate lightmap stages + for (i = 0; i < MAX_SHADER_STAGES; i++) + { + shaderStage_t *pStage = &stages[i]; + + if (!pStage->active) + continue; + + if (pStage->bundle[0].tcGen >= TCGEN_LIGHTMAP && + pStage->bundle[0].tcGen <= TCGEN_LIGHTMAP3 && + lightmaps[i] == NULL) + { + pStage->active = qfalse; + } + } + } + + if (skip) + { + // set default specular scale for skipped shaders that will use metalness workflow by default + for (i = 0; i < MAX_SHADER_STAGES; i++) + { + shaderStage_t *pStage = &stages[i]; + pStage->specularScale[0] = 0.0f; + pStage->specularScale[2] = + pStage->specularScale[3] = 1.0f; + pStage->specularScale[1] = 0.5f; + } + } + + // remove inactive stages + numStages = 0; + for (i = 0; i < MAX_SHADER_STAGES; i++) + { + if (!stages[i].active) + continue; + + if (i == numStages) + { + numStages++; + continue; + } + + stages[numStages] = stages[i]; + stages[i].active = qfalse; + numStages++; + } + + // convert any remaining lightmap stages to a lighting pass with a white texture + // only do this with r_sunlightMode non-zero, as it's only for correct shadows. + if (r_sunlightMode->integer && shader.numDeforms != 1) + { + for (i = 0; i < MAX_SHADER_STAGES; i++) + { + shaderStage_t *pStage = &stages[i]; + + if (!pStage->active) + continue; + + if (pStage->adjustColorsForFog) + continue; + + if (pStage->bundle[TB_DIFFUSEMAP].tcGen >= TCGEN_LIGHTMAP + && pStage->bundle[TB_DIFFUSEMAP].tcGen <= TCGEN_LIGHTMAP3 + && pStage->rgbGen != CGEN_LIGHTMAPSTYLE) //don't convert lightstyled lightmap stages + { + pStage->glslShaderGroup = tr.lightallShader; + pStage->glslShaderIndex = LIGHTDEF_USE_LIGHTMAP; + pStage->bundle[TB_LIGHTMAP] = pStage->bundle[TB_DIFFUSEMAP]; + pStage->bundle[TB_DIFFUSEMAP].image[0] = tr.whiteImage; + pStage->bundle[TB_DIFFUSEMAP].isLightmap = qfalse; + pStage->bundle[TB_DIFFUSEMAP].tcGen = TCGEN_TEXTURE; + } + } + } + + // convert any remaining lightingdiffuse stages to a lighting pass + if (shader.numDeforms != 1) + { + for (i = 0; i < MAX_SHADER_STAGES; i++) + { + shaderStage_t *pStage = &stages[i]; + + if (!pStage->active) + continue; + + if (pStage->adjustColorsForFog) + continue; + + if (pStage->rgbGen == CGEN_LIGHTING_DIFFUSE || + pStage->rgbGen == CGEN_LIGHTING_DIFFUSE_ENTITY) + { + if (pStage->glslShaderGroup != tr.lightallShader) + { + pStage->glslShaderGroup = tr.lightallShader; + pStage->glslShaderIndex = LIGHTDEF_USE_LIGHT_VECTOR; + } + else if (!(pStage->glslShaderIndex & LIGHTDEF_USE_LIGHT_VECTOR)) + { + pStage->glslShaderIndex &= ~LIGHTDEF_LIGHTTYPE_MASK; + pStage->glslShaderIndex |= LIGHTDEF_USE_LIGHT_VECTOR; + } + + if (pStage->bundle[0].tcGen != TCGEN_TEXTURE || pStage->bundle[0].numTexMods != 0) + pStage->glslShaderIndex |= LIGHTDEF_USE_TCGEN_AND_TCMOD; + } + } + } + + ri.Printf (PRINT_DEVELOPER, "> New shader stage order:\n"); + + for ( int i = 0; i < MAX_SHADER_STAGES; i++ ) + { + shaderStage_t *stage = &stages[i]; + + if ( !stage->active ) + { + continue; + } + + ri.Printf (PRINT_DEVELOPER, "-> %s\n", stage->bundle[0].image[0]->imgName); + } + + return (qboolean)numStages; +} + +/* +============= + +FixRenderCommandList +https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493 +Arnout: this is a nasty issue. Shaders can be registered after drawsurfaces are generated +but before the frame is rendered. This will, for the duration of one frame, cause drawsurfaces +to be rendered with bad shaders. To fix this, need to go through all render commands and fix +sortedIndex. +============== +*/ +extern bool gServerSkinHack; +static void FixRenderCommandList( int newShader ) { + if( !gServerSkinHack ) { + renderCommandList_t *cmdList = &backEndData->commands; + + if( cmdList ) { + const void *curCmd = cmdList->cmds; + + while ( 1 ) { + curCmd = PADP(curCmd, sizeof(void *)); + + switch ( *(const int *)curCmd ) { + case RC_SET_COLOR: + { + const setColorCommand_t *sc_cmd = (const setColorCommand_t *)curCmd; + curCmd = (const void *)(sc_cmd + 1); + break; + } + case RC_STRETCH_PIC: + { + const stretchPicCommand_t *sp_cmd = (const stretchPicCommand_t *)curCmd; + curCmd = (const void *)(sp_cmd + 1); + break; + } + case RC_ROTATE_PIC: + case RC_ROTATE_PIC2: + { + const rotatePicCommand_t *sp_cmd = (const rotatePicCommand_t *)curCmd; + curCmd = (const void *)(sp_cmd + 1); + break; + } + case RC_DRAW_SURFS: + { + int i; + drawSurf_t *drawSurf; + shader_t *shader; + int postRender; + int sortedIndex; + int cubemap; + int entityNum; + const drawSurfsCommand_t *ds_cmd = (const drawSurfsCommand_t *)curCmd; + + for( i = 0, drawSurf = ds_cmd->drawSurfs; i < ds_cmd->numDrawSurfs; i++, drawSurf++ ) { + R_DecomposeSort( drawSurf->sort, &entityNum, &shader, &cubemap, &postRender ); + sortedIndex = (( drawSurf->sort >> QSORT_SHADERNUM_SHIFT ) & (MAX_SHADERS-1)); + if( sortedIndex >= newShader ) { + sortedIndex++; + drawSurf->sort = R_CreateSortKey(entityNum, sortedIndex, cubemap, postRender); + } + } + curCmd = (const void *)(ds_cmd + 1); + break; + } + case RC_DRAW_BUFFER: + { + const drawBufferCommand_t *db_cmd = (const drawBufferCommand_t *)curCmd; + curCmd = (const void *)(db_cmd + 1); + break; + } + case RC_SWAP_BUFFERS: + { + const swapBuffersCommand_t *sb_cmd = (const swapBuffersCommand_t *)curCmd; + curCmd = (const void *)(sb_cmd + 1); + break; + } + case RC_END_OF_LIST: + default: + return; + } + } + } + } +} + +/* +============== +SortNewShader + +Positions the most recently created shader in the tr.sortedShaders[] +array so that the shader->sort key is sorted reletive to the other +shaders. + +Sets shader->sortedIndex +============== +*/ +static void SortNewShader( void ) { + int i; + float sort; + shader_t *newShader; + + newShader = tr.shaders[ tr.numShaders - 1 ]; + sort = newShader->sort; + + int numStagesInNewShader = 0; + while ( newShader->stages[numStagesInNewShader] ) + numStagesInNewShader++; + + for ( i = tr.numShaders - 2 ; i >= 0 ; i-- ) { + shader_t *shader = tr.sortedShaders[i]; + int numStages = 0; + while ( shader->stages[numStages] ) + numStages++; + + if ( shader->sort < sort ) { + break; + } + + if ( shader->sort == sort && numStages <= numStagesInNewShader ) + { + break; + } + + tr.sortedShaders[i+1] = shader; + tr.sortedShaders[i+1]->sortedIndex++; + } + + // Arnout: fix rendercommandlist + // https://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=493 + FixRenderCommandList( i+1 ); + + newShader->sortedIndex = i+1; + tr.sortedShaders[i+1] = newShader; +} + + +/* +==================== +GeneratePermanentShader +==================== +*/ +static shader_t *GeneratePermanentShader( void ) { + shader_t *newShader; + int i, b; + int size, hash; + + if ( tr.numShaders == MAX_SHADERS ) { + ri.Printf( PRINT_WARNING, "WARNING: GeneratePermanentShader - MAX_SHADERS hit\n"); + return tr.defaultShader; + } + + newShader = (shader_t *)ri.Hunk_Alloc( sizeof( shader_t ), h_low ); + + *newShader = shader; + + if ( shader.sort <= SS_SEE_THROUGH ) { + newShader->fogPass = FP_EQUAL; + } else if ( shader.contentFlags & CONTENTS_FOG ) { + newShader->fogPass = FP_LE; + } else { + newShader->fogPass = FP_NONE; + } + + // determain if fog pass can use depth equal or not + if (newShader->fogPass == FP_EQUAL) + { + newShader->fogPass = FP_LE; + bool allPassesAlpha = true; + for (int stage = 0; stage < MAX_SHADER_STAGES; stage++) { + shaderStage_t *pStage = &stages[stage]; + + if (!pStage->active) + continue; + + if (pStage->glow && stage > 0) + continue; + + if (pStage->adjustColorsForFog != ACFF_MODULATE_ALPHA) + allPassesAlpha = false; + + if (pStage->stateBits & GLS_DEPTHMASK_TRUE) + { + newShader->fogPass = FP_EQUAL; + break; + } + } + + if (allPassesAlpha) + newShader->fogPass = FP_NONE; + } + + tr.shaders[ tr.numShaders ] = newShader; + newShader->index = tr.numShaders; + + tr.sortedShaders[ tr.numShaders ] = newShader; + newShader->sortedIndex = tr.numShaders; + + tr.numShaders++; + + for ( i = 0 ; i < newShader->numUnfoggedPasses ; i++ ) { + if ( !stages[i].active ) { + break; + } + newShader->stages[i] = (shaderStage_t *)ri.Hunk_Alloc( sizeof( stages[i] ), h_low ); + *newShader->stages[i] = stages[i]; + + for ( b = 0 ; b < NUM_TEXTURE_BUNDLES ; b++ ) { + size = newShader->stages[i]->bundle[b].numTexMods * sizeof( texModInfo_t ); + newShader->stages[i]->bundle[b].texMods = (texModInfo_t *)ri.Hunk_Alloc( size, h_low ); + Com_Memcpy( newShader->stages[i]->bundle[b].texMods, stages[i].bundle[b].texMods, size ); + } + } + + RB_AddShaderToShaderInstanceUBO(newShader); + + SortNewShader(); + + hash = generateHashValue(newShader->name, FILE_HASH_SIZE); + newShader->next = hashTable[hash]; + hashTable[hash] = newShader; + + return newShader; +} + +/* +================= +VertexLightingCollapse + +If vertex lighting is enabled, only render a single +pass, trying to guess which is the correct one to best aproximate +what it is supposed to look like. +================= +*/ +static void VertexLightingCollapse( void ) { + int stage; + shaderStage_t *bestStage; + int bestImageRank; + int rank; + + // if we aren't opaque, just use the first pass + if ( shader.sort == SS_OPAQUE ) { + + // pick the best texture for the single pass + bestStage = &stages[0]; + bestImageRank = -999999; + + for ( stage = 0; stage < MAX_SHADER_STAGES; stage++ ) { + shaderStage_t *pStage = &stages[stage]; + + if ( !pStage->active ) { + break; + } + rank = 0; + + if ( pStage->bundle[0].isLightmap ) { + rank -= 100; + } + if ( pStage->bundle[0].tcGen != TCGEN_TEXTURE ) { + rank -= 5; + } + if ( pStage->bundle[0].numTexMods ) { + rank -= 5; + } + if ( pStage->rgbGen != CGEN_IDENTITY && pStage->rgbGen != CGEN_IDENTITY_LIGHTING ) { + rank -= 3; + } + + if ( rank > bestImageRank ) { + bestImageRank = rank; + bestStage = pStage; + } + } + + stages[0].bundle[0] = bestStage->bundle[0]; + stages[0].stateBits &= ~( GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS ); + stages[0].stateBits |= GLS_DEPTHMASK_TRUE; + if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; + } else { + stages[0].rgbGen = CGEN_EXACT_VERTEX; + } + stages[0].alphaGen = AGEN_SKIP; + } else { + // don't use a lightmap (tesla coils) + if ( stages[0].bundle[0].isLightmap ) { + stages[0] = stages[1]; + } + + // if we were in a cross-fade cgen, hack it to normal + if ( stages[0].rgbGen == CGEN_ONE_MINUS_ENTITY || stages[1].rgbGen == CGEN_ONE_MINUS_ENTITY ) { + stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; + } + if ( ( stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_SAWTOOTH ) + && ( stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_INVERSE_SAWTOOTH ) ) { + stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; + } + if ( ( stages[0].rgbGen == CGEN_WAVEFORM && stages[0].rgbWave.func == GF_INVERSE_SAWTOOTH ) + && ( stages[1].rgbGen == CGEN_WAVEFORM && stages[1].rgbWave.func == GF_SAWTOOTH ) ) { + stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; + } + } + + for ( stage = 1; stage < MAX_SHADER_STAGES; stage++ ) { + shaderStage_t *pStage = &stages[stage]; + + if ( !pStage->active ) { + break; + } + + Com_Memset( pStage, 0, sizeof( *pStage ) ); + } +} + +int FindFirstLightmapStage ( const shaderStage_t *stages, int numStages ) +{ + for ( int i = 0; i < numStages; i++ ) + { + const shaderStage_t *stage = &stages[i]; + if ( stage->active && stage->bundle[0].isLightmap ) + { + return i; + } + } + + return numStages; +} + +int GetNumStylesInShader ( const shader_t *shader ) +{ + for ( int i = 0; i < MAXLIGHTMAPS; i++ ) + { + if ( shader->styles[i] >= LS_UNUSED ) + { + return i - 1; + } + } + + return MAXLIGHTMAPS - 1; +} + +/* +========================= +FinishShader + +Returns a freshly allocated shader with all the needed info +from the current global working shader +========================= +*/ +static shader_t *FinishShader( void ) { + int stage; + uint32_t shaderStateBits = 0; + qboolean hasLightmapStage = qfalse; + + // + // set sky stuff appropriate + // + if ( shader.isSky ) { + shader.sort = SS_ENVIRONMENT; + } + + // + // set polygon offset + // + if ( shader.polygonOffset ) { + shaderStateBits |= GLS_POLYGON_OFFSET_FILL; + if ( !shader.sort ) { + shader.sort = SS_DECAL; + } + } + + int lmStage; + for(lmStage = 0; lmStage < MAX_SHADER_STAGES; lmStage++) + { + shaderStage_t *pStage = &stages[lmStage]; + if (pStage->active && pStage->bundle[0].isLightmap) + { + break; + } + } + + if (lmStage < MAX_SHADER_STAGES) + { + if (shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX) + { + if (lmStage == 0) //< MAX_SHADER_STAGES-1) + {//copy the rest down over the lightmap slot + memmove(&stages[lmStage], &stages[lmStage+1], sizeof(shaderStage_t) * (MAX_SHADER_STAGES-lmStage-1)); + memset(&stages[MAX_SHADER_STAGES-1], 0, sizeof(shaderStage_t)); + //change blending on the moved down stage + stages[lmStage].stateBits = GLS_DEFAULT; + } + //change anything that was moved down (or the *white if LM is first) to use vertex color + stages[lmStage].rgbGen = CGEN_EXACT_VERTEX; + stages[lmStage].alphaGen = AGEN_SKIP; + lmStage = MAX_SHADER_STAGES; //skip the style checking below + } + } + + // if 2+ stages and first stage is lightmap, switch them + // this makes it easier for the later bits to process + if (stages[0].active && + stages[0].bundle[0].isLightmap && + stages[1].active && + shader.numDeforms != 1) + { + int blendBits = stages[1].stateBits & (GLS_DSTBLEND_BITS | GLS_SRCBLEND_BITS); + + if (blendBits == (GLS_DSTBLEND_SRC_COLOR | GLS_SRCBLEND_ZERO) + || blendBits == (GLS_DSTBLEND_ZERO | GLS_SRCBLEND_DST_COLOR)) + { + int stateBits0 = stages[0].stateBits; + int stateBits1 = stages[1].stateBits; + shaderStage_t swapStage; + + swapStage = stages[0]; + stages[0] = stages[1]; + stages[1] = swapStage; + + stages[0].stateBits = stateBits0; + stages[1].stateBits = stateBits1; + + lmStage = 1; + } + } + + if (lmStage < MAX_SHADER_STAGES)// && !r_fullbright->value) + { + int numStyles; + int i; + + for(numStyles=0;numStyles= LS_UNUSED) + { + break; + } + } + numStyles--; + if (numStyles > 0) + { + for(i=MAX_SHADER_STAGES-1;i>lmStage+numStyles;i--) + { + stages[i] = stages[i-numStyles]; + } + + for(i=0;iinteger && tr.worldDeluxeMapping) + { + stages[lmStage+i+1].bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[i+1]]; + stages[lmStage+i+1].bundle[TB_DELUXEMAP].tcGen = (texCoordGen_t)(TCGEN_LIGHTMAP+i+1); + } + } + stages[lmStage+i+1].rgbGen = CGEN_LIGHTMAPSTYLE; + stages[lmStage+i+1].stateBits &= ~(GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS); + stages[lmStage+i+1].stateBits |= GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; + } + } + + for(i=0;i<=numStyles;i++) + { + stages[lmStage+i].lightmapStyle = shader.styles[i]; + } + } + + // + // set appropriate stage information + // + for ( stage = 0; stage < MAX_SHADER_STAGES; ) { + shaderStage_t *pStage = &stages[stage]; + + if ( !pStage->active ) { + break; + } + + // check for a missing texture + if ( !pStage->bundle[0].image[0] ) { + ri.Printf( PRINT_WARNING, "Shader %s, stage %d has no image. This stage will be ignored\n", shader.name, stage + 1 ); + pStage->active = qfalse; + stage++; + continue; + } + + // + // ditch this stage if it's detail and detail textures are disabled + // + if ( pStage->isDetail && !r_detailTextures->integer ) + { + int index; + + for(index = stage + 1; index < MAX_SHADER_STAGES; index++) + { + if(!stages[index].active) + break; + } + + if(index < MAX_SHADER_STAGES) + memmove(pStage, pStage + 1, sizeof(*pStage) * (index - stage)); + else + { + if(stage + 1 < MAX_SHADER_STAGES) + memmove(pStage, pStage + 1, sizeof(*pStage) * (index - stage - 1)); + + Com_Memset(&stages[index - 1], 0, sizeof(*stages)); + } + + continue; + } + + pStage->stateBits |= shaderStateBits; + + // + // default texture coordinate generation + // + if ( pStage->bundle[0].isLightmap ) { + if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + pStage->bundle[0].tcGen = TCGEN_LIGHTMAP; + if (r_deluxeMapping->integer && tr.worldDeluxeMapping) + pStage->bundle[TB_DELUXEMAP].tcGen = TCGEN_LIGHTMAP; + } + hasLightmapStage = qtrue; + } else { + if ( pStage->bundle[0].tcGen == TCGEN_BAD ) { + pStage->bundle[0].tcGen = TCGEN_TEXTURE; + } + } + + // + // determine sort order and fog color adjustment + // + if ( ( pStage->stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) && + ( stages[0].stateBits & ( GLS_SRCBLEND_BITS | GLS_DSTBLEND_BITS ) ) ) { + int blendSrcBits = pStage->stateBits & GLS_SRCBLEND_BITS; + int blendDstBits = pStage->stateBits & GLS_DSTBLEND_BITS; + + // fog color adjustment only works for blend modes that have a contribution + // that aproaches 0 as the modulate values aproach 0 -- + // GL_ONE, GL_ONE + // GL_ZERO, GL_ONE_MINUS_SRC_COLOR + // GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA + + // modulate, additive + if ( ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE ) ) || + ( ( blendSrcBits == GLS_SRCBLEND_ZERO ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_COLOR ) ) ) { + pStage->adjustColorsForFog = ACFF_MODULATE_RGB; + } + // strict blend + else if ( ( blendSrcBits == GLS_SRCBLEND_SRC_ALPHA ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) + { + pStage->adjustColorsForFog = ACFF_MODULATE_ALPHA; + } + // premultiplied alpha + else if ( ( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA ) ) + { + pStage->adjustColorsForFog = ACFF_MODULATE_RGBA; + } else { + // we can't adjust this one correctly, so it won't be exactly correct in fog + } + + if (pStage->alphaGen == AGEN_PORTAL && pStage->adjustColorsForFog == ACFF_MODULATE_ALPHA) + pStage->adjustColorsForFog = ACFF_NONE; + + // don't screw with sort order if this is a portal or environment + if ( !shader.sort ) { + // see through item, like a grill or grate + if ( pStage->stateBits & GLS_DEPTHMASK_TRUE ) { + shader.sort = SS_SEE_THROUGH; + } else { + if (( blendSrcBits == GLS_SRCBLEND_ONE ) && ( blendDstBits == GLS_DSTBLEND_ONE )) + { + // GL_ONE GL_ONE needs to come a bit later + shader.sort = SS_BLEND1; + } + else + { + shader.sort = SS_BLEND0; + } + } + } + } + + stage++; + } + + // there are times when you will need to manually apply a sort to + // opaque alpha tested shaders that have later blend passes + if ( !shader.sort ) { + shader.sort = SS_OPAQUE; + } + + // + // if we are in r_vertexLight mode, never use a lightmap texture + // + if ( stage > 1 && (r_vertexLight->integer && !r_uiFullScreen->integer) ) { + VertexLightingCollapse(); + hasLightmapStage = qfalse; + } + + // + // look for multitexture potential + // + stage = CollapseStagesToGLSL(); + + if ( shader.lightmapIndex[0] >= 0 && !hasLightmapStage ) { + ri.Printf( PRINT_DEVELOPER, "WARNING: shader '%s' has lightmap but no lightmap stage!\n", shader.name ); + // Don't set this, it will just add duplicate shaders to the hash + //shader.lightmapIndex = LIGHTMAP_NONE; + } + + // + // compute number of passes + // + shader.numUnfoggedPasses = stage; + + // fogonly shaders don't have any normal passes + if (stage == 0 && !shader.isSky) + shader.sort = SS_FOG; + + // determain if the shader can be simplified when beeing rendered to depth + if (shader.sort == SS_OPAQUE && + shader.numDeforms == 0) + { + for (stage = 0; stage < MAX_SHADER_STAGES; stage++) { + shaderStage_t *pStage = &stages[stage]; + + if (!pStage->active) + continue; + + if (pStage->alphaTestType == ALPHA_TEST_NONE) + shader.useSimpleDepthShader = qtrue; + break; + } + } + + // determine which stage iterator function is appropriate + ComputeStageIteratorFunc(); + + // determine which vertex attributes this shader needs + ComputeVertexAttribs(); + + return GeneratePermanentShader(); +} + +//======================================================================================== + +/* +==================== +FindShaderInShaderText + +Scans the combined text description of all the shader files for +the given shader name. + +return NULL if not found + +If found, it will return a valid shader +===================== +*/ +static const char *FindShaderInShaderText( const char *shadername ) { + + char *token; + const char *p; + + int i, hash; + + hash = generateHashValue(shadername, MAX_SHADERTEXT_HASH); + + if(shaderTextHashTable[hash]) + { + for (i = 0; shaderTextHashTable[hash][i]; i++) + { + p = shaderTextHashTable[hash][i]; + token = COM_ParseExt(&p, qtrue); + + if(!Q_stricmp(token, shadername)) + return p; + } + } + + p = s_shaderText; + + if ( !p ) { + return NULL; + } + + // look for label + while ( 1 ) { + token = COM_ParseExt( &p, qtrue ); + if ( token[0] == 0 ) { + break; + } + + if ( !Q_stricmp( token, shadername ) ) { + return p; + } + else { + // skip the definition + SkipBracedSection( &p, 0 ); + } + } + + return NULL; +} + + +/* +================== +R_FindShaderByName + +Will always return a valid shader, but it might be the +default shader if the real one can't be found. +================== +*/ +shader_t *R_FindShaderByName( const char *name ) { + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; + + if ( (name==NULL) || (name[0] == 0) ) { + return tr.defaultShader; + } + + COM_StripExtension(name, strippedName, sizeof(strippedName)); + + hash = generateHashValue(strippedName, FILE_HASH_SIZE); + + // + // see if the shader is already loaded + // + for (sh=hashTable[hash]; sh; sh=sh->next) { + // NOTE: if there was no shader or image available with the name strippedName + // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we + // have to check all default shaders otherwise for every call to R_FindShader + // with that same strippedName a new default shader is created. + if (Q_stricmp(sh->name, strippedName) == 0) { + // match found + return sh; + } + } + + return tr.defaultShader; +} + +static qboolean IsShader ( const shader_t *sh, const char *name, const int *lightmapIndexes, const byte *styles ) +{ + if ( Q_stricmp (sh->name, name) != 0 ) + { + return qfalse; + } + + if ( sh->defaultShader ) + { + return qtrue; + } + + for ( int i = 0; i < MAXLIGHTMAPS; i++ ) + { + if ( sh->lightmapIndex[i] != lightmapIndexes[i] ) + { + return qfalse; + } + + if ( sh->styles[i] != styles[i] ) + { + return qfalse; + } + } + + return qtrue; +} + +/* +=============== +R_FindLightmaps +=============== +*/ +static inline const int *R_FindLightmaps(const int *lightmapIndexes) +{ + // don't bother with vertex lighting + if (*lightmapIndexes < 0) + return lightmapIndexes; + + // do the lightmaps exist? + for (int i = 0; i < MAXLIGHTMAPS; i++) + { + if (lightmapIndexes[i] >= tr.numLightmaps || tr.lightmaps[lightmapIndexes[i]] == NULL) + return lightmapsVertex; + } + return lightmapIndexes; +} + +/* +=============== +R_FindShader + +Will always return a valid shader, but it might be the +default shader if the real one can't be found. + +In the interest of not requiring an explicit shader text entry to +be defined for every single image used in the game, three default +shader behaviors can be auto-created for any image: + +If lightmapIndex == LIGHTMAP_NONE, then the image will have +dynamic diffuse lighting applied to it, as apropriate for most +entity skin surfaces. + +If lightmapIndex == LIGHTMAP_2D, then the image will be used +for 2D rendering unless an explicit shader is found + +If lightmapIndex == LIGHTMAP_BY_VERTEX, then the image will use +the vertex rgba modulate values, as apropriate for misc_model +pre-lit surfaces. + +Other lightmapIndex values will have a lightmap stage created +and src*dest blending applied with the texture, as apropriate for +most world construction surfaces. + +=============== +*/ +shader_t *R_FindShader( const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage ) { + char strippedName[MAX_QPATH]; + int hash, flags; + const char *shaderText; + image_t *image; + shader_t *sh; + + if ( name[0] == 0 ) { + return tr.defaultShader; + } + + // use (fullbright) vertex lighting if the bsp file doesn't have + // lightmaps + if ( lightmapIndexes[0] >= 0 && lightmapIndexes[0] >= tr.numLightmaps ) { + lightmapIndexes = lightmapsVertex; + } else if ( lightmapIndexes[0] < LIGHTMAP_2D ) { + // negative lightmap indexes cause stray pointers (think tr.lightmaps[lightmapIndex]) + ri.Printf( PRINT_WARNING, "WARNING: shader '%s' has invalid lightmap index of %d\n", name, lightmapIndexes[0] ); + lightmapIndexes = lightmapsVertex; + } + + lightmapIndexes = R_FindLightmaps(lightmapIndexes); + + COM_StripExtension(name, strippedName, sizeof(strippedName)); + + hash = generateHashValue(strippedName, FILE_HASH_SIZE); + + // + // see if the shader is already loaded + // + for (sh = hashTable[hash]; sh; sh = sh->next) { + // NOTE: if there was no shader or image available with the name strippedName + // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we + // have to check all default shaders otherwise for every call to R_FindShader + // with that same strippedName a new default shader is created. + if ( IsShader (sh, strippedName, lightmapIndexes, styles) ) { + // match found + return sh; + } + } + + // clear the global shader + ClearGlobalShader(); + Q_strncpyz(shader.name, strippedName, sizeof(shader.name)); + Com_Memcpy (shader.lightmapIndex, lightmapIndexes, sizeof (shader.lightmapIndex)); + Com_Memcpy (shader.styles, styles, sizeof (shader.styles)); + switch (lightmapIndexes[0]) { + case LIGHTMAP_2D: + case LIGHTMAP_WHITEIMAGE: + { + shader.isHDRLit = qfalse; + break; + } + default: + { + shader.isHDRLit = tr.hdrLighting; + break; + } + } + + // + // attempt to define shader from an explicit parameter file + // + shaderText = FindShaderInShaderText( strippedName ); + if ( shaderText ) { + // enable this when building a pak file to get a global list + // of all explicit shaders + if ( r_printShaders->integer ) { + ri.Printf( PRINT_ALL, "*SHADER* %s\n", name ); + } + + if ( !ParseShader( &shaderText ) ) { + // had errors, so use default shader + shader.defaultShader = qtrue; + } + sh = FinishShader(); + return sh; + } + + + // + // if not defined in the in-memory shader descriptions, + // look for a single supported image file + // + + flags = IMGFLAG_NONE; + + if (shader.isHDRLit == qtrue) + flags |= IMGFLAG_SRGB; + + if (mipRawImage) + { + flags |= IMGFLAG_MIPMAP | IMGFLAG_PICMIP; + + if (r_genNormalMaps->integer) + flags |= IMGFLAG_GENNORMALMAP; + } + else + { + flags |= IMGFLAG_CLAMPTOEDGE; + } + + image = R_FindImageFile( name, IMGTYPE_COLORALPHA, flags ); + if ( !image ) { + ri.Printf( PRINT_DEVELOPER, "Couldn't find image file for shader %s\n", name ); + shader.defaultShader = qtrue; + return FinishShader(); + } + + // + // create the default shading commands + // + if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + // dynamic colors at vertexes + stages[0].bundle[0].image[0] = image; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; + stages[0].stateBits = GLS_DEFAULT; + } else if ( shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX ) { + // explicit colors at vertexes + stages[0].bundle[0].image[0] = image; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_EXACT_VERTEX; + stages[0].alphaGen = AGEN_SKIP; + stages[0].stateBits = GLS_DEFAULT; + } else if ( shader.lightmapIndex[0] == LIGHTMAP_2D ) { + // GUI elements + stages[0].bundle[0].image[0] = image; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_VERTEX; + stages[0].alphaGen = AGEN_VERTEX; + stages[0].stateBits = GLS_DEPTHTEST_DISABLE | + GLS_SRCBLEND_SRC_ALPHA | + GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + } else if ( shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE ) { + // fullbright level + stages[0].bundle[0].image[0] = tr.whiteImage; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; + stages[0].stateBits = GLS_DEFAULT; + + stages[1].bundle[0].image[0] = image; + stages[1].active = qtrue; + stages[1].rgbGen = CGEN_IDENTITY; + stages[1].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO; + } else { + // two pass lightmap + stages[0].bundle[0].image[0] = tr.lightmaps[shader.lightmapIndex[0]]; + stages[0].bundle[0].isLightmap = qtrue; + if (r_deluxeMapping->integer && tr.worldDeluxeMapping) + stages[0].bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[0]]; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation + // for identitylight + stages[0].stateBits = GLS_DEFAULT; + + stages[1].bundle[0].image[0] = image; + stages[1].active = qtrue; + stages[1].rgbGen = CGEN_IDENTITY; + stages[1].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO; + } + + return FinishShader(); +} + +shader_t *R_FindServerShader( const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage ) +{ + char strippedName[MAX_QPATH]; + int hash; + shader_t *sh; + + if ( name[0] == 0 ) { + return tr.defaultShader; + } + + COM_StripExtension( name, strippedName, sizeof( strippedName ) ); + + hash = generateHashValue(strippedName, FILE_HASH_SIZE); + + // + // see if the shader is already loaded + // + for (sh = hashTable[hash]; sh; sh = sh->next) { + // NOTE: if there was no shader or image available with the name strippedName + // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we + // have to check all default shaders otherwise for every call to R_FindShader + // with that same strippedName a new default shader is created. + if ( IsShader (sh, name, lightmapIndexes, styles) ) { + // match found + return sh; + } + } + + // clear the global shader + ClearGlobalShader(); + Q_strncpyz(shader.name, strippedName, sizeof(shader.name)); + Com_Memcpy (shader.lightmapIndex, lightmapIndexes, sizeof (shader.lightmapIndex)); + + shader.defaultShader = qtrue; + return FinishShader(); +} + +qhandle_t RE_RegisterShaderFromImage(const char *name, const int *lightmapIndexes, const byte *styles, image_t *image, qboolean mipRawImage) { + int hash; + shader_t *sh; + + hash = generateHashValue(name, FILE_HASH_SIZE); + + // probably not necessary since this function + // only gets called from tr_font.c with lightmapIndex == LIGHTMAP_2D + // but better safe than sorry. + if ( lightmapIndexes[0] >= tr.numLightmaps ) { + lightmapIndexes = lightmapsFullBright; + } + + // + // see if the shader is already loaded + // + for (sh=hashTable[hash]; sh; sh=sh->next) { + // NOTE: if there was no shader or image available with the name strippedName + // then a default shader is created with lightmapIndex == LIGHTMAP_NONE, so we + // have to check all default shaders otherwise for every call to R_FindShader + // with that same strippedName a new default shader is created. + if ( IsShader (sh, name, lightmapIndexes, styles) ) { + // match found + return sh->index; + } + } + + // clear the global shader + ClearGlobalShader(); + Q_strncpyz(shader.name, name, sizeof(shader.name)); + Com_Memcpy (shader.lightmapIndex, lightmapIndexes, sizeof (shader.lightmapIndex)); + + // + // create the default shading commands + // + shader.isHDRLit = tr.hdrLighting; + if ( shader.lightmapIndex[0] == LIGHTMAP_NONE ) { + // dynamic colors at vertexes + stages[0].bundle[0].image[0] = image; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_LIGHTING_DIFFUSE; + stages[0].stateBits = GLS_DEFAULT; + } else if ( shader.lightmapIndex[0] == LIGHTMAP_BY_VERTEX ) { + // explicit colors at vertexes + stages[0].bundle[0].image[0] = image; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_EXACT_VERTEX; + stages[0].alphaGen = AGEN_SKIP; + stages[0].stateBits = GLS_DEFAULT; + } else if ( shader.lightmapIndex[0] == LIGHTMAP_2D ) { + // GUI elements + stages[0].bundle[0].image[0] = image; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_VERTEX; + stages[0].alphaGen = AGEN_VERTEX; + stages[0].stateBits = GLS_DEPTHTEST_DISABLE | + GLS_SRCBLEND_SRC_ALPHA | + GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA; + shader.isHDRLit = qfalse; + } else if ( shader.lightmapIndex[0] == LIGHTMAP_WHITEIMAGE ) { + // fullbright level + stages[0].bundle[0].image[0] = tr.whiteImage; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_IDENTITY_LIGHTING; + stages[0].stateBits = GLS_DEFAULT; + + stages[1].bundle[0].image[0] = image; + stages[1].active = qtrue; + stages[1].rgbGen = CGEN_IDENTITY; + stages[1].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO; + shader.isHDRLit = qfalse; + } else { + // two pass lightmap + stages[0].bundle[0].image[0] = tr.lightmaps[shader.lightmapIndex[0]]; + stages[0].bundle[0].isLightmap = qtrue; + if (r_deluxeMapping->integer && tr.worldDeluxeMapping) + stages[0].bundle[TB_DELUXEMAP].image[0] = tr.deluxemaps[shader.lightmapIndex[0]]; + stages[0].active = qtrue; + stages[0].rgbGen = CGEN_IDENTITY; // lightmaps are scaled on creation + // for identitylight + stages[0].stateBits = GLS_DEFAULT; + + stages[1].bundle[0].image[0] = image; + stages[1].active = qtrue; + stages[1].rgbGen = CGEN_IDENTITY; + stages[1].stateBits |= GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO; + } + + sh = FinishShader(); + return sh->index; +} + + +/* +==================== +RE_RegisterShader + +This is the exported shader entry point for the rest of the system +It will always return an index that will be valid. + +This should really only be used for explicit shaders, because there is no +way to ask for different implicit lighting modes (vertex, lightmap, etc) +==================== +*/ +qhandle_t RE_RegisterShaderLightMap( const char *name, const int *lightmapIndexes, const byte *styles ) { + shader_t *sh; + + if ( strlen( name ) >= MAX_QPATH ) { + ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + return 0; + } + + sh = R_FindShader( name, lightmapIndexes, styles, qtrue ); + + // we want to return 0 if the shader failed to + // load for some reason, but R_FindShader should + // still keep a name allocated for it, so if + // something calls RE_RegisterShader again with + // the same name, we don't try looking for it again + if ( sh->defaultShader ) { + return 0; + } + + return sh->index; +} + + +/* +==================== +RE_RegisterShader + +This is the exported shader entry point for the rest of the system +It will always return an index that will be valid. + +This should really only be used for explicit shaders, because there is no +way to ask for different implicit lighting modes (vertex, lightmap, etc) +==================== +*/ +qhandle_t RE_RegisterShader( const char *name ) { + shader_t *sh; + + if ( strlen( name ) >= MAX_QPATH ) { + ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + return 0; + } + + sh = R_FindShader( name, lightmaps2d, stylesDefault, qtrue ); + + // we want to return 0 if the shader failed to + // load for some reason, but R_FindShader should + // still keep a name allocated for it, so if + // something calls RE_RegisterShader again with + // the same name, we don't try looking for it again + if ( sh->defaultShader ) { + return 0; + } + + return sh->index; +} + + +/* +==================== +RE_RegisterShaderNoMip + +For menu graphics that should never be picmiped +==================== +*/ +qhandle_t RE_RegisterShaderNoMip( const char *name ) { + shader_t *sh; + + if ( strlen( name ) >= MAX_QPATH ) { + ri.Printf( PRINT_ALL, "Shader name exceeds MAX_QPATH\n" ); + return 0; + } + + sh = R_FindShader( name, lightmaps2d, stylesDefault, qfalse ); + + // we want to return 0 if the shader failed to + // load for some reason, but R_FindShader should + // still keep a name allocated for it, so if + // something calls RE_RegisterShader again with + // the same name, we don't try looking for it again + if ( sh->defaultShader ) { + return 0; + } + + return sh->index; +} + +//added for ui -rww +const char *RE_ShaderNameFromIndex(int index) +{ + assert(index >= 0 && index < tr.numShaders && tr.shaders[index]); + return tr.shaders[index]->name; +} + +/* +==================== +R_GetShaderByHandle + +When a handle is passed in by another module, this range checks +it and returns a valid (possibly default) shader_t to be used internally. +==================== +*/ +shader_t *R_GetShaderByHandle( qhandle_t hShader ) { + if ( hShader < 0 ) { + ri.Printf( PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); + return tr.defaultShader; + } + if ( hShader >= tr.numShaders ) { + ri.Printf( PRINT_WARNING, "R_GetShaderByHandle: out of range hShader '%d'\n", hShader ); + return tr.defaultShader; + } + return tr.shaders[hShader]; +} + +/* +=============== +R_ShaderList_f + +Dump information on all valid shaders to the console +A second parameter will cause it to print in sorted order +=============== +*/ +void R_ShaderList_f (void) { + int i; + int count; + shader_t *shader; + + ri.Printf (PRINT_ALL, "-----------------------\n"); + + count = 0; + for ( i = 0 ; i < tr.numShaders ; i++ ) { + if ( ri.Cmd_Argc() > 1 ) { + shader = tr.sortedShaders[i]; + } else { + shader = tr.shaders[i]; + } + + ri.Printf( PRINT_ALL, "%i ", shader->numUnfoggedPasses ); + + if (shader->lightmapIndex[0] >= 0 ) { + ri.Printf (PRINT_ALL, "L "); + } else { + ri.Printf (PRINT_ALL, " "); + } + + if ( shader->explicitlyDefined ) { + ri.Printf( PRINT_ALL, "E " ); + } else { + ri.Printf( PRINT_ALL, " " ); + } + + if ( shader->optimalStageIteratorFunc == RB_StageIteratorGeneric ) { + ri.Printf( PRINT_ALL, "gen " ); + } else if ( shader->optimalStageIteratorFunc == RB_StageIteratorSky ) { + ri.Printf( PRINT_ALL, "sky " ); + } else { + ri.Printf( PRINT_ALL, " " ); + } + + if ( shader->defaultShader ) { + ri.Printf (PRINT_ALL, ": %s (DEFAULTED)\n", shader->name); + } else { + ri.Printf (PRINT_ALL, ": %s\n", shader->name); + } + count++; + } + ri.Printf (PRINT_ALL, "%i total shaders\n", count); + ri.Printf (PRINT_ALL, "------------------\n"); +} + +/* +==================== +ScanAndLoadShaderFiles + +Finds and loads all .shader files, combining them into +a single large text block that can be scanned for shader names +===================== +*/ +#define MAX_SHADER_FILES 4096 +static void ScanAndLoadShaderFiles( void ) +{ + char **shaderFiles; + char *buffers[MAX_SHADER_FILES]; + const char *p; + char *pw; + int numShaderFiles; + int i; + const char *token, *oldp; + char *hashMem; + int shaderTextHashTableSizes[MAX_SHADERTEXT_HASH], hash, size; + int sum; + + // scan for shader files + shaderFiles = ri.FS_ListFiles( "shaders", ".shader", &numShaderFiles ); + + + if ( numShaderFiles > MAX_SHADER_FILES ) { + ri.Printf( PRINT_WARNING, "WARNING: too many shader files, truncating...\n" ); + numShaderFiles = MAX_SHADER_FILES; + } + + if (numShaderFiles == 0) { + ri.Error( ERR_FATAL, "ERROR: no shader files found" ); + } + + assert(numShaderFiles > 0); + sum = 0; + // load and parse shader files + for ( i = 0; i < numShaderFiles; i++) + { + char filename[MAX_QPATH]; + + Com_sprintf( filename, sizeof( filename ), "%s/%s", "shaders", shaderFiles[i] ); + ri.Printf( PRINT_ALL, "...loading '%s'\n", filename ); + ri.FS_ReadFile( filename, (void **)&buffers[i] ); + if ( !buffers[i] ) { + ri.Error( ERR_DROP, "Couldn't load %s", filename ); + } + sum += COM_Compress(buffers[i]); + } + + // build single large buffer + s_shaderText = (char *)ri.Hunk_Alloc( sum + numShaderFiles + 1, h_low ); + pw = s_shaderText; + for ( i = 0; i < numShaderFiles ; i++ ) { + strcat( pw, buffers[i] ); + strcat( pw, "\n" ); + pw += strlen( pw ); + ri.FS_FreeFile( (void*) buffers[i] ); + } + assert((int)strlen(s_shaderText) == sum + numShaderFiles); + + // free up memory + ri.FS_FreeFileList( shaderFiles ); + + Com_Memset(shaderTextHashTableSizes, 0, sizeof(shaderTextHashTableSizes)); + size = 0; + p = s_shaderText; + + while ( 1 ) { + // look for label + token = COM_ParseExt( &p, qtrue ); + if ( token[0] == 0 ) { + break; + } + + hash = generateHashValue(token, MAX_SHADERTEXT_HASH); + shaderTextHashTableSizes[hash]++; + size++; + SkipBracedSection(&p, 0); + } + + size += MAX_SHADERTEXT_HASH; + + hashMem = (char *)ri.Hunk_Alloc( size * sizeof(char *), h_low ); + + for (i = 0; i < MAX_SHADERTEXT_HASH; i++) { + shaderTextHashTable[i] = (const char **) hashMem; + hashMem = ((char *) hashMem) + ((shaderTextHashTableSizes[i] + 1) * sizeof(char *)); + } + + Com_Memset(shaderTextHashTableSizes, 0, sizeof(shaderTextHashTableSizes)); + + // look for label + p = s_shaderText; + while ( 1 ) { + oldp = p; + token = COM_ParseExt( &p, qtrue ); + if ( token[0] == 0 ) { + break; + } + + hash = generateHashValue(token, MAX_SHADERTEXT_HASH); + shaderTextHashTable[hash][shaderTextHashTableSizes[hash]++] = oldp; + + SkipBracedSection(&p, 0); + } +} + +shader_t *R_CreateShaderFromTextureBundle( + const char *name, + const textureBundle_t *bundle, + uint32_t stateBits) +{ + shader_t *result = R_FindShaderByName(name); + if ( result == tr.defaultShader ) + { + Com_Memset(&shader, 0, sizeof(shader)); + Com_Memset(&stages, 0, sizeof(stages)); + + Q_strncpyz(shader.name, name, sizeof(shader.name)); + + stages[0].active = qtrue; + stages[0].bundle[0] = *bundle; + stages[0].stateBits = stateBits; + result = FinishShader(); + } + return result; +} + +/* +==================== +CreateInternalShaders +==================== +*/ +static void CreateInternalShaders( void ) { + tr.numShaders = 0; + + // init the default shader + Com_Memset( &shader, 0, sizeof( shader ) ); + Com_Memset( &stages, 0, sizeof( stages ) ); + + Q_strncpyz( shader.name, "", sizeof( shader.name ) ); + + Com_Memcpy (shader.lightmapIndex, lightmapsNone, sizeof (shader.lightmapIndex)); + for ( int i = 0 ; i < MAX_SHADER_STAGES ; i++ ) { + stages[i].bundle[0].texMods = texMods[i]; + } + + stages[0].bundle[0].image[0] = tr.defaultImage; + stages[0].active = qtrue; + stages[0].stateBits = GLS_DEFAULT; + tr.defaultShader = FinishShader(); + + // shadow shader is just a marker + Q_strncpyz( shader.name, "", sizeof( shader.name ) ); + shader.sort = SS_BANNER; //SS_STENCIL_SHADOW; + tr.shadowShader = FinishShader(); + + // distortion shader is just a marker + Q_strncpyz( shader.name, "internal_distortion", sizeof( shader.name ) ); + shader.sort = SS_BLEND0; + shader.defaultShader = qfalse; + tr.distortionShader = FinishShader(); + tr.distortionShader->useDistortion = qtrue; + shader.defaultShader = qtrue; + + // weather shader placeholder + Q_strncpyz(shader.name, "", sizeof(shader.name)); + shader.sort = SS_SEE_THROUGH; + tr.weatherInternalShader = FinishShader(); +} + +static void CreateExternalShaders( void ) { + tr.projectionShadowShader = R_FindShader( "projectionShadow", lightmapsNone, stylesDefault, qtrue ); + tr.flareShader = R_FindShader( "gfx/misc/flare", lightmapsNone, stylesDefault, qtrue ); + + tr.sunShader = R_FindShader( "sun", lightmapsNone, stylesDefault, qtrue ); + + tr.sunFlareShader = R_FindShader( "gfx/2d/sunflare", lightmapsNone, stylesDefault, qtrue); + + // HACK: if sunflare is missing, make one using the flare image or dlight image + if (tr.sunFlareShader->defaultShader) + { + image_t *image; + + if (!tr.flareShader->defaultShader && tr.flareShader->stages[0] && tr.flareShader->stages[0]->bundle[0].image[0]) + image = tr.flareShader->stages[0]->bundle[0].image[0]; + else + image = tr.dlightImage; + + Com_Memset( &shader, 0, sizeof( shader ) ); + Com_Memset( &stages, 0, sizeof( stages ) ); + + Q_strncpyz( shader.name, "gfx/2d/sunflare", sizeof( shader.name ) ); + + Com_Memcpy (shader.lightmapIndex, lightmapsNone, sizeof (shader.lightmapIndex)); + stages[0].bundle[0].image[0] = image; + stages[0].active = qtrue; + stages[0].stateBits = GLS_DEFAULT; + tr.sunFlareShader = FinishShader(); + } + +} + +/* +================== +R_InitShaders +================== +*/ +void R_InitShaders( qboolean server ) { + ri.Printf( PRINT_ALL, "Initializing Shaders\n" ); + + Com_Memset(hashTable, 0, sizeof(hashTable)); + + if ( !server ) + { + CreateInternalShaders(); + + ScanAndLoadShaderFiles(); + + CreateExternalShaders(); + } +} diff --git a/codemp/rd-rend2/tr_shadows.cpp b/codemp/rd-rend2/tr_shadows.cpp new file mode 100644 index 0000000000..eb0b472dfc --- /dev/null +++ b/codemp/rd-rend2/tr_shadows.cpp @@ -0,0 +1,121 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +#include "tr_local.h" + +/* +================= +RB_ShadowFinish + +Darken everything that is is a shadow volume. +We have to delay this until everything has been shadowed, +because otherwise shadows from different body parts would +overlap and double darken. +================= +*/ +void RB_ShadowFinish(void) { + if (r_shadows->integer != 2) { + return; + } + if (glConfig.stencilBits < 4) { + return; + } + + GL_Cull(CT_TWO_SIDED); + + GL_BindToTMU(tr.whiteImage, TB_COLORMAP); + + GL_State(GLS_STENCILTEST_ENABLE | GLS_DEPTHMASK_TRUE | GLS_SRCBLEND_DST_COLOR | GLS_DSTBLEND_ZERO); + + qglStencilFunc(GL_NOTEQUAL, 0, 0xff); + qglViewport(0, 0, glConfig.vidWidth, glConfig.vidHeight); + qglScissor(0, 0, glConfig.vidWidth, glConfig.vidHeight); + matrix_t projection; + Matrix16Ortho(0, glConfig.vidWidth, glConfig.vidHeight, 0, 0, 1, projection); + + GL_Cull(CT_TWO_SIDED); + GLSL_BindProgram(&tr.textureColorShader); + vec4_t color; + VectorSet4(color, 0.6f, 0.6f, 0.6f, 1.0f); + GLSL_SetUniformVec4(&tr.textureColorShader, UNIFORM_COLOR, color); + GLSL_SetUniformMatrix4x4(&tr.textureColorShader, UNIFORM_MODELVIEWPROJECTIONMATRIX, projection); + + vec4i_t dstBox; + vec4_t quadVerts[4]; + vec2_t texCoords[4]; + VectorSet4(dstBox, 0, glConfig.vidHeight, glConfig.vidWidth, 0); + + VectorSet4(quadVerts[0], dstBox[0], dstBox[1], 0, 1); + VectorSet4(quadVerts[1], dstBox[2], dstBox[1], 0, 1); + VectorSet4(quadVerts[2], dstBox[2], dstBox[3], 0, 1); + VectorSet4(quadVerts[3], dstBox[0], dstBox[3], 0, 1); + + RB_InstantQuad2(quadVerts, texCoords); + + qglStencilFunc(GL_ALWAYS, 0, 0xff); +} + + +/* +================= +RB_ProjectionShadowDeform + +================= +*/ +void RB_ProjectionShadowDeform( void ) { + float *xyz; + int i; + float h; + vec3_t ground; + vec3_t light; + float groundDist; + float d; + vec3_t lightDir; + + xyz = ( float * ) tess.xyz; + + ground[0] = backEnd.ori.axis[0][2]; + ground[1] = backEnd.ori.axis[1][2]; + ground[2] = backEnd.ori.axis[2][2]; + + groundDist = backEnd.ori.origin[2] - backEnd.currentEntity->e.shadowPlane; + + VectorCopy( backEnd.currentEntity->modelLightDir, lightDir ); + d = DotProduct( lightDir, ground ); + // don't let the shadows get too long or go negative + if ( d < 0.5 ) { + VectorMA( lightDir, (0.5 - d), ground, lightDir ); + d = DotProduct( lightDir, ground ); + } + d = 1.0 / d; + + light[0] = lightDir[0] * d; + light[1] = lightDir[1] * d; + light[2] = lightDir[2] * d; + + for ( i = 0; i < tess.numVertexes; i++, xyz += 4 ) { + h = DotProduct( xyz, ground ) + groundDist; + + xyz[0] -= light[0] * h; + xyz[1] -= light[1] * h; + xyz[2] -= light[2] * h; + } +} diff --git a/codemp/rd-rend2/tr_skin.cpp b/codemp/rd-rend2/tr_skin.cpp new file mode 100644 index 0000000000..d14f211b6a --- /dev/null +++ b/codemp/rd-rend2/tr_skin.cpp @@ -0,0 +1,417 @@ +#include "tr_local.h" + +/* +============================================================================ + +SKINS + +============================================================================ +*/ + +static char *CommaParse( char **data_p ); +//can't be dec'd here since we need it for non-dedicated builds now as well. + +/* +=============== +RE_RegisterSkin + +=============== +*/ + +bool gServerSkinHack = false; + + +shader_t *R_FindServerShader( const char *name, const int *lightmapIndexes, const byte *styles, qboolean mipRawImage ) ; +static char *CommaParse( char **data_p ); +/* +=============== +RE_SplitSkins +input = skinname, possibly being a macro for three skins +return= true if three part skins found +output= qualified names to three skins if return is true, undefined if false +=============== +*/ +bool RE_SplitSkins(const char *INname, char *skinhead, char *skintorso, char *skinlower) +{ //INname= "models/players/jedi_tf/|head01_skin1|torso01|lower01"; + if (strchr(INname, '|')) + { + char name[MAX_QPATH]; + strcpy(name, INname); + char *p = strchr(name, '|'); + *p=0; + p++; + //fill in the base path + strcpy (skinhead, name); + strcpy (skintorso, name); + strcpy (skinlower, name); + + //now get the the individual files + + //advance to second + char *p2 = strchr(p, '|'); + assert(p2); + if (!p2) + { + return false; + } + *p2=0; + p2++; + strcat (skinhead, p); + strcat (skinhead, ".skin"); + + + //advance to third + p = strchr(p2, '|'); + assert(p); + if (!p) + { + return false; + } + *p=0; + p++; + strcat (skintorso,p2); + strcat (skintorso, ".skin"); + + strcat (skinlower,p); + strcat (skinlower, ".skin"); + + return true; + } + return false; +} + +// given a name, go get the skin we want and return +qhandle_t RE_RegisterIndividualSkin( const char *name , qhandle_t hSkin) +{ + skin_t *skin; + skinSurface_t *surf; + char *text, *text_p; + char *token; + char surfName[MAX_QPATH]; + + // load and parse the skin file + ri.FS_ReadFile( name, (void **)&text ); + if ( !text ) { +#ifndef FINAL_BUILD + Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) failed to load!\n", name ); +#endif + return 0; + } + + assert (tr.skins[hSkin]); //should already be setup, but might be an 3part append + + skin = tr.skins[hSkin]; + + text_p = text; + while ( text_p && *text_p ) { + // get surface name + token = CommaParse( &text_p ); + Q_strncpyz( surfName, token, sizeof( surfName ) ); + + if ( !token[0] ) { + break; + } + // lowercase the surface name so skin compares are faster + Q_strlwr( surfName ); + + if ( *text_p == ',' ) { + text_p++; + } + + if ( !strncmp( token, "tag_", 4 ) ) { //these aren't in there, but just in case you load an id style one... + continue; + } + + // parse the shader name + token = CommaParse( &text_p ); + + if ( !strcmp( &surfName[strlen(surfName)-4], "_off") ) + { + if ( !strcmp( token ,"*off" ) ) + { + continue; //don't need these double offs + } + surfName[strlen(surfName)-4] = 0; //remove the "_off" + } + if ( (unsigned)skin->numSurfaces >= ARRAY_LEN( skin->surfaces ) ) + { + assert( ARRAY_LEN( skin->surfaces ) > (unsigned)skin->numSurfaces ); + Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) more than %d surfaces!\n", name, ARRAY_LEN( skin->surfaces ) ); + break; + } + surf = (skinSurface_t *) Hunk_Alloc( sizeof( *skin->surfaces[0] ), h_low ); + skin->surfaces[skin->numSurfaces] = (_skinSurface_t *)surf; + + Q_strncpyz( surf->name, surfName, sizeof( surf->name ) ); + + if (gServerSkinHack) surf->shader = R_FindServerShader( token, lightmapsNone, stylesDefault, qtrue ); + else surf->shader = R_FindShader( token, lightmapsNone, stylesDefault, qtrue ); + skin->numSurfaces++; + } + + ri.FS_FreeFile( text ); + + + // never let a skin have 0 shaders + if ( skin->numSurfaces == 0 ) { + return 0; // use default skin + } + + return hSkin; +} + +qhandle_t RE_RegisterSkin( const char *name ) { + qhandle_t hSkin; + skin_t *skin; + + if ( !name || !name[0] ) { + Com_Printf( "Empty name passed to RE_RegisterSkin\n" ); + return 0; + } + + if ( strlen( name ) >= MAX_QPATH ) { + Com_Printf( "Skin name exceeds MAX_QPATH\n" ); + return 0; + } + + // see if the skin is already loaded + for ( hSkin = 1; hSkin < tr.numSkins ; hSkin++ ) { + skin = tr.skins[hSkin]; + if ( !Q_stricmp( skin->name, name ) ) { + if( skin->numSurfaces == 0 ) { + return 0; // default skin + } + return hSkin; + } + } + + // allocate a new skin + if ( tr.numSkins == MAX_SKINS ) { + Com_Printf( "WARNING: RE_RegisterSkin( '%s' ) MAX_SKINS hit\n", name ); + return 0; + } + tr.numSkins++; + skin = (struct skin_s *)Hunk_Alloc( sizeof( skin_t ), h_low ); + tr.skins[hSkin] = skin; + Q_strncpyz( skin->name, name, sizeof( skin->name ) ); + skin->numSurfaces = 0; + + // make sure the render thread is stopped + R_IssuePendingRenderCommands(); + + // If not a .skin file, load as a single shader + if ( strcmp( name + strlen( name ) - 5, ".skin" ) ) { +/* skin->numSurfaces = 1; + skin->surfaces[0] = (skinSurface_t *)Hunk_Alloc( sizeof(skin->surfaces[0]), h_low ); + skin->surfaces[0]->shader = R_FindShader( name, lightmapsNone, stylesDefault, qtrue ); + return hSkin; +*/ + } + + char skinhead[MAX_QPATH]={0}; + char skintorso[MAX_QPATH]={0}; + char skinlower[MAX_QPATH]={0}; + if ( RE_SplitSkins(name, (char*)&skinhead, (char*)&skintorso, (char*)&skinlower ) ) + {//three part + hSkin = RE_RegisterIndividualSkin(skinhead, hSkin); + if (hSkin) + { + hSkin = RE_RegisterIndividualSkin(skintorso, hSkin); + if (hSkin) + { + hSkin = RE_RegisterIndividualSkin(skinlower, hSkin); + } + } + } + else + {//single skin + hSkin = RE_RegisterIndividualSkin(name, hSkin); + } + return(hSkin); +} + + + +/* +================== +CommaParse + +This is unfortunate, but the skin files aren't +compatible with our normal parsing rules. +================== +*/ +static char *CommaParse( char **data_p ) { + int c = 0, len; + char *data; + static char com_token[MAX_TOKEN_CHARS]; + + data = *data_p; + len = 0; + com_token[0] = 0; + + // make sure incoming data is valid + if ( !data ) { + *data_p = NULL; + return com_token; + } + + while ( 1 ) { + // skip whitespace + while( (c = *data) <= ' ') { + if( !c ) { + break; + } + data++; + } + + + c = *data; + + // skip double slash comments + if ( c == '/' && data[1] == '/' ) + { + while (*data && *data != '\n') + data++; + } + // skip /* */ comments + else if ( c=='/' && data[1] == '*' ) + { + while ( *data && ( *data != '*' || data[1] != '/' ) ) + { + data++; + } + if ( *data ) + { + data += 2; + } + } + else + { + break; + } + } + + if ( c == 0 ) { + return ""; + } + + // handle quoted strings + if (c == '\"') + { + data++; + while (1) + { + c = *data++; + if (c=='\"' || !c) + { + com_token[len] = 0; + *data_p = ( char * ) data; + return com_token; + } + if (len < MAX_TOKEN_CHARS) + { + com_token[len] = c; + len++; + } + } + } + + // parse a regular word + do + { + if (len < MAX_TOKEN_CHARS) + { + com_token[len] = c; + len++; + } + data++; + c = *data; + } while (c>32 && c != ',' ); + + if (len == MAX_TOKEN_CHARS) + { +// Com_Printf ("Token exceeded %i chars, discarded.\n", MAX_TOKEN_CHARS); + len = 0; + } + com_token[len] = 0; + + *data_p = ( char * ) data; + return com_token; +} + +/* +=============== +RE_RegisterServerSkin + +Mangled version of the above function to load .skin files on the server. +=============== +*/ +qhandle_t RE_RegisterServerSkin( const char *name ) { + qhandle_t r; + + if (ri.Cvar_VariableIntegerValue( "cl_running" ) && + ri.Com_TheHunkMarkHasBeenMade() && + ShaderHashTableExists()) + { //If the client is running then we can go straight into the normal registerskin func + return RE_RegisterSkin(name); + } + + gServerSkinHack = true; + r = RE_RegisterSkin(name); + gServerSkinHack = false; + + return r; +} + +/* +=============== +R_InitSkins +=============== +*/ +void R_InitSkins( void ) { + skin_t *skin; + + tr.numSkins = 1; + + // make the default skin have all default shaders + skin = tr.skins[0] = (struct skin_s *)ri.Hunk_Alloc( sizeof( skin_t ), h_low ); + Q_strncpyz( skin->name, "", sizeof( skin->name ) ); + skin->numSurfaces = 1; + skin->surfaces[0] = (_skinSurface_t *)ri.Hunk_Alloc( sizeof( skinSurface_t ), h_low ); + skin->surfaces[0]->shader = tr.defaultShader; +} + +/* +=============== +R_GetSkinByHandle +=============== +*/ +skin_t *R_GetSkinByHandle( qhandle_t hSkin ) { + if ( hSkin < 1 || hSkin >= tr.numSkins ) { + return tr.skins[0]; + } + return tr.skins[ hSkin ]; +} + +/* +=============== +R_SkinList_f +=============== +*/ +void R_SkinList_f( void ) { + int i, j; + skin_t *skin; + + Com_Printf ( "------------------\n"); + + for ( i = 0 ; i < tr.numSkins ; i++ ) { + skin = tr.skins[i]; + + Com_Printf ("%3i:%s\n", i, skin->name ); + for ( j = 0 ; j < skin->numSurfaces ; j++ ) { + Com_Printf (" %s = %s\n", + skin->surfaces[j]->name, ((shader_t* )skin->surfaces[j]->shader)->name ); + } + } + Com_Printf ( "------------------\n"); +} diff --git a/codemp/rd-rend2/tr_sky.cpp b/codemp/rd-rend2/tr_sky.cpp new file mode 100644 index 0000000000..98a60c6058 --- /dev/null +++ b/codemp/rd-rend2/tr_sky.cpp @@ -0,0 +1,871 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_sky.c +#include "tr_local.h" + +#define SKY_SUBDIVISIONS 8 +#define HALF_SKY_SUBDIVISIONS (SKY_SUBDIVISIONS/2) + +static float s_cloudTexCoords[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2]; +static float s_cloudTexP[6][SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1]; + +/* +=================================================================================== + +POLYGON TO BOX SIDE PROJECTION + +=================================================================================== +*/ + +static vec3_t sky_clip[6] = +{ + {1,1,0}, + {1,-1,0}, + {0,-1,1}, + {0,1,1}, + {1,0,1}, + {-1,0,1} +}; + +static float sky_mins[2][6], sky_maxs[2][6]; +static float sky_min, sky_max; + +/* +================ +AddSkyPolygon +================ +*/ +static void AddSkyPolygon (int nump, vec3_t vecs) +{ + int i,j; + vec3_t v, av; + float s, t, dv; + int axis; + float *vp; + // s = [0]/[2], t = [1]/[2] + static int vec_to_st[6][3] = + { + {-2,3,1}, + {2,3,-1}, + + {1,3,2}, + {-1,3,-2}, + + {-2,-1,3}, + {-2,1,-3} + + // {-1,2,3}, + // {1,2,-3} + }; + + // decide which face it maps to + VectorCopy (vec3_origin, v); + for (i=0, vp=vecs ; i av[1] && av[0] > av[2]) + { + if (v[0] < 0) + axis = 1; + else + axis = 0; + } + else if (av[1] > av[2] && av[1] > av[0]) + { + if (v[1] < 0) + axis = 3; + else + axis = 2; + } + else + { + if (v[2] < 0) + axis = 5; + else + axis = 4; + } + + // project new texture coords + for (i=0 ; i 0) + dv = vecs[j - 1]; + else + dv = -vecs[-j - 1]; + if (dv < 0.001) + continue; // don't divide by zero + j = vec_to_st[axis][0]; + if (j < 0) + s = -vecs[-j -1] / dv; + else + s = vecs[j-1] / dv; + j = vec_to_st[axis][1]; + if (j < 0) + t = -vecs[-j -1] / dv; + else + t = vecs[j-1] / dv; + + if (s < sky_mins[0][axis]) + sky_mins[0][axis] = s; + if (t < sky_mins[1][axis]) + sky_mins[1][axis] = t; + if (s > sky_maxs[0][axis]) + sky_maxs[0][axis] = s; + if (t > sky_maxs[1][axis]) + sky_maxs[1][axis] = t; + } +} + +#define ON_EPSILON 0.1f // point on plane side epsilon +#define MAX_CLIP_VERTS 64 +/* +================ +ClipSkyPolygon +================ +*/ +static void ClipSkyPolygon (int nump, vec3_t vecs, int stage) +{ + float *norm; + float *v; + qboolean front, back; + float d, e; + float dists[MAX_CLIP_VERTS]; + int sides[MAX_CLIP_VERTS]; + vec3_t newv[2][MAX_CLIP_VERTS]; + int newc[2]; + int i, j; + + if (nump > MAX_CLIP_VERTS-2) + ri.Error (ERR_DROP, "ClipSkyPolygon: MAX_CLIP_VERTS"); + if (stage == 6) + { // fully clipped, so draw it + AddSkyPolygon (nump, vecs); + return; + } + + front = back = qfalse; + norm = sky_clip[stage]; + for (i=0, v = vecs ; i ON_EPSILON) + { + front = qtrue; + sides[i] = SIDE_FRONT; + } + else if (d < -ON_EPSILON) + { + back = qtrue; + sides[i] = SIDE_BACK; + } + else + sides[i] = SIDE_ON; + dists[i] = d; + } + + if (!front || !back) + { // not clipped + ClipSkyPolygon (nump, vecs, stage+1); + return; + } + + // clip it + sides[i] = sides[0]; + dists[i] = dists[0]; + VectorCopy (vecs, (vecs+(i*3)) ); + newc[0] = newc[1] = 0; + + for (i=0, v = vecs ; inumIndexes; i += 3 ) + { + for (j = 0 ; j < 3 ; j++) + { + VectorSubtract( input->xyz[input->indexes[i+j]], + backEnd.viewParms.ori.origin, + p[j] ); + } + ClipSkyPolygon( 3, p[0], 0 ); + } +} + +/* +=================================================================================== + +CLOUD VERTEX GENERATION + +=================================================================================== +*/ + +/* +** MakeSkyVec +** +** Parms: s, t range from -1 to 1 +*/ +static void MakeSkyVec( float s, float t, int axis, float outSt[2], vec3_t outXYZ ) +{ + // 1 = s, 2 = t, 3 = 2048 + static int st_to_vec[6][3] = + { + {3,-1,2}, + {-3,1,2}, + + {1,3,2}, + {-1,-3,2}, + + {-2,-1,3}, // 0 degrees yaw, look straight up + {2,-1,-3} // look straight down + }; + + vec3_t b; + int j, k; + float boxSize; + + boxSize = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + b[0] = s*boxSize; + b[1] = t*boxSize; + b[2] = boxSize; + + for (j=0 ; j<3 ; j++) + { + k = st_to_vec[axis][j]; + if (k < 0) + { + outXYZ[j] = -b[-k - 1]; + } + else + { + outXYZ[j] = b[k - 1]; + } + } + + // avoid bilerp seam + s = (s+1)*0.5; + t = (t+1)*0.5; + if (s < sky_min) + { + s = sky_min; + } + else if (s > sky_max) + { + s = sky_max; + } + + if (t < sky_min) + { + t = sky_min; + } + else if (t > sky_max) + { + t = sky_max; + } + + t = 1.0 - t; + + + if ( outSt ) + { + outSt[0] = s; + outSt[1] = t; + } +} + +static vec3_t s_skyPoints[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1]; +static float s_skyTexCoords[SKY_SUBDIVISIONS+1][SKY_SUBDIVISIONS+1][2]; + +static void DrawSkySide( struct image_s *image, const int mins[2], const int maxs[2] ) +{ + const uint32_t SKY_BOX_VERTEX_ATTRIBUTES = ATTR_POSITION | ATTR_TEXCOORD0 | ATTR_COLOR | ATTR_NORMAL; + int s, t; + int firstVertex = tess.numVertexes; + int minIndex = tess.minIndex; + int maxIndex = tess.maxIndex; + + tess.firstIndex = tess.numIndexes; + + for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; + t <= maxs[1]+HALF_SKY_SUBDIVISIONS; t++ ) + { + for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; + s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ ) + { + tess.xyz[tess.numVertexes][0] = s_skyPoints[t][s][0]; + tess.xyz[tess.numVertexes][1] = s_skyPoints[t][s][1]; + tess.xyz[tess.numVertexes][2] = s_skyPoints[t][s][2]; + tess.xyz[tess.numVertexes][3] = 1.0; + + tess.texCoords[tess.numVertexes][0][0] = s_skyTexCoords[t][s][0]; + tess.texCoords[tess.numVertexes][0][1] = s_skyTexCoords[t][s][1]; + + VectorSet4(tess.vertexColors[tess.numVertexes], 1.0f, 1.0f, 1.0f, 1.0f); + tess.normal[tess.numVertexes] = 0; + + tess.numVertexes++; + + if(tess.numVertexes >= SHADER_MAX_VERTEXES) + { + ri.Error(ERR_DROP, "SHADER_MAX_VERTEXES hit in DrawSkySideVBO()"); + } + } + } + + float ssize = maxs[0] - mins[0]; + float tsize = maxs[1] - mins[1]; + float ssizePlusOne = ssize + 1.0f; + for ( t = 0; t < tsize; t++ ) + { + for ( s = 0; s < ssize; s++ ) + { + if ((tess.numIndexes + 6) >= SHADER_MAX_INDEXES) + { + ri.Error(ERR_DROP, "SHADER_MAX_INDEXES hit in DrawSkySideVBO()"); + } + + tess.indexes[tess.numIndexes++] = s + t * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = s + (t + 1) * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = (s + 1) + t * ssizePlusOne + firstVertex; + + tess.indexes[tess.numIndexes++] = (s + 1) + t * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = s + (t + 1) * ssizePlusOne + firstVertex; + tess.indexes[tess.numIndexes++] = (s + 1) + (t + 1) * ssizePlusOne + firstVertex; + } + } + + tess.minIndex = firstVertex; + tess.maxIndex = tess.numVertexes; + tess.useInternalVBO = qtrue; + + RB_UpdateVBOs(SKY_BOX_VERTEX_ATTRIBUTES); + + VertexArraysProperties vertexArrays; + CalculateVertexArraysProperties(SKY_BOX_VERTEX_ATTRIBUTES, &vertexArrays); + for ( int i = 0; i < vertexArrays.numVertexArrays; i++ ) + { + int attributeIndex = vertexArrays.enabledAttributes[i]; + vertexArrays.offsets[attributeIndex] += + backEndData->currentFrame->dynamicVboCommitOffset; + } + + vertexAttribute_t attribs[ATTR_INDEX_MAX] = {}; + GL_VertexArraysToAttribs(attribs, ARRAY_LEN(attribs), &vertexArrays); + + UniformDataWriter uniformDataWriter; + SamplerBindingsWriter samplerBindingsWriter; + Allocator& frameAllocator = *backEndData->perFrameMemory; + + shaderProgram_t *sp = &tr.lightallShader[0]; + float colorScale = backEnd.refdef.colorScale; + uniformDataWriter.Start(sp); + uniformDataWriter.SetUniformVec4( + UNIFORM_BASECOLOR, colorScale, colorScale, colorScale, 1.0f); + uniformDataWriter.SetUniformVec4( + UNIFORM_VERTCOLOR, 0.0f, 0.0f, 0.0f, 0.0f); + uniformDataWriter.SetUniformVec4( + UNIFORM_DIFFUSETEXMATRIX, 1.0f, 0.0f, 0.0f, 1.0f); + uniformDataWriter.SetUniformVec4( + UNIFORM_DIFFUSETEXOFFTURB, 0.0f, 0.0f, 0.0f, 0.0f); + + samplerBindingsWriter.AddStaticImage(image, TB_DIFFUSEMAP); + + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + const UniformBlockBinding uniformBlockBindings[] = { + { currentFrameUbo, tr.skyEntityUboOffset, UNIFORM_BLOCK_ENTITY }, + { currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA } + }; + + DrawItem item = {}; + item.renderState.cullType = CT_TWO_SIDED; + item.renderState.depthRange = RB_GetDepthRange(backEnd.currentEntity, tess.shader); + item.program = sp; + item.ibo = backEndData->currentFrame->dynamicIbo; + item.uniformData = uniformDataWriter.Finish(frameAllocator); + + item.samplerBindings = samplerBindingsWriter.Finish( + frameAllocator, &item.numSamplerBindings); + + DrawItemSetVertexAttributes( + item, attribs, vertexArrays.numVertexArrays, frameAllocator); + DrawItemSetUniformBlockBindings( + item, uniformBlockBindings, frameAllocator); + + RB_FillDrawCommand(item.draw, GL_TRIANGLES, 1, &tess); + item.draw.params.indexed.numIndices -= tess.firstIndex; + + uint32_t key = RB_CreateSortKey(item, 0, SS_ENVIRONMENT); + RB_AddDrawItem(backEndData->currentPass, key, item); + + RB_CommitInternalBufferData(); + + tess.useInternalVBO = qfalse; + tess.numIndexes = tess.firstIndex; + tess.numVertexes = firstVertex; + tess.firstIndex = 0; + tess.minIndex = minIndex; + tess.maxIndex = maxIndex; +} + +static void DrawSkyBox( shader_t *shader ) +{ + int i; + + sky_min = 0; + sky_max = 1; + + Com_Memset( s_skyTexCoords, 0, sizeof( s_skyTexCoords ) ); + + for (i=0 ; i<6 ; i++) + { + int sky_mins_subd[2], sky_maxs_subd[2]; + int s, t; + + sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + + if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) || + ( sky_mins[1][i] >= sky_maxs[1][i] ) ) + { + continue; + } + + sky_mins_subd[0] = sky_mins[0][i] * HALF_SKY_SUBDIVISIONS; + sky_mins_subd[1] = sky_mins[1][i] * HALF_SKY_SUBDIVISIONS; + sky_maxs_subd[0] = sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS; + sky_maxs_subd[1] = sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS; + + if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS ) + sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS; + else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS ) + sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS; + if ( sky_mins_subd[1] < -HALF_SKY_SUBDIVISIONS ) + sky_mins_subd[1] = -HALF_SKY_SUBDIVISIONS; + else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS ) + sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS; + + if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS ) + sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS; + else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS ) + sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS; + if ( sky_maxs_subd[1] < -HALF_SKY_SUBDIVISIONS ) + sky_maxs_subd[1] = -HALF_SKY_SUBDIVISIONS; + else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS ) + sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS; + + // + // iterate through the subdivisions + // + for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; + t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ ) + { + for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; + s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ ) + { + MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, + ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, + i, + s_skyTexCoords[t][s], + s_skyPoints[t][s] ); + } + } + + DrawSkySide( shader->sky.outerbox[i], + sky_mins_subd, + sky_maxs_subd ); + } + +} + +static void FillCloudySkySide( const int mins[2], const int maxs[2], qboolean addIndexes ) +{ + int s, t; + int vertexStart = tess.numVertexes; + int tHeight, sWidth; + + tHeight = maxs[1] - mins[1] + 1; + sWidth = maxs[0] - mins[0] + 1; + + for ( t = mins[1]+HALF_SKY_SUBDIVISIONS; t <= maxs[1]+HALF_SKY_SUBDIVISIONS; t++ ) + { + for ( s = mins[0]+HALF_SKY_SUBDIVISIONS; s <= maxs[0]+HALF_SKY_SUBDIVISIONS; s++ ) + { + VectorAdd( s_skyPoints[t][s], backEnd.viewParms.ori.origin, + tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = s_skyTexCoords[t][s][0]; + tess.texCoords[tess.numVertexes][0][1] = s_skyTexCoords[t][s][1]; + + tess.numVertexes++; + + if ( tess.numVertexes >= SHADER_MAX_VERTEXES ) + { + ri.Error( ERR_DROP, "SHADER_MAX_VERTEXES hit in FillCloudySkySide()" ); + } + } + } + + // only add indexes for one pass, otherwise it would draw multiple times for each pass + if ( addIndexes ) { + for ( t = 0; t < tHeight-1; t++ ) + { + for ( s = 0; s < sWidth-1; s++ ) + { + tess.indexes[tess.numIndexes] = vertexStart + s + t * ( sWidth ); + tess.numIndexes++; + tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth ); + tess.numIndexes++; + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth ); + tess.numIndexes++; + + tess.indexes[tess.numIndexes] = vertexStart + s + ( t + 1 ) * ( sWidth ); + tess.numIndexes++; + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + ( t + 1 ) * ( sWidth ); + tess.numIndexes++; + tess.indexes[tess.numIndexes] = vertexStart + s + 1 + t * ( sWidth ); + tess.numIndexes++; + } + } + } +} + +static void FillCloudBox( const shader_t *shader, int stage ) +{ + int i; + + // don't want to draw the bottom + for ( i =0; i < 5; i++ ) + { + int sky_mins_subd[2], sky_maxs_subd[2]; + int s, t; + const float MIN_T = -HALF_SKY_SUBDIVISIONS; + + sky_mins[0][i] = floor( sky_mins[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_mins[1][i] = floor( sky_mins[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_maxs[0][i] = ceil( sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + sky_maxs[1][i] = ceil( sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS ) / HALF_SKY_SUBDIVISIONS; + + if ( ( sky_mins[0][i] >= sky_maxs[0][i] ) || + ( sky_mins[1][i] >= sky_maxs[1][i] ) ) + { + continue; + } + + sky_mins_subd[0] = Q_ftol(sky_mins[0][i] * HALF_SKY_SUBDIVISIONS); + sky_mins_subd[1] = Q_ftol(sky_mins[1][i] * HALF_SKY_SUBDIVISIONS); + sky_maxs_subd[0] = Q_ftol(sky_maxs[0][i] * HALF_SKY_SUBDIVISIONS); + sky_maxs_subd[1] = Q_ftol(sky_maxs[1][i] * HALF_SKY_SUBDIVISIONS); + + if ( sky_mins_subd[0] < -HALF_SKY_SUBDIVISIONS ) + sky_mins_subd[0] = -HALF_SKY_SUBDIVISIONS; + else if ( sky_mins_subd[0] > HALF_SKY_SUBDIVISIONS ) + sky_mins_subd[0] = HALF_SKY_SUBDIVISIONS; + if ( sky_mins_subd[1] < MIN_T ) + sky_mins_subd[1] = MIN_T; + else if ( sky_mins_subd[1] > HALF_SKY_SUBDIVISIONS ) + sky_mins_subd[1] = HALF_SKY_SUBDIVISIONS; + + if ( sky_maxs_subd[0] < -HALF_SKY_SUBDIVISIONS ) + sky_maxs_subd[0] = -HALF_SKY_SUBDIVISIONS; + else if ( sky_maxs_subd[0] > HALF_SKY_SUBDIVISIONS ) + sky_maxs_subd[0] = HALF_SKY_SUBDIVISIONS; + if ( sky_maxs_subd[1] < MIN_T ) + sky_maxs_subd[1] = MIN_T; + else if ( sky_maxs_subd[1] > HALF_SKY_SUBDIVISIONS ) + sky_maxs_subd[1] = HALF_SKY_SUBDIVISIONS; + + // + // iterate through the subdivisions + // + for ( t = sky_mins_subd[1]+HALF_SKY_SUBDIVISIONS; + t <= sky_maxs_subd[1]+HALF_SKY_SUBDIVISIONS; t++ ) + { + for ( s = sky_mins_subd[0]+HALF_SKY_SUBDIVISIONS; + s <= sky_maxs_subd[0]+HALF_SKY_SUBDIVISIONS; s++ ) + { + MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, + ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, + i, + NULL, + s_skyPoints[t][s] ); + + s_skyTexCoords[t][s][0] = s_cloudTexCoords[i][t][s][0]; + s_skyTexCoords[t][s][1] = s_cloudTexCoords[i][t][s][1]; + } + } + + // only add indexes for first stage + FillCloudySkySide( sky_mins_subd, sky_maxs_subd, (qboolean)( stage == 0 ) ); + } +} + +/* +** R_BuildCloudData +*/ +void R_BuildCloudData( shaderCommands_t *input ) +{ + int i; + shader_t *shader; + + shader = input->shader; + + assert( shader->isSky ); + + sky_min = 1.0 / 256.0f; // FIXME: not correct? + sky_max = 255.0 / 256.0f; + + // set up for drawing + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + tess.useInternalVBO = qtrue; + tess.externalIBO = nullptr; + + if ( shader->sky.cloudHeight ) + { + for ( i = 0; i < MAX_SHADER_STAGES; i++ ) + { + if ( !tess.xstages[i] ) { + break; + } + FillCloudBox( shader, i ); + } + } +} + +/* +** R_InitSkyTexCoords +** Called when a sky shader is parsed +*/ +#define SQR( a ) ((a)*(a)) +void R_InitSkyTexCoords( float heightCloud ) +{ + int i, s, t; + float radiusWorld = 4096; + float p; + float sRad, tRad; + vec3_t skyVec; + vec3_t v; + + // init zfar so MakeSkyVec works even though + // a world hasn't been bounded + backEnd.viewParms.zFar = 1024; + + for ( i = 0; i < 6; i++ ) + { + for ( t = 0; t <= SKY_SUBDIVISIONS; t++ ) + { + for ( s = 0; s <= SKY_SUBDIVISIONS; s++ ) + { + // compute vector from view origin to sky side integral point + MakeSkyVec( ( s - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, + ( t - HALF_SKY_SUBDIVISIONS ) / ( float ) HALF_SKY_SUBDIVISIONS, + i, + NULL, + skyVec ); + + // compute parametric value 'p' that intersects with cloud layer + p = ( 1.0f / ( 2 * DotProduct( skyVec, skyVec ) ) ) * + ( -2 * skyVec[2] * radiusWorld + + 2 * sqrt( SQR( skyVec[2] ) * SQR( radiusWorld ) + + 2 * SQR( skyVec[0] ) * radiusWorld * heightCloud + + SQR( skyVec[0] ) * SQR( heightCloud ) + + 2 * SQR( skyVec[1] ) * radiusWorld * heightCloud + + SQR( skyVec[1] ) * SQR( heightCloud ) + + 2 * SQR( skyVec[2] ) * radiusWorld * heightCloud + + SQR( skyVec[2] ) * SQR( heightCloud ) ) ); + + s_cloudTexP[i][t][s] = p; + + // compute intersection point based on p + VectorScale( skyVec, p, v ); + v[2] += radiusWorld; + + // compute vector from world origin to intersection point 'v' + VectorNormalize( v ); + + sRad = Q_acos( v[0] ); + tRad = Q_acos( v[1] ); + + s_cloudTexCoords[i][t][s][0] = sRad; + s_cloudTexCoords[i][t][s][1] = tRad; + } + } + } +} + +//====================================================================================== + +/* +** RB_DrawSun +*/ +void RB_DrawSun( float scale, shader_t *shader ) { + float size; + float dist; + vec3_t origin, vec1, vec2; + + if ( !backEnd.skyRenderedThisView ) { + return; + } + + // FIXME: this could be a lot cleaner + matrix_t translation, modelview; + + Matrix16Translation( backEnd.viewParms.ori.origin, translation ); + Matrix16Multiply( backEnd.viewParms.world.modelViewMatrix, translation, modelview ); + GL_SetModelviewMatrix( modelview ); + + dist = backEnd.viewParms.zFar / 1.75; // div sqrt(3) + size = dist * scale; + + VectorScale( tr.sunDirection, dist, origin ); + PerpendicularVector( vec1, tr.sunDirection ); + CrossProduct( tr.sunDirection, vec1, vec2 ); + + VectorScale( vec1, size, vec1 ); + VectorScale( vec2, size, vec2 ); + + // farthest depth range + GL_DepthRange(1.0f, 1.0f); + + RB_BeginSurface( shader, 0, 0 ); + + RB_AddQuadStamp(origin, vec1, vec2, colorWhite); + + RB_EndSurface(); + + // back to normal depth range + GL_DepthRange(0.0f, 1.0f); +} + + + + +/* +================ +RB_StageIteratorSky + +All of the visible sky triangles are in tess + +Other things could be stuck in here, like birds in the sky, etc +================ +*/ +void RB_StageIteratorSky( void ) { + if ( r_fastsky->integer ) { + return; + } + + if (tr.world->skyboxportal && !(tr.viewParms.isSkyPortal)) { + return; + } + + // go through all the polygons and project them onto + // the sky box to see which blocks on each side need + // to be drawn + RB_ClipSkyPolygons( &tess ); + + // draw the outer skybox + if ( tess.shader->sky.outerbox[0] && + tess.shader->sky.outerbox[0] != tr.defaultImage ) { + DrawSkyBox( tess.shader ); + } + + // generate the vertexes for all the clouds, which will be drawn + // by the generic shader routine + R_BuildCloudData( &tess ); + + RB_StageIteratorGeneric(); + + // note that sky was drawn so we will draw a sun later + backEnd.skyRenderedThisView = qtrue; +} + + + + + diff --git a/codemp/rd-rend2/tr_subs.cpp b/codemp/rd-rend2/tr_subs.cpp new file mode 100644 index 0000000000..0228319861 --- /dev/null +++ b/codemp/rd-rend2/tr_subs.cpp @@ -0,0 +1,95 @@ +/* +=========================================================================== +Copyright (C) 2010 James Canete (use.less01@gmail.com) + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_subs.c - common function replacements for modular renderer + +#include "tr_local.h" + + +void QDECL Com_Printf( const char *msg, ... ) +{ + va_list argptr; + char text[1024]; + + va_start(argptr, msg); + Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); + + ri.Printf(PRINT_ALL, "%s", text); +} + +void QDECL Com_OPrintf( const char *msg, ... ) +{ + va_list argptr; + char text[1024]; + + va_start(argptr, msg); + Q_vsnprintf(text, sizeof(text), msg, argptr); + va_end(argptr); + + ri.OPrintf("%s", text); +} + +void QDECL Com_Error( int level, const char *error, ... ) +{ + va_list argptr; + char text[1024]; + + va_start(argptr, error); + Q_vsnprintf(text, sizeof(text), error, argptr); + va_end(argptr); + + ri.Error(level, "%s", text); +} + +// HUNK +void *Hunk_AllocateTempMemory( int size ) { + return ri.Hunk_AllocateTempMemory( size ); +} + +void Hunk_FreeTempMemory( void *buf ) { + ri.Hunk_FreeTempMemory( buf ); +} + +void *Hunk_Alloc( int size, ha_pref preference ) { + return ri.Hunk_Alloc( size, preference ); +} + +int Hunk_MemoryRemaining( void ) { + return ri.Hunk_MemoryRemaining(); +} + +// ZONE +void *Z_Malloc( int iSize, memtag_t eTag, qboolean bZeroit, int iAlign ) { + return ri.Z_Malloc( iSize, eTag, bZeroit, iAlign ); +} + +void Z_Free( void *ptr ) { + ri.Z_Free( ptr ); +} + +int Z_MemSize( memtag_t eTag ) { + return ri.Z_MemSize( eTag ); +} + +void Z_MorphMallocTag( void *pvBuffer, memtag_t eDesiredTag ) { + ri.Z_MorphMallocTag( pvBuffer, eDesiredTag ); +} diff --git a/codemp/rd-rend2/tr_surface.cpp b/codemp/rd-rend2/tr_surface.cpp new file mode 100644 index 0000000000..ce29b21156 --- /dev/null +++ b/codemp/rd-rend2/tr_surface.cpp @@ -0,0 +1,2308 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_surf.c +#include "tr_local.h" +#include "tr_weather.h" + +/* + + THIS ENTIRE FILE IS BACK END + +backEnd.currentEntity will be valid. + +Tess_Begin has already been called for the surface's shader. + +The modelview matrix will be set. + +It is safe to actually issue drawing commands here if you don't want to +use the shader system. +*/ + + +//============================================================================ + + +/* +============== +RB_CheckOverflow +============== +*/ +void RB_CheckOverflow( int verts, int indexes ) { + if ((tess.numVertexes + verts) < SHADER_MAX_VERTEXES && + (tess.numIndexes + indexes) < SHADER_MAX_INDEXES) + { + return; + } + + RB_EndSurface(); + + if ( verts >= SHADER_MAX_VERTEXES ) { + ri.Error(ERR_DROP, "RB_CheckOverflow: verts > MAX (%d > %d)", verts, SHADER_MAX_VERTEXES ); + } + if ( indexes >= SHADER_MAX_INDEXES ) { + ri.Error(ERR_DROP, "RB_CheckOverflow: indices > MAX (%d > %d)", indexes, SHADER_MAX_INDEXES ); + } + + RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex ); +} + +void RB_CheckVBOandIBO(VBO_t *vbo, IBO_t *ibo) +{ + if (vbo != glState.currentVBO || + ibo != glState.currentIBO || + tess.multiDrawPrimitives >= MAX_MULTIDRAW_PRIMITIVES) + { + RB_EndSurface(); + RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex ); + + R_BindVBO(vbo); + R_BindIBO(ibo); + } + + if (vbo != backEndData->currentFrame->dynamicVbo && + ibo != backEndData->currentFrame->dynamicIbo) + { + tess.useInternalVBO = qfalse; + } + + if ( ibo != backEndData->currentFrame->dynamicIbo ) + { + tess.externalIBO = ibo; + } +} + + +/* +============== +RB_AddQuadStampExt +============== +*/ +void RB_AddQuadStampExt( vec3_t origin, vec3_t left, vec3_t up, float color[4], float s1, float t1, float s2, float t2 ) { + vec3_t normal; + int ndx; + + RB_CHECKOVERFLOW( 4, 6 ); + + ndx = tess.numVertexes; + + // triangle indexes for a simple quad + tess.indexes[ tess.numIndexes ] = ndx; + tess.indexes[ tess.numIndexes + 1 ] = ndx + 1; + tess.indexes[ tess.numIndexes + 2 ] = ndx + 3; + + tess.indexes[ tess.numIndexes + 3 ] = ndx + 3; + tess.indexes[ tess.numIndexes + 4 ] = ndx + 1; + tess.indexes[ tess.numIndexes + 5 ] = ndx + 2; + + tess.xyz[ndx][0] = origin[0] + left[0] + up[0]; + tess.xyz[ndx][1] = origin[1] + left[1] + up[1]; + tess.xyz[ndx][2] = origin[2] + left[2] + up[2]; + + tess.xyz[ndx+1][0] = origin[0] - left[0] + up[0]; + tess.xyz[ndx+1][1] = origin[1] - left[1] + up[1]; + tess.xyz[ndx+1][2] = origin[2] - left[2] + up[2]; + + tess.xyz[ndx+2][0] = origin[0] - left[0] - up[0]; + tess.xyz[ndx+2][1] = origin[1] - left[1] - up[1]; + tess.xyz[ndx+2][2] = origin[2] - left[2] - up[2]; + + tess.xyz[ndx+3][0] = origin[0] + left[0] - up[0]; + tess.xyz[ndx+3][1] = origin[1] + left[1] - up[1]; + tess.xyz[ndx+3][2] = origin[2] + left[2] - up[2]; + + + // constant normal all the way around + VectorSubtract( vec3_origin, backEnd.viewParms.ori.axis[0], normal ); + + tess.normal[ndx] = + tess.normal[ndx+1] = + tess.normal[ndx+2] = + tess.normal[ndx+3] = R_VboPackNormal(normal); + + // standard square texture coordinates + VectorSet2(tess.texCoords[ndx ][0], s1, t1); + VectorSet2(tess.texCoords[ndx ][1], s1, t1); + + VectorSet2(tess.texCoords[ndx+1][0], s2, t1); + VectorSet2(tess.texCoords[ndx+1][1], s2, t1); + + VectorSet2(tess.texCoords[ndx+2][0], s2, t2); + VectorSet2(tess.texCoords[ndx+2][1], s2, t2); + + VectorSet2(tess.texCoords[ndx+3][0], s1, t2); + VectorSet2(tess.texCoords[ndx+3][1], s1, t2); + + // constant color all the way around + // should this be identity and let the shader specify from entity? + VectorCopy4(color, tess.vertexColors[ndx]); + VectorCopy4(color, tess.vertexColors[ndx+1]); + VectorCopy4(color, tess.vertexColors[ndx+2]); + VectorCopy4(color, tess.vertexColors[ndx+3]); + + tess.numVertexes += 4; + tess.numIndexes += 6; +} + +/* +============== +RB_AddQuadStamp +============== +*/ +void RB_AddQuadStamp( vec3_t origin, vec3_t left, vec3_t up, float color[4] ) { + RB_AddQuadStampExt( origin, left, up, color, 0, 0, 1, 1 ); +} + + +/* +============== +RB_InstantQuad + +based on Tess_InstantQuad from xreal +============== +*/ +void RB_InstantQuad2(vec4_t quadVerts[4], vec2_t texCoords[4]) +{ +// GLimp_LogComment("--- RB_InstantQuad2 ---\n"); // FIXME: REIMPLEMENT (wasn't implemented in ioq3 to begin with) --eez + + tess.numVertexes = 0; + tess.numIndexes = 0; + tess.firstIndex = 0; + + VectorCopy4(quadVerts[0], tess.xyz[tess.numVertexes]); + VectorCopy2(texCoords[0], tess.texCoords[tess.numVertexes][0]); + tess.numVertexes++; + + VectorCopy4(quadVerts[1], tess.xyz[tess.numVertexes]); + VectorCopy2(texCoords[1], tess.texCoords[tess.numVertexes][0]); + tess.numVertexes++; + + VectorCopy4(quadVerts[2], tess.xyz[tess.numVertexes]); + VectorCopy2(texCoords[2], tess.texCoords[tess.numVertexes][0]); + tess.numVertexes++; + + VectorCopy4(quadVerts[3], tess.xyz[tess.numVertexes]); + VectorCopy2(texCoords[3], tess.texCoords[tess.numVertexes][0]); + tess.numVertexes++; + + tess.indexes[tess.numIndexes++] = 0; + tess.indexes[tess.numIndexes++] = 1; + tess.indexes[tess.numIndexes++] = 2; + tess.indexes[tess.numIndexes++] = 0; + tess.indexes[tess.numIndexes++] = 2; + tess.indexes[tess.numIndexes++] = 3; + tess.minIndex = 0; + tess.maxIndex = 3; + tess.useInternalVBO = qtrue; + + RB_UpdateVBOs(ATTR_POSITION | ATTR_TEXCOORD0); + + GLSL_VertexAttribsState(ATTR_POSITION | ATTR_TEXCOORD0, NULL); + + R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); + + RB_CommitInternalBufferData(); + + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + tess.minIndex = 0; + tess.maxIndex = 0; + tess.useInternalVBO = qfalse; +} + + +void RB_InstantQuad(vec4_t quadVerts[4]) +{ + vec2_t texCoords[4]; + + VectorSet2(texCoords[0], 0.0f, 0.0f); + VectorSet2(texCoords[1], 1.0f, 0.0f); + VectorSet2(texCoords[2], 1.0f, 1.0f); + VectorSet2(texCoords[3], 0.0f, 1.0f); + + GLSL_BindProgram(&tr.textureColorShader); + + GLSL_SetUniformMatrix4x4(&tr.textureColorShader, UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); + GLSL_SetUniformVec4(&tr.textureColorShader, UNIFORM_COLOR, colorWhite); + + RB_InstantQuad2(quadVerts, texCoords); +} + +void RB_InstantTriangle() +{ + qglDrawArrays(GL_TRIANGLES, 0, 3); +} + + + +/* +============== +RB_SurfaceSprite +============== +*/ +static void RB_SurfaceSprite( void ) { + vec3_t left, up; + float radius; + float colors[4]; + trRefEntity_t *ent = backEnd.currentEntity; + + // calculate the xyz locations for the four corners + radius = ent->e.radius; + if ( ent->e.rotation == 0 ) { + VectorScale( backEnd.viewParms.ori.axis[1], radius, left ); + VectorScale( backEnd.viewParms.ori.axis[2], radius, up ); + } else { + float s, c; + float ang; + + ang = M_PI * ent->e.rotation / 180; + s = sin( ang ); + c = cos( ang ); + + VectorScale( backEnd.viewParms.ori.axis[1], c * radius, left ); + VectorMA( left, -s * radius, backEnd.viewParms.ori.axis[2], left ); + + VectorScale( backEnd.viewParms.ori.axis[2], c * radius, up ); + VectorMA( up, s * radius, backEnd.viewParms.ori.axis[1], up ); + } + if ( backEnd.viewParms.isMirror ) { + VectorSubtract( vec3_origin, left, left ); + } + + VectorScale4(ent->e.shaderRGBA, 1.0f / 255.0f, colors); + + RB_AddQuadStamp( ent->e.origin, left, up, colors ); +} + +/* +======================= +RB_SurfaceOrientedQuad +======================= +*/ +static void RB_SurfaceOrientedQuad( void ) +{ + vec3_t left, up; + float radius; + float color[4]; + + // calculate the xyz locations for the four corners + radius = backEnd.currentEntity->e.radius; +// MakeNormalVectors( backEnd.currentEntity->e.axis[0], left, up ); + VectorCopy( backEnd.currentEntity->e.axis[1], left ); + VectorCopy( backEnd.currentEntity->e.axis[2], up ); + + if ( backEnd.currentEntity->e.rotation == 0 ) + { + VectorScale( left, radius, left ); + VectorScale( up, radius, up ); + } + else + { + vec3_t tempLeft, tempUp; + float s, c; + float ang; + + ang = M_PI * backEnd.currentEntity->e.rotation / 180; + s = sin( ang ); + c = cos( ang ); + + // Use a temp so we don't trash the values we'll need later + VectorScale( left, c * radius, tempLeft ); + VectorMA( tempLeft, -s * radius, up, tempLeft ); + + VectorScale( up, c * radius, tempUp ); + VectorMA( tempUp, s * radius, left, up ); // no need to use the temp anymore, so copy into the dest vector ( up ) + + // This was copied for safekeeping, we're done, so we can move it back to left + VectorCopy( tempLeft, left ); + } + + if ( backEnd.viewParms.isMirror ) + { + VectorSubtract( vec3_origin, left, left ); + } + + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, color); + + RB_AddQuadStamp( backEnd.currentEntity->e.origin, left, up, color); +} + +/* +============= +RB_SurfacePolychain +============= +*/ +static void RB_SurfacePolychain( srfPoly_t *p ) { + int i; + int numv; + + RB_CHECKOVERFLOW( p->numVerts, 3*(p->numVerts - 2) ); + + // fan triangles into the tess array + numv = tess.numVertexes; + for ( i = 0; i < p->numVerts; i++ ) { + VectorCopy( p->verts[i].xyz, tess.xyz[numv] ); + tess.texCoords[numv][0][0] = p->verts[i].st[0]; + tess.texCoords[numv][0][1] = p->verts[i].st[1]; + tess.vertexColors[numv][0] = p->verts[ i ].modulate[0] / 255.0f; + tess.vertexColors[numv][1] = p->verts[ i ].modulate[1] / 255.0f; + tess.vertexColors[numv][2] = p->verts[ i ].modulate[2] / 255.0f; + tess.vertexColors[numv][3] = p->verts[ i ].modulate[3] / 255.0f; + + numv++; + } + + // generate fan indexes into the tess array + for ( i = 0; i < p->numVerts-2; i++ ) { + tess.indexes[tess.numIndexes + 0] = tess.numVertexes; + tess.indexes[tess.numIndexes + 1] = tess.numVertexes + i + 1; + tess.indexes[tess.numIndexes + 2] = tess.numVertexes + i + 2; + tess.numIndexes += 3; + } + + tess.numVertexes = numv; +} + +static void RB_SurfaceVertsAndIndexes( int numVerts, srfVert_t *verts, int numIndexes, glIndex_t *indexes, int dlightBits, int pshadowBits) +{ + int i; + glIndex_t *inIndex; + srfVert_t *dv; + float *xyz, *texCoords, *lightCoords; + uint32_t *lightdir; + uint32_t *normal; + uint32_t *tangent; + glIndex_t *outIndex; + float *color; + gpuFrame_t *currentFrame = backEndData->currentFrame; + + RB_CheckVBOandIBO(currentFrame->dynamicVbo, currentFrame->dynamicIbo); + + RB_CHECKOVERFLOW( numVerts, numIndexes ); + + inIndex = indexes; + outIndex = &tess.indexes[ tess.numIndexes ]; + for ( i = 0 ; i < numIndexes ; i++ ) { + *outIndex++ = tess.numVertexes + *inIndex++; + } + tess.numIndexes += numIndexes; + + if ( tess.shader->vertexAttribs & ATTR_POSITION ) + { + dv = verts; + xyz = tess.xyz[ tess.numVertexes ]; + for ( i = 0 ; i < numVerts ; i++, dv++, xyz+=4 ) + VectorCopy(dv->xyz, xyz); + } + + if ( tess.shader->vertexAttribs & ATTR_NORMAL ) + { + dv = verts; + normal = &tess.normal[ tess.numVertexes ]; + for ( i = 0 ; i < numVerts ; i++, dv++, normal++ ) + *normal = R_VboPackNormal(dv->normal); + } + + if ( tess.shader->vertexAttribs & ATTR_TANGENT ) + { + dv = verts; + tangent = &tess.tangent[ tess.numVertexes ]; + for ( i = 0 ; i < numVerts ; i++, dv++, tangent++ ) + *tangent = R_VboPackTangent(dv->tangent); + } + + if ( tess.shader->vertexAttribs & ATTR_TEXCOORD0 ) + { + dv = verts; + texCoords = tess.texCoords[ tess.numVertexes ][0]; + for ( i = 0 ; i < numVerts ; i++, dv++, texCoords+=NUM_TESS_TEXCOORDS*2 ) + VectorCopy2(dv->st, texCoords); + } + + for (int tc = 0; tc < MAXLIGHTMAPS; ++tc) + { + if ( tess.shader->vertexAttribs & (ATTR_TEXCOORD1 + tc) ) + { + dv = verts; + lightCoords = tess.texCoords[ tess.numVertexes ][1 + tc]; + for ( i = 0 ; i < numVerts ; i++, dv++, lightCoords+=NUM_TESS_TEXCOORDS*2 ) + VectorCopy2(dv->lightmap[tc], lightCoords); + } + } + + if ( tess.shader->vertexAttribs & ATTR_COLOR ) + { + dv = verts; + color = tess.vertexColors[ tess.numVertexes ]; + for ( i = 0 ; i < numVerts ; i++, dv++, color+=4 ) + VectorCopy4(dv->vertexColors[0], color); + } + + if ( tess.shader->vertexAttribs & ATTR_LIGHTDIRECTION ) + { + dv = verts; + lightdir = &tess.lightdir[ tess.numVertexes ]; + for ( i = 0 ; i < numVerts ; i++, dv++, lightdir++ ) + *lightdir = R_VboPackNormal(dv->lightdir); + } + +#if 0 // nothing even uses vertex dlightbits + for ( i = 0 ; i < numVerts ; i++ ) { + tess.vertexDlightBits[ tess.numVertexes + i ] = dlightBits; + } +#endif + + tess.dlightBits |= dlightBits; + tess.pshadowBits |= pshadowBits; + + tess.numVertexes += numVerts; +} + +static qboolean RB_SurfaceVbo( + VBO_t *vbo, IBO_t *ibo, int numVerts, int numIndexes, int firstIndex, + int minIndex, int maxIndex, int dlightBits, int pshadowBits, qboolean shaderCheck) +{ + int i, mergeForward, mergeBack; + GLvoid *firstIndexOffset, *lastIndexOffset; + + if (!vbo || !ibo) + { + return qfalse; + } + + if (shaderCheck && + (ShaderRequiresCPUDeforms(tess.shader) || + tess.shader->isSky || + tess.shader->isPortal)) + { + return qfalse; + } + + RB_CheckVBOandIBO(vbo, ibo); + + tess.dlightBits |= dlightBits; + tess.pshadowBits |= pshadowBits; + + // merge this into any existing multidraw primitives + mergeForward = -1; + mergeBack = -1; + firstIndexOffset = BUFFER_OFFSET(firstIndex * sizeof(glIndex_t)); + lastIndexOffset = BUFFER_OFFSET((firstIndex + numIndexes) * sizeof(glIndex_t)); + + if (r_mergeMultidraws->integer) + { + i = 0; + + if (r_mergeMultidraws->integer == 1) + { + // lazy merge, only check the last primitive + if (tess.multiDrawPrimitives) + { + i = tess.multiDrawPrimitives - 1; + } + } + + for (; i < tess.multiDrawPrimitives; i++) + { + if (tess.multiDrawLastIndex[i] == firstIndexOffset) + { + mergeBack = i; + } + + if (lastIndexOffset == tess.multiDrawFirstIndex[i]) + { + mergeForward = i; + } + } + } + + if (mergeBack != -1 && mergeForward == -1) + { + tess.multiDrawNumIndexes[mergeBack] += numIndexes; + tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; + tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], minIndex); + tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], maxIndex); + backEnd.pc.c_multidrawsMerged++; + } + else if (mergeBack == -1 && mergeForward != -1) + { + tess.multiDrawNumIndexes[mergeForward] += numIndexes; + tess.multiDrawFirstIndex[mergeForward] = (glIndex_t *)firstIndexOffset; + tess.multiDrawLastIndex[mergeForward] = tess.multiDrawFirstIndex[mergeForward] + tess.multiDrawNumIndexes[mergeForward]; + tess.multiDrawMinIndex[mergeForward] = MIN(tess.multiDrawMinIndex[mergeForward], minIndex); + tess.multiDrawMaxIndex[mergeForward] = MAX(tess.multiDrawMaxIndex[mergeForward], maxIndex); + backEnd.pc.c_multidrawsMerged++; + } + else if (mergeBack != -1 && mergeForward != -1) + { + tess.multiDrawNumIndexes[mergeBack] += numIndexes + tess.multiDrawNumIndexes[mergeForward]; + tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; + tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], MIN(tess.multiDrawMinIndex[mergeForward], minIndex)); + tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], MAX(tess.multiDrawMaxIndex[mergeForward], maxIndex)); + tess.multiDrawPrimitives--; + + if (mergeForward != tess.multiDrawPrimitives) + { + tess.multiDrawNumIndexes[mergeForward] = tess.multiDrawNumIndexes[tess.multiDrawPrimitives]; + tess.multiDrawFirstIndex[mergeForward] = tess.multiDrawFirstIndex[tess.multiDrawPrimitives]; + } + backEnd.pc.c_multidrawsMerged += 2; + } + else if (mergeBack == -1 && mergeForward == -1) + { + tess.multiDrawNumIndexes[tess.multiDrawPrimitives] = numIndexes; + tess.multiDrawFirstIndex[tess.multiDrawPrimitives] = (glIndex_t *)firstIndexOffset; + tess.multiDrawLastIndex[tess.multiDrawPrimitives] = (glIndex_t *)lastIndexOffset; + tess.multiDrawMinIndex[tess.multiDrawPrimitives] = minIndex; + tess.multiDrawMaxIndex[tess.multiDrawPrimitives] = maxIndex; + tess.multiDrawPrimitives++; + } + + backEnd.pc.c_multidraws++; + + tess.numIndexes += numIndexes; + tess.numVertexes += numVerts; + + return qtrue; +} + +/* +============= +RB_SurfaceBSPTriangles +============= +*/ +static void RB_SurfaceBSPTriangles( srfBspSurface_t *srf ) { + if( RB_SurfaceVbo (srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, + srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qtrue ) ) + { + return; + } + + RB_SurfaceVertsAndIndexes(srf->numVerts, srf->verts, srf->numIndexes, + srf->indexes, srf->dlightBits, srf->pshadowBits); +} + + + +/* +============== +RB_SurfaceBeam +============== +*/ +static void RB_SurfaceBeam( void ) +{ +#define NUM_BEAM_SEGS 6 + refEntity_t *e; + shaderProgram_t *sp = &tr.textureColorShader; + int i; + vec3_t perpvec; + vec3_t direction, normalized_direction; + vec3_t start_points[NUM_BEAM_SEGS], end_points[NUM_BEAM_SEGS]; + vec3_t oldorigin, origin; + + e = &backEnd.currentEntity->e; + + oldorigin[0] = e->oldorigin[0]; + oldorigin[1] = e->oldorigin[1]; + oldorigin[2] = e->oldorigin[2]; + + origin[0] = e->origin[0]; + origin[1] = e->origin[1]; + origin[2] = e->origin[2]; + + normalized_direction[0] = direction[0] = oldorigin[0] - origin[0]; + normalized_direction[1] = direction[1] = oldorigin[1] - origin[1]; + normalized_direction[2] = direction[2] = oldorigin[2] - origin[2]; + + if ( VectorNormalize( normalized_direction ) == 0 ) + return; + + PerpendicularVector( perpvec, normalized_direction ); + + VectorScale( perpvec, 4, perpvec ); + + for ( i = 0; i < NUM_BEAM_SEGS ; i++ ) + { + RotatePointAroundVector( start_points[i], normalized_direction, perpvec, (360.0/NUM_BEAM_SEGS)*i ); +// VectorAdd( start_points[i], origin, start_points[i] ); + VectorAdd( start_points[i], direction, end_points[i] ); + } + + GL_Bind( tr.whiteImage ); + + GL_State( GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE ); + + // FIXME: Quake3 doesn't use this, so I never tested it + tess.numVertexes = 0; + tess.numIndexes = 0; + tess.firstIndex = 0; + tess.minIndex = 0; + tess.maxIndex = 0; + + for ( i = 0; i <= NUM_BEAM_SEGS; i++ ) { + VectorCopy(start_points[ i % NUM_BEAM_SEGS ], tess.xyz[tess.numVertexes++]); + VectorCopy(end_points [ i % NUM_BEAM_SEGS ], tess.xyz[tess.numVertexes++]); + } + + for ( i = 0; i < NUM_BEAM_SEGS; i++ ) { + tess.indexes[tess.numIndexes++] = i * 2; + tess.indexes[tess.numIndexes++] = (i + 1) * 2; + tess.indexes[tess.numIndexes++] = 1 + i * 2; + + tess.indexes[tess.numIndexes++] = 1 + i * 2; + tess.indexes[tess.numIndexes++] = (i + 1) * 2; + tess.indexes[tess.numIndexes++] = 1 + (i + 1) * 2; + } + + tess.minIndex = 0; + tess.maxIndex = tess.numVertexes; + tess.useInternalVBO = qtrue; + + // FIXME: A lot of this can probably be removed for speed, and refactored into a more convenient function + RB_UpdateVBOs(ATTR_POSITION); + + GLSL_VertexAttribsState(ATTR_POSITION, NULL); + GLSL_BindProgram(sp); + + GLSL_SetUniformMatrix4x4(sp, UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); + + GLSL_SetUniformVec4(sp, UNIFORM_COLOR, colorRed); + + R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); + + RB_CommitInternalBufferData(); + + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + tess.minIndex = 0; + tess.maxIndex = 0; + tess.useInternalVBO = qfalse; +} + +//------------------ +// DoSprite +//------------------ +static void DoSprite( vec3_t origin, float radius, float rotation ) +{ + float s, c; + float ang; + vec3_t left, up; + float color[4]; + + ang = M_PI * rotation / 180.0f; + s = sin( ang ); + c = cos( ang ); + + VectorScale( backEnd.viewParms.ori.axis[1], c * radius, left ); + VectorMA( left, -s * radius, backEnd.viewParms.ori.axis[2], left ); + + VectorScale( backEnd.viewParms.ori.axis[2], c * radius, up ); + VectorMA( up, s * radius, backEnd.viewParms.ori.axis[1], up ); + + if ( backEnd.viewParms.isMirror ) + { + VectorSubtract( vec3_origin, left, left ); + } + + VectorScale4(backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, color); + + RB_AddQuadStamp( origin, left, up, color ); +} + +//------------------ +// RB_SurfaceSaber +//------------------ +static void RB_SurfaceSaberGlow() +{ + vec3_t end; + refEntity_t *e; + + e = &backEnd.currentEntity->e; + + // Render the glow part of the blade + for ( float i = e->saberLength; i > 0; i -= e->radius * 0.65f ) + { + VectorMA( e->origin, i, e->axis[0], end ); + + DoSprite( end, e->radius, 0.0f );//random() * 360.0f ); + e->radius += 0.017f; + } + + // Big hilt sprite + // Please don't kill me Pat...I liked the hilt glow blob, but wanted a subtle pulse.:) Feel free to ditch it if you don't like it. --Jeff + // Please don't kill me Jeff... The pulse is good, but now I want the halo bigger if the saber is shorter... --Pat + DoSprite( e->origin, 5.5f + Q_flrand(0.0f, 1.0f) * 0.25f, 0.0f );//random() * 360.0f ); +} + +/* +============== +RB_SurfaceLine +============== +*/ +// +// Values for a proper line render primitive... +// Width +// STScale (how many times to loop a texture) +// alpha +// RGB +// +// Values for proper line object... +// lifetime +// dscale +// startalpha, endalpha +// startRGB, endRGB +// + +static void DoLine( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth ) +{ + float spanWidth2; + int vbase; + + RB_CHECKOVERFLOW( 4, 6 ); + + vbase = tess.numVertexes; + + spanWidth2 = -spanWidth; + + VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 0; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( start, spanWidth2, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 0; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( end, spanWidth, up, tess.xyz[tess.numVertexes] ); + + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + tess.indexes[tess.numIndexes++] = vbase; + tess.indexes[tess.numIndexes++] = vbase + 1; + tess.indexes[tess.numIndexes++] = vbase + 2; + + tess.indexes[tess.numIndexes++] = vbase + 2; + tess.indexes[tess.numIndexes++] = vbase + 1; + tess.indexes[tess.numIndexes++] = vbase + 3; +} + +static void DoLine2( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth, float spanWidth2 ) +{ + int vbase; + + RB_CHECKOVERFLOW( 4, 6 ); + + vbase = tess.numVertexes; + + VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 0; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( start, -spanWidth, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 0; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); + + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( end, -spanWidth2, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 1;//backEnd.currentEntity->e.shaderTexCoord[0]; + tess.texCoords[tess.numVertexes][0][1] = 1;//backEnd.currentEntity->e.shaderTexCoord[1]; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + tess.indexes[tess.numIndexes++] = vbase; + tess.indexes[tess.numIndexes++] = vbase + 1; + tess.indexes[tess.numIndexes++] = vbase + 2; + + tess.indexes[tess.numIndexes++] = vbase + 2; + tess.indexes[tess.numIndexes++] = vbase + 1; + tess.indexes[tess.numIndexes++] = vbase + 3; +} + +static void DoLine_Oriented( const vec3_t start, const vec3_t end, const vec3_t up, float spanWidth ) +{ + float spanWidth2; + int vbase; + + vbase = tess.numVertexes; + + spanWidth2 = -spanWidth; + + // FIXME: use quad stamp? + VectorMA( start, spanWidth, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = 0; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( start, spanWidth2, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 1; + tess.texCoords[tess.numVertexes][0][1] = 0; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( end, spanWidth, up, tess.xyz[tess.numVertexes] ); + + tess.texCoords[tess.numVertexes][0][0] = 0; + tess.texCoords[tess.numVertexes][0][1] = backEnd.currentEntity->e.data.line.stscale; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + VectorMA( end, spanWidth2, up, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = 1; + tess.texCoords[tess.numVertexes][0][1] = backEnd.currentEntity->e.data.line.stscale; + VectorScale4 (backEnd.currentEntity->e.shaderRGBA, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + + tess.indexes[tess.numIndexes++] = vbase; + tess.indexes[tess.numIndexes++] = vbase + 1; + tess.indexes[tess.numIndexes++] = vbase + 2; + + tess.indexes[tess.numIndexes++] = vbase + 2; + tess.indexes[tess.numIndexes++] = vbase + 1; + tess.indexes[tess.numIndexes++] = vbase + 3; +} + +//----------------- +// RB_SurfaceLine +//----------------- +static void RB_SurfaceLine( void ) +{ + refEntity_t *e; + vec3_t right; + vec3_t start, end; + vec3_t v1, v2; + + e = &backEnd.currentEntity->e; + + VectorCopy( e->oldorigin, end ); + VectorCopy( e->origin, start ); + + // compute side vector + VectorSubtract( start, backEnd.viewParms.ori.origin, v1 ); + VectorSubtract( end, backEnd.viewParms.ori.origin, v2 ); + CrossProduct( v1, v2, right ); + VectorNormalize( right ); + + DoLine( start, end, right, e->radius); +} + +static void RB_SurfaceOrientedLine( void ) +{ + refEntity_t *e; + vec3_t right; + vec3_t start, end; + + e = &backEnd.currentEntity->e; + + VectorCopy( e->oldorigin, end ); + VectorCopy( e->origin, start ); + + // compute side vector + VectorNormalize( e->axis[1] ); + VectorCopy(e->axis[1], right); + DoLine_Oriented( start, end, right, e->data.line.width*0.5 ); +} + +/* +============== +RB_SurfaceCylinder +============== +*/ + +#define NUM_CYLINDER_SEGMENTS 32 + +// FIXME: use quad stamp? +static void DoCylinderPart(polyVert_t *verts) +{ + int vbase; + int i; + + RB_CHECKOVERFLOW( 4, 6 ); + + vbase = tess.numVertexes; + + for (i=0; i<4; i++) + { + VectorCopy( verts->xyz, tess.xyz[tess.numVertexes] ); + tess.texCoords[tess.numVertexes][0][0] = verts->st[0]; + tess.texCoords[tess.numVertexes][0][1] = verts->st[1]; + VectorScale4 (verts->modulate, 1.0f / 255.0f, tess.vertexColors[tess.numVertexes]); + tess.numVertexes++; + verts++; + } + + tess.indexes[tess.numIndexes++] = vbase; + tess.indexes[tess.numIndexes++] = vbase + 1; + tess.indexes[tess.numIndexes++] = vbase + 2; + + tess.indexes[tess.numIndexes++] = vbase + 2; + tess.indexes[tess.numIndexes++] = vbase + 3; + tess.indexes[tess.numIndexes++] = vbase; +} + +// e->origin holds the bottom point +// e->oldorigin holds the top point +// e->radius holds the radius + +static void RB_SurfaceCylinder( void ) +{ + static polyVert_t lower_points[NUM_CYLINDER_SEGMENTS], upper_points[NUM_CYLINDER_SEGMENTS], verts[4]; + vec3_t vr, vu, midpoint, v1; + float detail, length; + int i; + int segments; + refEntity_t *e; + int nextSegment; + + e = &backEnd.currentEntity->e; + + //Work out the detail level of this cylinder + VectorAdd( e->origin, e->oldorigin, midpoint ); + VectorScale(midpoint, 0.5f, midpoint); // Average start and end + + VectorSubtract( midpoint, backEnd.viewParms.ori.origin, midpoint ); + length = VectorNormalize( midpoint ); + + // this doesn't need to be perfect....just a rough compensation for zoom level is enough + length *= (backEnd.viewParms.fovX / 90.0f); + + detail = 1 - ((float) length / 1024 ); + segments = NUM_CYLINDER_SEGMENTS * detail; + + // 3 is the absolute minimum, but the pop between 3-8 is too noticeable + if ( segments < 8 ) + { + segments = 8; + } + + if ( segments > NUM_CYLINDER_SEGMENTS ) + { + segments = NUM_CYLINDER_SEGMENTS; + } + + //Get the direction vector + MakeNormalVectors( e->axis[0], vr, vu ); + + VectorScale( vu, e->radius, v1 ); // size1 + VectorScale( vu, e->rotation, vu ); // size2 + + // Calculate the step around the cylinder + detail = 360.0f / (float)segments; + + for ( i = 0; i < segments; i++ ) + { + //Upper ring + RotatePointAroundVector( upper_points[i].xyz, e->axis[0], vu, detail * i ); + VectorAdd( upper_points[i].xyz, e->origin, upper_points[i].xyz ); + + //Lower ring + RotatePointAroundVector( lower_points[i].xyz, e->axis[0], v1, detail * i ); + VectorAdd( lower_points[i].xyz, e->oldorigin, lower_points[i].xyz ); + } + + // Calculate the texture coords so the texture can wrap around the whole cylinder + detail = 1.0f / (float)segments; + + for ( i = 0; i < segments; i++ ) + { + if ( i + 1 < segments ) + nextSegment = i + 1; + else + nextSegment = 0; + + VectorCopy( upper_points[i].xyz, verts[0].xyz ); + verts[0].st[1] = 1.0f; + verts[0].st[0] = detail * i; + verts[0].modulate[0] = (byte)(e->shaderRGBA[0]); + verts[0].modulate[1] = (byte)(e->shaderRGBA[1]); + verts[0].modulate[2] = (byte)(e->shaderRGBA[2]); + verts[0].modulate[3] = (byte)(e->shaderRGBA[3]); + + VectorCopy( lower_points[i].xyz, verts[1].xyz ); + verts[1].st[1] = 0.0f; + verts[1].st[0] = detail * i; + verts[1].modulate[0] = (byte)(e->shaderRGBA[0]); + verts[1].modulate[1] = (byte)(e->shaderRGBA[1]); + verts[1].modulate[2] = (byte)(e->shaderRGBA[2]); + verts[1].modulate[3] = (byte)(e->shaderRGBA[3]); + + VectorCopy( lower_points[nextSegment].xyz, verts[2].xyz ); + verts[2].st[1] = 0.0f; + verts[2].st[0] = detail * ( i + 1 ); + verts[2].modulate[0] = (byte)(e->shaderRGBA[0]); + verts[2].modulate[1] = (byte)(e->shaderRGBA[1]); + verts[2].modulate[2] = (byte)(e->shaderRGBA[2]); + verts[2].modulate[3] = (byte)(e->shaderRGBA[3]); + + VectorCopy( upper_points[nextSegment].xyz, verts[3].xyz ); + verts[3].st[1] = 1.0f; + verts[3].st[0] = detail * ( i + 1 ); + verts[3].modulate[0] = (byte)(e->shaderRGBA[0]); + verts[3].modulate[1] = (byte)(e->shaderRGBA[1]); + verts[3].modulate[2] = (byte)(e->shaderRGBA[2]); + verts[3].modulate[3] = (byte)(e->shaderRGBA[3]); + + DoCylinderPart(verts); + } +} + +static vec3_t sh1, sh2; +static float f_count; + +#define LIGHTNING_RECURSION_LEVEL 1 // was 2 + +// these functions are pretty crappy in terms of returning a nice range of rnd numbers, but it's probably good enough? +/*static int Q_rand( int *seed ) { + *seed = (69069 * *seed + 1); + return *seed; +} + +static float Q_random( int *seed ) { + return ( Q_rand( seed ) & 0xffff ) / (float)0x10000; +} + +static float Q_crandom( int *seed ) { + return 2.0F * ( Q_random( seed ) - 0.5f ); +} +*/ +// Up front, we create a random "shape", then apply that to each line segment...and then again to each of those segments...kind of like a fractal +//---------------------------------------------------------------------------- +static void CreateShape() +//---------------------------------------------------------------------------- +{ + VectorSet( sh1, 0.66f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd + 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f, + 0.07f + Q_flrand(-1.0f, 1.0f) * 0.025f ); + + // it seems to look best to have a point on one side of the ideal line, then the other point on the other side. + VectorSet( sh2, 0.33f + Q_flrand(-1.0f, 1.0f) * 0.1f, // fwd + -sh1[1] + Q_flrand(-1.0f, 1.0f) * 0.02f, // forcing point to be on the opposite side of the line -- right + -sh1[2] + Q_flrand(-1.0f, 1.0f) * 0.02f );// up +} + +//---------------------------------------------------------------------------- +static void ApplyShape( vec3_t start, vec3_t end, vec3_t right, float sradius, float eradius, int count ) +//---------------------------------------------------------------------------- +{ + vec3_t point1, point2, fwd; + vec3_t rt, up; + float perc, dis; + + if ( count < 1 ) + { + // done recursing + DoLine2( start, end, right, sradius, eradius ); + return; + } + + CreateShape(); + + VectorSubtract( end, start, fwd ); + dis = VectorNormalize( fwd ) * 0.7f; + MakeNormalVectors( fwd, rt, up ); + + perc = sh1[0]; + + VectorScale( start, perc, point1 ); + VectorMA( point1, 1.0f - perc, end, point1 ); + VectorMA( point1, dis * sh1[1], rt, point1 ); + VectorMA( point1, dis * sh1[2], up, point1 ); + + // do a quick and dirty interpolation of the radius at that point + float rads1, rads2; + + rads1 = sradius * 0.666f + eradius * 0.333f; + rads2 = sradius * 0.333f + eradius * 0.666f; + + // recursion + ApplyShape( start, point1, right, sradius, rads1, count - 1 ); + + perc = sh2[0]; + + VectorScale( start, perc, point2 ); + VectorMA( point2, 1.0f - perc, end, point2 ); + VectorMA( point2, dis * sh2[1], rt, point2 ); + VectorMA( point2, dis * sh2[2], up, point2 ); + + // recursion + ApplyShape( point2, point1, right, rads1, rads2, count - 1 ); + ApplyShape( point2, end, right, rads2, eradius, count - 1 ); +} + +//---------------------------------------------------------------------------- +static void DoBoltSeg( vec3_t start, vec3_t end, vec3_t right, float radius ) +//---------------------------------------------------------------------------- +{ + refEntity_t *e; + vec3_t fwd, old; + vec3_t cur, off={10,10,10}; + vec3_t rt, up; + vec3_t temp; + int i; + float dis, oldPerc = 0.0f, perc, oldRadius, newRadius; + + e = &backEnd.currentEntity->e; + + VectorSubtract( end, start, fwd ); + dis = VectorNormalize( fwd ); + + MakeNormalVectors( fwd, rt, up ); + + VectorCopy( start, old ); + + oldRadius = newRadius = radius; + + for ( i = 20; i <= dis; i+= 20 ) + { + // because of our large step size, we may not actually draw to the end. In this case, fudge our percent so that we are basically complete + if ( i + 20 > dis ) + { + perc = 1.0f; + } + else + { + // percentage of the amount of line completed + perc = (float)i / dis; + } + + // create our level of deviation for this point + VectorScale( fwd, Q_crandom(&e->frame) * 3.0f, temp ); // move less in fwd direction, chaos also does not affect this + VectorMA( temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], rt, temp ); // move more in direction perpendicular to line, angles is really the chaos + VectorMA( temp, Q_crandom(&e->frame) * 7.0f * e->axis[0][0], up, temp ); // move more in direction perpendicular to line + + // track our total level of offset from the ideal line + VectorAdd( off, temp, off ); + + // Move from start to end, always adding our current level of offset from the ideal line + // Even though we are adding a random offset.....by nature, we always move from exactly start....to end + VectorAdd( start, off, cur ); + VectorScale( cur, 1.0f - perc, cur ); + VectorMA( cur, perc, end, cur ); + + if ( e->renderfx & RF_TAPERED ) + { + // This does pretty close to perfect tapering since apply shape interpolates the old and new as it goes along. + // by using one minus the square, the radius stays fairly constant, then drops off quickly at the very point of the bolt + oldRadius = radius * (1.0f-oldPerc*oldPerc); + newRadius = radius * (1.0f-perc*perc); + } + + // Apply the random shape to our line seg to give it some micro-detail-jaggy-coolness. + ApplyShape( cur, old, right, newRadius, oldRadius, LIGHTNING_RECURSION_LEVEL ); + + // randomly split off to create little tendrils, but don't do it too close to the end and especially if we are not even of the forked variety + if ( ( e->renderfx & RF_FORKED ) && f_count > 0 && Q_random(&e->frame) > 0.94f && radius * (1.0f - perc) > 0.2f ) + { + vec3_t newDest; + + f_count--; + + // Pick a point somewhere between the current point and the final endpoint + VectorAdd( cur, e->oldorigin, newDest ); + VectorScale( newDest, 0.5f, newDest ); + + // And then add some crazy offset + for ( int t = 0; t < 3; t++ ) + { + newDest[t] += Q_crandom(&e->frame) * 80; + } + + // we could branch off using OLD and NEWDEST, but that would allow multiple forks...whereas, we just want simpler brancing + DoBoltSeg( cur, newDest, right, newRadius ); + } + + // Current point along the line becomes our new old attach point + VectorCopy( cur, old ); + oldPerc = perc; + } +} + +//------------------------------------------ +static void RB_SurfaceElectricity() +//------------------------------------------ +{ + refEntity_t *e; + vec3_t right, fwd; + vec3_t start, end; + vec3_t v1, v2; + float radius, perc = 1.0f, dis; + + e = &backEnd.currentEntity->e; + radius = e->radius; + + VectorCopy( e->origin, start ); + + VectorSubtract( e->oldorigin, start, fwd ); + dis = VectorNormalize( fwd ); + + // see if we should grow from start to end + if ( e->renderfx & RF_GROW ) + { + perc = 1.0f - ( e->axis[0][2]/*endTime*/ - tr.refdef.time ) / e->axis[0][1]/*duration*/; + + if ( perc > 1.0f ) + { + perc = 1.0f; + } + else if ( perc < 0.0f ) + { + perc = 0.0f; + } + } + + VectorMA( start, perc * dis, fwd, e->oldorigin ); + VectorCopy( e->oldorigin, end ); + + // compute side vector + VectorSubtract( start, backEnd.viewParms.ori.origin, v1 ); + VectorSubtract( end, backEnd.viewParms.ori.origin, v2 ); + CrossProduct( v1, v2, right ); + VectorNormalize( right ); + + DoBoltSeg( start, end, right, radius ); +} + +//================================================================================ + +#if 0 +/* +** VectorArrayNormalize +* +* The inputs to this routing seem to always be close to length = 1.0 (about 0.6 to 2.0) +* This means that we don't have to worry about zero length or enormously long vectors. +*/ +static void VectorArrayNormalize(vec4_t *normals, unsigned int count) +{ +// assert(count); + +#if idppc + { + register float half = 0.5; + register float one = 1.0; + float *components = (float *)normals; + + // Vanilla PPC code, but since PPC has a reciprocal square root estimate instruction, + // runs *much* faster than calling sqrt(). We'll use a single Newton-Raphson + // refinement step to get a little more precision. This seems to yeild results + // that are correct to 3 decimal places and usually correct to at least 4 (sometimes 5). + // (That is, for the given input range of about 0.6 to 2.0). + do { + float x, y, z; + float B, y0, y1; + + x = components[0]; + y = components[1]; + z = components[2]; + components += 4; + B = x*x + y*y + z*z; + +#ifdef __GNUC__ + asm("frsqrte %0,%1" : "=f" (y0) : "f" (B)); +#else + y0 = __frsqrte(B); +#endif + y1 = y0 + half*y0*(one - B*y0*y0); + + x = x * y1; + y = y * y1; + components[-4] = x; + z = z * y1; + components[-3] = y; + components[-2] = z; + } while(count--); + } +#else // No assembly version for this architecture, or C_ONLY defined + // given the input, it's safe to call VectorNormalizeFast + while (count--) { + VectorNormalizeFast(normals[0]); + normals++; + } +#endif + +} +#endif + + + +/* +** LerpMeshVertexes +*/ +#if 0 +#if idppc_altivec +static void LerpMeshVertexes_altivec(md3Surface_t *surf, float backlerp) +{ + short *oldXyz, *newXyz, *oldNormals, *newNormals; + float *outXyz, *outNormal; + float oldXyzScale QALIGN(16); + float newXyzScale QALIGN(16); + float oldNormalScale QALIGN(16); + float newNormalScale QALIGN(16); + int vertNum; + unsigned lat, lng; + int numVerts; + + outXyz = tess.xyz[tess.numVertexes]; + outNormal = tess.normal[tess.numVertexes]; + + newXyz = (short *)((byte *)surf + surf->ofsXyzNormals) + + (backEnd.currentEntity->e.frame * surf->numVerts * 4); + newNormals = newXyz + 3; + + newXyzScale = MD3_XYZ_SCALE * (1.0 - backlerp); + newNormalScale = 1.0 - backlerp; + + numVerts = surf->numVerts; + + if ( backlerp == 0 ) { + vector signed short newNormalsVec0; + vector signed short newNormalsVec1; + vector signed int newNormalsIntVec; + vector float newNormalsFloatVec; + vector float newXyzScaleVec; + vector unsigned char newNormalsLoadPermute; + vector unsigned char newNormalsStorePermute; + vector float zero; + + newNormalsStorePermute = vec_lvsl(0,(float *)&newXyzScaleVec); + newXyzScaleVec = *(vector float *)&newXyzScale; + newXyzScaleVec = vec_perm(newXyzScaleVec,newXyzScaleVec,newNormalsStorePermute); + newXyzScaleVec = vec_splat(newXyzScaleVec,0); + newNormalsLoadPermute = vec_lvsl(0,newXyz); + newNormalsStorePermute = vec_lvsr(0,outXyz); + zero = (vector float)vec_splat_s8(0); + // + // just copy the vertexes + // + for (vertNum=0 ; vertNum < numVerts ; vertNum++, + newXyz += 4, newNormals += 4, + outXyz += 4, outNormal += 4) + { + newNormalsLoadPermute = vec_lvsl(0,newXyz); + newNormalsStorePermute = vec_lvsr(0,outXyz); + newNormalsVec0 = vec_ld(0,newXyz); + newNormalsVec1 = vec_ld(16,newXyz); + newNormalsVec0 = vec_perm(newNormalsVec0,newNormalsVec1,newNormalsLoadPermute); + newNormalsIntVec = vec_unpackh(newNormalsVec0); + newNormalsFloatVec = vec_ctf(newNormalsIntVec,0); + newNormalsFloatVec = vec_madd(newNormalsFloatVec,newXyzScaleVec,zero); + newNormalsFloatVec = vec_perm(newNormalsFloatVec,newNormalsFloatVec,newNormalsStorePermute); + //outXyz[0] = newXyz[0] * newXyzScale; + //outXyz[1] = newXyz[1] * newXyzScale; + //outXyz[2] = newXyz[2] * newXyzScale; + + lat = ( newNormals[0] >> 8 ) & 0xff; + lng = ( newNormals[0] & 0xff ); + lat *= (FUNCTABLE_SIZE/256); + lng *= (FUNCTABLE_SIZE/256); + + // decode X as cos( lat ) * sin( long ) + // decode Y as sin( lat ) * sin( long ) + // decode Z as cos( long ) + + outNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + outNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; + outNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + + vec_ste(newNormalsFloatVec,0,outXyz); + vec_ste(newNormalsFloatVec,4,outXyz); + vec_ste(newNormalsFloatVec,8,outXyz); + } + } else { + // + // interpolate and copy the vertex and normal + // + oldXyz = (short *)((byte *)surf + surf->ofsXyzNormals) + + (backEnd.currentEntity->e.oldframe * surf->numVerts * 4); + oldNormals = oldXyz + 3; + + oldXyzScale = MD3_XYZ_SCALE * backlerp; + oldNormalScale = backlerp; + + for (vertNum=0 ; vertNum < numVerts ; vertNum++, + oldXyz += 4, newXyz += 4, oldNormals += 4, newNormals += 4, + outXyz += 4, outNormal += 4) + { + vec3_t uncompressedOldNormal, uncompressedNewNormal; + + // interpolate the xyz + outXyz[0] = oldXyz[0] * oldXyzScale + newXyz[0] * newXyzScale; + outXyz[1] = oldXyz[1] * oldXyzScale + newXyz[1] * newXyzScale; + outXyz[2] = oldXyz[2] * oldXyzScale + newXyz[2] * newXyzScale; + + // FIXME: interpolate lat/long instead? + lat = ( newNormals[0] >> 8 ) & 0xff; + lng = ( newNormals[0] & 0xff ); + lat *= 4; + lng *= 4; + uncompressedNewNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + uncompressedNewNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; + uncompressedNewNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + + lat = ( oldNormals[0] >> 8 ) & 0xff; + lng = ( oldNormals[0] & 0xff ); + lat *= 4; + lng *= 4; + + uncompressedOldNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + uncompressedOldNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; + uncompressedOldNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + + outNormal[0] = uncompressedOldNormal[0] * oldNormalScale + uncompressedNewNormal[0] * newNormalScale; + outNormal[1] = uncompressedOldNormal[1] * oldNormalScale + uncompressedNewNormal[1] * newNormalScale; + outNormal[2] = uncompressedOldNormal[2] * oldNormalScale + uncompressedNewNormal[2] * newNormalScale; + +// VectorNormalize (outNormal); + } + VectorArrayNormalize((vec4_t *)tess.normal[tess.numVertexes], numVerts); + } +} +#endif +#endif + +static void LerpMeshVertexes_scalar(mdvSurface_t *surf, float backlerp) +{ +#if 0 + short *oldXyz, *newXyz, *oldNormals, *newNormals; + float *outXyz, *outNormal; + float oldXyzScale, newXyzScale; + float oldNormalScale, newNormalScale; + int vertNum; + unsigned lat, lng; + int numVerts; + + outXyz = tess.xyz[tess.numVertexes]; + outNormal = tess.normal[tess.numVertexes]; + + newXyz = (short *)((byte *)surf + surf->ofsXyzNormals) + + (backEnd.currentEntity->e.frame * surf->numVerts * 4); + newNormals = newXyz + 3; + + newXyzScale = MD3_XYZ_SCALE * (1.0 - backlerp); + newNormalScale = 1.0 - backlerp; + + numVerts = surf->numVerts; + + if ( backlerp == 0 ) { + // + // just copy the vertexes + // + for (vertNum=0 ; vertNum < numVerts ; vertNum++, + newXyz += 4, newNormals += 4, + outXyz += 4, outNormal += 4) + { + + outXyz[0] = newXyz[0] * newXyzScale; + outXyz[1] = newXyz[1] * newXyzScale; + outXyz[2] = newXyz[2] * newXyzScale; + + lat = ( newNormals[0] >> 8 ) & 0xff; + lng = ( newNormals[0] & 0xff ); + lat *= (FUNCTABLE_SIZE/256); + lng *= (FUNCTABLE_SIZE/256); + + // decode X as cos( lat ) * sin( long ) + // decode Y as sin( lat ) * sin( long ) + // decode Z as cos( long ) + + outNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + outNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; + outNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + } + } else { + // + // interpolate and copy the vertex and normal + // + oldXyz = (short *)((byte *)surf + surf->ofsXyzNormals) + + (backEnd.currentEntity->e.oldframe * surf->numVerts * 4); + oldNormals = oldXyz + 3; + + oldXyzScale = MD3_XYZ_SCALE * backlerp; + oldNormalScale = backlerp; + + for (vertNum=0 ; vertNum < numVerts ; vertNum++, + oldXyz += 4, newXyz += 4, oldNormals += 4, newNormals += 4, + outXyz += 4, outNormal += 4) + { + vec3_t uncompressedOldNormal, uncompressedNewNormal; + + // interpolate the xyz + outXyz[0] = oldXyz[0] * oldXyzScale + newXyz[0] * newXyzScale; + outXyz[1] = oldXyz[1] * oldXyzScale + newXyz[1] * newXyzScale; + outXyz[2] = oldXyz[2] * oldXyzScale + newXyz[2] * newXyzScale; + + // FIXME: interpolate lat/long instead? + lat = ( newNormals[0] >> 8 ) & 0xff; + lng = ( newNormals[0] & 0xff ); + lat *= 4; + lng *= 4; + uncompressedNewNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + uncompressedNewNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; + uncompressedNewNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + + lat = ( oldNormals[0] >> 8 ) & 0xff; + lng = ( oldNormals[0] & 0xff ); + lat *= 4; + lng *= 4; + + uncompressedOldNormal[0] = tr.sinTable[(lat+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK] * tr.sinTable[lng]; + uncompressedOldNormal[1] = tr.sinTable[lat] * tr.sinTable[lng]; + uncompressedOldNormal[2] = tr.sinTable[(lng+(FUNCTABLE_SIZE/4))&FUNCTABLE_MASK]; + + outNormal[0] = uncompressedOldNormal[0] * oldNormalScale + uncompressedNewNormal[0] * newNormalScale; + outNormal[1] = uncompressedOldNormal[1] * oldNormalScale + uncompressedNewNormal[1] * newNormalScale; + outNormal[2] = uncompressedOldNormal[2] * oldNormalScale + uncompressedNewNormal[2] * newNormalScale; + +// VectorNormalize (outNormal); + } + VectorArrayNormalize((vec4_t *)tess.normal[tess.numVertexes], numVerts); + } +#endif + float *outXyz; + uint32_t *outNormal; + mdvVertex_t *newVerts; + int vertNum; + + newVerts = surf->verts + backEnd.currentEntity->e.frame * surf->numVerts; + + outXyz = tess.xyz[tess.numVertexes]; + outNormal = &tess.normal[tess.numVertexes]; + + if (backlerp == 0) + { + // + // just copy the vertexes + // + + for (vertNum=0 ; vertNum < surf->numVerts ; vertNum++) + { + vec3_t normal; + + VectorCopy(newVerts->xyz, outXyz); + VectorCopy(newVerts->normal, normal); + + *outNormal = R_VboPackNormal(normal); + + newVerts++; + outXyz += 4; + outNormal++; + } + } + else + { + // + // interpolate and copy the vertex and normal + // + + mdvVertex_t *oldVerts; + + oldVerts = surf->verts + backEnd.currentEntity->e.oldframe * surf->numVerts; + + for (vertNum=0 ; vertNum < surf->numVerts ; vertNum++) + { + vec3_t normal; + + VectorLerp(newVerts->xyz, oldVerts->xyz, backlerp, outXyz); + VectorLerp(newVerts->normal, oldVerts->normal, backlerp, normal); + VectorNormalize(normal); + + *outNormal = R_VboPackNormal(normal); + + newVerts++; + oldVerts++; + outXyz += 4; + outNormal++; + } + } + +} + +static void LerpMeshVertexes(mdvSurface_t *surf, float backlerp) +{ +#if 0 +#if idppc_altivec + if (com_altivec->integer) { + // must be in a seperate function or G3 systems will crash. + LerpMeshVertexes_altivec( surf, backlerp ); + return; + } +#endif // idppc_altivec +#endif + LerpMeshVertexes_scalar( surf, backlerp ); +} + + +/* +============= +RB_SurfaceMesh +============= +*/ +static void RB_SurfaceMesh(mdvSurface_t *surface) { + int j; + float backlerp; + mdvSt_t *texCoords; + int Bob, Doug; + int numVerts; + + if ( backEnd.currentEntity->e.oldframe == backEnd.currentEntity->e.frame ) { + backlerp = 0; + } else { + backlerp = backEnd.currentEntity->e.backlerp; + } + + RB_CHECKOVERFLOW( surface->numVerts, surface->numIndexes ); + + LerpMeshVertexes (surface, backlerp); + + Bob = tess.numIndexes; + Doug = tess.numVertexes; + for (j = 0 ; j < surface->numIndexes ; j++) { + tess.indexes[Bob + j] = Doug + surface->indexes[j]; + } + tess.numIndexes += surface->numIndexes; + + texCoords = surface->st; + + numVerts = surface->numVerts; + for ( j = 0; j < numVerts; j++ ) { + tess.texCoords[Doug + j][0][0] = texCoords[j].st[0]; + tess.texCoords[Doug + j][0][1] = texCoords[j].st[1]; + // FIXME: fill in lightmapST for completeness? + } + + tess.numVertexes += surface->numVerts; + +} + + +/* +============== +RB_SurfaceFace +============== +*/ +static void RB_SurfaceBSPFace( srfBspSurface_t *srf ) { + if( RB_SurfaceVbo(srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, + srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qtrue ) ) + { + return; + } + + RB_SurfaceVertsAndIndexes(srf->numVerts, srf->verts, srf->numIndexes, + srf->indexes, srf->dlightBits, srf->pshadowBits); +} + + +static float LodErrorForVolume( vec3_t local, float radius ) { + vec3_t world; + float d; + + // never let it go negative + if ( r_lodCurveError->value < 0 ) { + return 0; + } + + world[0] = local[0] * backEnd.ori.axis[0][0] + local[1] * backEnd.ori.axis[1][0] + + local[2] * backEnd.ori.axis[2][0] + backEnd.ori.origin[0]; + world[1] = local[0] * backEnd.ori.axis[0][1] + local[1] * backEnd.ori.axis[1][1] + + local[2] * backEnd.ori.axis[2][1] + backEnd.ori.origin[1]; + world[2] = local[0] * backEnd.ori.axis[0][2] + local[1] * backEnd.ori.axis[1][2] + + local[2] * backEnd.ori.axis[2][2] + backEnd.ori.origin[2]; + + VectorSubtract( world, backEnd.viewParms.ori.origin, world ); + d = DotProduct( world, backEnd.viewParms.ori.axis[0] ); + + if ( d < 0 ) { + d = -d; + } + d -= radius; + if ( d < 1 ) { + d = 1; + } + + return r_lodCurveError->value / d; +} + +/* +============= +RB_SurfaceGrid + +Just copy the grid of points and triangulate +============= +*/ +static void RB_SurfaceBSPGrid( srfBspSurface_t *srf ) { + int i, j; + float *xyz; + float *texCoords, *lightCoords[MAXLIGHTMAPS]; + uint32_t *normal; + uint32_t *tangent; + float *color; + uint32_t *lightdir; + srfVert_t *dv; + int rows, irows, vrows; + int used; + int widthTable[MAX_GRID_SIZE]; + int heightTable[MAX_GRID_SIZE]; + float lodError; + int lodWidth, lodHeight; + int numVertexes; + int dlightBits; + int pshadowBits; + //int *vDlightBits; + + if( RB_SurfaceVbo (srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, + srf->firstIndex, srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qtrue ) ) + { + return; + } + + dlightBits = srf->dlightBits; + tess.dlightBits |= dlightBits; + + pshadowBits = srf->pshadowBits; + tess.pshadowBits |= pshadowBits; + + // determine the allowable discrepance + lodError = LodErrorForVolume( srf->lodOrigin, srf->lodRadius ); + + // determine which rows and columns of the subdivision + // we are actually going to use + widthTable[0] = 0; + lodWidth = 1; + for ( i = 1 ; i < srf->width-1 ; i++ ) { + if ( srf->widthLodError[i] <= lodError ) { + widthTable[lodWidth] = i; + lodWidth++; + } + } + widthTable[lodWidth] = srf->width-1; + lodWidth++; + + heightTable[0] = 0; + lodHeight = 1; + for ( i = 1 ; i < srf->height-1 ; i++ ) { + if ( srf->heightLodError[i] <= lodError ) { + heightTable[lodHeight] = i; + lodHeight++; + } + } + heightTable[lodHeight] = srf->height-1; + lodHeight++; + + + // very large grids may have more points or indexes than can be fit + // in the tess structure, so we may have to issue it in multiple passes + + used = 0; + while ( used < lodHeight - 1 ) { + // see how many rows of both verts and indexes we can add without overflowing + do { + vrows = ( SHADER_MAX_VERTEXES - tess.numVertexes ) / lodWidth; + irows = ( SHADER_MAX_INDEXES - tess.numIndexes ) / ( lodWidth * 6 ); + + // if we don't have enough space for at least one strip, flush the buffer + if ( vrows < 2 || irows < 1 ) { + RB_EndSurface(); + RB_BeginSurface(tess.shader, tess.fogNum, tess.cubemapIndex ); + } else { + break; + } + } while ( 1 ); + + rows = irows; + if ( vrows < irows + 1 ) { + rows = vrows - 1; + } + if ( used + rows > lodHeight ) { + rows = lodHeight - used; + } + + numVertexes = tess.numVertexes; + + xyz = tess.xyz[numVertexes]; + normal = &tess.normal[numVertexes]; + tangent = &tess.tangent[numVertexes]; + texCoords = tess.texCoords[numVertexes][0]; + for (int tc = 0; tc < MAXLIGHTMAPS; ++tc) + lightCoords[tc] = tess.texCoords[numVertexes][1 + tc]; + color = tess.vertexColors[numVertexes]; + lightdir = &tess.lightdir[numVertexes]; + //vDlightBits = &tess.vertexDlightBits[numVertexes]; + + for ( i = 0 ; i < rows ; i++ ) { + for ( j = 0 ; j < lodWidth ; j++ ) { + dv = srf->verts + heightTable[ used + i ] * srf->width + + widthTable[ j ]; + + if ( tess.shader->vertexAttribs & ATTR_POSITION ) + { + VectorCopy(dv->xyz, xyz); + xyz += 4; + } + + if ( tess.shader->vertexAttribs & ATTR_NORMAL ) + { + *normal++ = R_VboPackNormal(dv->normal); + } + + if ( tess.shader->vertexAttribs & ATTR_TANGENT ) + { + *tangent++ = R_VboPackTangent(dv->tangent); + } + + if ( tess.shader->vertexAttribs & ATTR_TEXCOORD0 ) + { + VectorCopy2(dv->st, texCoords); + texCoords += NUM_TESS_TEXCOORDS*2; + } + + for (int tc = 0; tc < MAXLIGHTMAPS; ++tc) + { + if ( tess.shader->vertexAttribs & (ATTR_TEXCOORD1 + tc) ) + { + VectorCopy2(dv->lightmap[tc], lightCoords[tc]); + lightCoords[tc] += NUM_TESS_TEXCOORDS*2; + } + } + + if ( tess.shader->vertexAttribs & ATTR_COLOR ) + { + VectorCopy4(dv->vertexColors[0], color); + color += 4; + } + + if ( tess.shader->vertexAttribs & ATTR_LIGHTDIRECTION ) + { + *lightdir++ = R_VboPackNormal(dv->lightdir); + } + + //*vDlightBits++ = dlightBits; + } + } + + + // add the indexes + { + int numIndexes; + int w, h; + + h = rows - 1; + w = lodWidth - 1; + numIndexes = tess.numIndexes; + for (i = 0 ; i < h ; i++) { + for (j = 0 ; j < w ; j++) { + int v1, v2, v3, v4; + + // vertex order to be reckognized as tristrips + v1 = numVertexes + i*lodWidth + j + 1; + v2 = v1 - 1; + v3 = v2 + lodWidth; + v4 = v3 + 1; + + tess.indexes[numIndexes] = v2; + tess.indexes[numIndexes+1] = v3; + tess.indexes[numIndexes+2] = v1; + + tess.indexes[numIndexes+3] = v1; + tess.indexes[numIndexes+4] = v3; + tess.indexes[numIndexes+5] = v4; + numIndexes += 6; + } + } + + tess.numIndexes = numIndexes; + } + + tess.numVertexes += rows * lodWidth; + + used += rows - 1; + } +} + + +/* +=========================================================================== + +NULL MODEL + +=========================================================================== +*/ + +/* +=================== +RB_SurfaceAxis + +Draws x/y/z lines from the origin for orientation debugging +=================== +*/ +static void RB_SurfaceAxis( void ) { + // FIXME: implement this +#if 0 + GL_Bind( tr.whiteImage ); + GL_State( GLS_DEFAULT ); + qglLineWidth( 3 ); + qglBegin( GL_LINES ); + qglColor3f( 1,0,0 ); + qglVertex3f( 0,0,0 ); + qglVertex3f( 16,0,0 ); + qglColor3f( 0,1,0 ); + qglVertex3f( 0,0,0 ); + qglVertex3f( 0,16,0 ); + qglColor3f( 0,0,1 ); + qglVertex3f( 0,0,0 ); + qglVertex3f( 0,0,16 ); + qglEnd(); + qglLineWidth( 1 ); +#endif +} + +//=========================================================================== + +/* +==================== +RB_SurfaceEntity + +Entities that have a single procedurally generated surface +==================== +*/ +static void RB_SurfaceEntity( surfaceType_t *surfType ) { + switch( backEnd.currentEntity->e.reType ) { + case RT_SPRITE: + RB_SurfaceSprite(); + break; + case RT_ORIENTED_QUAD: + RB_SurfaceOrientedQuad(); + break; + case RT_BEAM: + RB_SurfaceBeam(); + break; + case RT_ELECTRICITY: + RB_SurfaceElectricity(); + break; + case RT_LINE: + RB_SurfaceLine(); + break; + case RT_ORIENTEDLINE: + RB_SurfaceOrientedLine(); + break; + case RT_SABER_GLOW: + RB_SurfaceSaberGlow(); + break; + case RT_CYLINDER: + RB_SurfaceCylinder(); + break; + case RT_ENT_CHAIN: + { + static trRefEntity_t tempEnt = *backEnd.currentEntity; + + //rww - if not static then currentEntity is garbage because + //this is a local. This was not static in sof2.. but I guess + //they never check ce.renderfx so it didn't show up. + + const int start = backEnd.currentEntity->e.uRefEnt.uMini.miniStart; + const int count = backEnd.currentEntity->e.uRefEnt.uMini.miniCount; + assert(count > 0); + backEnd.currentEntity = &tempEnt; + + assert(backEnd.currentEntity->e.renderfx >= 0); + + for (int i = 0, j = start; i < count; i++, j++) + { + backEnd.currentEntity->e = backEnd.refdef.entities[j].e; + assert(backEnd.currentEntity->e.renderfx >= 0); + + RB_SurfaceEntity(surfType); + } + } + break; + default: + RB_SurfaceAxis(); + break; + } + // FIX ME: just a testing hack. Pretty sure we can merge all of these + tess.shader->entityMergable = qtrue; +} + +static void RB_SurfaceBad( surfaceType_t *surfType ) { + ri.Printf( PRINT_ALL, "Bad surface tesselated.\n" ); +} + +static void RB_SurfaceFlare(srfFlare_t *surf) +{ + if (r_flares->integer) + RB_AddFlare(surf, tess.fogNum, surf->origin, surf->color, surf->normal); +} + +static void RB_SurfaceVBOMesh(srfBspSurface_t * srf) +{ + RB_SurfaceVbo (srf->vbo, srf->ibo, srf->numVerts, srf->numIndexes, srf->firstIndex, + srf->minIndex, srf->maxIndex, srf->dlightBits, srf->pshadowBits, qfalse ); +} + +void RB_SurfaceVBOMDVMesh(srfVBOMDVMesh_t * surface) +{ + int i, mergeForward, mergeBack; + GLvoid *firstIndexOffset, *lastIndexOffset; + + GLimp_LogComment("--- RB_SurfaceVBOMDVMesh ---\n"); + + if(!surface->vbo || !surface->ibo) + return; + + if (glState.currentVBO != surface->vbo) + { + RB_EndSurface(); + } + + //drawSurf_t drawSurf = + + R_BindVBO(surface->vbo); + R_BindIBO(surface->ibo); + + tess.useInternalVBO = qfalse; + tess.externalIBO = surface->ibo; + + // tess.dlightBits is already set in the renderloop + + // merge this into any existing multidraw primitives + mergeForward = -1; + mergeBack = -1; + firstIndexOffset = BUFFER_OFFSET(surface->indexOffset * sizeof(glIndex_t)); + lastIndexOffset = BUFFER_OFFSET(surface->numIndexes * sizeof(glIndex_t)); + + if (r_mergeMultidraws->integer) + { + i = 0; + + if (r_mergeMultidraws->integer == 1) + { + // lazy merge, only check the last primitive + if (tess.multiDrawPrimitives) + { + i = tess.multiDrawPrimitives - 1; + } + } + + for (; i < tess.multiDrawPrimitives; i++) + { + if (tess.multiDrawLastIndex[i] == firstIndexOffset) + { + mergeBack = i; + } + + if (lastIndexOffset == tess.multiDrawFirstIndex[i]) + { + mergeForward = i; + } + } + } + + if (mergeBack != -1 && mergeForward == -1) + { + tess.multiDrawNumIndexes[mergeBack] += surface->numIndexes; + tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; + tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], surface->minIndex); + tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], surface->maxIndex); + backEnd.pc.c_multidrawsMerged++; + } + else if (mergeBack == -1 && mergeForward != -1) + { + tess.multiDrawNumIndexes[mergeForward] += surface->numIndexes; + tess.multiDrawFirstIndex[mergeForward] = (glIndex_t *)firstIndexOffset; + tess.multiDrawLastIndex[mergeForward] = tess.multiDrawFirstIndex[mergeForward] + tess.multiDrawNumIndexes[mergeForward]; + tess.multiDrawMinIndex[mergeForward] = MIN(tess.multiDrawMinIndex[mergeForward], surface->minIndex); + tess.multiDrawMaxIndex[mergeForward] = MAX(tess.multiDrawMaxIndex[mergeForward], surface->maxIndex); + backEnd.pc.c_multidrawsMerged++; + } + else if (mergeBack != -1 && mergeForward != -1) + { + tess.multiDrawNumIndexes[mergeBack] += surface->numIndexes + tess.multiDrawNumIndexes[mergeForward]; + tess.multiDrawLastIndex[mergeBack] = tess.multiDrawFirstIndex[mergeBack] + tess.multiDrawNumIndexes[mergeBack]; + tess.multiDrawMinIndex[mergeBack] = MIN(tess.multiDrawMinIndex[mergeBack], MIN(tess.multiDrawMinIndex[mergeForward], surface->minIndex)); + tess.multiDrawMaxIndex[mergeBack] = MAX(tess.multiDrawMaxIndex[mergeBack], MAX(tess.multiDrawMaxIndex[mergeForward], surface->maxIndex)); + tess.multiDrawPrimitives--; + + if (mergeForward != tess.multiDrawPrimitives) + { + tess.multiDrawNumIndexes[mergeForward] = tess.multiDrawNumIndexes[tess.multiDrawPrimitives]; + tess.multiDrawFirstIndex[mergeForward] = tess.multiDrawFirstIndex[tess.multiDrawPrimitives]; + } + backEnd.pc.c_multidrawsMerged += 2; + } + else if (mergeBack == -1 && mergeForward == -1) + { + tess.multiDrawNumIndexes[tess.multiDrawPrimitives] = surface->numIndexes; + tess.multiDrawFirstIndex[tess.multiDrawPrimitives] = (glIndex_t *)firstIndexOffset; + tess.multiDrawLastIndex[tess.multiDrawPrimitives] = (glIndex_t *)lastIndexOffset; + tess.multiDrawMinIndex[tess.multiDrawPrimitives] = surface->minIndex; + tess.multiDrawMaxIndex[tess.multiDrawPrimitives] = surface->maxIndex; + tess.multiDrawPrimitives++; + } + + backEnd.pc.c_multidraws++; + + tess.numIndexes += surface->numIndexes; + tess.numVertexes += surface->numVerts; +} + +static void RB_SurfaceSkip( void *surf ) { +} + +static void RB_SurfaceSprites( srfSprites_t *surf ) +{ + if ( !r_surfaceSprites->integer || surf->numSprites == 0) + return; + + RB_EndSurface(); + + // TODO: Do we want a 2-level lod system where far away sprites are + // just flat surfaces? + + // TODO: Check which pass (z-prepass/shadow/forward) we're rendering for? + shader_t *shader = surf->shader; + shaderStage_t *firstStage = shader->stages[0]; + shaderProgram_t *programGroup = firstStage->glslShaderGroup; + const surfaceSprite_t *ss = surf->sprite; + + uint32_t shaderFlags = 0; + if ( surf->alphaTestType != ALPHA_TEST_NONE ) + shaderFlags |= SSDEF_ALPHA_TEST; + + if ( ss->type == SURFSPRITE_ORIENTED ) + shaderFlags |= SSDEF_FACE_CAMERA; + + if (ss->facing == SURFSPRITE_FACING_UP) + shaderFlags |= SSDEF_FACE_UP; + + if (ss->facing == SURFSPRITE_FACING_NORMAL) + shaderFlags |= SSDEF_FLATTENED; + + if (ss->type == SURFSPRITE_EFFECT || ss->type == SURFSPRITE_WEATHERFX) + shaderFlags |= SSDEF_FX_SPRITE; + + if ((firstStage->stateBits & (GLS_SRCBLEND_BITS|GLS_DSTBLEND_BITS)) == (GLS_SRCBLEND_ONE|GLS_DSTBLEND_ONE)) + shaderFlags |= SSDEF_ADDITIVE; + + if (surf->fogIndex > 0 && r_drawfog->integer) + shaderFlags |= SSDEF_USE_FOG; + + shaderProgram_t *program = programGroup + shaderFlags; + assert(program->uniformBlocks & (1 << UNIFORM_BLOCK_SURFACESPRITE)); + + UniformDataWriter uniformDataWriter; + uniformDataWriter.Start(program); + + // FIXME: Use entity block for this + uniformDataWriter.SetUniformMatrix4x4( + UNIFORM_MODELVIEWPROJECTIONMATRIX, glState.modelviewProjection); + + uniformDataWriter.SetUniformInt( + UNIFORM_ALPHA_TEST_TYPE, surf->alphaTestType); + + if (surf->fogIndex != -1) + uniformDataWriter.SetUniformInt(UNIFORM_FOGINDEX, surf->fogIndex - 1); + + Allocator& frameAllocator = *backEndData->perFrameMemory; + + SamplerBindingsWriter samplerBindingsWriter; + samplerBindingsWriter.AddAnimatedImage(&firstStage->bundle[0], TB_COLORMAP); + + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + const GLuint currentSpriteUbo = shader->spriteUbo; + const UniformBlockBinding uniformBlockBindings[] = { + { currentSpriteUbo, ss->spriteUboOffset, UNIFORM_BLOCK_SURFACESPRITE }, + { currentFrameUbo, tr.sceneUboOffset, UNIFORM_BLOCK_SCENE }, + { currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA }, + { currentFrameUbo, tr.fogsUboOffset, UNIFORM_BLOCK_FOGS } + }; + + DrawItem item = {}; + item.renderState.stateBits = firstStage->stateBits; + item.renderState.cullType = CT_TWO_SIDED; + item.renderState.depthRange = DepthRange{0.0f, 1.0f}; + item.program = program; + item.ibo = surf->ibo; + + item.uniformData = uniformDataWriter.Finish(frameAllocator); + + item.samplerBindings = samplerBindingsWriter.Finish( + frameAllocator, &item.numSamplerBindings); + + DrawItemSetVertexAttributes( + item, surf->attributes, surf->numAttributes, frameAllocator); + DrawItemSetUniformBlockBindings( + item, uniformBlockBindings, frameAllocator); + + item.draw.type = DRAW_COMMAND_INDEXED; + item.draw.primitiveType = GL_TRIANGLES; + item.draw.numInstances = 1; + item.draw.params.indexed.indexType = GL_UNSIGNED_SHORT; + item.draw.params.indexed.firstIndex = 0; + item.draw.params.indexed.numIndices = surf->numIndices; + item.draw.params.indexed.baseVertex = surf->baseVertex; + + tess.externalIBO = surf->ibo; + + uint32_t RB_CreateSortKey( const DrawItem& item, int stage, int layer ); + uint32_t key = RB_CreateSortKey(item, 0, surf->shader->sort); + RB_AddDrawItem(backEndData->currentPass, key, item); +} + +void (*rb_surfaceTable[SF_NUM_SURFACE_TYPES])( void *) = { + (void(*)(void*))RB_SurfaceBad, // SF_BAD, + (void(*)(void*))RB_SurfaceSkip, // SF_SKIP, + (void(*)(void*))RB_SurfaceBSPFace, // SF_FACE, + (void(*)(void*))RB_SurfaceBSPGrid, // SF_GRID, + (void(*)(void*))RB_SurfaceBSPTriangles, // SF_TRIANGLES, + (void(*)(void*))RB_SurfacePolychain, // SF_POLY, + (void(*)(void*))RB_SurfaceMesh, // SF_MDV, + (void(*)(void*))RB_MDRSurfaceAnim, // SF_MDR, + (void(*)(void*))RB_IQMSurfaceAnim, // SF_IQM, + (void(*)(void*))RB_SurfaceGhoul, // SF_MDX, + (void(*)(void*))RB_SurfaceFlare, // SF_FLARE, + (void(*)(void*))RB_SurfaceEntity, // SF_ENTITY + (void(*)(void*))RB_SurfaceVBOMesh, // SF_VBO_MESH, + (void(*)(void*))RB_SurfaceVBOMDVMesh, // SF_VBO_MDVMESH + (void(*)(void*))RB_SurfaceSprites, // SF_SPRITES + (void(*)(void*))RB_SurfaceWeather, // SF_WEATHER +}; diff --git a/codemp/rd-rend2/tr_tangentspace.cpp b/codemp/rd-rend2/tr_tangentspace.cpp new file mode 100644 index 0000000000..0c523784e6 --- /dev/null +++ b/codemp/rd-rend2/tr_tangentspace.cpp @@ -0,0 +1,291 @@ +/* +=========================================================================== +Copyright (C) 2016, OpenJK contributors + +This file is part of the OpenJK source code. + +OpenJK is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . +=========================================================================== +*/ + +#include "tr_local.h" +#include "MikkTSpace/mikktspace.h" + + +/* +================ +R_FixMikktVertIndex + +Swaps second index to third and the other way around. +When baking normal maps for models, the mesh importer will swap face indices to change the face orientation. +To generate exactly the same tangents, we have to swap indices to the same order. +Change when mesh importers swaps different indices! +(modelling tool standard is backface culling vs frontface culling in id tech 3) +================ +*/ +int R_FixMikktVertIndex(const int index) +{ + switch (index % 3) + { + case 2: return 1; + case 1: return 2; + default: return index; + } + return index; +} + +struct BspMeshData +{ + int numSurfaces; + packedVertex_t *vertices; + glIndex_t *indices; +}; + +int R_GetNumFaces(const SMikkTSpaceContext * pContext) +{ + BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; + return meshData->numSurfaces; +} + +int R_GetNumVertices(const SMikkTSpaceContext * pContext, const int iFace) +{ + return 3; +} + +void R_GetBSPPosition(const SMikkTSpaceContext * pContext, float *fvPosOut, const int iFace, const int iVert) +{ + BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + packedVertex_t& vertex = meshData->vertices[index]; + fvPosOut[0] = vertex.position[0]; + fvPosOut[1] = vertex.position[1]; + fvPosOut[2] = vertex.position[2]; +} + +void R_GetNormalBSPSurface(const SMikkTSpaceContext * pContext, float *fvNormOut, const int iFace, const int iVert) +{ + BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + packedVertex_t& vertex = meshData->vertices[index]; + + fvNormOut[0] = ((vertex.normal) & 0x3ff) * 1.0f / 511.5f - 1.0f; + fvNormOut[1] = ((vertex.normal >> 10) & 0x3ff) * 1.0f / 511.5f - 1.0f; + fvNormOut[2] = ((vertex.normal >> 20) & 0x3ff) * 1.0f / 511.5f - 1.0f; +} + +void R_GetBSPTexCoord(const SMikkTSpaceContext * pContext, float *fvTexcOut, const int iFace, const int iVert) +{ + BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + packedVertex_t& vertex = meshData->vertices[index]; + fvTexcOut[0] = vertex.texcoords[0][0]; + fvTexcOut[1] = vertex.texcoords[0][1]; +} + +void R_SetBSPTSpaceBasic(const SMikkTSpaceContext * pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) +{ + BspMeshData *meshData = (BspMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + packedVertex_t& vertex = meshData->vertices[index]; + if (vertex.tangent == 0u) + vertex.tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) + | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) + | (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) + | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); +} + +void R_CalcMikkTSpaceBSPSurface(int numSurfaces, packedVertex_t *vertices, glIndex_t *indices) +{ + SMikkTSpaceInterface tangentSpaceInterface; + + tangentSpaceInterface.m_getNumFaces = R_GetNumFaces; + tangentSpaceInterface.m_getNumVerticesOfFace = R_GetNumVertices; + tangentSpaceInterface.m_getPosition = R_GetBSPPosition; + tangentSpaceInterface.m_getNormal = R_GetNormalBSPSurface; + tangentSpaceInterface.m_getTexCoord = R_GetBSPTexCoord; + tangentSpaceInterface.m_setTSpaceBasic = R_SetBSPTSpaceBasic; + tangentSpaceInterface.m_setTSpace = NULL; + + BspMeshData meshData; + meshData.numSurfaces = numSurfaces; + meshData.vertices = vertices; + meshData.indices = indices; + + SMikkTSpaceContext modelContext; + modelContext.m_pUserData = &meshData; + modelContext.m_pInterface = &tangentSpaceInterface; + + genTangSpaceDefault(&modelContext); +} + +struct ModelMeshData +{ + int numSurfaces; + mdvVertex_t *verts; + uint32_t *tangents; + mdvSt_t *texcoords; + glIndex_t *indices; +}; + +void R_GetModelPosition(const SMikkTSpaceContext * pContext, float *fvPosOut, const int iFace, const int iVert) +{ + ModelMeshData *meshData = (ModelMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + fvPosOut[0] = meshData->verts[index].xyz[0]; + fvPosOut[1] = meshData->verts[index].xyz[1]; + fvPosOut[2] = meshData->verts[index].xyz[2]; +} + +void R_GetNormalModelSurface(const SMikkTSpaceContext * pContext, float *fvNormOut, const int iFace, const int iVert) +{ + ModelMeshData *meshData = (ModelMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + + fvNormOut[0] = meshData->verts[index].normal[0]; + fvNormOut[1] = meshData->verts[index].normal[1]; + fvNormOut[2] = meshData->verts[index].normal[2]; +} + +void R_GetModelTexCoord(const SMikkTSpaceContext * pContext, float *fvTexcOut, const int iFace, const int iVert) +{ + ModelMeshData *meshData = (ModelMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + fvTexcOut[0] = meshData->texcoords[index].st[0]; + fvTexcOut[1] = meshData->texcoords[index].st[1]; +} + +void R_SetModelTSpaceBasic(const SMikkTSpaceContext * pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) +{ + ModelMeshData *meshData = (ModelMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + + uint32_t& tangent = meshData->tangents[index]; + tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) + | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) + | (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) + | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); + +} + +void R_CalcMikkTSpaceMD3Surface(int numSurfaces, mdvVertex_t *verts, uint32_t *tangents, mdvSt_t *texcoords, glIndex_t *indices) +{ + SMikkTSpaceInterface tangentSpaceInterface; + tangentSpaceInterface.m_getNumFaces = R_GetNumFaces; + tangentSpaceInterface.m_getNumVerticesOfFace = R_GetNumVertices; + tangentSpaceInterface.m_getPosition = R_GetModelPosition; + tangentSpaceInterface.m_getNormal = R_GetNormalModelSurface; + tangentSpaceInterface.m_getTexCoord = R_GetModelTexCoord; + tangentSpaceInterface.m_setTSpaceBasic = R_SetModelTSpaceBasic; + tangentSpaceInterface.m_setTSpace = NULL; + + ModelMeshData meshData; + meshData.numSurfaces = numSurfaces; + meshData.verts = verts; + meshData.tangents = tangents; + meshData.texcoords = texcoords; + meshData.indices = indices; + + SMikkTSpaceContext modelContext; + modelContext.m_pUserData = &meshData; + modelContext.m_pInterface = &tangentSpaceInterface; + genTangSpaceDefault(&modelContext); +} + +struct GlmMeshData +{ + int numSurfaces; + mdxmVertex_t *vertices; + mdxmVertexTexCoord_t *tcs; + uint32_t *tangents; + glIndex_t *indices; +}; + +void R_GetGlmPosition(const SMikkTSpaceContext * pContext, float *fvPosOut, const int iFace, const int iVert) +{ + GlmMeshData *meshData = (GlmMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + mdxmVertex_t& vertex = meshData->vertices[index]; + fvPosOut[0] = vertex.vertCoords[0]; + fvPosOut[1] = vertex.vertCoords[1]; + fvPosOut[2] = vertex.vertCoords[2]; +} + +void R_GetNormalGlmSurface(const SMikkTSpaceContext * pContext, float *fvNormOut, const int iFace, const int iVert) +{ + GlmMeshData *meshData = (GlmMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + mdxmVertex_t& vertex = meshData->vertices[index]; + + fvNormOut[0] = vertex.normal[0]; + fvNormOut[1] = vertex.normal[1]; + fvNormOut[2] = vertex.normal[2]; +} + +void R_GetGlmTexCoord(const SMikkTSpaceContext * pContext, float *fvTexcOut, const int iFace, const int iVert) +{ + GlmMeshData *meshData = (GlmMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + mdxmVertexTexCoord_t& tcs = meshData->tcs[index]; + fvTexcOut[0] = tcs.texCoords[0]; + fvTexcOut[1] = tcs.texCoords[1]; +} + +void R_SetGlmTSpaceBasic(const SMikkTSpaceContext * pContext, const float *fvTangent, const float fSign, const int iFace, const int iVert) +{ + GlmMeshData *meshData = (GlmMeshData *)pContext->m_pUserData; + const int vert_index = R_FixMikktVertIndex(iVert); + glIndex_t index = meshData->indices[iFace * 3 + vert_index]; + uint32_t& tangent = meshData->tangents[index]; + + tangent = (((uint32_t)(fSign * 1.5f + 2.0f)) << 30) + | (((uint32_t)(fvTangent[2] * 511.5f + 512.0f)) << 20) + | (((uint32_t)(fvTangent[1] * 511.5f + 512.0f)) << 10) + | (((uint32_t)(fvTangent[0] * 511.5f + 512.0f))); +} + +void R_CalcMikkTSpaceGlmSurface(int numSurfaces, mdxmVertex_t *vertices, mdxmVertexTexCoord_t *textureCoordinates, uint32_t *tangents, glIndex_t *indices) +{ + SMikkTSpaceInterface tangentSpaceInterface; + + tangentSpaceInterface.m_getNumFaces = R_GetNumFaces; + tangentSpaceInterface.m_getNumVerticesOfFace = R_GetNumVertices; + tangentSpaceInterface.m_getPosition = R_GetGlmPosition; + tangentSpaceInterface.m_getNormal = R_GetNormalGlmSurface; + tangentSpaceInterface.m_getTexCoord = R_GetGlmTexCoord; + tangentSpaceInterface.m_setTSpaceBasic = R_SetGlmTSpaceBasic; + tangentSpaceInterface.m_setTSpace = NULL; + + GlmMeshData meshData; + meshData.numSurfaces = numSurfaces; + meshData.vertices = vertices; + meshData.tcs = textureCoordinates; + meshData.tangents = tangents; + meshData.indices = indices; + + SMikkTSpaceContext modelContext; + modelContext.m_pUserData = &meshData; + modelContext.m_pInterface = &tangentSpaceInterface; + + genTangSpaceDefault(&modelContext); +} \ No newline at end of file diff --git a/codemp/rd-rend2/tr_vbo.cpp b/codemp/rd-rend2/tr_vbo.cpp new file mode 100644 index 0000000000..4025bd31d5 --- /dev/null +++ b/codemp/rd-rend2/tr_vbo.cpp @@ -0,0 +1,825 @@ +/* +=========================================================================== +Copyright (C) 2007-2009 Robert Beckebans + +This file is part of XreaL source code. + +XreaL source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +XreaL source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with XreaL source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +// tr_vbo.c +#include "tr_local.h" + +#ifdef _G2_GORE +#include "G2_gore_r2.h" +#endif + + +uint32_t R_VboPackTangent(vec4_t v) +{ + return (((uint32_t)(v[3] * 1.5f + 2.0f )) << 30) + | (((uint32_t)(v[2] * 511.5f + 512.0f)) << 20) + | (((uint32_t)(v[1] * 511.5f + 512.0f)) << 10) + | (((uint32_t)(v[0] * 511.5f + 512.0f))); +} + +uint32_t R_VboPackNormal(vec3_t v) +{ + return (((uint32_t)(v[2] * 511.5f + 512.0f)) << 20) + | (((uint32_t)(v[1] * 511.5f + 512.0f)) << 10) + | (((uint32_t)(v[0] * 511.5f + 512.0f))); +} + +void R_VboUnpackTangent(vec4_t v, uint32_t b) +{ + v[0] = ((b) & 0x3ff) * 1.0f/511.5f - 1.0f; + v[1] = ((b >> 10) & 0x3ff) * 1.0f/511.5f - 1.0f; + v[2] = ((b >> 20) & 0x3ff) * 1.0f/511.5f - 1.0f; + v[3] = ((b >> 30) & 0x3) * 1.0f/1.5f - 1.0f; +} + +void R_VboUnpackNormal(vec3_t v, uint32_t b) +{ + v[0] = ((b) & 0x3ff) * 1.0f/511.5f - 1.0f; + v[1] = ((b >> 10) & 0x3ff) * 1.0f/511.5f - 1.0f; + v[2] = ((b >> 20) & 0x3ff) * 1.0f/511.5f - 1.0f; +} + +static GLenum GetGLBufferUsage ( vboUsage_t usage ) +{ + switch (usage) + { + case VBO_USAGE_STATIC: + return GL_STATIC_DRAW; + + case VBO_USAGE_DYNAMIC: + return GL_STREAM_DRAW; + + case VBO_USAGE_XFB: + return GL_STREAM_COPY; + + default: + ri.Error (ERR_FATAL, "bad vboUsage_t given: %i", usage); + return GL_INVALID_OPERATION; + } +} + +/* +============ +R_CreateVBO +============ +*/ +VBO_t *R_CreateVBO(byte * vertexes, int vertexesSize, vboUsage_t usage) +{ + VBO_t *vbo; + + if ( tr.numVBOs == MAX_VBOS ) { + ri.Error( ERR_DROP, "R_CreateVBO: MAX_VBOS hit"); + } + + R_IssuePendingRenderCommands(); + + vbo = tr.vbos[tr.numVBOs] = (VBO_t *)ri.Hunk_Alloc(sizeof(*vbo), h_low); + + memset(vbo, 0, sizeof(*vbo)); + + vbo->vertexesSize = vertexesSize; + qglGenBuffers(1, &vbo->vertexesVBO); + tr.numVBOs++; + + qglBindBuffer(GL_ARRAY_BUFFER, vbo->vertexesVBO); + if ( glRefConfig.immutableBuffers ) + { + GLbitfield creationFlags = 0; + if ( usage == VBO_USAGE_DYNAMIC ) + { + creationFlags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; + } + + qglBufferStorage(GL_ARRAY_BUFFER, vertexesSize, vertexes, creationFlags); + } + else + { + int glUsage = GetGLBufferUsage (usage); + qglBufferData(GL_ARRAY_BUFFER, vertexesSize, vertexes, glUsage); + } + + qglBindBuffer(GL_ARRAY_BUFFER, 0); + + glState.currentVBO = NULL; + + GL_CheckErrors(); + + return vbo; +} + +/* +============ +R_CreateIBO +============ +*/ +IBO_t *R_CreateIBO(byte * indexes, int indexesSize, vboUsage_t usage) +{ + IBO_t *ibo; + + if ( tr.numIBOs == MAX_IBOS ) { + ri.Error( ERR_DROP, "R_CreateIBO: MAX_IBOS hit"); + } + + R_IssuePendingRenderCommands(); + + ibo = tr.ibos[tr.numIBOs] = (IBO_t *)ri.Hunk_Alloc(sizeof(*ibo), h_low); + + ibo->indexesSize = indexesSize; + qglGenBuffers(1, &ibo->indexesVBO); + tr.numIBOs++; + + qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo->indexesVBO); + if ( glRefConfig.immutableBuffers ) + { + GLbitfield creationFlags = 0; + if ( usage == VBO_USAGE_DYNAMIC ) + { + creationFlags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; + } + + qglBufferStorage(GL_ELEMENT_ARRAY_BUFFER, indexesSize, indexes, creationFlags); + GL_CheckErrors(); + } + else + { + int glUsage = GetGLBufferUsage (usage); + qglBufferData(GL_ELEMENT_ARRAY_BUFFER, indexesSize, indexes, glUsage); + } + + qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + glState.currentIBO = NULL; + + GL_CheckErrors(); + + return ibo; +} + +/* +============ +R_BindVBO +============ +*/ +void R_BindVBO(VBO_t * vbo) +{ + if(!vbo) + { + //R_BindNullVBO(); + ri.Error(ERR_DROP, "R_BindVBO: NULL vbo"); + return; + } + + if(r_logFile->integer) + { + GLimp_LogComment("--- R_BindVBO() ---\n"); + } + + if(glState.currentVBO != vbo) + { + glState.currentVBO = vbo; + + glState.vertexAttribsInterpolation = 0; + glState.vertexAttribsOldFrame = 0; + glState.vertexAttribsNewFrame = 0; + glState.vertexAttribsTexCoordOffset[0] = 0; + glState.vertexAttribsTexCoordOffset[1] = 1; + glState.vertexAnimation = qfalse; + glState.skeletalAnimation = qfalse; + + qglBindBuffer(GL_ARRAY_BUFFER, vbo->vertexesVBO); + + backEnd.pc.c_vboVertexBuffers++; + } +} + +/* +============ +R_BindNullVBO +============ +*/ +void R_BindNullVBO(void) +{ + GLimp_LogComment("--- R_BindNullVBO ---\n"); + + if(glState.currentVBO) + { + qglBindBuffer(GL_ARRAY_BUFFER, 0); + glState.currentVBO = NULL; + } + + GL_CheckErrors(); +} + +/* +============ +R_BindIBO +============ +*/ +void R_BindIBO(IBO_t * ibo) +{ + if(!ibo) + { + //R_BindNullIBO(); + ri.Error(ERR_DROP, "R_BindIBO: NULL ibo"); + return; + } + + if(r_logFile->integer) + { + GLimp_LogComment("--- R_BindIBO() ---\n"); + } + + if(glState.currentIBO != ibo) + { + qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo->indexesVBO); + + glState.currentIBO = ibo; + + backEnd.pc.c_vboIndexBuffers++; + } +} + +/* +============ +R_BindNullIBO +============ +*/ +void R_BindNullIBO(void) +{ + GLimp_LogComment("--- R_BindNullIBO ---\n"); + + if(glState.currentIBO) + { + qglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glState.currentIBO = NULL; + } +} + +/* +============ +R_InitGPUBuffers +============ +*/ +void R_InitGPUBuffers(void) +{ + ri.Printf(PRINT_ALL, "------- R_InitGPUBuffers -------\n"); + + // glGenBuffers only allocates the IDs for these buffers. The 'buffer object' is + // actually created on first bind. + qglGenBuffers(1, &tr.staticUbo); + qglGenBuffers(MAX_SUB_BSP + 1, tr.spriteUbos); + qglGenBuffers(1, &tr.shaderInstanceUbo); + + // Allocate/create ShaderInstanceBlock ubo + const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; + const size_t alignedBlockSize = (sizeof(ShaderInstanceBlock) + alignment) & ~alignment; + + qglBindBuffer(GL_UNIFORM_BUFFER, tr.shaderInstanceUbo); + glState.currentGlobalUBO = tr.shaderInstanceUbo; + qglBufferData( + GL_UNIFORM_BUFFER, + MAX_SHADERS * alignedBlockSize, + nullptr, + GL_STATIC_DRAW); + + tr.numVBOs = 0; + tr.numIBOs = 0; + + R_BindNullVBO(); + R_BindNullIBO(); + + GL_CheckErrors(); +} + +/* +============ +R_DestroyGPUBuffers +============ +*/ +void R_DestroyGPUBuffers(void) +{ + ri.Printf(PRINT_ALL, "------- R_DestroyGPUBuffers -------\n"); + + R_BindNullVBO(); + R_BindNullIBO(); + + qglDeleteBuffers(1, &tr.staticUbo); + qglDeleteBuffers(MAX_SUB_BSP + 1, tr.spriteUbos); + qglDeleteBuffers(1, &tr.shaderInstanceUbo); + + for (int i = 0; i < tr.numVBOs; i++) + { + VBO_t *vbo = tr.vbos[i]; + + if (vbo->vertexesVBO) + { + qglDeleteBuffers(1, &vbo->vertexesVBO); + } + } + + for (int i = 0; i < tr.numIBOs; i++) + { + IBO_t *ibo = tr.ibos[i]; + + if (ibo->indexesVBO) + { + qglDeleteBuffers(1, &ibo->indexesVBO); + } + } + + tr.numVBOs = 0; + tr.numIBOs = 0; +} + +/* +============ +R_VBOList_f +============ +*/ +void R_VBOList_f(void) +{ + int i; + VBO_t *vbo; + IBO_t *ibo; + int vertexesSize = 0; + int indexesSize = 0; + + ri.Printf (PRINT_ALL, " vertex buffers\n"); + ri.Printf (PRINT_ALL, "----------------\n\n"); + + ri.Printf(PRINT_ALL, " id size (MB)\n"); + ri.Printf(PRINT_ALL, "---------------\n"); + + for(i = 0; i < tr.numVBOs; i++) + { + vbo = tr.vbos[i]; + + ri.Printf(PRINT_ALL, " %4i %4.2f\n", i, vbo->vertexesSize / (1024.0f * 1024.0f)); + + vertexesSize += vbo->vertexesSize; + } + + ri.Printf(PRINT_ALL, " %d total buffers\n", tr.numVBOs); + ri.Printf(PRINT_ALL, " %.2f MB in total\n\n", vertexesSize / (1024.0f * 1024.0f)); + + + ri.Printf (PRINT_ALL, " index buffers\n"); + ri.Printf (PRINT_ALL, "---------------\n\n"); + + ri.Printf(PRINT_ALL, " id size (MB)\n"); + ri.Printf(PRINT_ALL, "---------------\n"); + + for(i = 0; i < tr.numIBOs; i++) + { + ibo = tr.ibos[i]; + + ri.Printf(PRINT_ALL, " %4i %4.2f\n", i, ibo->indexesSize / (1024.0f * 1024.0f)); + + indexesSize += ibo->indexesSize; + } + + ri.Printf(PRINT_ALL, " %d total buffers\n", tr.numIBOs); + ri.Printf(PRINT_ALL, " %.2f MB in total\n\n", indexesSize / (1024.0f * 1024.0f)); +} + +void AddVertexArray( + VertexArraysProperties *properties, + int attributeIndex, + size_t size, + int stride, + int offset, + void *stream, + int streamStride) +{ + properties->enabledAttributes[properties->numVertexArrays] = attributeIndex; + properties->offsets[attributeIndex] = offset; + properties->vertexDataSize += size; + properties->sizes[attributeIndex] = size; + properties->strides[attributeIndex] = stride; + properties->streams[attributeIndex] = stream; + properties->streamStrides[attributeIndex] = streamStride; + + properties->numVertexArrays++; +} + +void CalculateVertexArraysProperties(uint32_t attributes, VertexArraysProperties *properties) +{ + properties->vertexDataSize = 0; + properties->numVertexArrays = 0; + + if (!attributes) + { + attributes = + ATTR_POSITION | + ATTR_TEXCOORD0 | + ATTR_TEXCOORD1 | + ATTR_NORMAL | + ATTR_TANGENT | + ATTR_COLOR | + ATTR_LIGHTDIRECTION; + } + + if (attributes & ATTR_BITS) + { + if (attributes & ATTR_POSITION) + AddVertexArray( + properties, + ATTR_INDEX_POSITION, + sizeof(tess.xyz[0]), + 0, + properties->vertexDataSize, + tess.xyz, + sizeof(tess.xyz[0])); + + if (attributes & ATTR_TEXCOORD0) + AddVertexArray( + properties, + ATTR_INDEX_TEXCOORD0, + sizeof(tess.texCoords[0][0]), + 0, + properties->vertexDataSize, + tess.texCoords[0][0], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); + + if (attributes & ATTR_TEXCOORD1) + AddVertexArray( + properties, + ATTR_INDEX_TEXCOORD1, + sizeof(tess.texCoords[0][1]), + 0, + properties->vertexDataSize, + tess.texCoords[0][1], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); + + if (attributes & ATTR_TEXCOORD2) + AddVertexArray( + properties, + ATTR_INDEX_TEXCOORD2, + sizeof(tess.texCoords[0][2]) * 2, + 0, + properties->vertexDataSize, + tess.texCoords[0][2], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); +; + + if (attributes & ATTR_TEXCOORD3) + AddVertexArray( + properties, + ATTR_INDEX_TEXCOORD3, + sizeof(tess.texCoords[0][3]) * 2, + 0, + properties->vertexDataSize, + tess.texCoords[0][3], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); + + + if (attributes & ATTR_TEXCOORD4) + AddVertexArray( + properties, + ATTR_INDEX_TEXCOORD4, + sizeof(tess.texCoords[0][4]) * 2, + 0, + properties->vertexDataSize, + tess.texCoords[0][4], + sizeof(tess.texCoords[0][0]) * NUM_TESS_TEXCOORDS); + + if (attributes & ATTR_NORMAL) + AddVertexArray( + properties, + ATTR_INDEX_NORMAL, + sizeof(tess.normal[0]), + 0, + properties->vertexDataSize, + tess.normal, + sizeof(tess.normal[0])); + + if (attributes & ATTR_TANGENT) + AddVertexArray( + properties, + ATTR_INDEX_TANGENT, + sizeof(tess.tangent[0]), + 0, + properties->vertexDataSize, + tess.tangent, + sizeof(tess.tangent[0])); + + if (attributes & ATTR_COLOR) + AddVertexArray( + properties, + ATTR_INDEX_COLOR, + sizeof(tess.vertexColors[0]), + 0, + properties->vertexDataSize, + tess.vertexColors, + sizeof(tess.vertexColors[0])); + + if (attributes & ATTR_LIGHTDIRECTION) + AddVertexArray( + properties, + ATTR_INDEX_LIGHTDIRECTION, + sizeof(tess.lightdir[0]), + 0, + properties->vertexDataSize, + tess.lightdir, + sizeof(tess.lightdir[0])); + } + + for ( int i = 0; i < properties->numVertexArrays; i++ ) + properties->strides[properties->enabledAttributes[i]] = properties->vertexDataSize; +} + +void CalculateVertexArraysFromVBO( + uint32_t attributes, + const VBO_t *vbo, + VertexArraysProperties *properties) +{ + properties->vertexDataSize = 0; + properties->numVertexArrays = 0; + + for (int i = 0, j = 1; i < ATTR_INDEX_MAX; i++, j <<= 1) + { + if (vbo->sizes[i] == 0) + continue; + if (attributes & j) + AddVertexArray( + properties, + i, + vbo->sizes[i], + vbo->strides[i], + vbo->offsets[i], + NULL, + 0); + } +} + +/* +============== +RB_UpdateVBOs + +Adapted from Tess_UpdateVBOs from xreal + +Update the default VBO to replace the client side vertex arrays +============== +*/ +void RB_UpdateVBOs(unsigned int attribBits) +{ + gpuFrame_t *currentFrame = backEndData->currentFrame; + + GLimp_LogComment("--- RB_UpdateVBOs ---\n"); + + backEnd.pc.c_dynamicVboDraws++; + + // update the default VBO + if (tess.numVertexes > 0 && tess.numVertexes <= SHADER_MAX_VERTEXES) + { + VBO_t *frameVbo = currentFrame->dynamicVbo; + GLbitfield mapFlags = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; + VertexArraysProperties vertexArrays = {}; + CalculateVertexArraysProperties(attribBits, &vertexArrays); + + int totalVertexDataSize = tess.numVertexes * vertexArrays.vertexDataSize; + backEnd.pc.c_dynamicVboTotalSize += totalVertexDataSize; + + if ( (currentFrame->dynamicVboWriteOffset + totalVertexDataSize) > frameVbo->vertexesSize ) + { + // TODO: Eh...resize? + assert(!"This shouldn't happen"); + return; + } + + R_BindVBO(frameVbo); + + void *dstPtr; + if ( glRefConfig.immutableBuffers ) + { + dstPtr = (byte *)currentFrame->dynamicVboMemory + currentFrame->dynamicVboWriteOffset; + } + else + { + dstPtr = qglMapBufferRange(GL_ARRAY_BUFFER, currentFrame->dynamicVboWriteOffset, + totalVertexDataSize, mapFlags); + } + + // Interleave the data + void *writePtr = dstPtr; + for ( int i = 0; i < tess.numVertexes; i++ ) + { + for ( int j = 0; j < vertexArrays.numVertexArrays; j++ ) + { + const int attributeIndex = vertexArrays.enabledAttributes[j]; + const size_t attribSize = vertexArrays.sizes[attributeIndex]; + const int streamStride = vertexArrays.streamStrides[attributeIndex]; + void *stream = vertexArrays.streams[attributeIndex]; + + memcpy(writePtr, (byte *)stream + i * streamStride, attribSize); + writePtr = (byte *)writePtr + attribSize; + } + } + + if ( !glRefConfig.immutableBuffers ) + { + qglUnmapBuffer(GL_ARRAY_BUFFER); + } + + currentFrame->dynamicVboWriteOffset += totalVertexDataSize; + } + + // update the default IBO + if(tess.numIndexes > 0 && tess.numIndexes <= SHADER_MAX_INDEXES) + { + IBO_t *frameIbo = currentFrame->dynamicIbo; + GLbitfield mapFlags = GL_MAP_WRITE_BIT | GL_MAP_UNSYNCHRONIZED_BIT; + int totalIndexDataSize = tess.numIndexes * sizeof(tess.indexes[0]); + + R_BindIBO(frameIbo); + + if ( (currentFrame->dynamicIboWriteOffset + totalIndexDataSize) > frameIbo->indexesSize ) + { + // TODO: Resize the buffer? + assert(!"This shouldn't happen"); + return; + } + + void *dst; + if ( glRefConfig.immutableBuffers ) + { + dst = (byte *)currentFrame->dynamicIboMemory + currentFrame->dynamicIboWriteOffset; + } + else + { + dst = qglMapBufferRange(GL_ELEMENT_ARRAY_BUFFER, currentFrame->dynamicIboWriteOffset, + totalIndexDataSize, mapFlags); + } + + memcpy(dst, tess.indexes, totalIndexDataSize); + + if ( !glRefConfig.immutableBuffers ) + { + qglUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); + } + + currentFrame->dynamicIboWriteOffset += totalIndexDataSize; + } +} + +#ifdef _G2_GORE +void RB_UpdateGoreVBO(srfG2GoreSurface_t *goreSurface) +{ + goreSurface->firstVert = tr.goreVBOCurrentIndex; + goreSurface->firstIndex = tr.goreIBOCurrentIndex; + + if (tr.goreVBOCurrentIndex + goreSurface->numVerts >= (MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_VERTS * MAX_FRAMES)) + tr.goreVBOCurrentIndex = 0; + + R_BindVBO(tr.goreVBO); + qglBufferSubData( + GL_ARRAY_BUFFER, + sizeof(g2GoreVert_t) * tr.goreVBOCurrentIndex, + sizeof(g2GoreVert_t) * goreSurface->numVerts, + goreSurface->verts + ); + tr.goreVBOCurrentIndex += goreSurface->numVerts; + + if (tr.goreIBOCurrentIndex + goreSurface->numVerts >= (MAX_LODS * MAX_GORE_RECORDS * MAX_GORE_INDECIES * MAX_FRAMES)) + tr.goreIBOCurrentIndex = 0; + + R_BindIBO(tr.goreIBO); + qglBufferSubData( + GL_ELEMENT_ARRAY_BUFFER, + sizeof(glIndex_t) * tr.goreIBOCurrentIndex, + sizeof(glIndex_t) * goreSurface->numIndexes, + goreSurface->indexes + ); + tr.goreIBOCurrentIndex += goreSurface->numIndexes; +} +#endif + +void RB_CommitInternalBufferData() +{ + gpuFrame_t *currentFrame = backEndData->currentFrame; + + currentFrame->dynamicIboCommitOffset = currentFrame->dynamicIboWriteOffset; + currentFrame->dynamicVboCommitOffset = currentFrame->dynamicVboWriteOffset; +} + +void RB_BindUniformBlock(GLuint ubo, uniformBlock_t block, int offset) +{ + const uniformBlockInfo_t *blockInfo = uniformBlocksInfo + block; + + assert(blockInfo->slot < MAX_UBO_BINDINGS); + + bufferBinding_t *currentBinding = glState.currentUBOs + blockInfo->slot; + if (currentBinding->buffer != ubo || + currentBinding->offset != offset || + currentBinding->size != blockInfo->size) + { + qglBindBufferRange( + GL_UNIFORM_BUFFER, blockInfo->slot, ubo, offset, blockInfo->size); + glState.currentGlobalUBO = ubo; + + currentBinding->buffer = ubo; + currentBinding->offset = offset; + currentBinding->size = blockInfo->size; + } +} + +int RB_BindAndUpdateFrameUniformBlock(uniformBlock_t block, void *data) +{ + const uniformBlockInfo_t *blockInfo = uniformBlocksInfo + block; + gpuFrame_t *thisFrame = backEndData->currentFrame; + const int offset = thisFrame->uboWriteOffset; + + RB_BindUniformBlock(thisFrame->ubo, block, offset); + + qglBufferSubData(GL_UNIFORM_BUFFER, + thisFrame->uboWriteOffset, blockInfo->size, data); + + const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; + const size_t alignedBlockSize = (blockInfo->size + alignment) & ~alignment; + thisFrame->uboWriteOffset += alignedBlockSize; + + return offset; +} + +int RB_AddShaderInstanceBlock(void *data) +{ + if (glState.currentGlobalUBO != tr.shaderInstanceUbo) + { + qglBindBuffer(GL_UNIFORM_BUFFER, tr.shaderInstanceUbo); + glState.currentGlobalUBO = tr.shaderInstanceUbo; + } + const size_t writeOffset = tr.shaderInstanceUboWriteOffset; + + qglBufferSubData(GL_UNIFORM_BUFFER, + tr.shaderInstanceUboWriteOffset, sizeof(ShaderInstanceBlock), data); + + const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; + const size_t alignedBlockSize = (sizeof(ShaderInstanceBlock) + alignment) & ~alignment; + tr.shaderInstanceUboWriteOffset += alignedBlockSize; + + return writeOffset; +} + +void RB_BeginConstantsUpdate(gpuFrame_t *frame) +{ + if (glState.currentGlobalUBO != frame->ubo) + { + qglBindBuffer(GL_UNIFORM_BUFFER, frame->ubo); + glState.currentGlobalUBO = frame->ubo; + } + + const GLbitfield mapFlags = + GL_MAP_WRITE_BIT | + GL_MAP_UNSYNCHRONIZED_BIT | + GL_MAP_FLUSH_EXPLICIT_BIT; + + frame->uboMapBase = frame->uboWriteOffset; + frame->uboMemory = qglMapBufferRange( + GL_UNIFORM_BUFFER, + frame->uboWriteOffset, + frame->uboSize - frame->uboWriteOffset, + mapFlags); +} + +int RB_AppendConstantsData( + gpuFrame_t *frame, const void *data, size_t dataSize) +{ + const size_t writeOffset = frame->uboWriteOffset; + const size_t relativeOffset = writeOffset - frame->uboMapBase; + + memcpy((char *)frame->uboMemory + relativeOffset, data, dataSize); + + const int alignment = glRefConfig.uniformBufferOffsetAlignment - 1; + const size_t alignedBlockSize = (dataSize + alignment) & ~alignment; + + frame->uboWriteOffset += alignedBlockSize; + assert(frame->uboWriteOffset > 0); + return writeOffset; +} + +void RB_EndConstantsUpdate(const gpuFrame_t *frame) +{ + qglFlushMappedBufferRange( + GL_UNIFORM_BUFFER, + frame->uboMapBase, + frame->uboWriteOffset - frame->uboMapBase); + qglUnmapBuffer(GL_UNIFORM_BUFFER); +} \ No newline at end of file diff --git a/codemp/rd-rend2/tr_weather.cpp b/codemp/rd-rend2/tr_weather.cpp new file mode 100644 index 0000000000..f3a5620673 --- /dev/null +++ b/codemp/rd-rend2/tr_weather.cpp @@ -0,0 +1,1258 @@ +/* +=========================================================================== +Copyright (C) 2016, OpenJK contributors + +This file is part of the OpenJK source code. + +OpenJK is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . +=========================================================================== +*/ + +#include "tr_weather.h" +#include +#include +#include + +namespace +{ + const int CHUNK_COUNT = 9; // in 3x3 arrangement + const float CHUNK_EXTENDS = 2000.f; + const float HALF_CHUNK_EXTENDS = CHUNK_EXTENDS * 0.5f; + + struct rainVertex_t + { + vec3_t position; + vec3_t velocity; + }; + + void RB_UpdateWindObject( windObject_t *wo ) + { + if (wo->targetVelocityTimeRemaining == 0) + { + if (Q_flrand(0.f, 1.f) < wo->chanceOfDeadTime) + { + wo->targetVelocityTimeRemaining = Q_flrand(wo->deadTimeMinMax[0], wo->deadTimeMinMax[1]); + VectorSet(wo->targetVelocity, 0.0f, 0.0f, 0.0f); + } + else + { + wo->targetVelocityTimeRemaining = Q_flrand(1000.f, 2500.f); + VectorSet( + wo->targetVelocity, + Q_flrand(wo->minVelocity[0], wo->maxVelocity[0]), + Q_flrand(wo->minVelocity[1], wo->maxVelocity[1]), + Q_flrand(wo->minVelocity[2], wo->maxVelocity[2])); + } + return; + } + + wo->targetVelocityTimeRemaining--; + vec3_t deltaVelocity; + VectorSubtract(wo->targetVelocity, wo->currentVelocity, deltaVelocity); + float DeltaVelocityLen = VectorNormalize(deltaVelocity); + if (DeltaVelocityLen > 10.f) + { + DeltaVelocityLen = 10.f; + } + VectorScale(deltaVelocity, DeltaVelocityLen, deltaVelocity); + VectorAdd(wo->currentVelocity, deltaVelocity, wo->currentVelocity); + } + + void GenerateRainModel( weatherObject_t& ws, const int maxParticleCount ) + { + const int mapExtentZ = (int)(tr.world->bmodels[0].bounds[1][2] - tr.world->bmodels[0].bounds[0][2]); + const int PARTICLE_COUNT = (int)(maxParticleCount * mapExtentZ / CHUNK_EXTENDS); + std::vector rainVertices(PARTICLE_COUNT * CHUNK_COUNT); + + for ( int i = 0; i < rainVertices.size(); ++i ) + { + rainVertex_t& vertex = rainVertices[i]; + vertex.position[0] = Q_flrand(-HALF_CHUNK_EXTENDS, HALF_CHUNK_EXTENDS); + vertex.position[1] = Q_flrand(-HALF_CHUNK_EXTENDS, HALF_CHUNK_EXTENDS); + vertex.position[2] = Q_flrand(tr.world->bmodels[0].bounds[0][2], tr.world->bmodels[0].bounds[1][2]); + vertex.velocity[0] = 0.0f; //Q_flrand(0.0f, 0.0f); + vertex.velocity[1] = 0.0f; //Q_flrand(0.0f, 0.0f); + vertex.velocity[2] = 0.0f; //Q_flrand(-1.0f, 0.0f); + } + + ws.lastVBO = R_CreateVBO( + nullptr, + sizeof(rainVertex_t) * rainVertices.size(), + VBO_USAGE_XFB); + ws.vbo = R_CreateVBO( + (byte *)rainVertices.data(), + sizeof(rainVertex_t) * rainVertices.size(), + VBO_USAGE_XFB); + ws.vboLastUpdateFrame = 0; + + ws.attribsTemplate[0].index = ATTR_INDEX_POSITION; + ws.attribsTemplate[0].numComponents = 3; + ws.attribsTemplate[0].offset = offsetof(rainVertex_t, position); + ws.attribsTemplate[0].stride = sizeof(rainVertex_t); + ws.attribsTemplate[0].type = GL_FLOAT; + ws.attribsTemplate[0].vbo = nullptr; + + ws.attribsTemplate[1].index = ATTR_INDEX_COLOR; + ws.attribsTemplate[1].numComponents = 3; + ws.attribsTemplate[1].offset = offsetof(rainVertex_t, velocity); + ws.attribsTemplate[1].stride = sizeof(rainVertex_t); + ws.attribsTemplate[1].type = GL_FLOAT; + ws.attribsTemplate[1].vbo = nullptr; + } + + bool intersectPlane(const vec3_t n, const float dist, const vec3_t l0, const vec3_t l, float &t) + { + // assuming vectors are all normalized + float denom = DotProduct(n, l); + if (denom > 1e-6) { + t = -(DotProduct(l0, n) + dist) / denom; + return (t >= 0); + } + + return false; + } + + void GenerateDepthMap() + { + R_IssuePendingRenderCommands(); + R_InitNextFrame(); + RE_BeginFrame(STEREO_CENTER); + + vec3_t mapSize; + vec3_t halfMapSize; + VectorSubtract( + tr.world->bmodels[0].bounds[0], + tr.world->bmodels[0].bounds[1], + mapSize); + VectorScale(mapSize, -0.5f, halfMapSize); + mapSize[2] = 0.0f; + + const vec3_t forward = {0.0f, 0.0f, -1.0f}; + const vec3_t left = {0.0f, 1.0f, 0.0f}; + const vec3_t up = {-1.0f, 0.0f, 0.0f}; + + vec3_t viewOrigin; + VectorMA(tr.world->bmodels[0].bounds[1], 0.5f, mapSize, viewOrigin); + viewOrigin[2] = tr.world->bmodels[0].bounds[1][2]; + + orientationr_t orientation; + R_SetOrientationOriginAndAxis(orientation, viewOrigin, forward, left, up); + + const vec3_t viewBounds[2] = { + { 0.0f, -halfMapSize[1], -halfMapSize[0] }, + { halfMapSize[2] * 2.0f, halfMapSize[1], halfMapSize[0] } + }; + + R_SetupViewParmsForOrthoRendering( + tr.weatherDepthFbo->width, + tr.weatherDepthFbo->height, + tr.weatherDepthFbo, + VPF_DEPTHCLAMP | VPF_DEPTHSHADOW | VPF_ORTHOGRAPHIC | VPF_NOVIEWMODEL, + orientation, + viewBounds); + Matrix16Multiply( + tr.viewParms.projectionMatrix, + tr.viewParms.world.modelViewMatrix, + tr.weatherSystem->weatherMVP); + + if (tr.weatherSystem->numWeatherBrushes > 0) + { + FBO_Bind(tr.weatherDepthFbo); + + qglViewport(0, 0, tr.weatherDepthFbo->width, tr.weatherDepthFbo->height); + qglScissor(0, 0, tr.weatherDepthFbo->width, tr.weatherDepthFbo->height); + + if (tr.weatherSystem->weatherBrushType == WEATHER_BRUSHES_OUTSIDE) // used outside brushes + { + qglClearDepth(0.0f); + GL_State(GLS_DEPTHMASK_TRUE | GLS_DEPTHFUNC_GREATER); + } + else // used inside brushes + { + qglClearDepth(1.0f); + GL_State(GLS_DEPTHMASK_TRUE); + } + + qglClear(GL_DEPTH_BUFFER_BIT); + qglClearDepth(1.0f); + qglEnable(GL_DEPTH_CLAMP); + + GL_Cull(CT_TWO_SIDED); + vec4_t color = { 0.0f, 0.0f, 0.0f, 1.0f }; + backEnd.currentEntity = &tr.worldEntity; + + vec3_t stepSize = { + abs(mapSize[0]) / tr.weatherDepthFbo->width, + abs(mapSize[1]) / tr.weatherDepthFbo->height, + 0.0, + }; + + vec3_t up = { + stepSize[0] * 0.5f, + 0.0f, + 0.0f + }; + vec3_t left = { + 0.0f, + stepSize[1] * 0.5f, + 0.0f + }; + vec3_t traceVec = { + 0.0f, + 0.0f, + -1.0f + }; + + for (int i = 0; i < tr.weatherSystem->numWeatherBrushes; i++) + { + RE_BeginFrame(STEREO_CENTER); + weatherBrushes_t *currentWeatherBrush = &tr.weatherSystem->weatherBrushes[i]; + + // RBSP brushes actually store their bounding box in the first 6 planes! Nice + vec3_t mins = { + -currentWeatherBrush->planes[0][3], + -currentWeatherBrush->planes[2][3], + -currentWeatherBrush->planes[4][3], + }; + vec3_t maxs = { + currentWeatherBrush->planes[1][3], + currentWeatherBrush->planes[3][3], + currentWeatherBrush->planes[5][3], + }; + + ivec2_t numSteps = { + int((maxs[0] - mins[0]) / stepSize[0]) + 2, + int((maxs[1] - mins[1]) / stepSize[1]) + 2 + }; + + vec2_t rayOrigin = { + tr.world->bmodels[0].bounds[0][0] + (floorf((mins[0] - tr.world->bmodels[0].bounds[0][0]) / stepSize[0]) + 0.5f) * stepSize[0], + tr.world->bmodels[0].bounds[0][1] + (floorf((mins[1] - tr.world->bmodels[0].bounds[0][1]) / stepSize[1]) + 0.5f) * stepSize[1] + }; + + for (int y = 0; y < (int)numSteps[1]; y++) + { + for (int x = 0; x < (int)numSteps[0]; x++) + { + vec3_t rayPos = { + rayOrigin[0] + x * stepSize[0], + rayOrigin[1] + y * stepSize[1], + tr.world->bmodels[0].bounds[1][2] + }; + + // Find intersection point with the brush + float t = 0.0f; + for (int j = 0; j < currentWeatherBrush->numPlanes; j++) + { + vec3_t plane_normal; + float plane_dist; + if (tr.weatherSystem->weatherBrushType == WEATHER_BRUSHES_OUTSIDE) + { + plane_normal[0] = currentWeatherBrush->planes[j][0]; + plane_normal[1] = currentWeatherBrush->planes[j][1]; + plane_normal[2] = currentWeatherBrush->planes[j][2]; + plane_dist = -currentWeatherBrush->planes[j][3]; + } + else + { + plane_normal[0] = -currentWeatherBrush->planes[j][0]; + plane_normal[1] = -currentWeatherBrush->planes[j][1]; + plane_normal[2] = -currentWeatherBrush->planes[j][2]; + plane_dist = currentWeatherBrush->planes[j][3]; + } + + float dist = 0.0f; + if (intersectPlane(plane_normal, plane_dist, rayPos, traceVec, dist)) + t = MAX(t, dist); + } + + bool hit = true; + rayPos[2] -= t; + + // Now test if the intersected point is actually on the brush + for (int j = 0; j < currentWeatherBrush->numPlanes; j++) + { + vec4_t *plane = ¤tWeatherBrush->planes[j]; + vec3_t normal = { + currentWeatherBrush->planes[j][0], + currentWeatherBrush->planes[j][1], + currentWeatherBrush->planes[j][2] + }; + if (DotProduct(rayPos, normal) > currentWeatherBrush->planes[j][3] + 1e-3) + hit = false; + } + + if (!hit) + continue; + + // Just draw it when batch is full + if (tess.numVertexes + 4 >= SHADER_MAX_VERTEXES || tess.numIndexes + 6 >= SHADER_MAX_INDEXES) + { + RB_UpdateVBOs(ATTR_POSITION); + GLSL_VertexAttribsState(ATTR_POSITION, NULL); + GLSL_BindProgram(&tr.textureColorShader); + GLSL_SetUniformMatrix4x4( + &tr.textureColorShader, + UNIFORM_MODELVIEWPROJECTIONMATRIX, + tr.weatherSystem->weatherMVP); + R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); + + RB_CommitInternalBufferData(); + + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + tess.multiDrawPrimitives = 0; + tess.externalIBO = nullptr; + } + + RB_AddQuadStamp(rayPos, left, up, color); + } + } + R_NewFrameSync(); + } + + // draw remaining quads + RB_UpdateVBOs(ATTR_POSITION); + GLSL_VertexAttribsState(ATTR_POSITION, NULL); + GLSL_BindProgram(&tr.textureColorShader); + GLSL_SetUniformMatrix4x4( + &tr.textureColorShader, + UNIFORM_MODELVIEWPROJECTIONMATRIX, + tr.weatherSystem->weatherMVP); + R_DrawElementsVBO(tess.numIndexes, tess.firstIndex, tess.minIndex, tess.maxIndex); + + RB_CommitInternalBufferData(); + + tess.numIndexes = 0; + tess.numVertexes = 0; + tess.firstIndex = 0; + tess.multiDrawPrimitives = 0; + tess.externalIBO = nullptr; + + qglDisable(GL_DEPTH_CLAMP); + } + + RE_BeginFrame(STEREO_CENTER); + + if (tr.weatherSystem->numWeatherBrushes > 0) + tr.viewParms.flags |= VPF_NOCLEAR; + + tr.refdef.numDrawSurfs = 0; + tr.refdef.drawSurfs = backEndData->drawSurfs; + + tr.refdef.num_entities = 0; + tr.refdef.entities = backEndData->entities; + + tr.refdef.num_dlights = 0; + tr.refdef.dlights = backEndData->dlights; + + tr.refdef.fistDrawSurf = 0; + + tr.skyPortalEntities = 0; + + tr.viewParms.targetFbo = tr.weatherDepthFbo; + tr.viewParms.currentViewParm = 0; + Com_Memcpy(&tr.cachedViewParms[0], &tr.viewParms, sizeof(viewParms_t)); + tr.numCachedViewParms = 1; + + RB_UpdateConstants(&tr.refdef); + + R_GenerateDrawSurfs(&tr.viewParms, &tr.refdef); + R_SortAndSubmitDrawSurfs(tr.refdef.drawSurfs, tr.refdef.numDrawSurfs); + + R_IssuePendingRenderCommands(); + tr.refdef.numDrawSurfs = 0; + tr.numCachedViewParms = 0; + + RE_EndScene(); + + R_NewFrameSync(); + } + + void RB_SimulateWeather(weatherObject_t *ws, vec2_t *zoneOffsets, int zoneIndex) + { + if (ws->vboLastUpdateFrame == backEndData->realFrameNumber || + tr.weatherSystem->frozen) + { + // Already simulated for this frame + return; + } + + // Intentionally switched. Previous frame's VBO would be in ws.vbo and + // this frame's VBO would be ws.lastVBO. + VBO_t *lastRainVBO = ws->vbo; + VBO_t *rainVBO = ws->lastVBO; + + Allocator& frameAllocator = *backEndData->perFrameMemory; + + DrawItem item = {}; + item.renderState.transformFeedback = true; + item.transformFeedbackBuffer = {rainVBO->vertexesVBO, 0, rainVBO->vertexesSize}; + item.program = &tr.weatherUpdateShader; + + const size_t numAttribs = ARRAY_LEN(ws->attribsTemplate); + item.numAttributes = numAttribs; + item.attributes = ojkAllocArray( + *backEndData->perFrameMemory, numAttribs); + memcpy( + item.attributes, + ws->attribsTemplate, + sizeof(*item.attributes) * numAttribs); + item.attributes[0].vbo = lastRainVBO; + item.attributes[1].vbo = lastRainVBO; + + UniformDataWriter uniformDataWriter; + uniformDataWriter.Start(&tr.weatherUpdateShader); + + const vec2_t mapZExtents = { + tr.world->bmodels[0].bounds[0][2], + tr.world->bmodels[0].bounds[1][2] + }; + const float frictionInverse = 0.7f; + vec3_t envForce = { + tr.weatherSystem->windDirection[0] * frictionInverse, + tr.weatherSystem->windDirection[1] * frictionInverse, + -ws->gravity * frictionInverse + }; + vec4_t randomOffset = { + Q_flrand(-4.0f, 4.0f), + Q_flrand(-4.0f, 4.0f), + Q_flrand(0.0f, 1.0f), + tr.world->bmodels[0].bounds[1][2] - backEnd.viewParms.ori.origin[2] + }; + uniformDataWriter.SetUniformVec2(UNIFORM_MAPZEXTENTS, mapZExtents); + uniformDataWriter.SetUniformVec3(UNIFORM_ENVFORCE, envForce); + uniformDataWriter.SetUniformVec4(UNIFORM_RANDOMOFFSET, randomOffset); + uniformDataWriter.SetUniformVec2(UNIFORM_ZONEOFFSET, (float*)zoneOffsets, 9); + uniformDataWriter.SetUniformInt(UNIFORM_CHUNK_PARTICLES, ws->particleCount); + + item.uniformData = uniformDataWriter.Finish(*backEndData->perFrameMemory); + + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + const UniformBlockBinding uniformBlockBindings[] = { + { currentFrameUbo, tr.sceneUboOffset, UNIFORM_BLOCK_SCENE } + }; + DrawItemSetUniformBlockBindings( + item, uniformBlockBindings, frameAllocator); + + item.draw.type = DRAW_COMMAND_ARRAYS; + item.draw.numInstances = 1; + item.draw.primitiveType = GL_POINTS; + item.draw.params.arrays.numVertices = ws->particleCount * CHUNK_COUNT; + + // This is a bit dodgy. Push this towards the front of the queue so we + // guarantee this happens before the actual drawing + const uint32_t key = RB_CreateSortKey(item, 0, SS_ENVIRONMENT); + RB_AddDrawItem(backEndData->currentPass, key, item); + + ws->vboLastUpdateFrame = backEndData->realFrameNumber; + std::swap(ws->lastVBO, ws->vbo); + } +} + +void R_InitWeatherForMap() +{ + for (int i = 0; i < NUM_WEATHER_TYPES; i++) + if (tr.weatherSystem->weatherSlots[i].active) + GenerateRainModel(tr.weatherSystem->weatherSlots[i], maxWeatherTypeParticles[i]); + GenerateDepthMap(); +} + +void R_InitWeatherSystem() +{ + Com_Printf("Initializing weather system\n"); + tr.weatherSystem = + (weatherSystem_t *)Z_Malloc(sizeof(*tr.weatherSystem), TAG_R_TERRAIN, qtrue); + tr.weatherSystem->weatherSurface.surfaceType = SF_WEATHER; + tr.weatherSystem->frozen = false; + tr.weatherSystem->activeWeatherTypes = 0; + tr.weatherSystem->constWindDirection[0] = .0f; + tr.weatherSystem->constWindDirection[1] = .0f; + + for (int i = 0; i < NUM_WEATHER_TYPES; i++) + tr.weatherSystem->weatherSlots[i].active = false; +} + +void R_ShutdownWeatherSystem() +{ + if (tr.weatherSystem != nullptr) + { + Com_Printf("Shutting down weather system\n"); + + Z_Free(tr.weatherSystem); + tr.weatherSystem = nullptr; + } + else + { + ri.Printf(PRINT_DEVELOPER, + "Weather system shutdown requested, but it is already shut down.\n"); + } +} + +/* +=============== +WE_ParseVector +=============== +*/ +qboolean WE_ParseVector(const char **text, int count, float *v) { + char *token; + int i; + + // FIXME: spaces are currently required after parens, should change parseext... + token = COM_ParseExt(text, qfalse); + if (strcmp(token, "(")) { + ri.Printf(PRINT_WARNING, "WARNING: missing parenthesis in weather effect\n"); + return qfalse; + } + + for (i = 0; i < count; i++) { + token = COM_ParseExt(text, qfalse); + if (!token[0]) { + ri.Printf(PRINT_WARNING, "WARNING: missing vector element in weather effect\n"); + return qfalse; + } + v[i] = atof(token); + } + + token = COM_ParseExt(text, qfalse); + if (strcmp(token, ")")) { + ri.Printf(PRINT_WARNING, "WARNING: missing parenthesis in weather effect\n"); + return qfalse; + } + + return qtrue; +} + +void R_AddWeatherBrush(uint8_t numPlanes, vec4_t *planes) +{ + if (tr.weatherSystem->numWeatherBrushes >= (MAX_WEATHER_ZONES * 2)) + { + ri.Printf(PRINT_WARNING, "Max weather brushes hit. Skipping new inside/outside brush\n"); + return; + } + tr.weatherSystem->weatherBrushes[tr.weatherSystem->numWeatherBrushes].numPlanes = numPlanes; + memcpy(tr.weatherSystem->weatherBrushes[tr.weatherSystem->numWeatherBrushes].planes, planes, numPlanes * sizeof(vec4_t)); + + tr.weatherSystem->numWeatherBrushes++; +} + +void RE_WorldEffectCommand(const char *command) +{ + if (!command) + { + return; + } + + COM_BeginParseSession("RE_WorldEffectCommand"); + + const char *token;//, *origCommand; + + token = COM_ParseExt(&command, qfalse); + + if (!token) + { + return; + } + + //Die - clean up the whole weather system -rww + if (Q_stricmp(token, "die") == 0) + { + for (int i = 0; i < NUM_WEATHER_TYPES; i++) + tr.weatherSystem->weatherSlots[i].active = false; + tr.weatherSystem->activeWeatherTypes = 0; + tr.weatherSystem->frozen = false; + return; + } + + // Clear - Removes All Particle Clouds And Wind Zones + //---------------------------------------------------- + else if (Q_stricmp(token, "clear") == 0) + { + for (int i = 0; i < NUM_WEATHER_TYPES; i++) + tr.weatherSystem->weatherSlots[i].active = false; + tr.weatherSystem->activeWeatherTypes = 0; + tr.weatherSystem->activeWindObjects = 0; + tr.weatherSystem->frozen = false; + } + + // Freeze / UnFreeze - Stops All Particle Motion Updates + //-------------------------------------------------------- + else if (Q_stricmp(token, "freeze") == 0) + { + tr.weatherSystem->frozen = !tr.weatherSystem->frozen; + } + + //// Add a zone + ////--------------- + else if (Q_stricmp(token, "zone") == 0) + { + ri.Printf(PRINT_DEVELOPER, "Weather zones aren't used in rend2, but inside/outside brushes\n"); + } + + // Basic Wind + //------------ + else if (Q_stricmp(token, "wind") == 0) + { + windObject_t *currentWindObject = &tr.weatherSystem->windSlots[tr.weatherSystem->activeWindObjects]; + currentWindObject->chanceOfDeadTime = 0.3f; + currentWindObject->deadTimeMinMax[0] = 1000.0f; + currentWindObject->deadTimeMinMax[1] = 3000.0f; + currentWindObject->maxVelocity[0] = 1.5f; + currentWindObject->maxVelocity[1] = 1.5f; + currentWindObject->maxVelocity[2] = 0.01f; + currentWindObject->minVelocity[0] = -1.5f; + currentWindObject->minVelocity[1] = -1.5f; + currentWindObject->minVelocity[2] = -0.01f; + currentWindObject->targetVelocityTimeRemaining = 0; + tr.weatherSystem->activeWindObjects++; + } + + // Constant Wind + //--------------- + else if (Q_stricmp(token, "constantwind") == 0) + { + vec3_t parsedWind; + vec3_t defaultWind = { 0.f, 0.8f, 0.f }; + if (!WE_ParseVector(&command, 3, parsedWind)) + VectorAdd( + tr.weatherSystem->constWindDirection, + defaultWind, + tr.weatherSystem->constWindDirection); + else + VectorMA( + tr.weatherSystem->constWindDirection, + 0.001f, + parsedWind, + tr.weatherSystem->constWindDirection); + } + + // Gusting Wind + //-------------- + else if (Q_stricmp(token, "gustingwind") == 0) + { + windObject_t *currentWindObject = &tr.weatherSystem->windSlots[tr.weatherSystem->activeWindObjects]; + currentWindObject->chanceOfDeadTime = 0.3f; + currentWindObject->deadTimeMinMax[0] = 2000.0f; + currentWindObject->deadTimeMinMax[1] = 4000.0f; + currentWindObject->maxVelocity[0] = 3.0f; + currentWindObject->maxVelocity[1] = 3.0f; + currentWindObject->maxVelocity[2] = 0.1f; + currentWindObject->minVelocity[0] = -3.0f; + currentWindObject->minVelocity[1] = -3.0f; + currentWindObject->minVelocity[2] = -0.1f; + currentWindObject->targetVelocityTimeRemaining = 0; + tr.weatherSystem->activeWindObjects++; + } + + // Create A Rain Storm + //--------------------- + else if (Q_stricmp(token, "lightrain") == 0) + { + /*nCloud.Initialize(500, "gfx/world/rain.jpg", 3); + nCloud.mHeight = 80.0f; + nCloud.mWidth = 1.2f; + nCloud.mGravity = 2000.0f; + nCloud.mFilterMode = 1; + nCloud.mBlendMode = 1; + nCloud.mFade = 100.0f; + nCloud.mColor = 0.5f; + nCloud.mOrientWithVelocity = true; + nCloud.mWaterParticles = true;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_RAIN].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].particleCount = 1000; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].active = true; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].gravity = 2.0f; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].fadeDistance = 6000.f; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].size[0] = 1.5f; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].size[1] = 14.0f; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].velocityOrientationScale = 1.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].drawImage = R_FindImageFile("gfx/world/rain.jpg", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, 0.5f, 0.5f, 0.5f); + VectorScale( + tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, + 0.5f, + tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); + } + + // Create A Rain Storm + //--------------------- + else if (Q_stricmp(token, "rain") == 0) + { + /*nCloud.Initialize(1000, "gfx/world/rain.jpg", 3); + nCloud.mHeight = 80.0f; + nCloud.mWidth = 1.2f; + nCloud.mGravity = 2000.0f; + nCloud.mFilterMode = 1; + nCloud.mBlendMode = 1; + nCloud.mFade = 100.0f; + nCloud.mColor = 0.5f; + nCloud.mOrientWithVelocity = true; + nCloud.mWaterParticles = true;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_RAIN].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].particleCount = 2000; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].active = true; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].gravity = 2.0f; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].fadeDistance = 6000.f; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].size[0] = 1.5f; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].size[1] = 14.0f; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].velocityOrientationScale = 1.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].drawImage = R_FindImageFile("gfx/world/rain.jpg", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, 0.5f, 0.5f, 0.5f); + VectorScale( + tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, + 0.5f, + tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); + } + + // Create A Rain Storm + //--------------------- + else if (Q_stricmp(token, "acidrain") == 0) + { + /*nCloud.Initialize(1000, "gfx/world/rain.jpg", 3); + nCloud.mHeight = 80.0f; + nCloud.mWidth = 2.0f; + nCloud.mGravity = 2000.0f; + nCloud.mFilterMode = 1; + nCloud.mBlendMode = 1; + nCloud.mFade = 100.0f; + + nCloud.mColor[0] = 0.34f; + nCloud.mColor[1] = 0.70f; + nCloud.mColor[2] = 0.34f; + nCloud.mColor[3] = 0.70f; + + nCloud.mOrientWithVelocity = true; + nCloud.mWaterParticles = true;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_RAIN].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].particleCount = 2000; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].active = true; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].gravity = 2.0f; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].fadeDistance = 6000.0f; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].size[0] = 2.0f; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].size[1] = 14.0f; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].velocityOrientationScale = 1.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].drawImage = R_FindImageFile("gfx/world/rain.jpg", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.34f, 0.7f, 0.34f, 0.7f); + VectorScale( + tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, + 0.7f, + tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); + } + + // Create A Rain Storm + //--------------------- + else if (Q_stricmp(token, "heavyrain") == 0) + { + /*nCloud.Initialize(1000, "gfx/world/rain.jpg", 3); + nCloud.mHeight = 80.0f; + nCloud.mWidth = 1.2f; + nCloud.mGravity = 2800.0f; + nCloud.mFilterMode = 1; + nCloud.mBlendMode = 1; + nCloud.mFade = 15.0f; + nCloud.mColor = 0.5f; + nCloud.mOrientWithVelocity = true; + nCloud.mWaterParticles = true;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_RAIN].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].particleCount = 5000; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].active = true; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].gravity = 2.8f; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].fadeDistance = 6000.0f; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].size[0] = 1.5f; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].size[1] = 14.0f; + + tr.weatherSystem->weatherSlots[WEATHER_RAIN].velocityOrientationScale = 1.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_RAIN].drawImage = R_FindImageFile("gfx/world/rain", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, 0.5f, 0.5f, 0.5f, 0.5f); + VectorScale( + tr.weatherSystem->weatherSlots[WEATHER_RAIN].color, + 0.5f, + tr.weatherSystem->weatherSlots[WEATHER_RAIN].color); + } + + // Create A Snow Storm + //--------------------- + else if (Q_stricmp(token, "snow") == 0) + { + /*nCloud.Initialize(1000, "gfx/effects/snowflake1.bmp"); + nCloud.mBlendMode = 1; + nCloud.mRotationChangeNext = 0; + nCloud.mColor = 0.75f; + nCloud.mWaterParticles = true;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_SNOW].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_SNOW].particleCount = 1000; + tr.weatherSystem->weatherSlots[WEATHER_SNOW].active = true; + tr.weatherSystem->weatherSlots[WEATHER_SNOW].gravity = 0.3f; + tr.weatherSystem->weatherSlots[WEATHER_SNOW].fadeDistance = 6000.0f; + + tr.weatherSystem->weatherSlots[WEATHER_SNOW].size[0] = 1.5f; + tr.weatherSystem->weatherSlots[WEATHER_SNOW].size[1] = 1.5f; + + tr.weatherSystem->weatherSlots[WEATHER_SNOW].velocityOrientationScale = 0.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_SNOW].drawImage = R_FindImageFile("gfx/effects/snowflake1", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_SNOW].color, 0.75f, 0.75f, 0.75f, 0.75f); + VectorScale( + tr.weatherSystem->weatherSlots[WEATHER_SNOW].color, + 0.75f, + tr.weatherSystem->weatherSlots[WEATHER_SNOW].color); + } + + // Create A Some stuff + //--------------------- + else if (Q_stricmp(token, "spacedust") == 0) + { + /*nCloud.Initialize(count, "gfx/effects/snowpuff1.tga"); + nCloud.mHeight = 1.2f; + nCloud.mWidth = 1.2f; + nCloud.mGravity = 0.0f; + nCloud.mBlendMode = 1; + nCloud.mRotationChangeNext = 0; + nCloud.mColor = 0.75f; + nCloud.mWaterParticles = true; + nCloud.mMass.mMax = 30.0f; + nCloud.mMass.mMin = 10.0f; + nCloud.mSpawnRange.mMins[0] = -1500.0f; + nCloud.mSpawnRange.mMins[1] = -1500.0f; + nCloud.mSpawnRange.mMins[2] = -1500.0f; + nCloud.mSpawnRange.mMaxs[0] = 1500.0f; + nCloud.mSpawnRange.mMaxs[1] = 1500.0f; + nCloud.mSpawnRange.mMaxs[2] = 1500.0f;*/ + int count; + token = COM_ParseExt(&command, qfalse); + count = atoi(token); + + if (!tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].particleCount = count; + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].active = true; + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].gravity = 0.0f; + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].fadeDistance = 3000.f; + + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].size[0] = 2.5f; + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].size[1] = 2.5f; + + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].velocityOrientationScale = 0.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].drawImage = R_FindImageFile("gfx/effects/snowpuff1", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].color, 0.75f, 0.75f, 0.75f, 0.75f); + VectorScale( + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].color, + 0.75f, + tr.weatherSystem->weatherSlots[WEATHER_SPACEDUST].color); + } + + // Create A Sand Storm + //--------------------- + else if (Q_stricmp(token, "sand") == 0) + { + /*nCloud.Initialize(400, "gfx/effects/alpha_smoke2b.tga"); + + nCloud.mGravity = 0; + nCloud.mWidth = 70; + nCloud.mHeight = 70; + nCloud.mColor[0] = 0.9f; + nCloud.mColor[1] = 0.6f; + nCloud.mColor[2] = 0.0f; + nCloud.mColor[3] = 0.5f; + nCloud.mFade = 5.0f; + nCloud.mMass.mMax = 30.0f; + nCloud.mMass.mMin = 10.0f; + nCloud.mSpawnRange.mMins[2] = -150; + nCloud.mSpawnRange.mMaxs[2] = 150; + + nCloud.mRotationChangeNext = 0;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_SAND].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_SAND].particleCount = 400; + tr.weatherSystem->weatherSlots[WEATHER_SAND].active = true; + tr.weatherSystem->weatherSlots[WEATHER_SAND].gravity = 0.0f; + tr.weatherSystem->weatherSlots[WEATHER_SAND].fadeDistance = 2400.f; + + tr.weatherSystem->weatherSlots[WEATHER_SAND].size[0] = 300.f; + tr.weatherSystem->weatherSlots[WEATHER_SAND].size[1] = 300.f; + + tr.weatherSystem->weatherSlots[WEATHER_SAND].velocityOrientationScale = 0.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_SAND].drawImage = R_FindImageFile("gfx/effects/alpha_smoke2b", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_SAND].color, 0.9f, 0.6f, 0.0f, 0.5f); + } + + // Create Blowing Clouds Of Fog + //------------------------------ + else if (Q_stricmp(token, "fog") == 0) + { + /*nCloud.Initialize(60, "gfx/effects/alpha_smoke2b.tga"); + nCloud.mBlendMode = 1; + nCloud.mGravity = 0; + nCloud.mWidth = 70; + nCloud.mHeight = 70; + nCloud.mColor = 0.2f; + nCloud.mFade = 5.0f; + nCloud.mMass.mMax = 30.0f; + nCloud.mMass.mMin = 10.0f; + nCloud.mSpawnRange.mMins[2] = -150; + nCloud.mSpawnRange.mMaxs[2] = 150; + + nCloud.mRotationChangeNext = 0;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_FOG].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].particleCount = 60; + tr.weatherSystem->weatherSlots[WEATHER_FOG].active = true; + tr.weatherSystem->weatherSlots[WEATHER_FOG].gravity = 0.0f; + tr.weatherSystem->weatherSlots[WEATHER_FOG].fadeDistance = 2400.f; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].size[0] = 300.f; + tr.weatherSystem->weatherSlots[WEATHER_FOG].size[1] = 300.f; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].velocityOrientationScale = 0.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_FOG].drawImage = R_FindImageFile("gfx/effects/alpha_smoke2b", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_FOG].color, 0.2f, 0.2f, 0.2f, 0.2f); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_FOG].color, 0.2f, tr.weatherSystem->weatherSlots[WEATHER_FOG].color); + } + + // Create Heavy Rain Particle Cloud + //----------------------------------- + else if (Q_stricmp(token, "heavyrainfog") == 0) + { + /*nCloud.Initialize(70, "gfx/effects/alpha_smoke2b.tga"); + nCloud.mBlendMode = 1; + nCloud.mGravity = 0; + nCloud.mWidth = 100; + nCloud.mHeight = 100; + nCloud.mColor = 0.3f; + nCloud.mFade = 1.0f; + nCloud.mMass.mMax = 10.0f; + nCloud.mMass.mMin = 5.0f; + + nCloud.mSpawnRange.mMins = -(nCloud.mSpawnPlaneDistance*1.25f); + nCloud.mSpawnRange.mMaxs = (nCloud.mSpawnPlaneDistance*1.25f); + nCloud.mSpawnRange.mMins[2] = -150; + nCloud.mSpawnRange.mMaxs[2] = 150; + + nCloud.mRotationChangeNext = 0;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_FOG].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].particleCount = 70; + tr.weatherSystem->weatherSlots[WEATHER_FOG].active = true; + tr.weatherSystem->weatherSlots[WEATHER_FOG].gravity = 0.0f; + tr.weatherSystem->weatherSlots[WEATHER_FOG].fadeDistance = 2400.f; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].size[0] = 300.f; + tr.weatherSystem->weatherSlots[WEATHER_FOG].size[1] = 300.f; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].velocityOrientationScale = 0.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_FOG].drawImage = R_FindImageFile("gfx/effects/alpha_smoke2b", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_FOG].color, 0.3f, 0.3f, 0.3f, 0.3f); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_FOG].color, 0.3f, tr.weatherSystem->weatherSlots[WEATHER_FOG].color); + } + + // Create Blowing Clouds Of Fog + //------------------------------ + else if (Q_stricmp(token, "light_fog") == 0) + { + /*nCloud.Initialize(40, "gfx/effects/alpha_smoke2b.tga"); + nCloud.mBlendMode = 1; + nCloud.mGravity = 0; + nCloud.mWidth = 100; + nCloud.mHeight = 100; + nCloud.mColor[0] = 0.19f; + nCloud.mColor[1] = 0.6f; + nCloud.mColor[2] = 0.7f; + nCloud.mColor[3] = 0.12f; + nCloud.mFade = 0.10f; + nCloud.mMass.mMax = 30.0f; + nCloud.mMass.mMin = 10.0f; + nCloud.mSpawnRange.mMins[2] = -150; + nCloud.mSpawnRange.mMaxs[2] = 150; + + nCloud.mRotationChangeNext = 0;*/ + if (!tr.weatherSystem->weatherSlots[WEATHER_FOG].active) + tr.weatherSystem->activeWeatherTypes++; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].particleCount = 70; + tr.weatherSystem->weatherSlots[WEATHER_FOG].active = true; + tr.weatherSystem->weatherSlots[WEATHER_FOG].gravity = 0.0f; + tr.weatherSystem->weatherSlots[WEATHER_FOG].fadeDistance = 2000.f; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].size[0] = 300.f; + tr.weatherSystem->weatherSlots[WEATHER_FOG].size[1] = 300.f; + + tr.weatherSystem->weatherSlots[WEATHER_FOG].velocityOrientationScale = 0.0f; + + imgType_t type = IMGTYPE_COLORALPHA; + int flags = IMGFLAG_CLAMPTOEDGE; + tr.weatherSystem->weatherSlots[WEATHER_FOG].drawImage = R_FindImageFile("gfx/effects/alpha_smoke2b", type, flags); + + VectorSet4(tr.weatherSystem->weatherSlots[WEATHER_FOG].color, 0.19f, 0.6f, 0.7f, 0.12f); + VectorScale(tr.weatherSystem->weatherSlots[WEATHER_FOG].color, 0.12f, tr.weatherSystem->weatherSlots[WEATHER_FOG].color); + } + + else if (Q_stricmp(token, "outsideshake") == 0) + { + ri.Printf(PRINT_DEVELOPER, "outsideshake isn't supported in MP\n"); + } + else if (Q_stricmp(token, "outsidepain") == 0) + { + ri.Printf(PRINT_DEVELOPER, "outsidepain isn't supported in MP\n"); + } + else + { + ri.Printf(PRINT_ALL, "Weather Effect: Please enter a valid command.\n"); + ri.Printf(PRINT_ALL, " die\n"); + ri.Printf(PRINT_ALL, " clear\n"); + ri.Printf(PRINT_ALL, " freeze\n"); + ri.Printf(PRINT_ALL, " zone (mins) (maxs)\n"); + ri.Printf(PRINT_ALL, " wind\n"); + ri.Printf(PRINT_ALL, " constantwind (velocity)\n"); + ri.Printf(PRINT_ALL, " gustingwind\n"); + //ri.Printf(PRINT_ALL, " windzone (mins) (maxs) (velocity)\n"); + ri.Printf(PRINT_ALL, " lightrain\n"); + ri.Printf(PRINT_ALL, " rain\n"); + ri.Printf(PRINT_ALL, " acidrain\n"); + ri.Printf(PRINT_ALL, " heavyrain\n"); + ri.Printf(PRINT_ALL, " snow\n"); + ri.Printf(PRINT_ALL, " spacedust (count)\n"); + ri.Printf(PRINT_ALL, " sand\n"); + ri.Printf(PRINT_ALL, " fog\n"); + ri.Printf(PRINT_ALL, " heavyrainfog\n"); + ri.Printf(PRINT_ALL, " light_fog\n"); + ri.Printf(PRINT_ALL, " outsideshake\n"); // not available in MP + ri.Printf(PRINT_ALL, " outsidepain\n"); // not available in MP + } +} + +void R_WorldEffect_f(void) +{ + char temp[2048] = { 0 }; + ri.Cmd_ArgsBuffer(temp, sizeof(temp)); + RE_WorldEffectCommand(temp); +} + +void R_AddWeatherSurfaces() +{ + assert(tr.weatherSystem); + + if (tr.weatherSystem->activeWeatherTypes == 0 && + r_debugWeather->integer == 0) + return; + + R_AddDrawSurf( + (surfaceType_t *)&tr.weatherSystem->weatherSurface, + REFENTITYNUM_WORLD, + tr.weatherInternalShader, + 0, /* fogIndex */ + qfalse, /* dlightMap */ + qfalse, /* postRender */ + 0 /* cubemapIndex */ + ); +} + +void RB_SurfaceWeather( srfWeather_t *surf ) +{ + assert(tr.weatherSystem); + + weatherSystem_t& ws = *tr.weatherSystem; + assert(surf == &ws.weatherSurface); + + RB_EndSurface(); + + const float numMinZonesX = std::floor((abs(tr.world->bmodels[0].bounds[0][0]) / CHUNK_EXTENDS) + 0.5f); + const float numMinZonesY = std::floor((abs(tr.world->bmodels[0].bounds[0][1]) / CHUNK_EXTENDS) + 0.5f); + vec3_t viewOrigin; + VectorCopy(backEnd.viewParms.ori.origin, viewOrigin); + float centerZoneOffsetX = + std::floor((viewOrigin[0] / CHUNK_EXTENDS) + 0.5f); + float centerZoneOffsetY = + std::floor((viewOrigin[1] / CHUNK_EXTENDS) + 0.5f); + + vec2_t zoneOffsets[9]; + GLint zoneMapping[9]; + int centerZoneIndex; + { + int chunkIndex = 0; + int currentIndex = 0; + for (int y = -1; y <= 1; ++y) + { + for (int x = -1; x <= 1; ++x, ++currentIndex) + { + chunkIndex = (int(centerZoneOffsetX + numMinZonesX) + x + 1) % 3; + chunkIndex += (int(centerZoneOffsetY + numMinZonesY) + y + 1) % 3 * 3; + VectorSet2( + zoneOffsets[chunkIndex], + x, + y); + zoneMapping[currentIndex] = chunkIndex; + if (x == 0 && y == 0) + centerZoneIndex = currentIndex; + } + } + } + + // Get current global wind vector + VectorCopy(tr.weatherSystem->constWindDirection, tr.weatherSystem->windDirection); + for (int i = 0; i < tr.weatherSystem->activeWindObjects; i++) + { + windObject_t *windObject = &tr.weatherSystem->windSlots[i]; + RB_UpdateWindObject(windObject); + VectorAdd(windObject->currentVelocity, tr.weatherSystem->windDirection, tr.weatherSystem->windDirection); + } + + Allocator& frameAllocator = *backEndData->perFrameMemory; + + // Simulate and render all the weather zones + for (int weatherType = 0; weatherType < NUM_WEATHER_TYPES; weatherType++) + { + weatherObject_t *weatherObject = &ws.weatherSlots[weatherType]; + if (!weatherObject->active) + continue; + + if (weatherObject->vbo == nullptr) + GenerateRainModel( + tr.weatherSystem->weatherSlots[weatherType], + maxWeatherTypeParticles[weatherType]); + + RB_SimulateWeather(weatherObject, &zoneOffsets[0], centerZoneIndex); + + vec4_t viewInfo = { + weatherObject->size[0], + weatherObject->size[1], + weatherObject->velocityOrientationScale, + weatherObject->fadeDistance + }; + + int stateBits = weatherType == WEATHER_SAND ? + GLS_DEPTHFUNC_LESS | GLS_SRCBLEND_SRC_ALPHA | GLS_DSTBLEND_ONE_MINUS_SRC_ALPHA : + GLS_DEPTHFUNC_LESS | GLS_SRCBLEND_ONE | GLS_DSTBLEND_ONE; + + DrawItem item = {}; + + item.renderState.stateBits = stateBits; + item.renderState.cullType = CT_TWO_SIDED; + item.renderState.depthRange = { 0.0f, 1.0f }; + item.program = &tr.weatherShader; + + const size_t numAttribs = ARRAY_LEN(weatherObject->attribsTemplate); + item.numAttributes = numAttribs; + item.attributes = ojkAllocArray( + *backEndData->perFrameMemory, numAttribs); + memcpy( + item.attributes, + weatherObject->attribsTemplate, + sizeof(*item.attributes) * numAttribs); + item.attributes[0].vbo = weatherObject->vbo; + item.attributes[1].vbo = weatherObject->vbo; + + item.draw.type = DRAW_COMMAND_ARRAYS; + item.draw.numInstances = 1; + item.draw.primitiveType = GL_POINTS; + item.draw.params.arrays.numVertices = weatherObject->particleCount; + + //TODO: Cull non visable zones + int currentIndex = 0; + for (int y = -1; y <= 1; ++y) + { + for (int x = -1; x <= 1; ++x, ++currentIndex) + { + const GLuint currentFrameUbo = backEndData->currentFrame->ubo; + const UniformBlockBinding uniformBlockBindings[] = { + { currentFrameUbo, tr.cameraUboOffsets[tr.viewParms.currentViewParm], UNIFORM_BLOCK_CAMERA } + }; + DrawItemSetUniformBlockBindings( + item, uniformBlockBindings, frameAllocator); + + UniformDataWriter uniformDataWriter; + uniformDataWriter.Start(&tr.weatherShader); + uniformDataWriter.SetUniformVec2( + UNIFORM_ZONEOFFSET, + (centerZoneOffsetX + x) * CHUNK_EXTENDS, + (centerZoneOffsetY + y) * CHUNK_EXTENDS); + uniformDataWriter.SetUniformFloat(UNIFORM_TIME, backEnd.refdef.frameTime); + uniformDataWriter.SetUniformVec4(UNIFORM_COLOR, weatherObject->color); + uniformDataWriter.SetUniformVec4(UNIFORM_VIEWINFO, viewInfo); + uniformDataWriter.SetUniformMatrix4x4(UNIFORM_SHADOWMVP, tr.weatherSystem->weatherMVP); + item.uniformData = uniformDataWriter.Finish(*backEndData->perFrameMemory); + + SamplerBindingsWriter samplerBindingsWriter; + samplerBindingsWriter.AddStaticImage(tr.weatherDepthImage, TB_SHADOWMAP); + if (weatherObject->drawImage != NULL) + samplerBindingsWriter.AddStaticImage(weatherObject->drawImage, TB_DIFFUSEMAP); + else + samplerBindingsWriter.AddStaticImage(tr.whiteImage, TB_DIFFUSEMAP); + + item.samplerBindings = samplerBindingsWriter.Finish( + frameAllocator, &item.numSamplerBindings); + + item.draw.params.arrays.firstVertex = weatherObject->particleCount * zoneMapping[currentIndex]; + + uint32_t key = RB_CreateSortKey(item, 15, SS_SEE_THROUGH); + RB_AddDrawItem(backEndData->currentPass, key, item); + } + } + } +} diff --git a/codemp/rd-rend2/tr_weather.h b/codemp/rd-rend2/tr_weather.h new file mode 100644 index 0000000000..b03b25275d --- /dev/null +++ b/codemp/rd-rend2/tr_weather.h @@ -0,0 +1,121 @@ +/* +=========================================================================== +Copyright (C) 2016, OpenJK contributors + +This file is part of the OpenJK source code. + +OpenJK is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License version 2 as +published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, see . +=========================================================================== +*/ +#pragma once + +#include "qcommon/qcommon.h" +#include "tr_local.h" + +#define MAX_WINDOBJECTS 10 +#define MAX_WEATHER_ZONES 100 + +enum weatherType_t +{ + WEATHER_RAIN, + WEATHER_SNOW, + WEATHER_SPACEDUST, + WEATHER_SAND, + WEATHER_FOG, + + NUM_WEATHER_TYPES +}; + +const int maxWeatherTypeParticles[NUM_WEATHER_TYPES] = { + 30000, + 10000, + 5000, + 1000, + 1000 +}; + +struct weatherObject_t +{ + VBO_t *lastVBO; + VBO_t *vbo; + unsigned vboLastUpdateFrame; + vertexAttribute_t attribsTemplate[2]; + + bool active; + + float gravity; + float fadeDistance; + float velocityOrientationScale; + int particleCount; + image_t *drawImage; + vec4_t color; + vec2_t size; +}; + +struct windObject_t +{ + vec3_t currentVelocity; + vec3_t targetVelocity; + vec3_t maxVelocity; + vec3_t minVelocity; + float chanceOfDeadTime; + vec2_t deadTimeMinMax; + int targetVelocityTimeRemaining; +}; + +struct weatherBrushes_t +{ + uint8_t numPlanes; + vec4_t planes[64]; + +}; + +enum weatherBrushType_t +{ + WEATHER_BRUSHES_NONE, + WEATHER_BRUSHES_OUTSIDE, + WEATHER_BRUSHES_INSIDE, + + NUM_WEATHER_BRUSH_TYPES +}; + +struct weatherSystem_t +{ + weatherObject_t weatherSlots[NUM_WEATHER_TYPES]; + windObject_t windSlots[MAX_WINDOBJECTS]; + weatherBrushes_t weatherBrushes[MAX_WEATHER_ZONES * 2]; + weatherBrushType_t weatherBrushType = WEATHER_BRUSHES_NONE; + + int activeWeatherTypes = 0; + int activeWindObjects = 0; + int numWeatherBrushes = 0; + bool frozen; + + srfWeather_t weatherSurface; + + vec3_t constWindDirection; + vec3_t windDirection; + float windSpeed; + + float weatherMVP[16]; +}; +struct srfWeather_t; + +void R_InitWeatherSystem(); +void R_InitWeatherForMap(); +void R_AddWeatherSurfaces(); +void R_AddWeatherBrush(uint8_t numPlanes, vec4_t *planes); +void R_ShutdownWeatherSystem(); +void RB_SurfaceWeather( srfWeather_t *surfaceType ); + +void R_WorldEffect_f(void); diff --git a/codemp/rd-rend2/tr_world.cpp b/codemp/rd-rend2/tr_world.cpp new file mode 100644 index 0000000000..0204652440 --- /dev/null +++ b/codemp/rd-rend2/tr_world.cpp @@ -0,0 +1,942 @@ +/* +=========================================================================== +Copyright (C) 1999-2005 Id Software, Inc. + +This file is part of Quake III Arena source code. + +Quake III Arena source code is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 2 of the License, +or (at your option) any later version. + +Quake III Arena source code is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with Quake III Arena source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ +#include "tr_local.h" + + +world_t *R_GetWorld(int worldIndex) +{ + if (worldIndex == -1) + { + return tr.world; + } + else + { + return tr.bspModels[worldIndex]; + } +} + +/* +================ +R_CullSurface + +Tries to cull surfaces before they are lighted or +added to the sorting list. +================ +*/ +static qboolean R_CullSurface( msurface_t *surf, int entityNum ) { + if ( r_nocull->integer || surf->cullinfo.type == CULLINFO_NONE) { + return qfalse; + } + + if ( *surf->data == SF_GRID && r_nocurves->integer ) { + return qtrue; + } + + if (surf->cullinfo.type & CULLINFO_PLANE) + { + // Only true for SF_FACE, so treat like its own function + float d; + cullType_t ct; + + if ( !r_facePlaneCull->integer ) { + return qfalse; + } + + ct = surf->shader->cullType; + + if (ct == CT_TWO_SIDED) + { + return qfalse; + } + + if (tr.viewParms.flags & (VPF_DEPTHSHADOW) && tr.viewParms.flags & (VPF_SHADOWCASCADES)) + { + if (ct == CT_FRONT_SIDED) + { + ct = CT_BACK_SIDED; + } + else if (ct == CT_BACK_SIDED) + { + ct = CT_FRONT_SIDED; + } + } + + // do proper cull for orthographic projection + if (tr.viewParms.flags & VPF_ORTHOGRAPHIC) { + d = DotProduct(tr.viewParms.ori.axis[0], surf->cullinfo.plane.normal); + if ( ct == CT_FRONT_SIDED ) { + if (d > 0) + return qtrue; + } else { + if (d < 0) + return qtrue; + } + return qfalse; + } + + d = DotProduct (tr.ori.viewOrigin, surf->cullinfo.plane.normal); + + // don't cull exactly on the plane, because there are levels of rounding + // through the BSP, ICD, and hardware that may cause pixel gaps if an + // epsilon isn't allowed here + if ( ct == CT_FRONT_SIDED ) { + if ( d < surf->cullinfo.plane.dist - 8 ) { + return qtrue; + } + } else { + if ( d > surf->cullinfo.plane.dist + 8 ) { + return qtrue; + } + } + + return qfalse; + } + + if (surf->cullinfo.type & CULLINFO_SPHERE) + { + int sphereCull; + + if ( entityNum != REFENTITYNUM_WORLD ) { + sphereCull = R_CullLocalPointAndRadius( surf->cullinfo.localOrigin, surf->cullinfo.radius ); + } else { + sphereCull = R_CullPointAndRadius( surf->cullinfo.localOrigin, surf->cullinfo.radius ); + } + + if ( sphereCull == CULL_OUT ) + { + return qtrue; + } + } + + if (surf->cullinfo.type & CULLINFO_BOX) + { + int boxCull; + + if ( entityNum != REFENTITYNUM_WORLD ) { + boxCull = R_CullLocalBox( surf->cullinfo.bounds ); + } else { + boxCull = R_CullBox( surf->cullinfo.bounds ); + } + + if ( boxCull == CULL_OUT ) + { + return qtrue; + } + } + + return qfalse; +} + + +/* +==================== +R_DlightSurface + +The given surface is going to be drawn, and it touches a leaf +that is touched by one or more dlights, so try to throw out +more dlights if possible. +==================== +*/ +static int R_DlightSurface( msurface_t *surf, int dlightBits ) { + float d; + int i; + dlight_t *dl; + + if ( surf->cullinfo.type & CULLINFO_PLANE ) + { + for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { + if ( ! ( dlightBits & ( 1 << i ) ) ) { + continue; + } + dl = &tr.refdef.dlights[i]; + d = DotProduct( dl->origin, surf->cullinfo.plane.normal ) - surf->cullinfo.plane.dist; + if ( d < -dl->radius || d > dl->radius ) { + // dlight doesn't reach the plane + dlightBits &= ~( 1 << i ); + } + } + } + + if ( surf->cullinfo.type & CULLINFO_BOX ) + { + for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { + if ( ! ( dlightBits & ( 1 << i ) ) ) { + continue; + } + dl = &tr.refdef.dlights[i]; + if ( dl->origin[0] - dl->radius > surf->cullinfo.bounds[1][0] + || dl->origin[0] + dl->radius < surf->cullinfo.bounds[0][0] + || dl->origin[1] - dl->radius > surf->cullinfo.bounds[1][1] + || dl->origin[1] + dl->radius < surf->cullinfo.bounds[0][1] + || dl->origin[2] - dl->radius > surf->cullinfo.bounds[1][2] + || dl->origin[2] + dl->radius < surf->cullinfo.bounds[0][2] ) { + // dlight doesn't reach the bounds + dlightBits &= ~( 1 << i ); + } + } + } + + if ( surf->cullinfo.type & CULLINFO_SPHERE ) + { + for ( i = 0 ; i < tr.refdef.num_dlights ; i++ ) { + if ( ! ( dlightBits & ( 1 << i ) ) ) { + continue; + } + dl = &tr.refdef.dlights[i]; + if (!SpheresIntersect(dl->origin, dl->radius, surf->cullinfo.localOrigin, surf->cullinfo.radius)) + { + // dlight doesn't reach the bounds + dlightBits &= ~( 1 << i ); + } + } + } + + switch(*surf->data) + { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + case SF_VBO_MESH: + ((srfBspSurface_t *)surf->data)->dlightBits = dlightBits; + break; + + default: + dlightBits = 0; + break; + } + + if ( dlightBits ) { + tr.pc.c_dlightSurfaces++; + } else { + tr.pc.c_dlightSurfacesCulled++; + } + + return dlightBits; +} + +/* +==================== +R_PshadowSurface + +Just like R_DlightSurface, cull any we can +==================== +*/ +static int R_PshadowSurface( msurface_t *surf, int pshadowBits ) { + float d; + int i; + pshadow_t *ps; + + if ( surf->cullinfo.type & CULLINFO_PLANE ) + { + for ( i = 0 ; i < tr.refdef.num_pshadows ; i++ ) { + if ( ! ( pshadowBits & ( 1 << i ) ) ) { + continue; + } + ps = &tr.refdef.pshadows[i]; + d = DotProduct( ps->lightOrigin, surf->cullinfo.plane.normal ) - surf->cullinfo.plane.dist; + if ( d < -ps->lightRadius || d > ps->lightRadius ) { + // pshadow doesn't reach the plane + pshadowBits &= ~( 1 << i ); + } + } + } + + if ( surf->cullinfo.type & CULLINFO_BOX ) + { + for ( i = 0 ; i < tr.refdef.num_pshadows ; i++ ) { + if ( ! ( pshadowBits & ( 1 << i ) ) ) { + continue; + } + ps = &tr.refdef.pshadows[i]; + if ( ps->lightOrigin[0] - ps->lightRadius > surf->cullinfo.bounds[1][0] + || ps->lightOrigin[0] + ps->lightRadius < surf->cullinfo.bounds[0][0] + || ps->lightOrigin[1] - ps->lightRadius > surf->cullinfo.bounds[1][1] + || ps->lightOrigin[1] + ps->lightRadius < surf->cullinfo.bounds[0][1] + || ps->lightOrigin[2] - ps->lightRadius > surf->cullinfo.bounds[1][2] + || ps->lightOrigin[2] + ps->lightRadius < surf->cullinfo.bounds[0][2] + || BoxOnPlaneSide(surf->cullinfo.bounds[0], surf->cullinfo.bounds[1], &ps->cullPlane) == 2 ) { + // pshadow doesn't reach the bounds + pshadowBits &= ~( 1 << i ); + } + } + } + + if ( surf->cullinfo.type & CULLINFO_SPHERE ) + { + for ( i = 0 ; i < tr.refdef.num_pshadows ; i++ ) { + if ( ! ( pshadowBits & ( 1 << i ) ) ) { + continue; + } + ps = &tr.refdef.pshadows[i]; + if (!SpheresIntersect(ps->viewOrigin, ps->viewRadius, surf->cullinfo.localOrigin, surf->cullinfo.radius) + || DotProduct( surf->cullinfo.localOrigin, ps->cullPlane.normal ) - ps->cullPlane.dist < -surf->cullinfo.radius) + { + // pshadow doesn't reach the bounds + pshadowBits &= ~( 1 << i ); + } + } + } + + switch(*surf->data) + { + case SF_FACE: + case SF_GRID: + case SF_TRIANGLES: + case SF_VBO_MESH: + ((srfBspSurface_t *)surf->data)->pshadowBits = pshadowBits; + break; + + default: + pshadowBits = 0; + break; + } + + if ( pshadowBits ) { + //tr.pc.c_dlightSurfaces++; + } + + return pshadowBits; +} + + +/* +====================== +R_AddWorldSurface +====================== +*/ +static void R_AddWorldSurface( + msurface_t *surf, + const trRefEntity_t *entity, + int entityNum, + int dlightBits, + int pshadowBits) +{ + // FIXME: bmodel fog? + + // try to cull before dlighting or adding + if ( R_CullSurface( surf, entityNum ) ) { + return; + } + + // check for dlighting + // TODO: implement dlight culling for non worldspawn surfaces + if ( dlightBits ) { + if (entityNum != REFENTITYNUM_WORLD) + dlightBits = (1 << tr.refdef.num_dlights) - 1; + else + dlightBits = R_DlightSurface( surf, dlightBits ); + } + + // set pshadows + if ( pshadowBits ) { + R_PshadowSurface( surf, pshadowBits ); + } + + bool isPostRenderEntity = false; + if ( entityNum != REFENTITYNUM_WORLD ) + { + assert(entity); + isPostRenderEntity = R_IsPostRenderEntity(entity); + } + + R_AddDrawSurf( surf->data, entityNum, surf->shader, surf->fogIndex, + dlightBits, isPostRenderEntity, surf->cubemapIndex ); + + for ( int i = 0, numSprites = surf->numSurfaceSprites; + i < numSprites; ++i ) + { + srfSprites_t *sprites = surf->surfaceSprites + i; + R_AddDrawSurf((surfaceType_t *)sprites, entityNum, sprites->shader, + surf->fogIndex, dlightBits, isPostRenderEntity, 0); + } +} + +/* +============================================================= + + BRUSH MODELS + +============================================================= +*/ + +/* +================= +R_AddBrushModelSurfaces +================= +*/ +void R_AddBrushModelSurfaces ( trRefEntity_t *ent, int entityNum ) { + model_t *pModel = R_GetModelByHandle( ent->e.hModel ); + bmodel_t *bmodel = pModel->data.bmodel; + int clip = R_CullLocalBox( bmodel->bounds ); + if ( clip == CULL_OUT ) { + return; + } + + if (!(tr.viewParms.flags & VPF_DEPTHSHADOW)) + R_DlightBmodel( bmodel, ent ); + + world_t *world = R_GetWorld(bmodel->worldIndex); + for ( int i = 0 ; i < bmodel->numSurfaces ; i++ ) { + int surf = bmodel->firstSurface + i; + + if (world->surfacesViewCount[surf] != tr.viewCount) + { + world->surfacesViewCount[surf] = tr.viewCount; + R_AddWorldSurface(world->surfaces + surf, ent, entityNum, ent->needDlights, 0); + } + } +} + +float GetQuadArea(vec3_t v1, vec3_t v2, vec3_t v3, vec3_t v4) +{ + vec3_t vec1, vec2, dis1, dis2; + + // Get area of tri1 + VectorSubtract(v1, v2, vec1); + VectorSubtract(v1, v4, vec2); + CrossProduct(vec1, vec2, dis1); + VectorScale(dis1, 0.25f, dis1); + + // Get area of tri2 + VectorSubtract(v3, v2, vec1); + VectorSubtract(v3, v4, vec2); + CrossProduct(vec1, vec2, dis2); + VectorScale(dis2, 0.25f, dis2); + + // Return addition of disSqr of each tri area + return (dis1[0] * dis1[0] + dis1[1] * dis1[1] + dis1[2] * dis1[2] + + dis2[0] * dis2[0] + dis2[1] * dis2[1] + dis2[2] * dis2[2]); +} + +void RE_GetBModelVerts(int bmodelIndex, vec3_t *verts, vec3_t normal) +{ + int surf; + srfBspSurface_t *face; + // Not sure if we really need to track the best two candidates + int maxDist[2] = { 0,0 }; + int maxIndx[2] = { 0,0 }; + int dist = 0; + float dot1, dot2; + + model_t *pModel = R_GetModelByHandle(bmodelIndex); + bmodel_t *bmodel = pModel->data.bmodel; + world_t *world = R_GetWorld(bmodel->worldIndex); + + // Loop through all surfaces on the brush and find the best two candidates + for (int i = 0; i < bmodel->numSurfaces; i++) + { + surf = bmodel->firstSurface + i; + face = (srfBspSurface_t *)(world->surfaces + surf)->data; + + // It seems that the safest way to handle this is by finding the area of the faces + dist = GetQuadArea(face->verts[0].xyz, face->verts[1].xyz, face->verts[2].xyz, face->verts[3].xyz); + + // Check against the highest max + if (dist > maxDist[0]) + { + // Shuffle our current maxes down + maxDist[1] = maxDist[0]; + maxIndx[1] = maxIndx[0]; + + maxDist[0] = dist; + maxIndx[0] = i; + } + // Check against the second highest max + else if (dist >= maxDist[1]) + { + // just stomp the old + maxDist[1] = dist; + maxIndx[1] = i; + } + } + + // Hopefully we've found two best case candidates. Now we should see which of these faces the viewer + + surf = bmodel->firstSurface + maxIndx[0]; + face = (srfBspSurface_t *)(world->surfaces + surf)->data; + dot1 = DotProduct(face->cullPlane.normal, tr.refdef.viewaxis[0]); + + surf = bmodel->firstSurface + maxIndx[1]; + face = (srfBspSurface_t *)(world->surfaces + surf)->data; + dot2 = DotProduct(face->cullPlane.normal, tr.refdef.viewaxis[0]); + + if (dot2 < dot1 && dot2 < 0.0f) + { + surf = bmodel->firstSurface + maxIndx[1]; // use the second face + } + else if (dot1 < dot2 && dot1 < 0.0f) + { + surf = bmodel->firstSurface + maxIndx[0]; // use the first face + } + else + { // Possibly only have one face, so may as well use the first face, which also should be the best one + //i = rand() & 1; // ugh, we don't know which to use. I'd hope this would never happen + surf = bmodel->firstSurface + maxIndx[0]; // use the first face + } + face = (srfBspSurface_t *)(world->surfaces + surf)->data; + + for (int t = 0; t < 4; t++) + { + VectorCopy(face->verts[t].xyz, verts[t]); + } +} + +void RE_SetRangedFog ( float range ) +{ + tr.rangedFog = range; +} + + +/* +============================================================= + + WORLD MODEL + +============================================================= +*/ + + +/* +================ +R_RecursiveWorldNode +================ +*/ +void R_RecursiveWorldNode( mnode_t *node, int planeBits, int dlightBits, int pshadowBits ) +{ + do { + int newDlights[2]; + unsigned int newPShadows[2]; + + // if the node wasn't marked as potentially visible, exit + // pvs is skipped for depth shadows + if (!(tr.viewParms.flags & VPF_DEPTHSHADOW) && + node->visCounts[tr.visIndex] != tr.visCounts[tr.visIndex]) { + return; + } + + // if the bounding volume is outside the frustum, nothing + // inside can be visible OPTIMIZE: don't do this all the way to leafs? + + if ( !r_nocull->integer ) { + int r; + + if ( planeBits & 1 ) { + r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[0]); + if (r == 2) { + return; // culled + } + if ( r == 1 ) { + planeBits &= ~1; // all descendants will also be in front + } + } + + if ( planeBits & 2 ) { + r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[1]); + if (r == 2) { + return; // culled + } + if ( r == 1 ) { + planeBits &= ~2; // all descendants will also be in front + } + } + + if ( planeBits & 4 ) { + r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[2]); + if (r == 2) { + return; // culled + } + if ( r == 1 ) { + planeBits &= ~4; // all descendants will also be in front + } + } + + if ( planeBits & 8 ) { + r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[3]); + if (r == 2) { + return; // culled + } + if ( r == 1 ) { + planeBits &= ~8; // all descendants will also be in front + } + } + + if ( planeBits & 16 ) { + r = BoxOnPlaneSide(node->mins, node->maxs, &tr.viewParms.frustum[4]); + if (r == 2) { + return; // culled + } + if ( r == 1 ) { + planeBits &= ~16; // all descendants will also be in front + } + } + } + + if ( node->contents != -1 ) { + break; + } + + // node is just a decision point, so go down both sides + // since we don't care about sort orders, just go positive to negative + + // determine which dlights are needed + newDlights[0] = 0; + newDlights[1] = 0; + if ( dlightBits ) { + for ( int i = 0 ; i < tr.refdef.num_dlights ; i++ ) { + if ( !(dlightBits & (1 << i)) ) { + continue; + } + + dlight_t *dl = &tr.refdef.dlights[i]; + float dist = DotProduct(dl->origin, node->plane->normal) - node->plane->dist; + + if ( dist > -dl->radius ) { + newDlights[0] |= ( 1 << i ); + } + if ( dist < dl->radius ) { + newDlights[1] |= ( 1 << i ); + } + } + } + + newPShadows[0] = 0; + newPShadows[1] = 0; + if ( pshadowBits ) { + for ( int i = 0 ; i < tr.refdef.num_pshadows ; i++ ) { + if ( !(pshadowBits & (1 << i)) ) { + continue; + } + + pshadow_t *shadow = &tr.refdef.pshadows[i]; + float dist = DotProduct(shadow->lightOrigin, node->plane->normal) - node->plane->dist; + + if ( dist > -shadow->lightRadius ) { + newPShadows[0] |= ( 1 << i ); + } + + if ( dist < shadow->lightRadius ) { + newPShadows[1] |= ( 1 << i ); + } + } + } + + // recurse down the children, front side first + R_RecursiveWorldNode (node->children[0], planeBits, newDlights[0], newPShadows[0] ); + + // tail recurse + node = node->children[1]; + dlightBits = newDlights[1]; + pshadowBits = newPShadows[1]; + } while ( 1 ); + + { + // leaf node, so add mark surfaces + int c; + int surf, *view; + + tr.pc.c_leafs++; + + // add to z buffer bounds + tr.viewParms.visBounds[0][0] = MIN(node->mins[0], tr.viewParms.visBounds[0][0]); + tr.viewParms.visBounds[0][1] = MIN(node->mins[1], tr.viewParms.visBounds[0][1]); + tr.viewParms.visBounds[0][2] = MIN(node->mins[2], tr.viewParms.visBounds[0][2]); + + tr.viewParms.visBounds[1][0] = MAX(node->maxs[0], tr.viewParms.visBounds[1][0]); + tr.viewParms.visBounds[1][1] = MAX(node->maxs[1], tr.viewParms.visBounds[1][1]); + tr.viewParms.visBounds[1][2] = MAX(node->maxs[2], tr.viewParms.visBounds[1][2]); + + // add merged and unmerged surfaces + if (tr.world->viewSurfaces && !r_nocurves->integer) + view = tr.world->viewSurfaces + node->firstmarksurface; + else + view = tr.world->marksurfaces + node->firstmarksurface; + + c = node->nummarksurfaces; + while (c--) { + // just mark it as visible, so we don't jump out of the cache derefencing the surface + surf = *view; + if (surf < 0) + { + if (tr.world->mergedSurfacesViewCount[-surf - 1] != tr.viewCount) + { + tr.world->mergedSurfacesViewCount[-surf - 1] = tr.viewCount; + tr.world->mergedSurfacesDlightBits[-surf - 1] = dlightBits; + tr.world->mergedSurfacesPshadowBits[-surf - 1] = pshadowBits; + } + else + { + tr.world->mergedSurfacesDlightBits[-surf - 1] |= dlightBits; + tr.world->mergedSurfacesPshadowBits[-surf - 1] |= pshadowBits; + } + } + else + { + if (tr.world->surfacesViewCount[surf] != tr.viewCount) + { + tr.world->surfacesViewCount[surf] = tr.viewCount; + tr.world->surfacesDlightBits[surf] = dlightBits; + tr.world->surfacesPshadowBits[surf] = pshadowBits; + } + else + { + tr.world->surfacesDlightBits[surf] |= dlightBits; + tr.world->surfacesPshadowBits[surf] |= pshadowBits; + } + } + view++; + } + } +} + + +/* +=============== +R_PointInLeaf +=============== +*/ +static mnode_t *R_PointInLeaf( const vec3_t p ) { + mnode_t *node; + float d; + cplane_t *plane; + + if ( !tr.world ) { + ri.Error (ERR_DROP, "R_PointInLeaf: bad model"); + } + + node = tr.world->nodes; + while( 1 ) { + if (node->contents != -1) { + break; + } + plane = node->plane; + d = DotProduct (p,plane->normal) - plane->dist; + if (d > 0) { + node = node->children[0]; + } else { + node = node->children[1]; + } + } + + return node; +} + +/* +============== +R_ClusterPVS +============== +*/ +static const byte *R_ClusterPVS (int cluster) { + if (!tr.world->vis || cluster < 0 || cluster >= tr.world->numClusters ) { + return tr.world->novis; + } + + return tr.world->vis + cluster * tr.world->clusterBytes; +} + +/* +================= +R_inPVS +================= +*/ +qboolean R_inPVS( const vec3_t p1, const vec3_t p2, byte *mask ) { + int leafnum; + int cluster; + + leafnum = ri.CM_PointLeafnum (p1); + cluster = ri.CM_LeafCluster (leafnum); + + //agh, the damn snapshot mask doesn't work for this + mask = (byte *) ri.CM_ClusterPVS (cluster); + + leafnum = ri.CM_PointLeafnum (p2); + cluster = ri.CM_LeafCluster (leafnum); + if ( !(mask[cluster>>3] & (1<<(cluster&7))) ) + return qfalse; + + return qtrue; +} + +/* +=============== +R_MarkLeaves + +Mark the leaves and nodes that are in the PVS for the current +cluster +=============== +*/ +void R_MarkLeaves( void ) +{ + // lockpvs lets designers walk around to determine the + // extent of the current pvs + if ( r_lockpvs->integer ) { + return; + } + + // current viewcluster + mnode_t *leaf = R_PointInLeaf(tr.viewParms.pvsOrigin); + int cluster = leaf->cluster; + + // if the cluster is the same and the area visibility matrix + // hasn't changed, we don't need to mark everything again + + for (int i = 0; i < MAX_VISCOUNTS; i++) + { + // if the areamask or r_showcluster was modified, invalidate all visclusters + // this caused doors to open into undrawn areas + if (tr.refdef.areamaskModified || r_showcluster->modified) + { + tr.visClusters[i] = -2; + } + else if (tr.visClusters[i] == cluster) + { + if (tr.visClusters[i] != tr.visClusters[tr.visIndex] && r_showcluster->integer) + { + ri.Printf(PRINT_ALL, "found cluster:%i area:%i index:%i\n", + cluster, leaf->area, i); + } + + tr.visIndex = i; + return; + } + } + + tr.visIndex = (tr.visIndex + 1) % MAX_VISCOUNTS; + tr.visCounts[tr.visIndex]++; + tr.visClusters[tr.visIndex] = cluster; + + if ( r_showcluster->modified || r_showcluster->integer ) { + r_showcluster->modified = qfalse; + if ( r_showcluster->integer ) { + ri.Printf( PRINT_ALL, "cluster:%i area:%i\n", cluster, leaf->area ); + } + } + + const byte *vis = R_ClusterPVS(tr.visClusters[tr.visIndex]); + + int i; + for (i = 0, leaf = (tr.world->nodes + tr.world->numDecisionNodes); i < (tr.world->numnodes - tr.world->numDecisionNodes); i++, leaf++) { + cluster = leaf->cluster; + if ( cluster < 0 || cluster >= tr.world->numClusters ) { + continue; + } + + // check general pvs + if ( !(vis[cluster>>3] & (1<<(cluster&7))) ) { + continue; + } + + // Handle skyportal draws + byte *areamask = tr.viewParms.isSkyPortal == qtrue ? tr.skyPortalAreaMask : tr.refdef.areamask; + + // check for door connection + if ( (areamask[leaf->area>>3] & (1<<(leaf->area&7)) ) ) { + continue; // not visible + } + + mnode_t *parent = leaf; + do { + if (parent->visCounts[tr.visIndex] == tr.visCounts[tr.visIndex]) { + break; + } + + parent->visCounts[tr.visIndex] = tr.visCounts[tr.visIndex]; + parent = parent->parent; + } while (parent); + } +} + + +/* +============= +R_AddWorldSurfaces +============= +*/ +void R_AddWorldSurfaces( viewParms_t *viewParms, trRefdef_t *refdef ) { + int planeBits, dlightBits, pshadowBits; + + if ( !r_drawworld->integer ) { + return; + } + + if ( refdef->rdflags & RDF_NOWORLDMODEL ) { + return; + } + + // determine which leaves are in the PVS / areamask + if (!(viewParms->flags & VPF_DEPTHSHADOW)) { + R_MarkLeaves(); + } + + // clear out the visible min/max + ClearBounds(viewParms->visBounds[0], viewParms->visBounds[1]); + + // perform frustum culling and flag all the potentially visible surfaces + refdef->num_dlights = Q_min(refdef->num_dlights, 32); + refdef->num_pshadows = Q_min(refdef->num_pshadows, 32); + + planeBits = (viewParms->flags & VPF_FARPLANEFRUSTUM) ? 31 : 15; + + if ( viewParms->flags & VPF_DEPTHSHADOW ) + { + dlightBits = 0; + pshadowBits = 0; + } + else + { + dlightBits = (1 << refdef->num_dlights) - 1; + if (r_shadows->integer == 4) + pshadowBits = (1 << refdef->num_pshadows) - 1; + else + pshadowBits = 0; + } + + R_RecursiveWorldNode(tr.world->nodes, planeBits, dlightBits, pshadowBits); + + // now add all the potentially visible surfaces + R_RotateForEntity(&tr.worldEntity, &tr.viewParms, &tr.ori); + + for (int i = 0; i < tr.world->numWorldSurfaces; i++) + { + if (tr.world->surfacesViewCount[i] != tr.viewCount) + continue; + + R_AddWorldSurface( + tr.world->surfaces + i, + nullptr, + REFENTITYNUM_WORLD, + tr.world->surfacesDlightBits[i], + tr.world->surfacesPshadowBits[i]); + } + + for (int i = 0; i < tr.world->numMergedSurfaces; i++) + { + if (tr.world->mergedSurfacesViewCount[i] != tr.viewCount) + continue; + + R_AddWorldSurface( + tr.world->mergedSurfaces + i, + nullptr, + REFENTITYNUM_WORLD, + tr.world->mergedSurfacesDlightBits[i], + tr.world->mergedSurfacesPshadowBits[i]); + } +} diff --git a/codemp/rd-vanilla/G2_API.cpp b/codemp/rd-vanilla/G2_API.cpp index d09a90af5e..117cc8bbfd 100644 --- a/codemp/rd-vanilla/G2_API.cpp +++ b/codemp/rd-vanilla/G2_API.cpp @@ -2732,6 +2732,11 @@ qboolean G2API_SkinlessModel(CGhoul2Info_v& ghoul2, int modelIndex) return qtrue; } +int G2API_Ghoul2Size(CGhoul2Info_v &ghoul2) +{ + return ghoul2.size(); +} + //#ifdef _SOF2 #ifdef _G2_GORE void ResetGoreTag(); // put here to reduce coupling @@ -2768,11 +2773,6 @@ void G2API_ClearSkinGore ( CGhoul2Info_v &ghoul2 ) } } -int G2API_Ghoul2Size ( CGhoul2Info_v &ghoul2 ) -{ - return ghoul2.size(); -} - extern int G2_DecideTraceLod(CGhoul2Info &ghoul2, int useLod); void G2API_AddSkinGore(CGhoul2Info_v &ghoul2,SSkinGoreData &gore) { diff --git a/codemp/rd-vanilla/G2_misc.cpp b/codemp/rd-vanilla/G2_misc.cpp index 02cded0724..248fc88819 100644 --- a/codemp/rd-vanilla/G2_misc.cpp +++ b/codemp/rd-vanilla/G2_misc.cpp @@ -26,11 +26,10 @@ along with this program; if not, see . #include "server/server.h" #include "ghoul2/g2_local.h" +#include "tr_local.h" #ifdef _G2_GORE #include "ghoul2/G2_gore.h" -#include "tr_local.h" - #define GORE_TAG_UPPER (256) #define GORE_TAG_MASK (~255) @@ -549,6 +548,7 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, vec3_t correctScale; qboolean firstModelOnly = qfalse; +#ifdef _G2_GORE if ( cg_g2MarksAllModels == NULL ) { cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "" ); @@ -559,7 +559,7 @@ void G2_TransformModel(CGhoul2Info_v &ghoul2, const int frameNum, vec3_t scale, { firstModelOnly = qtrue; } - +#endif VectorCopy(scale, correctScale); // check for scales of 0 - that's the default I believe @@ -1498,6 +1498,7 @@ void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, Colli shader_t *cust_shader; qboolean firstModelOnly = qfalse; +#ifdef _G2_GORE if ( cg_g2MarksAllModels == NULL ) { cg_g2MarksAllModels = ri.Cvar_Get( "cg_g2MarksAllModels", "0", 0, "" ); @@ -1508,6 +1509,7 @@ void G2_TraceModels(CGhoul2Info_v &ghoul2, vec3_t rayStart, vec3_t rayEnd, Colli { firstModelOnly = qtrue; } +#endif // walk each possible model for this entity and try tracing against it for (i=0; i= 1800 -#define HAVE_STRTOLL 1 -#define HAVE_VSSCANF 1 -#define HAVE_SCALBN 1 -#define HAVE_SCALBNF 1 -#endif -/* This function is available with at least the VC++ 2008 C runtime library */ -#if _MSC_VER >= 1400 -#define HAVE__FSEEKI64 1 -#endif -#endif -#if !defined(_MSC_VER) || defined(_USE_MATH_DEFINES) -#define HAVE_M_PI 1 -#endif +/** + * \file SDL_config.h + */ + +/* Add any platform that doesn't build using the configure system. */ +#if defined(__WIN32__) +#include "SDL_config_windows.h" +#elif defined(__WINRT__) +#include "SDL_config_winrt.h" +#elif defined(__MACOSX__) +#include "SDL_config_macosx.h" +#elif defined(__IPHONEOS__) +#include "SDL_config_iphoneos.h" +#elif defined(__ANDROID__) +#include "SDL_config_android.h" +#elif defined(__PSP__) +#include "SDL_config_psp.h" +#elif defined(__OS2__) +#include "SDL_config_os2.h" #else -#define HAVE_STDARG_H 1 -#define HAVE_STDDEF_H 1 -#endif - -/* Enable various audio drivers */ -#define SDL_AUDIO_DRIVER_WASAPI 1 -#define SDL_AUDIO_DRIVER_DSOUND 1 -#define SDL_AUDIO_DRIVER_WINMM 1 -#define SDL_AUDIO_DRIVER_DISK 1 -#define SDL_AUDIO_DRIVER_DUMMY 1 - -/* Enable various input drivers */ -#define SDL_JOYSTICK_DINPUT 1 -#define SDL_JOYSTICK_XINPUT 1 -#define SDL_JOYSTICK_HIDAPI 1 -#define SDL_HAPTIC_DINPUT 1 -#define SDL_HAPTIC_XINPUT 1 - -/* Enable the dummy sensor driver */ -#define SDL_SENSOR_DUMMY 1 - -/* Enable various shared object loading systems */ -#define SDL_LOADSO_WINDOWS 1 - -/* Enable various threading systems */ -#define SDL_THREAD_WINDOWS 1 - -/* Enable various timer systems */ -#define SDL_TIMER_WINDOWS 1 - -/* Enable various video drivers */ -#define SDL_VIDEO_DRIVER_DUMMY 1 -#define SDL_VIDEO_DRIVER_WINDOWS 1 - -#ifndef SDL_VIDEO_RENDER_D3D -#define SDL_VIDEO_RENDER_D3D 1 -#endif -#ifndef SDL_VIDEO_RENDER_D3D11 -#define SDL_VIDEO_RENDER_D3D11 0 -#endif - -/* Enable OpenGL support */ -#ifndef SDL_VIDEO_OPENGL -#define SDL_VIDEO_OPENGL 1 -#endif -#ifndef SDL_VIDEO_OPENGL_WGL -#define SDL_VIDEO_OPENGL_WGL 1 -#endif -#ifndef SDL_VIDEO_RENDER_OGL -#define SDL_VIDEO_RENDER_OGL 1 -#endif -#ifndef SDL_VIDEO_RENDER_OGL_ES2 -#define SDL_VIDEO_RENDER_OGL_ES2 1 -#endif -#ifndef SDL_VIDEO_OPENGL_ES2 -#define SDL_VIDEO_OPENGL_ES2 1 -#endif -#ifndef SDL_VIDEO_OPENGL_EGL -#define SDL_VIDEO_OPENGL_EGL 1 -#endif - -/* Enable Vulkan support */ -#define SDL_VIDEO_VULKAN 1 - -/* Enable system power support */ -#define SDL_POWER_WINDOWS 1 - -/* Enable filesystem support */ -#define SDL_FILESYSTEM_WINDOWS 1 +/* This is a minimal configuration just to get SDL running on new platforms. */ +#include "SDL_config_minimal.h" +#endif /* platform config */ -/* Enable assembly routines (Win64 doesn't have inline asm) */ -#ifndef _WIN64 -#define SDL_ASSEMBLY_ROUTINES 1 +#ifdef USING_GENERATED_CONFIG_H +#error Wrong SDL_config.h, check your include path? #endif -#endif /* SDL_config_windows_h_ */ +#endif /* SDL_config_h_ */ diff --git a/lib/SDL2/include/SDL_config.h.cmake b/lib/SDL2/include/SDL_config.h.cmake index c57266c413..d6ea31eacd 100644 --- a/lib/SDL2/include/SDL_config.h.cmake +++ b/lib/SDL2/include/SDL_config.h.cmake @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -47,46 +47,32 @@ #cmakedefine HAVE_GCC_ATOMICS @HAVE_GCC_ATOMICS@ #cmakedefine HAVE_GCC_SYNC_LOCK_TEST_AND_SET @HAVE_GCC_SYNC_LOCK_TEST_AND_SET@ -#cmakedefine HAVE_D3D_H @HAVE_D3D_H@ -#cmakedefine HAVE_D3D11_H @HAVE_D3D11_H@ -#cmakedefine HAVE_DDRAW_H @HAVE_DDRAW_H@ -#cmakedefine HAVE_DSOUND_H @HAVE_DSOUND_H@ -#cmakedefine HAVE_DINPUT_H @HAVE_DINPUT_H@ -#cmakedefine HAVE_XAUDIO2_H @HAVE_XAUDIO2_H@ -#cmakedefine HAVE_XINPUT_H @HAVE_XINPUT_H@ -#cmakedefine HAVE_DXGI_H @HAVE_DXGI_H@ -#cmakedefine HAVE_XINPUT_GAMEPAD_EX @HAVE_XINPUT_GAMEPAD_EX@ -#cmakedefine HAVE_XINPUT_STATE_EX @HAVE_XINPUT_STATE_EX@ - /* Comment this if you want to build without any C library requirements */ #cmakedefine HAVE_LIBC 1 #if HAVE_LIBC /* Useful headers */ -#cmakedefine HAVE_ALLOCA_H 1 -#cmakedefine HAVE_SYS_TYPES_H 1 -#cmakedefine HAVE_STDIO_H 1 #cmakedefine STDC_HEADERS 1 -#cmakedefine HAVE_STDLIB_H 1 -#cmakedefine HAVE_STDARG_H 1 +#cmakedefine HAVE_ALLOCA_H 1 +#cmakedefine HAVE_CTYPE_H 1 +#cmakedefine HAVE_FLOAT_H 1 +#cmakedefine HAVE_ICONV_H 1 +#cmakedefine HAVE_INTTYPES_H 1 +#cmakedefine HAVE_LIMITS_H 1 #cmakedefine HAVE_MALLOC_H 1 +#cmakedefine HAVE_MATH_H 1 #cmakedefine HAVE_MEMORY_H 1 -#cmakedefine HAVE_STRING_H 1 +#cmakedefine HAVE_SIGNAL_H 1 +#cmakedefine HAVE_STDARG_H 1 +#cmakedefine HAVE_STDINT_H 1 +#cmakedefine HAVE_STDIO_H 1 +#cmakedefine HAVE_STDLIB_H 1 #cmakedefine HAVE_STRINGS_H 1 +#cmakedefine HAVE_STRING_H 1 +#cmakedefine HAVE_SYS_TYPES_H 1 #cmakedefine HAVE_WCHAR_H 1 -#cmakedefine HAVE_INTTYPES_H 1 -#cmakedefine HAVE_STDINT_H 1 -#cmakedefine HAVE_CTYPE_H 1 -#cmakedefine HAVE_MATH_H 1 -#cmakedefine HAVE_ICONV_H 1 -#cmakedefine HAVE_SIGNAL_H 1 -#cmakedefine HAVE_ALTIVEC_H 1 #cmakedefine HAVE_PTHREAD_NP_H 1 -#cmakedefine HAVE_LIBUDEV_H 1 -#cmakedefine HAVE_DBUS_DBUS_H 1 -#cmakedefine HAVE_IBUS_IBUS_H 1 -#cmakedefine HAVE_FCITX_FRONTEND_H 1 -#cmakedefine HAVE_LIBSAMPLERATE_H 1 +#cmakedefine HAVE_LIBUNWIND_H 1 /* C library functions */ #cmakedefine HAVE_MALLOC 1 @@ -110,11 +96,13 @@ #cmakedefine HAVE_WCSLEN 1 #cmakedefine HAVE_WCSLCPY 1 #cmakedefine HAVE_WCSLCAT 1 +#cmakedefine HAVE_WCSDUP 1 +#cmakedefine HAVE_WCSSTR 1 #cmakedefine HAVE_WCSCMP 1 +#cmakedefine HAVE_WCSNCMP 1 #cmakedefine HAVE_STRLEN 1 #cmakedefine HAVE_STRLCPY 1 #cmakedefine HAVE_STRLCAT 1 -#cmakedefine HAVE_STRDUP 1 #cmakedefine HAVE__STRREV 1 #cmakedefine HAVE__STRUPR 1 #cmakedefine HAVE__STRLWR 1 @@ -123,6 +111,8 @@ #cmakedefine HAVE_STRCHR 1 #cmakedefine HAVE_STRRCHR 1 #cmakedefine HAVE_STRSTR 1 +#cmakedefine HAVE_STRTOK_R 1 +#cmakedefine HAVE_STRTOK_S 1 #cmakedefine HAVE_ITOA 1 #cmakedefine HAVE__LTOA 1 #cmakedefine HAVE__UITOA 1 @@ -142,22 +132,40 @@ #cmakedefine HAVE_STRCASECMP 1 #cmakedefine HAVE__STRNICMP 1 #cmakedefine HAVE_STRNCASECMP 1 +#cmakedefine HAVE_SSCANF 1 #cmakedefine HAVE_VSSCANF 1 #cmakedefine HAVE_VSNPRINTF 1 #cmakedefine HAVE_M_PI 1 -#cmakedefine HAVE_ATAN 1 -#cmakedefine HAVE_ATAN2 1 #cmakedefine HAVE_ACOS 1 +#cmakedefine HAVE_ACOSF 1 #cmakedefine HAVE_ASIN 1 +#cmakedefine HAVE_ASINF 1 +#cmakedefine HAVE_ATAN 1 +#cmakedefine HAVE_ATANF 1 +#cmakedefine HAVE_ATAN2 1 +#cmakedefine HAVE_ATAN2F 1 #cmakedefine HAVE_CEIL 1 +#cmakedefine HAVE_CEILF 1 #cmakedefine HAVE_COPYSIGN 1 +#cmakedefine HAVE_COPYSIGNF 1 #cmakedefine HAVE_COS 1 #cmakedefine HAVE_COSF 1 +#cmakedefine HAVE_EXP 1 +#cmakedefine HAVE_EXPF 1 #cmakedefine HAVE_FABS 1 +#cmakedefine HAVE_FABSF 1 #cmakedefine HAVE_FLOOR 1 +#cmakedefine HAVE_FLOORF 1 +#cmakedefine HAVE_FMOD 1 +#cmakedefine HAVE_FMODF 1 #cmakedefine HAVE_LOG 1 +#cmakedefine HAVE_LOGF 1 +#cmakedefine HAVE_LOG10 1 +#cmakedefine HAVE_LOG10F 1 #cmakedefine HAVE_POW 1 +#cmakedefine HAVE_POWF 1 #cmakedefine HAVE_SCALBN 1 +#cmakedefine HAVE_SCALBNF 1 #cmakedefine HAVE_SIN 1 #cmakedefine HAVE_SINF 1 #cmakedefine HAVE_SQRT 1 @@ -182,15 +190,39 @@ #cmakedefine HAVE_SEM_TIMEDWAIT 1 #cmakedefine HAVE_GETAUXVAL 1 #cmakedefine HAVE_POLL 1 +#cmakedefine HAVE__EXIT 1 #elif __WIN32__ #cmakedefine HAVE_STDARG_H 1 #cmakedefine HAVE_STDDEF_H 1 +#cmakedefine HAVE_FLOAT_H 1 #else /* We may need some replacement for stdarg.h here */ #include #endif /* HAVE_LIBC */ +#cmakedefine HAVE_ALTIVEC_H 1 +#cmakedefine HAVE_DBUS_DBUS_H 1 +#cmakedefine HAVE_FCITX_FRONTEND_H 1 +#cmakedefine HAVE_IBUS_IBUS_H 1 +#cmakedefine HAVE_IMMINTRIN_H 1 +#cmakedefine HAVE_LIBSAMPLERATE_H 1 +#cmakedefine HAVE_LIBUDEV_H 1 + +#cmakedefine HAVE_D3D_H @HAVE_D3D_H@ +#cmakedefine HAVE_D3D11_H @HAVE_D3D11_H@ +#cmakedefine HAVE_DDRAW_H @HAVE_DDRAW_H@ +#cmakedefine HAVE_DSOUND_H @HAVE_DSOUND_H@ +#cmakedefine HAVE_DINPUT_H @HAVE_DINPUT_H@ +#cmakedefine HAVE_XINPUT_H @HAVE_XINPUT_H@ +#cmakedefine HAVE_DXGI_H @HAVE_DXGI_H@ + +#cmakedefine HAVE_MMDEVICEAPI_H @HAVE_MMDEVICEAPI_H@ +#cmakedefine HAVE_AUDIOCLIENT_H @HAVE_AUDIOCLIENT_H@ + +#cmakedefine HAVE_XINPUT_GAMEPAD_EX @HAVE_XINPUT_GAMEPAD_EX@ +#cmakedefine HAVE_XINPUT_STATE_EX @HAVE_XINPUT_STATE_EX@ + /* SDL internal assertion support */ #cmakedefine SDL_DEFAULT_ASSERT_LEVEL @SDL_DEFAULT_ASSERT_LEVEL@ @@ -202,6 +234,7 @@ #cmakedefine SDL_FILE_DISABLED @SDL_FILE_DISABLED@ #cmakedefine SDL_JOYSTICK_DISABLED @SDL_JOYSTICK_DISABLED@ #cmakedefine SDL_HAPTIC_DISABLED @SDL_HAPTIC_DISABLED@ +#cmakedefine SDL_SENSOR_DISABLED @SDL_SENSOR_DISABLED@ #cmakedefine SDL_LOADSO_DISABLED @SDL_LOADSO_DISABLED@ #cmakedefine SDL_RENDER_DISABLED @SDL_RENDER_DISABLED@ #cmakedefine SDL_THREADS_DISABLED @SDL_THREADS_DISABLED@ @@ -242,7 +275,6 @@ #cmakedefine SDL_AUDIO_DRIVER_SUNAUDIO @SDL_AUDIO_DRIVER_SUNAUDIO@ #cmakedefine SDL_AUDIO_DRIVER_WASAPI @SDL_AUDIO_DRIVER_WASAPI@ #cmakedefine SDL_AUDIO_DRIVER_WINMM @SDL_AUDIO_DRIVER_WINMM@ -#cmakedefine SDL_AUDIO_DRIVER_XAUDIO2 @SDL_AUDIO_DRIVER_XAUDIO2@ /* Enable various input drivers */ #cmakedefine SDL_INPUT_LINUXEV @SDL_INPUT_LINUXEV@ @@ -259,6 +291,7 @@ #cmakedefine SDL_JOYSTICK_WINMM @SDL_JOYSTICK_WINMM@ #cmakedefine SDL_JOYSTICK_USBHID @SDL_JOYSTICK_USBHID@ #cmakedefine SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H @SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H@ +#cmakedefine SDL_JOYSTICK_HIDAPI @SDL_JOYSTICK_HIDAPI@ #cmakedefine SDL_JOYSTICK_EMSCRIPTEN @SDL_JOYSTICK_EMSCRIPTEN@ #cmakedefine SDL_HAPTIC_DUMMY @SDL_HAPTIC_DUMMY@ #cmakedefine SDL_HAPTIC_LINUX @SDL_HAPTIC_LINUX@ @@ -266,6 +299,12 @@ #cmakedefine SDL_HAPTIC_DINPUT @SDL_HAPTIC_DINPUT@ #cmakedefine SDL_HAPTIC_XINPUT @SDL_HAPTIC_XINPUT@ #cmakedefine SDL_HAPTIC_ANDROID @SDL_HAPTIC_ANDROID@ +#cmakedefine SDL_LIBUSB_DYNAMIC @SDL_LIBUSB_DYNAMIC@ + +/* Enable various sensor drivers */ +#cmakedefine SDL_SENSOR_ANDROID @SDL_SENSOR_ANDROID@ +#cmakedefine SDL_SENSOR_COREMOTION @SDL_SENSOR_COREMOTION@ +#cmakedefine SDL_SENSOR_DUMMY @SDL_SENSOR_DUMMY@ /* Enable various shared object loading systems */ #cmakedefine SDL_LOADSO_DLOPEN @SDL_LOADSO_DLOPEN@ @@ -290,9 +329,11 @@ #cmakedefine SDL_VIDEO_DRIVER_ANDROID @SDL_VIDEO_DRIVER_ANDROID@ #cmakedefine SDL_VIDEO_DRIVER_HAIKU @SDL_VIDEO_DRIVER_HAIKU@ #cmakedefine SDL_VIDEO_DRIVER_COCOA @SDL_VIDEO_DRIVER_COCOA@ +#cmakedefine SDL_VIDEO_DRIVER_UIKIT @SDL_VIDEO_DRIVER_UIKIT@ #cmakedefine SDL_VIDEO_DRIVER_DIRECTFB @SDL_VIDEO_DRIVER_DIRECTFB@ #cmakedefine SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC @SDL_VIDEO_DRIVER_DIRECTFB_DYNAMIC@ #cmakedefine SDL_VIDEO_DRIVER_DUMMY @SDL_VIDEO_DRIVER_DUMMY@ +#cmakedefine SDL_VIDEO_DRIVER_OFFSCREEN @SDL_VIDEO_DRIVER_OFFSCREEN@ #cmakedefine SDL_VIDEO_DRIVER_WINDOWS @SDL_VIDEO_DRIVER_WINDOWS@ #cmakedefine SDL_VIDEO_DRIVER_WAYLAND @SDL_VIDEO_DRIVER_WAYLAND@ #cmakedefine SDL_VIDEO_DRIVER_RPI @SDL_VIDEO_DRIVER_RPI@ @@ -309,9 +350,6 @@ #cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR@ #cmakedefine SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON @SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON@ -#cmakedefine SDL_VIDEO_DRIVER_MIR @SDL_VIDEO_DRIVER_MIR@ -#cmakedefine SDL_VIDEO_DRIVER_MIR_DYNAMIC @SDL_VIDEO_DRIVER_MIR_DYNAMIC@ -#cmakedefine SDL_VIDEO_DRIVER_MIR_DYNAMIC_XKBCOMMON @SDL_VIDEO_DRIVER_MIR_DYNAMIC_XKBCOMMON@ #cmakedefine SDL_VIDEO_DRIVER_EMSCRIPTEN @SDL_VIDEO_DRIVER_EMSCRIPTEN@ #cmakedefine SDL_VIDEO_DRIVER_X11 @SDL_VIDEO_DRIVER_X11@ #cmakedefine SDL_VIDEO_DRIVER_X11_DYNAMIC @SDL_VIDEO_DRIVER_X11_DYNAMIC@ @@ -341,6 +379,7 @@ #cmakedefine SDL_VIDEO_RENDER_OGL_ES @SDL_VIDEO_RENDER_OGL_ES@ #cmakedefine SDL_VIDEO_RENDER_OGL_ES2 @SDL_VIDEO_RENDER_OGL_ES2@ #cmakedefine SDL_VIDEO_RENDER_DIRECTFB @SDL_VIDEO_RENDER_DIRECTFB@ +#cmakedefine SDL_VIDEO_RENDER_METAL @SDL_VIDEO_RENDER_METAL@ /* Enable OpenGL support */ #cmakedefine SDL_VIDEO_OPENGL @SDL_VIDEO_OPENGL@ @@ -357,11 +396,15 @@ /* Enable Vulkan support */ #cmakedefine SDL_VIDEO_VULKAN @SDL_VIDEO_VULKAN@ +/* Enable Metal support */ +#cmakedefine SDL_VIDEO_METAL @SDL_VIDEO_METAL@ + /* Enable system power support */ #cmakedefine SDL_POWER_ANDROID @SDL_POWER_ANDROID@ #cmakedefine SDL_POWER_LINUX @SDL_POWER_LINUX@ #cmakedefine SDL_POWER_WINDOWS @SDL_POWER_WINDOWS@ #cmakedefine SDL_POWER_MACOSX @SDL_POWER_MACOSX@ +#cmakedefine SDL_POWER_UIKIT @SDL_POWER_UIKIT@ #cmakedefine SDL_POWER_HAIKU @SDL_POWER_HAIKU@ #cmakedefine SDL_POWER_EMSCRIPTEN @SDL_POWER_EMSCRIPTEN@ #cmakedefine SDL_POWER_HARDWIRED @SDL_POWER_HARDWIRED@ @@ -378,11 +421,16 @@ /* Enable assembly routines */ #cmakedefine SDL_ASSEMBLY_ROUTINES @SDL_ASSEMBLY_ROUTINES@ #cmakedefine SDL_ALTIVEC_BLITTERS @SDL_ALTIVEC_BLITTERS@ +#cmakedefine SDL_ARM_SIMD_BLITTERS @SDL_ARM_SIMD_BLITTERS@ +#cmakedefine SDL_ARM_NEON_BLITTERS @SDL_ARM_NEON_BLITTERS@ /* Enable dynamic libsamplerate support */ #cmakedefine SDL_LIBSAMPLERATE_DYNAMIC @SDL_LIBSAMPLERATE_DYNAMIC@ /* Platform specific definitions */ +#cmakedefine SDL_IPHONE_KEYBOARD @SDL_IPHONE_KEYBOARD@ +#cmakedefine SDL_IPHONE_LAUNCHSCREEN @SDL_IPHONE_LAUNCHSCREEN@ + #if !defined(__WIN32__) # if !defined(_STDINT_H_) && !defined(_STDINT_H) && !defined(HAVE_STDINT_H) && !defined(_HAVE_STDINT_H) typedef unsigned int size_t; diff --git a/lib/SDL2/include/SDL_config.h.in b/lib/SDL2/include/SDL_config.h.in index 8b3d20880b..f769e3cf43 100644 --- a/lib/SDL2/include/SDL_config.h.in +++ b/lib/SDL2/include/SDL_config.h.in @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -33,7 +33,7 @@ /* Make sure that this isn't included by Visual C++ */ #ifdef _MSC_VER -#error You should run hg revert SDL_config.h +#error You should run hg revert SDL_config.h #endif /* C language features */ @@ -50,43 +50,32 @@ #undef HAVE_GCC_ATOMICS #undef HAVE_GCC_SYNC_LOCK_TEST_AND_SET -#undef HAVE_DDRAW_H -#undef HAVE_DINPUT_H -#undef HAVE_DSOUND_H -#undef HAVE_DXGI_H -#undef HAVE_XINPUT_H -#undef HAVE_XINPUT_GAMEPAD_EX -#undef HAVE_XINPUT_STATE_EX - /* Comment this if you want to build without any C library requirements */ #undef HAVE_LIBC #if HAVE_LIBC /* Useful headers */ -#undef HAVE_ALLOCA_H -#undef HAVE_SYS_TYPES_H -#undef HAVE_STDIO_H #undef STDC_HEADERS -#undef HAVE_STDLIB_H -#undef HAVE_STDARG_H +#undef HAVE_ALLOCA_H +#undef HAVE_CTYPE_H +#undef HAVE_FLOAT_H +#undef HAVE_ICONV_H +#undef HAVE_INTTYPES_H +#undef HAVE_LIMITS_H #undef HAVE_MALLOC_H +#undef HAVE_MATH_H #undef HAVE_MEMORY_H -#undef HAVE_STRING_H +#undef HAVE_SIGNAL_H +#undef HAVE_STDARG_H +#undef HAVE_STDINT_H +#undef HAVE_STDIO_H +#undef HAVE_STDLIB_H #undef HAVE_STRINGS_H +#undef HAVE_STRING_H +#undef HAVE_SYS_TYPES_H #undef HAVE_WCHAR_H -#undef HAVE_INTTYPES_H -#undef HAVE_STDINT_H -#undef HAVE_CTYPE_H -#undef HAVE_MATH_H -#undef HAVE_ICONV_H -#undef HAVE_SIGNAL_H -#undef HAVE_ALTIVEC_H #undef HAVE_PTHREAD_NP_H -#undef HAVE_LIBUDEV_H -#undef HAVE_DBUS_DBUS_H -#undef HAVE_IBUS_IBUS_H -#undef HAVE_FCITX_FRONTEND_H -#undef HAVE_LIBSAMPLERATE_H +#undef HAVE_LIBUNWIND_H /* C library functions */ #undef HAVE_MALLOC @@ -110,11 +99,13 @@ #undef HAVE_WCSLEN #undef HAVE_WCSLCPY #undef HAVE_WCSLCAT +#undef HAVE_WCSDUP +#undef HAVE_WCSSTR #undef HAVE_WCSCMP +#undef HAVE_WCSNCMP #undef HAVE_STRLEN #undef HAVE_STRLCPY #undef HAVE_STRLCAT -#undef HAVE_STRDUP #undef HAVE__STRREV #undef HAVE__STRUPR #undef HAVE__STRLWR @@ -123,6 +114,8 @@ #undef HAVE_STRCHR #undef HAVE_STRRCHR #undef HAVE_STRSTR +#undef HAVE_STRTOK_R +#undef HAVE_STRTOK_S #undef HAVE_ITOA #undef HAVE__LTOA #undef HAVE__UITOA @@ -147,19 +140,36 @@ #undef HAVE_SNPRINTF #undef HAVE_VSNPRINTF #undef HAVE_M_PI -#undef HAVE_ATAN -#undef HAVE_ATAN2 #undef HAVE_ACOS +#undef HAVE_ACOSF #undef HAVE_ASIN +#undef HAVE_ASINF +#undef HAVE_ATAN +#undef HAVE_ATANF +#undef HAVE_ATAN2 +#undef HAVE_ATAN2F #undef HAVE_CEIL +#undef HAVE_CEILF #undef HAVE_COPYSIGN +#undef HAVE_COPYSIGNF #undef HAVE_COS #undef HAVE_COSF +#undef HAVE_EXP +#undef HAVE_EXPF #undef HAVE_FABS +#undef HAVE_FABSF #undef HAVE_FLOOR +#undef HAVE_FLOORF +#undef HAVE_FMOD +#undef HAVE_FMODF #undef HAVE_LOG +#undef HAVE_LOGF +#undef HAVE_LOG10 +#undef HAVE_LOG10F #undef HAVE_POW +#undef HAVE_POWF #undef HAVE_SCALBN +#undef HAVE_SCALBNF #undef HAVE_SIN #undef HAVE_SINF #undef HAVE_SQRT @@ -184,13 +194,32 @@ #undef HAVE_SEM_TIMEDWAIT #undef HAVE_GETAUXVAL #undef HAVE_POLL +#undef HAVE__EXIT #else -#define HAVE_STDARG_H 1 -#define HAVE_STDDEF_H 1 -#define HAVE_STDINT_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_STDINT_H 1 #endif /* HAVE_LIBC */ +#undef HAVE_ALTIVEC_H +#undef HAVE_DBUS_DBUS_H +#undef HAVE_FCITX_FRONTEND_H +#undef HAVE_IBUS_IBUS_H +#undef HAVE_IMMINTRIN_H +#undef HAVE_LIBSAMPLERATE_H +#undef HAVE_LIBUDEV_H + +#undef HAVE_DDRAW_H +#undef HAVE_DINPUT_H +#undef HAVE_DSOUND_H +#undef HAVE_DXGI_H +#undef HAVE_XINPUT_H +#undef HAVE_MMDEVICEAPI_H +#undef HAVE_AUDIOCLIENT_H +#undef HAVE_XINPUT_GAMEPAD_EX +#undef HAVE_XINPUT_STATE_EX + /* SDL internal assertion support */ #undef SDL_DEFAULT_ASSERT_LEVEL @@ -202,6 +231,7 @@ #undef SDL_FILE_DISABLED #undef SDL_JOYSTICK_DISABLED #undef SDL_HAPTIC_DISABLED +#undef SDL_SENSOR_DISABLED #undef SDL_LOADSO_DISABLED #undef SDL_RENDER_DISABLED #undef SDL_THREADS_DISABLED @@ -243,7 +273,6 @@ #undef SDL_AUDIO_DRIVER_SUNAUDIO #undef SDL_AUDIO_DRIVER_WASAPI #undef SDL_AUDIO_DRIVER_WINMM -#undef SDL_AUDIO_DRIVER_XAUDIO2 /* Enable various input drivers */ #undef SDL_INPUT_LINUXEV @@ -259,13 +288,19 @@ #undef SDL_JOYSTICK_WINMM #undef SDL_JOYSTICK_USBHID #undef SDL_JOYSTICK_USBHID_MACHINE_JOYSTICK_H +#undef SDL_JOYSTICK_HIDAPI #undef SDL_JOYSTICK_EMSCRIPTEN #undef SDL_HAPTIC_DUMMY +#undef SDL_HAPTIC_ANDROID #undef SDL_HAPTIC_LINUX #undef SDL_HAPTIC_IOKIT #undef SDL_HAPTIC_DINPUT #undef SDL_HAPTIC_XINPUT +/* Enable various sensor drivers */ +#undef SDL_SENSOR_ANDROID +#undef SDL_SENSOR_DUMMY + /* Enable various shared object loading systems */ #undef SDL_LOADSO_DLOPEN #undef SDL_LOADSO_DUMMY @@ -297,9 +332,6 @@ #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_CURSOR #undef SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_XKBCOMMON -#undef SDL_VIDEO_DRIVER_MIR -#undef SDL_VIDEO_DRIVER_MIR_DYNAMIC -#undef SDL_VIDEO_DRIVER_MIR_DYNAMIC_XKBCOMMON #undef SDL_VIDEO_DRIVER_X11 #undef SDL_VIDEO_DRIVER_RPI #undef SDL_VIDEO_DRIVER_KMSDRM @@ -338,6 +370,7 @@ #undef SDL_VIDEO_RENDER_OGL_ES #undef SDL_VIDEO_RENDER_OGL_ES2 #undef SDL_VIDEO_RENDER_DIRECTFB +#undef SDL_VIDEO_RENDER_METAL /* Enable OpenGL support */ #undef SDL_VIDEO_OPENGL @@ -354,6 +387,9 @@ /* Enable Vulkan support */ #undef SDL_VIDEO_VULKAN +/* Enable Metal support */ +#undef SDL_VIDEO_METAL + /* Enable system power support */ #undef SDL_POWER_LINUX #undef SDL_POWER_WINDOWS @@ -376,6 +412,8 @@ /* Enable assembly routines */ #undef SDL_ASSEMBLY_ROUTINES #undef SDL_ALTIVEC_BLITTERS +#undef SDL_ARM_SIMD_BLITTERS +#undef SDL_ARM_NEON_BLITTERS /* Enable ime support */ #undef SDL_USE_IME @@ -383,6 +421,9 @@ /* Enable dynamic udev support */ #undef SDL_UDEV_DYNAMIC +/* Enable dynamic libusb support */ +#undef SDL_LIBUSB_DYNAMIC + /* Enable dynamic libsamplerate support */ #undef SDL_LIBSAMPLERATE_DYNAMIC diff --git a/lib/SDL2/include/SDL_config_android.h b/lib/SDL2/include/SDL_config_android.h index 361bad8b77..d057e17644 100644 --- a/lib/SDL2/include/SDL_config_android.h +++ b/lib/SDL2/include/SDL_config_android.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -35,16 +35,17 @@ #define HAVE_GCC_ATOMICS 1 -#define HAVE_ALLOCA_H 1 -#define HAVE_SYS_TYPES_H 1 -#define HAVE_STDIO_H 1 #define STDC_HEADERS 1 -#define HAVE_STRING_H 1 -#define HAVE_INTTYPES_H 1 -#define HAVE_STDINT_H 1 +#define HAVE_ALLOCA_H 1 #define HAVE_CTYPE_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 #define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 /* C library functions */ #define HAVE_MALLOC 1 @@ -67,10 +68,10 @@ #define HAVE_STRLEN 1 #define HAVE_STRLCPY 1 #define HAVE_STRLCAT 1 -#define HAVE_STRDUP 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOLL 1 @@ -84,20 +85,36 @@ #define HAVE_STRNCASECMP 1 #define HAVE_VSSCANF 1 #define HAVE_VSNPRINTF 1 -#define HAVE_M_PI 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 #define HAVE_ATAN 1 +#define HAVE_ATANF 1 #define HAVE_ATAN2 1 -#define HAVE_ACOS 1 -#define HAVE_ASIN 1 +#define HAVE_ATAN2F 1 #define HAVE_CEIL 1 +#define HAVE_CEILF 1 #define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 #define HAVE_COS 1 #define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 #define HAVE_FABS 1 +#define HAVE_FABSF 1 #define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 #define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 #define HAVE_POW 1 +#define HAVE_POWF 1 #define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 #define HAVE_SIN 1 #define HAVE_SINF 1 #define HAVE_SQRT 1 @@ -108,18 +125,23 @@ #define HAVE_SETJMP 1 #define HAVE_NANOSLEEP 1 #define HAVE_SYSCONF 1 -#define HAVE_CLOCK_GETTIME 1 +#define HAVE_CLOCK_GETTIME 1 #define SIZEOF_VOIDP 4 /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_ANDROID 1 +#define SDL_AUDIO_DRIVER_OPENSLES 1 #define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable various input drivers */ #define SDL_JOYSTICK_ANDROID 1 +#define SDL_JOYSTICK_HIDAPI 1 #define SDL_HAPTIC_ANDROID 1 +/* Enable sensor driver */ +#define SDL_SENSOR_ANDROID 1 + /* Enable various shared object loading systems */ #define SDL_LOADSO_DLOPEN 1 diff --git a/lib/SDL2/include/SDL_config_iphoneos.h b/lib/SDL2/include/SDL_config_iphoneos.h index deea030466..38929a8b3a 100644 --- a/lib/SDL2/include/SDL_config_iphoneos.h +++ b/lib/SDL2/include/SDL_config_iphoneos.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -33,16 +33,19 @@ #define HAVE_GCC_ATOMICS 1 -#define HAVE_ALLOCA_H 1 -#define HAVE_SYS_TYPES_H 1 -#define HAVE_STDIO_H 1 #define STDC_HEADERS 1 -#define HAVE_STRING_H 1 -#define HAVE_INTTYPES_H 1 -#define HAVE_STDINT_H 1 +#define HAVE_ALLOCA_H 1 #define HAVE_CTYPE_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 #define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 +/* The libunwind functions are only available on x86 */ +/* #undef HAVE_LIBUNWIND_H */ /* C library functions */ #define HAVE_MALLOC 1 @@ -65,10 +68,10 @@ #define HAVE_STRLEN 1 #define HAVE_STRLCPY 1 #define HAVE_STRLCAT 1 -#define HAVE_STRDUP 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOLL 1 @@ -83,19 +86,36 @@ #define HAVE_VSSCANF 1 #define HAVE_VSNPRINTF 1 #define HAVE_M_PI 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 #define HAVE_ATAN 1 +#define HAVE_ATANF 1 #define HAVE_ATAN2 1 -#define HAVE_ACOS 1 -#define HAVE_ASIN 1 +#define HAVE_ATAN2F 1 #define HAVE_CEIL 1 +#define HAVE_CEILF 1 #define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 #define HAVE_COS 1 #define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 #define HAVE_FABS 1 +#define HAVE_FABSF 1 #define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 #define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 #define HAVE_POW 1 +#define HAVE_POWF 1 #define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 #define HAVE_SIN 1 #define HAVE_SINF 1 #define HAVE_SQRT 1 @@ -118,6 +138,14 @@ /* Enable MFi joystick support */ #define SDL_JOYSTICK_MFI 1 +#define SDL_JOYSTICK_HIDAPI 1 + +#ifdef __TVOS__ +#define SDL_SENSOR_DUMMY 1 +#else +/* Enable the CoreMotion sensor driver */ +#define SDL_SENSOR_COREMOTION 1 +#endif /* Enable Unix style SO loading */ #define SDL_LOADSO_DLOPEN 1 @@ -133,17 +161,29 @@ #define SDL_VIDEO_DRIVER_UIKIT 1 #define SDL_VIDEO_DRIVER_DUMMY 1 -/* enable OpenGL ES */ +/* Enable OpenGL ES */ #define SDL_VIDEO_OPENGL_ES2 1 #define SDL_VIDEO_OPENGL_ES 1 #define SDL_VIDEO_RENDER_OGL_ES 1 #define SDL_VIDEO_RENDER_OGL_ES2 1 -/* Enable Vulkan support */ -#if !TARGET_OS_SIMULATOR && !TARGET_CPU_ARM // Only 64-bit devices have Metal -#define SDL_VIDEO_VULKAN 1 +/* Metal supported on 64-bit devices running iOS 8.0 and tvOS 9.0 and newer */ +#if !TARGET_OS_SIMULATOR && !TARGET_CPU_ARM && ((__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 90000)) +#define SDL_PLATFORM_SUPPORTS_METAL 1 #else -#define SDL_VIDEO_VULKAN 0 +#define SDL_PLATFORM_SUPPORTS_METAL 0 +#endif + +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_RENDER_METAL 1 +#endif + +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_VULKAN 1 +#endif + +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_METAL 1 #endif /* Enable system power support */ diff --git a/lib/SDL2/include/SDL_config_macosx.h b/lib/SDL2/include/SDL_config_macosx.h index 9b09899529..114134593c 100644 --- a/lib/SDL2/include/SDL_config_macosx.h +++ b/lib/SDL2/include/SDL_config_macosx.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -37,16 +37,19 @@ #endif /* Useful headers */ -#define HAVE_ALLOCA_H 1 -#define HAVE_SYS_TYPES_H 1 -#define HAVE_STDIO_H 1 #define STDC_HEADERS 1 -#define HAVE_STRING_H 1 -#define HAVE_INTTYPES_H 1 -#define HAVE_STDINT_H 1 +#define HAVE_ALLOCA_H 1 #define HAVE_CTYPE_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 #define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 +#define HAVE_LIBUNWIND_H 1 /* C library functions */ #define HAVE_MALLOC 1 @@ -68,10 +71,10 @@ #define HAVE_STRLEN 1 #define HAVE_STRLCPY 1 #define HAVE_STRLCAT 1 -#define HAVE_STRDUP 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOLL 1 @@ -85,15 +88,37 @@ #define HAVE_STRNCASECMP 1 #define HAVE_VSSCANF 1 #define HAVE_VSNPRINTF 1 +#define HAVE_M_PI 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 #define HAVE_CEIL 1 +#define HAVE_CEILF 1 #define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 #define HAVE_COS 1 #define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 #define HAVE_FABS 1 +#define HAVE_FABSF 1 #define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 #define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 #define HAVE_POW 1 +#define HAVE_POWF 1 #define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 #define HAVE_SIN 1 #define HAVE_SINF 1 #define HAVE_SQRT 1 @@ -105,10 +130,8 @@ #define HAVE_NANOSLEEP 1 #define HAVE_SYSCONF 1 #define HAVE_SYSCTLBYNAME 1 -#define HAVE_ATAN 1 -#define HAVE_ATAN2 1 -#define HAVE_ACOS 1 -#define HAVE_ASIN 1 + +#define HAVE_GCC_ATOMICS 1 /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_COREAUDIO 1 @@ -117,8 +140,12 @@ /* Enable various input drivers */ #define SDL_JOYSTICK_IOKIT 1 +#define SDL_JOYSTICK_HIDAPI 1 #define SDL_HAPTIC_IOKIT 1 +/* Enable the dummy sensor driver */ +#define SDL_SENSOR_DUMMY 1 + /* Enable various shared object loading systems */ #define SDL_LOADSO_DLOPEN 1 @@ -133,13 +160,13 @@ #define SDL_VIDEO_DRIVER_COCOA 1 #define SDL_VIDEO_DRIVER_DUMMY 1 #undef SDL_VIDEO_DRIVER_X11 -#define SDL_VIDEO_DRIVER_X11_DYNAMIC "/usr/X11R6/lib/libX11.6.dylib" -#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT "/usr/X11R6/lib/libXext.6.dylib" -#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA "/usr/X11R6/lib/libXinerama.1.dylib" -#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 "/usr/X11R6/lib/libXi.6.dylib" -#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR "/usr/X11R6/lib/libXrandr.2.dylib" -#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS "/usr/X11R6/lib/libXss.1.dylib" -#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE "/usr/X11R6/lib/libXxf86vm.1.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC "/opt/X11/lib/libX11.6.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT "/opt/X11/lib/libXext.6.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA "/opt/X11/lib/libXinerama.1.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2 "/opt/X11/lib/libXi.6.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR "/opt/X11/lib/libXrandr.2.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS "/opt/X11/lib/libXss.1.dylib" +#define SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE "/opt/X11/lib/libXxf86vm.1.dylib" #define SDL_VIDEO_DRIVER_X11_XDBE 1 #define SDL_VIDEO_DRIVER_X11_XINERAMA 1 #define SDL_VIDEO_DRIVER_X11_XRANDR 1 @@ -163,10 +190,35 @@ #define SDL_VIDEO_RENDER_OGL 1 #endif +#ifndef SDL_VIDEO_RENDER_OGL_ES2 +#define SDL_VIDEO_RENDER_OGL_ES2 1 +#endif + +/* Metal only supported on 64-bit architectures with 10.11+ */ +#if TARGET_CPU_X86_64 && (MAC_OS_X_VERSION_MAX_ALLOWED >= 101100) +#define SDL_PLATFORM_SUPPORTS_METAL 1 +#else +#define SDL_PLATFORM_SUPPORTS_METAL 0 +#endif + +#ifndef SDL_VIDEO_RENDER_METAL +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_RENDER_METAL 1 +#else +#define SDL_VIDEO_RENDER_METAL 0 +#endif +#endif + /* Enable OpenGL support */ #ifndef SDL_VIDEO_OPENGL #define SDL_VIDEO_OPENGL 1 #endif +#ifndef SDL_VIDEO_OPENGL_ES2 +#define SDL_VIDEO_OPENGL_ES2 1 +#endif +#ifndef SDL_VIDEO_OPENGL_EGL +#define SDL_VIDEO_OPENGL_EGL 1 +#endif #ifndef SDL_VIDEO_OPENGL_CGL #define SDL_VIDEO_OPENGL_CGL 1 #endif @@ -174,12 +226,21 @@ #define SDL_VIDEO_OPENGL_GLX 1 #endif -/* Enable Vulkan support */ -/* Metal/MoltenVK/Vulkan only supported on 64-bit architectures with 10.11+ */ -#if TARGET_CPU_X86_64 && (MAC_OS_X_VERSION_MAX_ALLOWED >= 101100) +/* Enable Vulkan and Metal support */ +#ifndef SDL_VIDEO_VULKAN +#if SDL_PLATFORM_SUPPORTS_METAL #define SDL_VIDEO_VULKAN 1 #else -#define SDL_VIDEO_VULKAN 0 +#define SDL_VIDEO_VULKAN 0 +#endif +#endif + +#ifndef SDL_VIDEO_METAL +#if SDL_PLATFORM_SUPPORTS_METAL +#define SDL_VIDEO_METAL 1 +#else +#define SDL_VIDEO_METAL 0 +#endif #endif /* Enable system power support */ diff --git a/lib/SDL2/include/SDL_config_minimal.h b/lib/SDL2/include/SDL_config_minimal.h index 31127006c5..b9c39584fc 100644 --- a/lib/SDL2/include/SDL_config_minimal.h +++ b/lib/SDL2/include/SDL_config_minimal.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -64,6 +64,9 @@ typedef unsigned long uintptr_t; /* Enable the stub haptic driver (src/haptic/dummy/\*.c) */ #define SDL_HAPTIC_DISABLED 1 +/* Enable the stub sensor driver (src/sensor/dummy/\*.c) */ +#define SDL_SENSOR_DISABLED 1 + /* Enable the stub shared object loader (src/loadso/dummy/\*.c) */ #define SDL_LOADSO_DISABLED 1 diff --git a/lib/SDL2/include/SDL_config_os2.h b/lib/SDL2/include/SDL_config_os2.h new file mode 100644 index 0000000000..f5799dce97 --- /dev/null +++ b/lib/SDL2/include/SDL_config_os2.h @@ -0,0 +1,180 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2020 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +#ifndef SDL_config_os2_h_ +#define SDL_config_os2_h_ +#define SDL_config_h_ + +#include "SDL_platform.h" + +#define SDL_AUDIO_DRIVER_DUMMY 1 +#define SDL_AUDIO_DRIVER_DISK 1 + +#define SDL_POWER_DISABLED 1 +#define SDL_JOYSTICK_DISABLED 1 +#define SDL_HAPTIC_DISABLED 1 +/*#undef SDL_JOYSTICK_HIDAPI */ + +#define SDL_SENSOR_DUMMY 1 +#define SDL_VIDEO_DRIVER_DUMMY 1 + +/* Enable OpenGL support */ +/* #undef SDL_VIDEO_OPENGL */ + +/* Enable Vulkan support */ +/* #undef SDL_VIDEO_VULKAN */ + +#define SDL_LOADSO_DISABLED 1 +#define SDL_THREADS_DISABLED 1 +#define SDL_TIMERS_DISABLED 1 +#define SDL_FILESYSTEM_DUMMY 1 + +/* Enable assembly routines */ +#define SDL_ASSEMBLY_ROUTINES 1 + +/* #undef HAVE_LIBSAMPLERATE_H */ + +/* Enable dynamic libsamplerate support */ +/* #undef SDL_LIBSAMPLERATE_DYNAMIC */ + +#define HAVE_LIBC 1 + +#define HAVE_SYS_TYPES_H 1 +#define HAVE_STDIO_H 1 +#define STDC_HEADERS 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_STDDEF_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MEMORY_H 1 +#define HAVE_STRING_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_WCHAR_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_CTYPE_H 1 +#define HAVE_MATH_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_SIGNAL_H 1 + +#define HAVE_MALLOC 1 +#define HAVE_CALLOC 1 +#define HAVE_REALLOC 1 +#define HAVE_FREE 1 +#if defined(__WATCOMC__) +#define HAVE__FSEEKI64 1 +#define HAVE__FTELLI64 1 +#endif +#define HAVE_ALLOCA 1 +#define HAVE_GETENV 1 +#define HAVE_SETENV 1 +#define HAVE_PUTENV 1 +#define HAVE_QSORT 1 +#define HAVE_ABS 1 +#define HAVE_BCOPY 1 +#define HAVE_MEMSET 1 +#define HAVE_MEMCPY 1 +#define HAVE_MEMMOVE 1 +#define HAVE_MEMCMP 1 +#define HAVE_WCSLEN 1 +#define HAVE_WCSLCPY 1 +#define HAVE_WCSLCAT 1 +#define HAVE_WCSCMP 1 +#define HAVE_STRLEN 1 +#define HAVE_STRLCPY 1 +#define HAVE_STRLCAT 1 +#define HAVE__STRREV 1 +#define HAVE__STRUPR 1 +#define HAVE__STRLWR 1 +#define HAVE_INDEX 1 +#define HAVE_RINDEX 1 +#define HAVE_STRCHR 1 +#define HAVE_STRRCHR 1 +#define HAVE_STRSTR 1 +/* #undef HAVE_STRTOK_R */ +#define HAVE_ITOA 1 +#define HAVE__LTOA 1 +#define HAVE__ULTOA 1 +#define HAVE_STRTOL 1 +#define HAVE_STRTOUL 1 +#define HAVE__I64TOA 1 +#define HAVE__UI64TOA 1 +#define HAVE_STRTOLL 1 +#define HAVE_STRTOULL 1 +#define HAVE_STRTOD 1 +#define HAVE_ATOI 1 +#define HAVE_ATOF 1 +#define HAVE_WCSLEN 1 +#define HAVE_WCSLCPY 1 +#define HAVE_WCSLCAT 1 +/* #define HAVE_WCSDUP 1 */ +/* #define wcsdup _wcsdup */ +#define HAVE_WCSSTR 1 +#define HAVE_WCSCMP 1 +#define HAVE_WCSNCMP 1 +#define HAVE_STRCMP 1 +#define HAVE_STRNCMP 1 +#define HAVE_STRICMP 1 +#define HAVE_STRCASECMP 1 +#define HAVE_STRNCASECMP 1 +#define HAVE_SSCANF 1 +#define HAVE_VSSCANF 1 +#define HAVE_SNPRINTF 1 +#define HAVE_VSNPRINTF 1 +#define HAVE_SETJMP 1 +#define HAVE_ACOS 1 +/* #undef HAVE_ACOSF */ +#define HAVE_ASIN 1 +/* #undef HAVE_ASINF */ +#define HAVE_ATAN 1 +#define HAVE_ATAN2 1 +/* #undef HAVE_ATAN2F */ +#define HAVE_CEIL 1 +/* #undef HAVE_CEILF */ +/* #undef HAVE_COPYSIGN */ +/* #undef HAVE_COPYSIGNF */ +#define HAVE_COS 1 +/* #undef HAVE_COSF */ +#define HAVE_EXP 1 +/* #undef HAVE_EXPF */ +#define HAVE_FABS 1 +/* #undef HAVE_FABSF */ +#define HAVE_FLOOR 1 +/* #undef HAVE_FLOORF */ +#define HAVE_FMOD 1 +/* #undef HAVE_FMODF */ +#define HAVE_LOG 1 +/* #undef HAVE_LOGF */ +#define HAVE_LOG10 1 +/* #undef HAVE_LOG10F */ +#define HAVE_POW 1 +/* #undef HAVE_POWF */ +#define HAVE_SIN 1 +/* #undef HAVE_SINF */ +/* #undef HAVE_SCALBN */ +/* #undef HAVE_SCALBNF */ +#define HAVE_SQRT 1 +/* #undef HAVE_SQRTF */ +#define HAVE_TAN 1 +/* #undef HAVE_TANF */ + +#endif /* SDL_config_os2_h_ */ diff --git a/lib/SDL2/include/SDL_config_pandora.h b/lib/SDL2/include/SDL_config_pandora.h index ea62fe59ac..bdc64c97c7 100644 --- a/lib/SDL2/include/SDL_config_pandora.h +++ b/lib/SDL2/include/SDL_config_pandora.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -36,22 +36,24 @@ #define SDL_BYTEORDER 1234 -#define HAVE_ALLOCA_H 1 -#define HAVE_SYS_TYPES_H 1 -#define HAVE_STDIO_H 1 #define STDC_HEADERS 1 -#define HAVE_STDLIB_H 1 -#define HAVE_STDARG_H 1 -#define HAVE_MALLOC_H 1 -#define HAVE_MEMORY_H 1 -#define HAVE_STRING_H 1 -#define HAVE_STRINGS_H 1 -#define HAVE_INTTYPES_H 1 -#define HAVE_STDINT_H 1 +#define HAVE_ALLOCA_H 1 #define HAVE_CTYPE_H 1 -#define HAVE_MATH_H 1 #define HAVE_ICONV_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MATH_H 1 +#define HAVE_MEMORY_H 1 #define HAVE_SIGNAL_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 + #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 @@ -68,7 +70,6 @@ #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_STRLEN 1 -#define HAVE_STRDUP 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 @@ -89,9 +90,11 @@ #define HAVE_COPYSIGN 1 #define HAVE_COS 1 #define HAVE_COSF 1 +#define HAVE_EXP 1 #define HAVE_FABS 1 #define HAVE_FLOOR 1 #define HAVE_LOG 1 +#define HAVE_LOG10 1 #define HAVE_SCALBN 1 #define HAVE_SIN 1 #define HAVE_SINF 1 @@ -111,6 +114,8 @@ #define SDL_JOYSTICK_LINUX 1 #define SDL_HAPTIC_LINUX 1 +#define SDL_SENSOR_DUMMY 1 + #define SDL_LOADSO_DLOPEN 1 #define SDL_THREAD_PTHREAD 1 diff --git a/lib/SDL2/include/SDL_config_psp.h b/lib/SDL2/include/SDL_config_psp.h index 28efb4c5c0..0cbb182e04 100644 --- a/lib/SDL2/include/SDL_config_psp.h +++ b/lib/SDL2/include/SDL_config_psp.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -33,16 +33,17 @@ #define HAVE_GCC_ATOMICS 1 -#define HAVE_ALLOCA_H 1 -#define HAVE_SYS_TYPES_H 1 -#define HAVE_STDIO_H 1 #define STDC_HEADERS 1 -#define HAVE_STRING_H 1 -#define HAVE_INTTYPES_H 1 -#define HAVE_STDINT_H 1 +#define HAVE_ALLOCA_H 1 #define HAVE_CTYPE_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 #define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 /* C library functions */ #define HAVE_MALLOC 1 @@ -65,7 +66,6 @@ #define HAVE_STRLEN 1 #define HAVE_STRLCPY 1 #define HAVE_STRLCAT 1 -#define HAVE_STRDUP 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 @@ -83,19 +83,36 @@ #define HAVE_VSSCANF 1 #define HAVE_VSNPRINTF 1 #define HAVE_M_PI 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 #define HAVE_ATAN 1 +#define HAVE_ATANF 1 #define HAVE_ATAN2 1 -#define HAVE_ACOS 1 -#define HAVE_ASIN 1 +#define HAVE_ATAN2F 1 #define HAVE_CEIL 1 +#define HAVE_CEILF 1 #define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 #define HAVE_COS 1 #define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 #define HAVE_FABS 1 +#define HAVE_FABSF 1 #define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 #define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 #define HAVE_POW 1 +#define HAVE_POWF 1 #define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 #define HAVE_SIN 1 #define HAVE_SINF 1 #define HAVE_SQRT 1 @@ -111,22 +128,25 @@ /* PSP isn't that sophisticated */ #define LACKS_SYS_MMAN_H 1 -/* Enable the stub thread support (src/thread/psp/\*.c) */ +/* Enable the PSP thread support (src/thread/psp/\*.c) */ #define SDL_THREAD_PSP 1 -/* Enable the stub timer support (src/timer/psp/\*.c) */ +/* Enable the PSP timer support (src/timer/psp/\*.c) */ #define SDL_TIMERS_PSP 1 -/* Enable the stub joystick driver (src/joystick/psp/\*.c) */ +/* Enable the PSP joystick driver (src/joystick/psp/\*.c) */ #define SDL_JOYSTICK_PSP 1 -/* Enable the stub audio driver (src/audio/psp/\*.c) */ +/* Enable the dummy sensor driver */ +#define SDL_SENSOR_DUMMY 1 + +/* Enable the PSP audio driver (src/audio/psp/\*.c) */ #define SDL_AUDIO_DRIVER_PSP 1 -/* PSP video dirver */ +/* PSP video driver */ #define SDL_VIDEO_DRIVER_PSP 1 -/* PSP render dirver */ +/* PSP render driver */ #define SDL_VIDEO_RENDER_PSP 1 #define SDL_POWER_PSP 1 diff --git a/lib/SDL2/include/SDL_config_windows.h b/lib/SDL2/include/SDL_config_windows.h index 2456c843fe..f269bfc04b 100644 --- a/lib/SDL2/include/SDL_config_windows.h +++ b/lib/SDL2/include/SDL_config_windows.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -82,16 +82,20 @@ typedef unsigned int uintptr_t; #define HAVE_DSOUND_H 1 #define HAVE_DXGI_H 1 #define HAVE_XINPUT_H 1 +#define HAVE_MMDEVICEAPI_H 1 +#define HAVE_AUDIOCLIENT_H 1 /* This is disabled by default to avoid C runtime dependencies and manifest requirements */ #ifdef HAVE_LIBC /* Useful headers */ -#define HAVE_STDIO_H 1 #define STDC_HEADERS 1 -#define HAVE_STRING_H 1 #define HAVE_CTYPE_H 1 +#define HAVE_FLOAT_H 1 +#define HAVE_LIMITS_H 1 #define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 /* C library functions */ #define HAVE_MALLOC 1 @@ -107,13 +111,19 @@ typedef unsigned int uintptr_t; #define HAVE_MEMCMP 1 #define HAVE_STRLEN 1 #define HAVE__STRREV 1 -#define HAVE__STRUPR 1 -#define HAVE__STRLWR 1 +/* These functions have security warnings, so we won't use them */ +/* #undef HAVE__STRUPR */ +/* #undef HAVE__STRLWR */ #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 -#define HAVE__LTOA 1 -#define HAVE__ULTOA 1 +/* #undef HAVE_STRTOK_R */ +#if defined(_MSC_VER) +#define HAVE_STRTOK_S 1 +#endif +/* These functions have security warnings, so we won't use them */ +/* #undef HAVE__LTOA */ +/* #undef HAVE__ULTOA */ #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOD 1 @@ -123,28 +133,50 @@ typedef unsigned int uintptr_t; #define HAVE_STRNCMP 1 #define HAVE__STRICMP 1 #define HAVE__STRNICMP 1 -#define HAVE_ATAN 1 -#define HAVE_ATAN2 1 -#define HAVE_ACOS 1 -#define HAVE_ASIN 1 -#define HAVE_CEIL 1 -#define HAVE_COS 1 -#define HAVE_COSF 1 -#define HAVE_FABS 1 -#define HAVE_FLOOR 1 -#define HAVE_LOG 1 -#define HAVE_POW 1 -#define HAVE_SIN 1 -#define HAVE_SINF 1 -#define HAVE_SQRT 1 -#define HAVE_SQRTF 1 -#define HAVE_TAN 1 -#define HAVE_TANF 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEILF 1 +#define HAVE__COPYSIGN 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 +#if defined(_MSC_VER) +/* These functions were added with the VC++ 2013 C runtime library */ #if _MSC_VER >= 1800 #define HAVE_STRTOLL 1 #define HAVE_VSSCANF 1 -#define HAVE_COPYSIGN 1 #define HAVE_SCALBN 1 +#define HAVE_SCALBNF 1 +#endif +/* This function is available with at least the VC++ 2008 C runtime library */ +#if _MSC_VER >= 1400 +#define HAVE__FSEEKI64 1 +#endif #endif #if !defined(_MSC_VER) || defined(_USE_MATH_DEFINES) #define HAVE_M_PI 1 @@ -157,7 +189,6 @@ typedef unsigned int uintptr_t; /* Enable various audio drivers */ #define SDL_AUDIO_DRIVER_WASAPI 1 #define SDL_AUDIO_DRIVER_DSOUND 1 -#define SDL_AUDIO_DRIVER_XAUDIO2 0 #define SDL_AUDIO_DRIVER_WINMM 1 #define SDL_AUDIO_DRIVER_DISK 1 #define SDL_AUDIO_DRIVER_DUMMY 1 @@ -165,9 +196,13 @@ typedef unsigned int uintptr_t; /* Enable various input drivers */ #define SDL_JOYSTICK_DINPUT 1 #define SDL_JOYSTICK_XINPUT 1 +#define SDL_JOYSTICK_HIDAPI 1 #define SDL_HAPTIC_DINPUT 1 #define SDL_HAPTIC_XINPUT 1 +/* Enable the dummy sensor driver */ +#define SDL_SENSOR_DUMMY 1 + /* Enable various shared object loading systems */ #define SDL_LOADSO_WINDOWS 1 @@ -185,7 +220,7 @@ typedef unsigned int uintptr_t; #define SDL_VIDEO_RENDER_D3D 1 #endif #ifndef SDL_VIDEO_RENDER_D3D11 -#define SDL_VIDEO_RENDER_D3D11 0 +#define SDL_VIDEO_RENDER_D3D11 0 #endif /* Enable OpenGL support */ diff --git a/lib/SDL2/include/SDL_config_winrt.h b/lib/SDL2/include/SDL_config_winrt.h index 24f9e17f20..fa03389e2d 100644 --- a/lib/SDL2/include/SDL_config_winrt.h +++ b/lib/SDL2/include/SDL_config_winrt.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -44,7 +44,7 @@ #if !defined(_STDINT_H_) && (!defined(HAVE_STDINT_H) || !_HAVE_STDINT_H) #if defined(__GNUC__) || defined(__DMC__) || defined(__WATCOMC__) -#define HAVE_STDINT_H 1 +#define HAVE_STDINT_H 1 #elif defined(_MSC_VER) typedef signed __int8 int8_t; typedef unsigned __int8 uint8_t; @@ -97,14 +97,19 @@ typedef unsigned int uintptr_t; #if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP #define HAVE_XINPUT_H 1 #endif + +#define HAVE_MMDEVICEAPI_H 1 +#define HAVE_AUDIOCLIENT_H 1 + #define HAVE_LIBC 1 -#define HAVE_STDIO_H 1 #define STDC_HEADERS 1 -#define HAVE_STRING_H 1 #define HAVE_CTYPE_H 1 -#define HAVE_MATH_H 1 #define HAVE_FLOAT_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MATH_H 1 #define HAVE_SIGNAL_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STRING_H 1 /* C library functions */ #define HAVE_MALLOC 1 @@ -121,13 +126,14 @@ typedef unsigned int uintptr_t; #define HAVE_STRLEN 1 #define HAVE__STRREV 1 #define HAVE__STRUPR 1 -//#define HAVE__STRLWR 1 // TODO, WinRT: consider using _strlwr_s instead +//#define HAVE__STRLWR 1 // TODO, WinRT: consider using _strlwr_s instead #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 +#define HAVE_STRTOK_S 1 //#define HAVE_ITOA 1 // TODO, WinRT: consider using _itoa_s instead -//#define HAVE__LTOA 1 // TODO, WinRT: consider using _ltoa_s instead -//#define HAVE__ULTOA 1 // TODO, WinRT: consider using _ultoa_s instead +//#define HAVE__LTOA 1 // TODO, WinRT: consider using _ltoa_s instead +//#define HAVE__ULTOA 1 // TODO, WinRT: consider using _ultoa_s instead #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 //#define HAVE_STRTOLL 1 @@ -139,44 +145,63 @@ typedef unsigned int uintptr_t; #define HAVE__STRICMP 1 #define HAVE__STRNICMP 1 #define HAVE_VSNPRINTF 1 -//#define HAVE_SSCANF 1 // TODO, WinRT: consider using sscanf_s instead +//#define HAVE_SSCANF 1 // TODO, WinRT: consider using sscanf_s instead #define HAVE_M_PI 1 -#define HAVE_ATAN 1 -#define HAVE_ATAN2 1 -#define HAVE_CEIL 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEIL 1 +#define HAVE_CEILF 1 #define HAVE__COPYSIGN 1 -#define HAVE_COS 1 -#define HAVE_COSF 1 -#define HAVE_FABS 1 -#define HAVE_FLOOR 1 -#define HAVE_LOG 1 -#define HAVE_POW 1 -//#define HAVE_SCALBN 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 #define HAVE__SCALB 1 -#define HAVE_SIN 1 -#define HAVE_SINF 1 -#define HAVE_SQRT 1 -#define HAVE_SQRTF 1 -#define HAVE_TAN 1 -#define HAVE_TANF 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 #define HAVE__FSEEKI64 1 /* Enable various audio drivers */ -#define SDL_AUDIO_DRIVER_XAUDIO2 1 -#define SDL_AUDIO_DRIVER_DISK 1 -#define SDL_AUDIO_DRIVER_DUMMY 1 +#define SDL_AUDIO_DRIVER_WASAPI 1 +#define SDL_AUDIO_DRIVER_DISK 1 +#define SDL_AUDIO_DRIVER_DUMMY 1 /* Enable various input drivers */ #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP #define SDL_JOYSTICK_DISABLED 1 -#define SDL_HAPTIC_DISABLED 1 +#define SDL_HAPTIC_DISABLED 1 #else #define SDL_JOYSTICK_XINPUT 1 #define SDL_HAPTIC_XINPUT 1 #endif +/* Enable the dummy sensor driver */ +#define SDL_SENSOR_DUMMY 1 + /* Enable various shared object loading systems */ -#define SDL_LOADSO_WINDOWS 1 +#define SDL_LOADSO_WINDOWS 1 /* Enable various threading systems */ #if (NTDDI_VERSION >= NTDDI_WINBLUE) @@ -187,10 +212,10 @@ typedef unsigned int uintptr_t; #endif /* Enable various timer systems */ -#define SDL_TIMER_WINDOWS 1 +#define SDL_TIMER_WINDOWS 1 /* Enable various video drivers */ -#define SDL_VIDEO_DRIVER_WINRT 1 +#define SDL_VIDEO_DRIVER_WINRT 1 #define SDL_VIDEO_DRIVER_DUMMY 1 /* Enable OpenGL ES 2.0 (via a modified ANGLE library) */ @@ -209,7 +234,7 @@ typedef unsigned int uintptr_t; /* Enable assembly routines (Win64 doesn't have inline asm) */ #ifndef _WIN64 -#define SDL_ASSEMBLY_ROUTINES 1 +#define SDL_ASSEMBLY_ROUTINES 1 #endif #endif /* SDL_config_winrt_h_ */ diff --git a/lib/SDL2/include/SDL_config_wiz.h b/lib/SDL2/include/SDL_config_wiz.h index 5bb845a0cc..92b1771e53 100644 --- a/lib/SDL2/include/SDL_config_wiz.h +++ b/lib/SDL2/include/SDL_config_wiz.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -30,22 +30,24 @@ #define SDL_BYTEORDER 1234 -#define HAVE_ALLOCA_H 1 -#define HAVE_SYS_TYPES_H 1 -#define HAVE_STDIO_H 1 #define STDC_HEADERS 1 -#define HAVE_STDLIB_H 1 -#define HAVE_STDARG_H 1 -#define HAVE_MALLOC_H 1 -#define HAVE_MEMORY_H 1 -#define HAVE_STRING_H 1 -#define HAVE_STRINGS_H 1 -#define HAVE_INTTYPES_H 1 -#define HAVE_STDINT_H 1 +#define HAVE_ALLOCA_H 1 #define HAVE_CTYPE_H 1 -#define HAVE_MATH_H 1 #define HAVE_ICONV_H 1 +#define HAVE_INTTYPES_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_MALLOC_H 1 +#define HAVE_MATH_H 1 +#define HAVE_MEMORY_H 1 #define HAVE_SIGNAL_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_STDINT_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_STDLIB_H 1 +#define HAVE_STRINGS_H 1 +#define HAVE_STRING_H 1 +#define HAVE_SYS_TYPES_H 1 + #define HAVE_MALLOC 1 #define HAVE_CALLOC 1 #define HAVE_REALLOC 1 @@ -62,10 +64,10 @@ #define HAVE_MEMCPY 1 #define HAVE_MEMMOVE 1 #define HAVE_STRLEN 1 -#define HAVE_STRDUP 1 #define HAVE_STRCHR 1 #define HAVE_STRRCHR 1 #define HAVE_STRSTR 1 +#define HAVE_STRTOK_R 1 #define HAVE_STRTOL 1 #define HAVE_STRTOUL 1 #define HAVE_STRTOLL 1 @@ -79,20 +81,42 @@ #define HAVE_VSSCANF 1 #define HAVE_VSNPRINTF 1 #define HAVE_M_PI 1 -#define HAVE_CEIL 1 -#define HAVE_COPYSIGN 1 -#define HAVE_COS 1 -#define HAVE_COSF 1 -#define HAVE_FABS 1 -#define HAVE_FLOOR 1 -#define HAVE_LOG 1 +#define HAVE_ACOS 1 +#define HAVE_ACOSF 1 +#define HAVE_ASIN 1 +#define HAVE_ASINF 1 +#define HAVE_ATAN 1 +#define HAVE_ATANF 1 +#define HAVE_ATAN2 1 +#define HAVE_ATAN2F 1 +#define HAVE_CEIL 1 +#define HAVE_CEILF 1 +#define HAVE_COPYSIGN 1 +#define HAVE_COPYSIGNF 1 +#define HAVE_COS 1 +#define HAVE_COSF 1 +#define HAVE_EXP 1 +#define HAVE_EXPF 1 +#define HAVE_FABS 1 +#define HAVE_FABSF 1 +#define HAVE_FLOOR 1 +#define HAVE_FLOORF 1 +#define HAVE_FMOD 1 +#define HAVE_FMODF 1 +#define HAVE_LOG 1 +#define HAVE_LOGF 1 +#define HAVE_LOG10 1 +#define HAVE_LOG10F 1 +#define HAVE_POW 1 +#define HAVE_POWF 1 #define HAVE_SCALBN 1 -#define HAVE_SIN 1 -#define HAVE_SINF 1 -#define HAVE_SQRT 1 -#define HAVE_SQRTF 1 -#define HAVE_TAN 1 -#define HAVE_TANF 1 +#define HAVE_SCALBNF 1 +#define HAVE_SIN 1 +#define HAVE_SINF 1 +#define HAVE_SQRT 1 +#define HAVE_SQRTF 1 +#define HAVE_TAN 1 +#define HAVE_TANF 1 #define HAVE_SIGACTION 1 #define HAVE_SETJMP 1 #define HAVE_NANOSLEEP 1 @@ -106,6 +130,8 @@ #define SDL_JOYSTICK_LINUX 1 #define SDL_HAPTIC_LINUX 1 +#define SDL_SENSOR_DUMMY 1 + #define SDL_LOADSO_DLOPEN 1 #define SDL_THREAD_PTHREAD 1 diff --git a/lib/SDL2/include/SDL_copying.h b/lib/SDL2/include/SDL_copying.h index 8f60af6b4f..4f8a2bcd49 100644 --- a/lib/SDL2/include/SDL_copying.h +++ b/lib/SDL2/include/SDL_copying.h @@ -1,6 +1,6 @@ /* Simple DirectMedia Layer - Copyright (C) 1997-2017 Sam Lantinga + Copyright (C) 1997-2020 Sam Lantinga This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages