diff --git a/.gitignore b/.gitignore index 22daf481e..39664e356 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +bld/ build/ build-32/ build-64/ @@ -37,3 +38,4 @@ data/.svn packets_log.txt history.dat +README.dependencies diff --git a/README.md b/README.md index 03267e3ee..1b202c23b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ #SuperTuxKart +[![Build Status](https://travis-ci.org/supertuxkart/stk-code.png?branch=master)](https://travis-ci.org/supertuxkart/stk-code) + SuperTuxKart is a free kart racing game. It is focusing on fun and not on realistic kart physics. Instruction can be found on the in-game help page. diff --git a/data/shaders/bloom.frag b/data/shaders/bloom.frag index 3376cdb4a..886b49ea0 100644 --- a/data/shaders/bloom.frag +++ b/data/shaders/bloom.frag @@ -11,7 +11,7 @@ void main() vec3 col = texture(tex, uv).xyz; float luma = dot(weights, col); - col *= smoothstep(low, 0.9, luma); + col *= smoothstep(1., 2., luma); FragColor = vec4(col, 1.0); } diff --git a/data/shaders/fog.frag b/data/shaders/fog.frag index 961400c7e..120f5734e 100644 --- a/data/shaders/fog.frag +++ b/data/shaders/fog.frag @@ -7,7 +7,6 @@ uniform float endH; uniform float start; uniform float end; uniform vec3 col; -uniform vec3 campos; uniform mat4 ipvmat; in vec2 uv; @@ -24,9 +23,8 @@ void main() xpos = ipvmat * xpos; xpos.xyz /= xpos.w; - float dist = distance(campos, xpos.xyz); + float dist = length(xpos.xyz); float fog = smoothstep(start, end, dist); - fog *= 1.0 - smoothstep(startH, endH, xpos.y); fog = min(fog, fogmax); diff --git a/data/shaders/grass.frag b/data/shaders/grass.frag deleted file mode 100644 index abd339b58..000000000 --- a/data/shaders/grass.frag +++ /dev/null @@ -1,17 +0,0 @@ -#version 130 -uniform float far; -uniform float objectid; -uniform sampler2D tex; - -noperspective in vec3 nor; -in vec2 uv; -out vec4 Albedo; -out vec4 NormalDepth; -out vec4 Specular; - -void main() -{ - Albedo = texture(tex, uv); - NormalDepth = vec4(0.5 * normalize(nor) + 0.5, gl_FragCoord.z); - Specular = vec4(0.); -} diff --git a/data/shaders/grass.vert b/data/shaders/grass.vert deleted file mode 100644 index cf22df960..000000000 --- a/data/shaders/grass.vert +++ /dev/null @@ -1,18 +0,0 @@ -#version 130 -uniform vec3 windDir; -uniform mat4 ModelViewProjectionMatrix; -uniform mat4 TransposeInverseModelView; - -noperspective out vec3 nor; -out vec2 uv; - -void main() -{ - uv = gl_MultiTexCoord0.st; - - vec4 vertexPosition = gl_Vertex; - vertexPosition.xyz += windDir * gl_Color.r; - - nor = (TransposeInverseModelView * vec4(gl_Normal, 1.)).xyz; - gl_Position = ModelViewProjectionMatrix * vertexPosition; -} diff --git a/data/shaders/gum_shield.frag b/data/shaders/gum_shield.frag deleted file mode 100644 index 0c1459627..000000000 --- a/data/shaders/gum_shield.frag +++ /dev/null @@ -1,39 +0,0 @@ -// SuperTuxKart - a fun racing game with go-kart -// Copyright (C) 2013 the SuperTuxKart team -// -// 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 3 -// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - - -// Jean-manuel clemencon (c) supertuxkart 2013 -// bubble gum shield -// TODO: Add a nice texture and soft edges when intersect with geometry -#version 130 -uniform sampler2D tex; -uniform float transparency; - -in vec2 uv; -noperspective in vec3 eyeVec; -noperspective in vec3 normal; -out vec4 FragColor; - -void main() -{ - float inter = dot(normal, eyeVec); - float m = texture(tex, vec2(0.5, uv.y)).r; - inter = 1.0 - inter; - float alpha = inter + 1.0;// * m; - - FragColor = vec4(0.8, 0.16, 0.48, alpha); -} diff --git a/data/shaders/gum_shield.vert b/data/shaders/gum_shield.vert deleted file mode 100644 index 919e01cc7..000000000 --- a/data/shaders/gum_shield.vert +++ /dev/null @@ -1,43 +0,0 @@ -// SuperTuxKart - a fun racing game with go-kart -// Copyright (C) 2013 the SuperTuxKart team -// -// 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 3 -// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - - -// Jean-manuel clemencon (c) supertuxkart 2013 -// Creates a bubble gum shield effect -// --- -// TODO: The texture should reflect the strength of the shield, -// such that the user gets to know whether the shield has several -// "layers" or whether the shield is about to break. -#version 130 -uniform mat4 ModelViewMatrix; -uniform mat4 ProjectionMatrix; -uniform mat4 TransposeInverseModelView; -out vec2 uv; -noperspective out vec3 eyeVec; -noperspective out vec3 normal; - -void main() -{ - vec4 viewp = ModelViewMatrix * gl_Vertex; - - eyeVec = normalize(-viewp).xyz; - normal = (TransposeInverseModelView * vec4(gl_Normal, 1.).xyz; - - gl_Position = ProjectionMatrix * viewp; - - uv = (gl_TextureMatrix[0] * gl_MultiTexCoord0).st; -} diff --git a/data/shaders/lightbeam.frag b/data/shaders/lightbeam.frag deleted file mode 100644 index 069cccbf3..000000000 --- a/data/shaders/lightbeam.frag +++ /dev/null @@ -1,40 +0,0 @@ -// SuperTuxKart - a fun racing game with go-kart -// Copyright (C) 2013 the SuperTuxKart team -// -// 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 3 -// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - - -// Jean-manuel clemencon supertuxkart -// Creates a cone lightbeam effect by smoothing edges -// Original idea: http://udn.epicgames.com/Three/VolumetricLightbeamTutorial.html -// TODO: Soft edges when it intesects geometry -// Some artefacts are still visible -#version 130 -uniform sampler2D tex; -uniform float transparency; - -in vec2 uv; -noperspective in vec3 eyeVec; -noperspective in vec3 normal; -out vec4 FragColor; - -void main() -{ - float inter = dot(normal, eyeVec); - float m = texture(tex, vec2(0.5, uv.y)).r; - float alpha = inter * inter * inter * inter * m; - - FragColor = vec4(1.0, 1.0, 0.8, alpha); -} diff --git a/data/shaders/lightbeam.vert b/data/shaders/lightbeam.vert deleted file mode 100644 index 3f8837991..000000000 --- a/data/shaders/lightbeam.vert +++ /dev/null @@ -1,39 +0,0 @@ -// SuperTuxKart - a fun racing game with go-kart -// Copyright (C) 2013 the SuperTuxKart team -// -// 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 3 -// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - - -// Jean-manuel clemencon (C) Copyright supertuxkart -// Creates a cone lightbeam effect by smoothing edges -#version 130 -uniform mat4 ModelViewMatrix; -uniform mat4 ProjectionMatrix; -uniform mat4 TransposeInverseModelView; -out vec2 uv; -noperspective out vec3 eyeVec; -noperspective out vec3 normal; - -void main() -{ - vec4 viewp = ModelViewMatrix * gl_Vertex; - - eyeVec = normalize(-viewp).xyz; - normal = (TransposeInverseModelView * vec4(gl_Normal, 1.).xyz; - - gl_Position = ProjectionMatrix * viewp; - - uv = gl_MultiTexCoord0.st; -} diff --git a/data/shaders/lightblend.frag b/data/shaders/lightblend.frag deleted file mode 100644 index 0cd68fe3b..000000000 --- a/data/shaders/lightblend.frag +++ /dev/null @@ -1,21 +0,0 @@ -#version 130 -uniform sampler2D diffuse; -uniform sampler2D specular; -uniform sampler2D ambient_occlusion; -uniform sampler2D specular_map; -uniform vec3 ambient; - -in vec2 uv; -out vec4 FragColor; - -void main() -{ - vec2 texc = uv; - - vec3 diffuse = texture(diffuse, texc).xyz; - vec3 spec = texture(specular, texc).xyz; - float specmap = texture(specular_map, texc).x; - float ao = texture(ambient_occlusion, texc).x; - - FragColor = vec4(diffuse + spec * specmap + ao * ambient, 1.0); -} diff --git a/data/shaders/sunlight.frag b/data/shaders/sunlight.frag index faedb9d61..c6519c5d9 100644 --- a/data/shaders/sunlight.frag +++ b/data/shaders/sunlight.frag @@ -12,7 +12,6 @@ uniform mat4 invproj; in vec2 uv; out vec4 Diff; out vec4 Spec; -out vec4 SpecularMap; vec3 DecodeNormal(vec2 n) { @@ -58,5 +57,4 @@ void main() { Diff = vec4(NdotL * col, 1.); Spec = vec4(Specular * col, 1.); - SpecularMap = vec4(1.0); } diff --git a/data/shaders/sunlightshadow.frag b/data/shaders/sunlightshadow.frag index 3151cfb7e..4fe0f9313 100644 --- a/data/shaders/sunlightshadow.frag +++ b/data/shaders/sunlightshadow.frag @@ -1,95 +1,92 @@ #version 130 uniform sampler2D ntex; uniform sampler2D dtex; -uniform sampler2D cloudtex; -uniform sampler2D shadowtex; -uniform sampler2D warpx; -uniform sampler2D warpy; +uniform sampler2DShadow shadowtex; +//uniform sampler2D warpx; +///uniform sampler2D warpy; -uniform vec3 center; +uniform vec3 direction; uniform vec3 col; -uniform vec2 screen; -uniform mat4 invprojview; +uniform mat4 invproj; uniform mat4 shadowmat; -uniform int hasclouds; -uniform vec2 wind; -uniform float shadowoffset; +//uniform int hasclouds; +//uniform vec2 wind; +//uniform float shadowoffset; -out vec4 FragColor; -out vec4 OtherOutput; +in vec2 uv; +out vec4 Diff; +out vec4 Spec; -float decdepth(vec4 rgba) { - return dot(rgba, vec4(1.0, 1.0/255.0, 1.0/65025.0, 1.0/16581375.0)); +vec3 DecodeNormal(vec2 n) +{ + float z = dot(n, n) * 2. - 1.; + vec2 xy = normalize(n) * sqrt(1. - z * z); + return vec3(xy,z); } void main() { - - vec2 texc = gl_FragCoord.xy / screen; - vec4 depthread = texture(dtex, texc); - float z = decdepth(vec4(depthread.xyz, 0.0)); + float z = texture(dtex, uv).x; + vec4 xpos = 2.0 * vec4(uv, z, 1.0) - 1.0; + xpos = invproj * xpos; + xpos.xyz /= xpos.w; if (z < 0.03) { // Skyboxes are fully lit - FragColor = vec4(1.0); - OtherOutput = vec4(0.0); + Diff = vec4(1.0); + Spec = vec4(1.0); return; } - vec3 norm = texture(ntex, texc).xyz; - norm = (norm - 0.5) * 2.0; + vec3 norm = normalize(DecodeNormal(2. * texture(ntex, uv).xy - 1.)); // Normalized on the cpu - vec3 L = center; + vec3 L = direction; float NdotL = max(0.0, dot(norm, L)); - if (NdotL < 0.01) discard; + vec3 R = reflect(L, norm); + float RdotE = max(0.0, dot(R, normalize(xpos.xyz))); + float Specular = pow(RdotE, 200); vec3 outcol = NdotL * col; - // World-space position - vec3 tmp = vec3(texc, z); - tmp = tmp * 2.0 - 1.0; +// if (hasclouds == 1) +// { +// vec2 cloudcoord = (xpos.xz * 0.00833333) + wind; +// float cloud = texture(cloudtex, cloudcoord).x; +// //float cloud = step(0.5, cloudcoord.x) * step(0.5, cloudcoord.y); - vec4 xpos = vec4(tmp, 1.0); - xpos = invprojview * xpos; - xpos.xyz /= xpos.w; - - if (hasclouds == 1) - { - vec2 cloudcoord = (xpos.xz * 0.00833333) + wind; - float cloud = texture(cloudtex, cloudcoord).x; - //float cloud = step(0.5, cloudcoord.x) * step(0.5, cloudcoord.y); - - outcol *= cloud; - } +// outcol *= cloud; +// } // Shadows - vec3 shadowcoord = (shadowmat * vec4(xpos.xyz, 1.0)).xyz; - shadowcoord = (shadowcoord * 0.5) + vec3(0.5); + vec4 shadowcoord = (shadowmat * vec4(xpos.xyz, 1.0)); + shadowcoord /= shadowcoord.w; + vec2 shadowtexcoord = shadowcoord.xy * 0.5 + 0.5; +// shadowcoord = (shadowcoord * 0.5) + vec3(0.5); - float movex = decdepth(texture(warpx, shadowcoord.xy)); - float movey = decdepth(texture(warpy, shadowcoord.xy)); - float dx = movex * 2.0 - 1.0; - float dy = movey * 2.0 - 1.0; - shadowcoord.xy += vec2(dx, dy); +// float movex = decdepth(texture(warpx, shadowcoord.xy)); +// float movey = decdepth(texture(warpy, shadowcoord.xy)); +// float dx = movex * 2.0 - 1.0; +// float dy = movey * 2.0 - 1.0; +// shadowcoord.xy += vec2(dx, dy);*/ - vec4 shadowread = texture(shadowtex, shadowcoord.xy); - float shadowmapz = decdepth(vec4(shadowread.xyz, 0.0)); - - float moved = (abs(dx) + abs(dy)) * 0.5; - - -/* + //float shadowmapz = 2. * texture(shadowtex, vec3(shadowtexcoord, shadowcoord.z).x - 1.; float bias = 0.002 * tan(acos(NdotL)); // According to the slope - bias += smoothstep(0.001, 0.1, moved) * 0.014; // According to the warping + // bias += smoothstep(0.001, 0.1, moved) * 0.014; // According to the warping bias = clamp(bias, 0.001, 0.014); -*/ -/* - float avi = 0.002; - float abi = 0.0025; */ + float factor = texture(shadowtex, vec3(shadowtexcoord, 0.5 * (shadowcoord.z + bias) + 0.5)); - float avi = 0.0018; + Diff = vec4(factor * NdotL * col, 1.); + Spec = vec4(factor * Specular * col, 1.); + return; + +// float moved = (abs(dx) + abs(dy)) * 0.5; + +// float avi = 0.002; +// float abi = 0.0025; + +/* float avi = 0.0018; float abi = 0.002; float bias = avi * tan(acos(NdotL)); // According to the slope @@ -113,11 +110,11 @@ void main() { float shadowed = step(shadowmapz + bias, shadowcoord.z); float dist = (shadowcoord.z / shadowmapz) - 1.0; float penumbra = dist * softness / gl_FragCoord.z; - penumbra *= shadowed; + penumbra *= shadowed;*/ /* outcol.r = (shadowcoord.z - shadowmapz) * 50.0; outcol.g = moved;*/ - FragColor = vec4(outcol, 0.05); - OtherOutput = vec4(shadowed, penumbra, shadowed, shadowed); +// FragColor = vec4(outcol, 0.05); +// OtherOutput = vec4(shadowed, penumbra, shadowed, shadowed); } diff --git a/data/shaders/transparentfog.frag b/data/shaders/transparentfog.frag new file mode 100644 index 000000000..f5365d011 --- /dev/null +++ b/data/shaders/transparentfog.frag @@ -0,0 +1,32 @@ +#version 130 +uniform sampler2D tex; + +uniform float fogmax; +uniform float startH; +uniform float endH; +uniform float start; +uniform float end; +uniform vec3 col; +uniform mat4 ipvmat; +uniform vec2 screen; + +in vec2 uv; +out vec4 FragColor; + +void main() +{ + vec4 color = texture(tex, uv); + vec3 tmp = vec3(gl_FragCoord.xy / screen, gl_FragCoord.z); + tmp = 2. * tmp - 1.; + + vec4 xpos = vec4(tmp, 1.0); + xpos = ipvmat * xpos; + xpos.xyz /= xpos.w; + + float dist = length(xpos.xyz); + float fog = smoothstep(start, end, dist); + + fog = min(fog, fogmax); + + FragColor = vec4(vec4(col, 0.) * fog + color *(1. - fog)); +} diff --git a/lib/irrlicht/source/Irrlicht/CIrrDeviceLinux.cpp b/lib/irrlicht/source/Irrlicht/CIrrDeviceLinux.cpp index 9826096f5..de2c76d61 100644 --- a/lib/irrlicht/source/Irrlicht/CIrrDeviceLinux.cpp +++ b/lib/irrlicht/source/Irrlicht/CIrrDeviceLinux.cpp @@ -210,11 +210,13 @@ CIrrDeviceLinux::~CIrrDeviceLinux() } -#if defined(_IRR_COMPILE_WITH_X11_) && defined(_DEBUG) +#if defined(_IRR_COMPILE_WITH_X11_) +static bool XErrorSignaled = false; int IrrPrintXError(Display *display, XErrorEvent *event) { char msg[256]; char msg2[256]; + XErrorSignaled = true; snprintf(msg, 256, "%d", event->request_code); XGetErrorDatabaseText(display, "XRequest", msg, "unknown", msg2, 256); @@ -370,10 +372,8 @@ void IrrPrintXGrabError(int grabResult, const c8 * grabCommand ) bool CIrrDeviceLinux::createWindow() { #ifdef _IRR_COMPILE_WITH_X11_ -#ifdef _DEBUG os::Printer::log("Creating X window...", ELL_INFORMATION); XSetErrorHandler(IrrPrintXError); -#endif display = XOpenDisplay(0); if (!display) @@ -750,12 +750,22 @@ bool CIrrDeviceLinux::createWindow() GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_DEBUG_BIT_ARB, None }; - PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = 0; glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddressARB( (const GLubyte *) "glXCreateContextAttribsARB" ); // create glx context Context = glXCreateContextAttribsARB(display, glxFBConfig, 0, True, context_attribs); + if (XErrorSignaled) + { + int context_attribs[] = + { + GLX_CONTEXT_MAJOR_VERSION_ARB, 2, + GLX_CONTEXT_MINOR_VERSION_ARB, 1, + None + }; + Context = glXCreateContextAttribsARB(display, glxFBConfig, 0, True, context_attribs); + XErrorSignaled = false; + } if (Context) { if (!glXMakeContextCurrent(display, glxWin, glxWin, Context)) diff --git a/lib/irrlicht/source/Irrlicht/COpenGLDriver.cpp b/lib/irrlicht/source/Irrlicht/COpenGLDriver.cpp index 7c609254b..50076bf1a 100644 --- a/lib/irrlicht/source/Irrlicht/COpenGLDriver.cpp +++ b/lib/irrlicht/source/Irrlicht/COpenGLDriver.cpp @@ -4397,12 +4397,6 @@ IImage* COpenGLDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RE if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS) return 0; - // allows to read pixels in top-to-bottom order -#ifdef GL_MESA_pack_invert - if (FeatureAvailable[IRR_MESA_pack_invert]) - glPixelStorei(GL_PACK_INVERT_MESA, GL_TRUE); -#endif - if (format==video::ECF_UNKNOWN) format=getColorFormat(); GLenum fmt; @@ -4542,11 +4536,6 @@ IImage* COpenGLDriver::createScreenShot(video::ECOLOR_FORMAT format, video::E_RE glReadBuffer(GL_BACK); } -#ifdef GL_MESA_pack_invert - if (FeatureAvailable[IRR_MESA_pack_invert]) - glPixelStorei(GL_PACK_INVERT_MESA, GL_FALSE); - else -#endif if (pixels) { // opengl images are horizontally flipped, so we have to fix that here. diff --git a/lib/irrlicht/source/Irrlicht/COpenGLExtensionHandler.h b/lib/irrlicht/source/Irrlicht/COpenGLExtensionHandler.h index 88ca596ab..822f114c6 100644 --- a/lib/irrlicht/source/Irrlicht/COpenGLExtensionHandler.h +++ b/lib/irrlicht/source/Irrlicht/COpenGLExtensionHandler.h @@ -61,9 +61,9 @@ #include #include #if defined(_IRR_OPENGL_USE_EXTPOINTER_) - #include "glext.h" + #include #undef GLX_ARB_get_proc_address // avoid problems with local glxext.h - #include "glxext.h" + #include #endif #endif diff --git a/sources.cmake b/sources.cmake index d499bfebd..00250cd3a 100644 --- a/sources.cmake +++ b/sources.cmake @@ -362,6 +362,7 @@ src/graphics/CBatchingMesh.hpp src/graphics/explosion.hpp src/graphics/glow.hpp src/graphics/glwrap.hpp +src/graphics/gpuparticles.hpp src/graphics/hardware_skinning.hpp src/graphics/hit_effect.hpp src/graphics/hit_sfx.hpp diff --git a/src/achievements/achievement.cpp b/src/achievements/achievement.cpp index 447ed2770..c663da52c 100644 --- a/src/achievements/achievement.cpp +++ b/src/achievements/achievement.cpp @@ -131,13 +131,14 @@ MapAchievement::MapAchievement(const AchievementInfo * info) // ============================================================================ void MapAchievement::load(XMLNode * input) { - std::string achieved(""); + bool achieved = false; input->get("achieved", &achieved); - if(achieved == "true") + if(achieved) { m_achieved = true; return; } + std::vector xml_entries; input->getNodes("entry", xml_entries); for (unsigned int n=0; n < xml_entries.size(); n++) diff --git a/src/addons/addons_manager.cpp b/src/addons/addons_manager.cpp index 42974a75f..79f8af473 100644 --- a/src/addons/addons_manager.cpp +++ b/src/addons/addons_manager.cpp @@ -194,7 +194,7 @@ void AddonsManager::initAddons(const XMLNode *xml) if(file_manager->fileExists(full_path)) { if(UserConfigParams::logAddons()) - Log::warn("[addons] Removing cached icon '%s'.\n", + Log::warn("[AddonsManager] Removing cached icon '%s'.\n", addon.getIconBasename().c_str()); file_manager->removeFile(full_path); } @@ -225,10 +225,9 @@ void AddonsManager::initAddons(const XMLNode *xml) } else { - fprintf(stderr, - "[addons] Found invalid node '%s' while downloading addons.\n", + Log::error("[AddonsManager]", "Found invalid node '%s' while downloading addons.", node->getName().c_str()); - fprintf(stderr, "[addons] Ignored.\n"); + Log::error("[AddonsManager]", "Ignored."); } } // for igetNumNodes delete xml; @@ -254,7 +253,7 @@ void AddonsManager::initAddons(const XMLNode *xml) // it from the list. if(UserConfigParams::logAddons()) Log::warn( - "[addons] Removing '%s' which is not on the server anymore.\n", + "[AddonsManager] Removing '%s' which is not on the server anymore.\n", m_addons_list.getData()[i].getId().c_str() ); std::string icon = m_addons_list.getData()[i].getIconBasename(); std::string icon_file =file_manager->getAddonsFile("icons/"+icon); @@ -311,7 +310,7 @@ void AddonsManager::checkInstalledAddons() if(n<0) continue; if(!m_addons_list.getData()[n].isInstalled()) { - Log::info("[addons] Marking '%s' as being installed.\n", + Log::info("[AddonsManager] Marking '%s' as being installed.", kp->getIdent().c_str()); m_addons_list.getData()[n].setInstalled(true); something_was_changed = true; @@ -330,7 +329,7 @@ void AddonsManager::checkInstalledAddons() if(n<0) continue; if(!m_addons_list.getData()[n].isInstalled()) { - Log::info("[addons] Marking '%s' as being installed.\n", + Log::info("[AddonsManager] Marking '%s' as being installed.", track->getIdent().c_str()); m_addons_list.getData()[n].setInstalled(true); something_was_changed = true; @@ -361,9 +360,8 @@ void AddonsManager::downloadIcons() if(icon=="") { if(UserConfigParams::logAddons()) - fprintf(stderr, - "[addons] No icon or image specified for '%s'.\n", - addon.getId().c_str()); + Log::error("[AddonsManager]", "No icon or image specified for '%s'.", + addon.getId().c_str()); continue; } @@ -401,8 +399,8 @@ void AddonsManager::loadInstalledAddons() /* checking for installed addons */ if(UserConfigParams::logAddons()) { - std::cout << "[addons] Loading an xml file for installed addons: "; - std::cout << m_file_installed << std::endl; + Log::info("[AddonsManager]", "Loading an xml file for installed addons: %s", + m_file_installed.c_str()); } const XMLNode *xml = file_manager->createXMLTree(m_file_installed); if(!xml) @@ -479,16 +477,16 @@ bool AddonsManager::install(const Addon &addon) if (!success) { // TODO: show a message in the interface - std::cerr << "[addons] Failed to unzip '" << from << "' to '" - << to << "'\n"; - std::cerr << "[addons] Zip file will not be removed.\n"; + Log::error("[AddonsManager]", "Failed to unzip '%s' to '%s'", + from.c_str(), to.c_str()); + Log::error("[AddonsManager]", "Zip file will not be removed."); return false; } if(!file_manager->removeFile(from)) { - std::cerr << "[addons] Problems removing temporary file '" - << from << "'.\n"; + Log::error("[AddonsManager]", "Problems removing temporary file '%s'", + from.c_str()); } int index = getAddonIndex(addon.getId()); @@ -521,8 +519,8 @@ bool AddonsManager::install(const Addon &addon) } catch (std::exception& e) { - fprintf(stderr, "[AddonsManager] ERROR: Cannot load track <%s> : %s\n", - addon.getDataDir().c_str(), e.what()); + Log::error("[AddonsManager]", "ERROR: Cannot load track <%s> : %s", + addon.getDataDir().c_str(), e.what()); } } saveInstalled(); @@ -536,8 +534,8 @@ bool AddonsManager::install(const Addon &addon) */ bool AddonsManager::uninstall(const Addon &addon) { - std::cout << "[addons] Uninstalling <" - << core::stringc(addon.getName()).c_str() << ">\n"; + Log::info("[AddonsManager]", "Uninstalling <%s>", + core::stringc(addon.getName()).c_str()); // addon is a const reference, and to avoid removing the const, we // find the proper index again to modify the installed state diff --git a/src/addons/news_manager.cpp b/src/addons/news_manager.cpp index 2c001a678..3f6671859 100644 --- a/src/addons/news_manager.cpp +++ b/src/addons/news_manager.cpp @@ -208,10 +208,8 @@ void NewsManager::checkRedirect(const XMLNode *xml) { if(UserConfigParams::logAddons()) { - std::cout << "[Addons] Current server: " - << (std::string)UserConfigParams::m_server_addons - << std::endl - << "[Addons] New server: " << new_server << std::endl; + Log::info("[Addons]", "Current server: '%s'\n [Addons] New server: '%s'", + UserConfigParams::m_server_addons.c_str(), new_server.c_str()); } UserConfigParams::m_server_addons = new_server; } diff --git a/src/challenges/game_slot.cpp b/src/challenges/game_slot.cpp index 63c529ff7..f5e8c2f7e 100644 --- a/src/challenges/game_slot.cpp +++ b/src/challenges/game_slot.cpp @@ -265,8 +265,10 @@ void GameSlot::grandPrixFinished() */ void GameSlot::save(UTFWriter &out) { - out << L" \n"; + out << " \n"; std::map::const_iterator i; for(i = m_challenges_state.begin(); i != m_challenges_state.end(); i++) diff --git a/src/graphics/callbacks.cpp b/src/graphics/callbacks.cpp index 96be2f3c2..889a75517 100644 --- a/src/graphics/callbacks.cpp +++ b/src/graphics/callbacks.cpp @@ -254,13 +254,6 @@ void ColorizeProvider::OnSetConstants(IMaterialRendererServices *srv, int) //------------------------------------- -void GlowProvider::OnSetConstants(IMaterialRendererServices *srv, int) -{ - srv->setVertexShaderConstant("res", m_res, 2); -} - -//------------------------------------- - void ObjectPassProvider::OnSetConstants(IMaterialRendererServices *srv, int) { core::matrix4 ModelViewProjectionMatrix = srv->getVideoDriver()->getTransform(ETS_PROJECTION); diff --git a/src/graphics/callbacks.hpp b/src/graphics/callbacks.hpp index 9be645e7d..a660d9d74 100644 --- a/src/graphics/callbacks.hpp +++ b/src/graphics/callbacks.hpp @@ -328,23 +328,6 @@ private: // -class GlowProvider: public CallBase -{ -public: - virtual void OnSetConstants(video::IMaterialRendererServices *srv, int); - - void setResolution(int x, int y) - { - m_res[0] = (float)x; - m_res[1] = (float)y; - } - -private: - float m_res[2]; -}; - -// - class ObjectPassProvider: public CallBase { public: diff --git a/src/graphics/glow.cpp b/src/graphics/glow.cpp index 323bffc74..5b19e9481 100644 --- a/src/graphics/glow.cpp +++ b/src/graphics/glow.cpp @@ -39,15 +39,6 @@ GlowNode::GlowNode(scene::ISceneManager* mgr, float radius): ISceneNode(mgr->get { if (!sphere) { - mat.Lighting = false; - mat.MaterialType = irr_driver->getShader(ES_GLOW); - - mat.setTexture(0, irr_driver->getRTT(RTT_QUARTER1)); - mat.TextureLayer[0].TextureWrapU = - mat.TextureLayer[0].TextureWrapV = ETC_CLAMP_TO_EDGE; - mat.setFlag(EMF_TRILINEAR_FILTER, true); - mat.BlendOperation = EBO_ADD; - sphere = mgr->getGeometryCreator()->createSphereMesh(1, 4, 4); box = sphere->getBoundingBox(); } @@ -65,10 +56,5 @@ void GlowNode::render() void GlowNode::OnRegisterSceneNode() { - if (IsVisible) - { - SceneManager->registerNodeForRendering(this, ESNRP_TRANSPARENT); - } - ISceneNode::OnRegisterSceneNode(); } diff --git a/src/graphics/glwrap.cpp b/src/graphics/glwrap.cpp index 535c5452d..ec6b0226c 100644 --- a/src/graphics/glwrap.cpp +++ b/src/graphics/glwrap.cpp @@ -2,6 +2,7 @@ #include "irr_driver.hpp" #include #include +#include "config/user_config.hpp" #ifdef _IRR_WINDOWS_API_ #define IRR_OGL_LOAD_EXTENSION(X) wglGetProcAddress(reinterpret_cast(X)) @@ -273,7 +274,7 @@ void bindUniformToTextureUnit(GLuint location, GLuint texid, unsigned textureUni glUniform1i(location, textureUnit); } -void setTexture(unsigned TextureUnit, GLuint TextureId, GLenum MagFilter, GLenum MinFilter) +void setTexture(unsigned TextureUnit, GLuint TextureId, GLenum MagFilter, GLenum MinFilter, bool allowAF) { glActiveTexture(GL_TEXTURE0 + TextureUnit); glBindTexture(GL_TEXTURE_2D, TextureId); @@ -281,6 +282,7 @@ void setTexture(unsigned TextureUnit, GLuint TextureId, GLenum MagFilter, GLenum glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, MinFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, allowAF ? UserConfigParams::m_anisotropic : 0); } static void drawTexColoredQuad(const video::ITexture *texture, const video::SColor *col, float width, float height, diff --git a/src/graphics/glwrap.hpp b/src/graphics/glwrap.hpp index a03a77c2c..0a78d12e1 100644 --- a/src/graphics/glwrap.hpp +++ b/src/graphics/glwrap.hpp @@ -22,7 +22,7 @@ void initGL(); GLuint LoadProgram(const char * vertex_file_path, const char * fragment_file_path); GLuint LoadTFBProgram(const char * vertex_file_path, const char **varyings, unsigned varyingscount); void bindUniformToTextureUnit(GLuint location, GLuint texid, unsigned textureUnit); -void setTexture(unsigned TextureUnit, GLuint TextureId, GLenum MagFilter, GLenum MinFilter); +void setTexture(unsigned TextureUnit, GLuint TextureId, GLenum MagFilter, GLenum MinFilter, bool allowAF = false); // already includes glext.h, which defines useful GL constants. // COpenGLDriver has already loaded the extension GL functions we use (e.g glBeginQuery) diff --git a/src/graphics/gpuparticles.cpp b/src/graphics/gpuparticles.cpp index f33d9e0ab..9f9894e6f 100644 --- a/src/graphics/gpuparticles.cpp +++ b/src/graphics/gpuparticles.cpp @@ -1,5 +1,5 @@ #include "graphics/irr_driver.hpp" -#include "gpuparticles.h" +#include "gpuparticles.hpp" #include "io/file_manager.hpp" #include "config/user_config.hpp" #include @@ -7,102 +7,119 @@ #include "guiengine/engine.hpp" GLuint getTextureGLuint(irr::video::ITexture *tex) { - return static_cast(tex)->getOpenGLTextureName(); + return static_cast(tex)->getOpenGLTextureName(); } #define COMPONENTCOUNT 8 GPUParticle::GPUParticle(scene::ISceneNode *parent, scene::ISceneManager* mgr, ITexture *tex) - : scene::ISceneNode(parent, mgr, -1) { - fakemat.Lighting = false; - fakemat.ZWriteEnable = false; - fakemat.MaterialType = irr_driver->getShader(ES_RAIN); - fakemat.Thickness = 200; - fakemat.setTexture(0, tex); - fakemat.BlendOperation = video::EBO_NONE; - setAutomaticCulling(0); - } +: scene::ISceneNode(parent, mgr, -1) { + fakemat.Lighting = false; + fakemat.ZWriteEnable = false; + fakemat.MaterialType = irr_driver->getShader(ES_RAIN); + fakemat.Thickness = 200; + fakemat.setTexture(0, tex); + fakemat.BlendOperation = video::EBO_NONE; + setAutomaticCulling(0); +} void GPUParticle::render() { - simulate(); - draw(); - // We need to force irrlicht to update its internal states - irr::video::IVideoDriver * const drv = irr_driver->getVideoDriver(); - drv->setMaterial(fakemat); - static_cast(drv)->setRenderStates3DMode(); + simulate(); + draw(); + // We need to force irrlicht to update its internal states + irr::video::IVideoDriver * const drv = irr_driver->getVideoDriver(); + drv->setMaterial(fakemat); + static_cast(drv)->setRenderStates3DMode(); } void GPUParticle::OnRegisterSceneNode() { - if ( - (irr_driver->getRenderPass() & irr::scene::ESNRP_TRANSPARENT) == irr::scene::ESNRP_TRANSPARENT) - { - SceneManager->registerNodeForRendering(this, irr::scene::ESNRP_TRANSPARENT); - } - ISceneNode::OnRegisterSceneNode(); + if ( + (irr_driver->getRenderPass() & irr::scene::ESNRP_TRANSPARENT) == irr::scene::ESNRP_TRANSPARENT) + { + SceneManager->registerNodeForRendering(this, irr::scene::ESNRP_TRANSPARENT); + } + ISceneNode::OnRegisterSceneNode(); } scene::IParticleSystemSceneNode *ParticleSystemProxy::addParticleNode( - bool withDefaultEmitter, ISceneNode* parent, s32 id, - const core::vector3df& position, - const core::vector3df& rotation, - const core::vector3df& scale) { - if (!irr_driver->isGLSL()) - return irr_driver->addParticleNode(); - if (!parent) - parent = irr_driver->getSceneManager()->getRootSceneNode(); + bool withDefaultEmitter, ISceneNode* parent, s32 id, + const core::vector3df& position, + const core::vector3df& rotation, + const core::vector3df& scale) { + if (!irr_driver->isGLSL()) + return irr_driver->addParticleNode(); + if (!parent) + parent = irr_driver->getSceneManager()->getRootSceneNode(); - IParticleSystemSceneNode* node = new ParticleSystemProxy(withDefaultEmitter, - parent, irr_driver->getSceneManager(), id, position, rotation, scale); - node->drop(); + IParticleSystemSceneNode* node = new ParticleSystemProxy(withDefaultEmitter, + parent, irr_driver->getSceneManager(), id, position, rotation, scale); + node->drop(); - return node; + return node; } GLuint ParticleSystemProxy::quad_vertex_buffer = 0; ParticleSystemProxy::ParticleSystemProxy(bool createDefaultEmitter, - ISceneNode* parent, scene::ISceneManager* mgr, s32 id, - const core::vector3df& position, - const core::vector3df& rotation, - const core::vector3df& scale) : CParticleSystemSceneNode(createDefaultEmitter, parent, mgr, id, position, rotation, scale), m_alpha_additive(false) { - fakemat.Lighting = false; - fakemat.ZWriteEnable = false; - fakemat.MaterialType = irr_driver->getShader(ES_RAIN); - fakemat.setTexture(0, getMaterial(0).getTexture(0)); - fakemat.BlendOperation = video::EBO_NONE; - fakemat.FrontfaceCulling = false; - fakemat.BackfaceCulling = false; - glGenBuffers(1, &initial_values_buffer); - glGenBuffers(2, tfb_buffers); - glGenBuffers(1, &quaternionsbuffer); - glGenVertexArrays(1, ¤t_rendering_vao); - glGenVertexArrays(1, &non_current_rendering_vao); - size_increase_factor = 0.; - if (quad_vertex_buffer) - return; - static const GLfloat quad_vertex[] = { - -.5, -.5, 0., 0., - .5, -.5, 1., 0., - -.5, .5, 0., 1., - .5, .5, 1., 1., - }; - glGenBuffers(1, &quad_vertex_buffer); - glBindBuffer(GL_ARRAY_BUFFER, quad_vertex_buffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertex), quad_vertex, GL_STATIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); + ISceneNode* parent, scene::ISceneManager* mgr, s32 id, + const core::vector3df& position, + const core::vector3df& rotation, + const core::vector3df& scale) : CParticleSystemSceneNode(createDefaultEmitter, parent, mgr, id, position, rotation, scale), m_alpha_additive(false) { + fakemat.Lighting = false; + fakemat.ZWriteEnable = false; + fakemat.MaterialType = irr_driver->getShader(ES_RAIN); + fakemat.setTexture(0, getMaterial(0).getTexture(0)); + fakemat.BlendOperation = video::EBO_NONE; + fakemat.FrontfaceCulling = false; + fakemat.BackfaceCulling = false; + glGenBuffers(1, &initial_values_buffer); + glGenBuffers(2, tfb_buffers); + glGenBuffers(1, &quaternionsbuffer); + glGenVertexArrays(1, ¤t_rendering_vao); + glGenVertexArrays(1, &non_current_rendering_vao); + size_increase_factor = 0.; + + // We set these later but avoid coverity report them + heighmapbuffer = 0; + heightmaptexture = 0; + current_simulation_vao = 0; + non_currenthm__simulation_vao = 0; + current_hm_simulation_vao = 0; + current_rendering_flip_vao = 0; + non_current_rendering_flip_vao = 0; + has_height_map = false; + flip = false; + track_x = 0; + track_z = 0; + track_x_len = 0; + track_z_len = 0; + texture = 0; + + if (quad_vertex_buffer) + return; + static const GLfloat quad_vertex[] = { + -.5, -.5, 0., 0., + .5, -.5, 1., 0., + -.5, .5, 0., 1., + .5, .5, 1., 1., + }; + glGenBuffers(1, &quad_vertex_buffer); + glBindBuffer(GL_ARRAY_BUFFER, quad_vertex_buffer); + glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertex), quad_vertex, GL_STATIC_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, 0); } ParticleSystemProxy::~ParticleSystemProxy() { - glDeleteBuffers(2, tfb_buffers); - glDeleteBuffers(1, &initial_values_buffer); - glDeleteBuffers(1, &quaternionsbuffer); - if (has_height_map) - { - glDeleteBuffers(1, &heighmapbuffer); - glDeleteTextures(1, &heightmaptexture); - } - + glDeleteBuffers(2, tfb_buffers); + glDeleteBuffers(1, &initial_values_buffer); + glDeleteBuffers(1, &quaternionsbuffer); + if (has_height_map) + { + glDeleteBuffers(1, &heighmapbuffer); + glDeleteTextures(1, &heightmaptexture); + } + } void ParticleSystemProxy::setAlphaAdditive(bool val) { m_alpha_additive = val; } @@ -110,583 +127,583 @@ void ParticleSystemProxy::setAlphaAdditive(bool val) { m_alpha_additive = val; } void ParticleSystemProxy::setIncreaseFactor(float val) { size_increase_factor = val; } void ParticleSystemProxy::setFlip() { - flip = true; - float *quaternions = new float[4 * count]; - for (unsigned i = 0; i < count; i++) - { - core::vector3df rotationdir(0., 1., 0.); + flip = true; + float *quaternions = new float[4 * count]; + for (unsigned i = 0; i < count; i++) + { + core::vector3df rotationdir(0., 1., 0.); - quaternions[4 * i] = rotationdir.X; - quaternions[4 * i + 1] = rotationdir.Y; - quaternions[4 * i + 2] = rotationdir.Z; - quaternions[4 * i + 3] = 3.14f * 3.f * (2.f * os::Randomizer::frand() - 1.f); // 3 half rotation during lifetime at max - } - glGenBuffers(1, &quaternionsbuffer); - glBindBuffer(GL_ARRAY_BUFFER, quaternionsbuffer); - glBufferData(GL_ARRAY_BUFFER, 4 * count * sizeof(float), quaternions, GL_STATIC_DRAW); + quaternions[4 * i] = rotationdir.X; + quaternions[4 * i + 1] = rotationdir.Y; + quaternions[4 * i + 2] = rotationdir.Z; + quaternions[4 * i + 3] = 3.14f * 3.f * (2.f * os::Randomizer::frand() - 1.f); // 3 half rotation during lifetime at max + } + glGenBuffers(1, &quaternionsbuffer); + glBindBuffer(GL_ARRAY_BUFFER, quaternionsbuffer); + glBufferData(GL_ARRAY_BUFFER, 4 * count * sizeof(float), quaternions, GL_STATIC_DRAW); - glGenVertexArrays(1, ¤t_rendering_flip_vao); - glBindVertexArray(current_rendering_flip_vao); - FlipParticleVAOBind(tfb_buffers[0], quaternionsbuffer); - glGenVertexArrays(1, &non_current_rendering_flip_vao); - glBindVertexArray(non_current_rendering_flip_vao); - FlipParticleVAOBind(tfb_buffers[1], quaternionsbuffer); - glBindVertexArray(0); + glGenVertexArrays(1, ¤t_rendering_flip_vao); + glBindVertexArray(current_rendering_flip_vao); + FlipParticleVAOBind(tfb_buffers[0], quaternionsbuffer); + glGenVertexArrays(1, &non_current_rendering_flip_vao); + glBindVertexArray(non_current_rendering_flip_vao); + FlipParticleVAOBind(tfb_buffers[1], quaternionsbuffer); + glBindVertexArray(0); - delete[] quaternions; + delete[] quaternions; } void ParticleSystemProxy::setHeightmap(const std::vector > &hm, - float f1, float f2, float f3, float f4) { - track_x = f1, track_z = f2, track_x_len = f3, track_z_len = f4; + float f1, float f2, float f3, float f4) { + track_x = f1, track_z = f2, track_x_len = f3, track_z_len = f4; - unsigned width = hm.size(); - unsigned height = hm[0].size(); - float *hm_array = new float[width * height]; - for (unsigned i = 0; i < width; i++) - { - for (unsigned j = 0; j < height; j++) - { - hm_array[i * height + j] = hm[i][j]; - } - } - has_height_map = true; - glGenBuffers(1, &heighmapbuffer); - glBindBuffer(GL_TEXTURE_BUFFER, heighmapbuffer); - glBufferData(GL_TEXTURE_BUFFER, width * height * sizeof(float), hm_array, GL_STATIC_DRAW); - glGenTextures(1, &heightmaptexture); - glBindTexture(GL_TEXTURE_BUFFER, heightmaptexture); - glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, heighmapbuffer); - glBindBuffer(GL_TEXTURE_BUFFER, 0); + unsigned width = hm.size(); + unsigned height = hm[0].size(); + float *hm_array = new float[width * height]; + for (unsigned i = 0; i < width; i++) + { + for (unsigned j = 0; j < height; j++) + { + hm_array[i * height + j] = hm[i][j]; + } + } + has_height_map = true; + glGenBuffers(1, &heighmapbuffer); + glBindBuffer(GL_TEXTURE_BUFFER, heighmapbuffer); + glBufferData(GL_TEXTURE_BUFFER, width * height * sizeof(float), hm_array, GL_STATIC_DRAW); + glGenTextures(1, &heightmaptexture); + glBindTexture(GL_TEXTURE_BUFFER, heightmaptexture); + glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, heighmapbuffer); + glBindBuffer(GL_TEXTURE_BUFFER, 0); - glGenVertexArrays(1, ¤t_hm_simulation_vao); - glBindVertexArray(current_hm_simulation_vao); - HeightmapSimulationBind(tfb_buffers[0], initial_values_buffer); + glGenVertexArrays(1, ¤t_hm_simulation_vao); + glBindVertexArray(current_hm_simulation_vao); + HeightmapSimulationBind(tfb_buffers[0], initial_values_buffer); - glGenVertexArrays(1, &non_currenthm__simulation_vao); - glBindVertexArray(non_currenthm__simulation_vao); - HeightmapSimulationBind(tfb_buffers[1], initial_values_buffer); + glGenVertexArrays(1, &non_currenthm__simulation_vao); + glBindVertexArray(non_currenthm__simulation_vao); + HeightmapSimulationBind(tfb_buffers[1], initial_values_buffer); - glBindVertexArray(0); + glBindVertexArray(0); - delete[] hm_array; + delete[] hm_array; } static void generateLifetimeSizeDirection(scene::IParticleEmitter *emitter, float &lifetime, float &size, float &dirX, float &dirY, float &dirZ) { - float sizeMin = emitter->getMinStartSize().Height; - float sizeMax = emitter->getMaxStartSize().Height; - float lifetime_range = float(emitter->getMaxLifeTime() - emitter->getMinLifeTime()); + float sizeMin = emitter->getMinStartSize().Height; + float sizeMax = emitter->getMaxStartSize().Height; + float lifetime_range = float(emitter->getMaxLifeTime() - emitter->getMinLifeTime()); - lifetime = os::Randomizer::frand() * lifetime_range; - lifetime += emitter->getMinLifeTime(); + lifetime = os::Randomizer::frand() * lifetime_range; + lifetime += emitter->getMinLifeTime(); - size = os::Randomizer::frand(); - size *= (sizeMax - sizeMin); - size += sizeMin; + size = os::Randomizer::frand(); + size *= (sizeMax - sizeMin); + size += sizeMin; - core::vector3df particledir = emitter->getDirection(); - particledir.rotateXYBy(os::Randomizer::frand() * emitter->getMaxAngleDegrees()); - particledir.rotateYZBy(os::Randomizer::frand() * emitter->getMaxAngleDegrees()); - particledir.rotateXZBy(os::Randomizer::frand() * emitter->getMaxAngleDegrees()); + core::vector3df particledir = emitter->getDirection(); + particledir.rotateXYBy(os::Randomizer::frand() * emitter->getMaxAngleDegrees()); + particledir.rotateYZBy(os::Randomizer::frand() * emitter->getMaxAngleDegrees()); + particledir.rotateXZBy(os::Randomizer::frand() * emitter->getMaxAngleDegrees()); - dirX = particledir.X; - dirY = particledir.Y; - dirZ = particledir.Z; + dirX = particledir.X; + dirY = particledir.Y; + dirZ = particledir.Z; } struct ParticleData { - float PositionX; - float PositionY; - float PositionZ; - float Lifetime; - float DirectionX; - float DirectionY; - float DirectionZ; - float Size; + float PositionX; + float PositionY; + float PositionZ; + float Lifetime; + float DirectionX; + float DirectionY; + float DirectionZ; + float Size; }; void ParticleSystemProxy::generateParticlesFromPointEmitter(scene::IParticlePointEmitter *emitter) { - ParticleData *particles = new ParticleData[count], *initialvalue = new ParticleData[count]; + ParticleData *particles = new ParticleData[count], *initialvalue = new ParticleData[count]; - for (unsigned i = 0; i < count; i++) { - particles[i].PositionX = 0; - particles[i].PositionY = 0; - particles[i].PositionZ = 0; - // Initial lifetime is >1 - particles[i].Lifetime = 2.; + for (unsigned i = 0; i < count; i++) { + particles[i].PositionX = 0; + particles[i].PositionY = 0; + particles[i].PositionZ = 0; + // Initial lifetime is >1 + particles[i].Lifetime = 2.; - memcpy(&(initialvalue[i].PositionX), &(particles[i].PositionX), 3 * sizeof(float)); + memcpy(&(initialvalue[i].PositionX), &(particles[i].PositionX), 3 * sizeof(float)); - generateLifetimeSizeDirection(emitter, initialvalue[i].Lifetime, initialvalue[i].Size, - initialvalue[i].DirectionX, initialvalue[i].DirectionY, initialvalue[i].DirectionZ); + generateLifetimeSizeDirection(emitter, initialvalue[i].Lifetime, initialvalue[i].Size, + initialvalue[i].DirectionX, initialvalue[i].DirectionY, initialvalue[i].DirectionZ); - memcpy(&(particles[i].DirectionX), &(initialvalue[i].DirectionX), 4 * sizeof(float)); - } + memcpy(&(particles[i].DirectionX), &(initialvalue[i].DirectionX), 4 * sizeof(float)); + } - glBindBuffer(GL_ARRAY_BUFFER, initial_values_buffer); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), initialvalue, GL_STREAM_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[0]); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), particles, GL_STREAM_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[1]); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), 0, GL_STREAM_DRAW); - delete[] particles; - delete[] initialvalue; + glBindBuffer(GL_ARRAY_BUFFER, initial_values_buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), initialvalue, GL_STREAM_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[0]); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), particles, GL_STREAM_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[1]); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), 0, GL_STREAM_DRAW); + delete[] particles; + delete[] initialvalue; } void ParticleSystemProxy::generateParticlesFromBoxEmitter(scene::IParticleBoxEmitter *emitter) { - ParticleData *particles = new ParticleData[count], *initialvalue = new ParticleData[count]; + ParticleData *particles = new ParticleData[count], *initialvalue = new ParticleData[count]; - const core::vector3df& extent = emitter->getBox().getExtent(); + const core::vector3df& extent = emitter->getBox().getExtent(); - for (unsigned i = 0; i < count; i++) { - particles[i].PositionX = emitter->getBox().MinEdge.X + os::Randomizer::frand() * extent.X; - particles[i].PositionY = emitter->getBox().MinEdge.Y + os::Randomizer::frand() * extent.Y; - particles[i].PositionZ = emitter->getBox().MinEdge.Z + os::Randomizer::frand() * extent.Z; - // Initial lifetime is random - particles[i].Lifetime = os::Randomizer::frand(); + for (unsigned i = 0; i < count; i++) { + particles[i].PositionX = emitter->getBox().MinEdge.X + os::Randomizer::frand() * extent.X; + particles[i].PositionY = emitter->getBox().MinEdge.Y + os::Randomizer::frand() * extent.Y; + particles[i].PositionZ = emitter->getBox().MinEdge.Z + os::Randomizer::frand() * extent.Z; + // Initial lifetime is random + particles[i].Lifetime = os::Randomizer::frand(); - memcpy(&(initialvalue[i].PositionX), &(particles[i].PositionX), 3 * sizeof(float)); - generateLifetimeSizeDirection(emitter, initialvalue[i].Lifetime, initialvalue[i].Size, - initialvalue[i].DirectionX, initialvalue[i].DirectionY, initialvalue[i].DirectionZ); - memcpy(&(particles[i].DirectionX), &(initialvalue[i].DirectionZ), 4 * sizeof(float)); - } - glBindBuffer(GL_ARRAY_BUFFER, initial_values_buffer); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), initialvalue, GL_STREAM_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[0]); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), particles, GL_STREAM_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[1]); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), 0, GL_STREAM_DRAW); - delete[] particles; - delete[] initialvalue; + memcpy(&(initialvalue[i].PositionX), &(particles[i].PositionX), 3 * sizeof(float)); + generateLifetimeSizeDirection(emitter, initialvalue[i].Lifetime, initialvalue[i].Size, + initialvalue[i].DirectionX, initialvalue[i].DirectionY, initialvalue[i].DirectionZ); + memcpy(&(particles[i].DirectionX), &(initialvalue[i].DirectionZ), 4 * sizeof(float)); + } + glBindBuffer(GL_ARRAY_BUFFER, initial_values_buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), initialvalue, GL_STREAM_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[0]); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), particles, GL_STREAM_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[1]); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), 0, GL_STREAM_DRAW); + delete[] particles; + delete[] initialvalue; } void ParticleSystemProxy::generateParticlesFromSphereEmitter(scene::IParticleSphereEmitter *emitter) { - ParticleData *particles = new ParticleData[count], *initialvalue = new ParticleData[count]; + ParticleData *particles = new ParticleData[count], *initialvalue = new ParticleData[count]; - for (unsigned i = 0; i < count; i++) { - // Random distance from center - const f32 distance = os::Randomizer::frand() * emitter->getRadius(); + for (unsigned i = 0; i < count; i++) { + // Random distance from center + const f32 distance = os::Randomizer::frand() * emitter->getRadius(); - // Random direction from center - vector3df pos = emitter->getCenter() + distance; - pos.rotateXYBy(os::Randomizer::frand() * 360.f, emitter->getCenter()); - pos.rotateYZBy(os::Randomizer::frand() * 360.f, emitter->getCenter()); - pos.rotateXZBy(os::Randomizer::frand() * 360.f, emitter->getCenter()); + // Random direction from center + vector3df pos = emitter->getCenter() + distance; + pos.rotateXYBy(os::Randomizer::frand() * 360.f, emitter->getCenter()); + pos.rotateYZBy(os::Randomizer::frand() * 360.f, emitter->getCenter()); + pos.rotateXZBy(os::Randomizer::frand() * 360.f, emitter->getCenter()); - particles[i].PositionX = pos.X; - particles[i].PositionY = pos.Y; - particles[i].PositionZ = pos.Z; - // Initial lifetime is > 1 - particles[i].Lifetime = 2.; + particles[i].PositionX = pos.X; + particles[i].PositionY = pos.Y; + particles[i].PositionZ = pos.Z; + // Initial lifetime is > 1 + particles[i].Lifetime = 2.; - memcpy(&(initialvalue[i].PositionX), &(particles[i].PositionX), 3 * sizeof(float)); - generateLifetimeSizeDirection(emitter, initialvalue[i].Lifetime, initialvalue[i].Size, - initialvalue[i].DirectionX, initialvalue[i].DirectionY, initialvalue[i].DirectionZ); - memcpy(&(particles[i].DirectionX), &(initialvalue[i].DirectionX), 4 * sizeof(float)); - } - glBindBuffer(GL_ARRAY_BUFFER, initial_values_buffer); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), initialvalue, GL_STREAM_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[0]); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), particles, GL_STREAM_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[1]); - glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), 0, GL_STREAM_DRAW); - delete[] particles; - delete[] initialvalue; + memcpy(&(initialvalue[i].PositionX), &(particles[i].PositionX), 3 * sizeof(float)); + generateLifetimeSizeDirection(emitter, initialvalue[i].Lifetime, initialvalue[i].Size, + initialvalue[i].DirectionX, initialvalue[i].DirectionY, initialvalue[i].DirectionZ); + memcpy(&(particles[i].DirectionX), &(initialvalue[i].DirectionX), 4 * sizeof(float)); + } + glBindBuffer(GL_ARRAY_BUFFER, initial_values_buffer); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), initialvalue, GL_STREAM_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[0]); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), particles, GL_STREAM_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, tfb_buffers[1]); + glBufferData(GL_ARRAY_BUFFER, count * sizeof(ParticleData), 0, GL_STREAM_DRAW); + delete[] particles; + delete[] initialvalue; } static bool isGPUParticleType(scene::E_PARTICLE_EMITTER_TYPE type) { - switch (type) - { - case scene::EPET_POINT: - case scene::EPET_BOX: - case scene::EPET_SPHERE: - return true; - default: - return false; - } + switch (type) + { + case scene::EPET_POINT: + case scene::EPET_BOX: + case scene::EPET_SPHERE: + return true; + default: + return false; + } } void ParticleSystemProxy::FlipParticleVAOBind(GLuint PositionBuffer, GLuint QuaternionBuffer) { - glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_pos); - glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_lf); - glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_quadcorner); - glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_texcoord); - glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_sz); + glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_pos); + glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_lf); + glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_quadcorner); + glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_texcoord); + glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_sz); - glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_rotationvec); - glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_anglespeed); - glBindBuffer(GL_ARRAY_BUFFER, QuaternionBuffer); - glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_rotationvec, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); - glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_anglespeed, 1, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (GLvoid *)(3 * sizeof(float))); + glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_rotationvec); + glEnableVertexAttribArray(ParticleShader::FlipParticleRender::attrib_anglespeed); + glBindBuffer(GL_ARRAY_BUFFER, QuaternionBuffer); + glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_rotationvec, 3, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); + glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_anglespeed, 1, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (GLvoid *)(3 * sizeof(float))); - glBindBuffer(GL_ARRAY_BUFFER, quad_vertex_buffer); - glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_quadcorner, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); - glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_texcoord, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (GLvoid *)(2 * sizeof(float))); - glBindBuffer(GL_ARRAY_BUFFER, PositionBuffer); - glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_pos, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), 0); - glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_lf, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid *)(3 * sizeof(float))); - glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_sz, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid *)(7 * sizeof(float))); + glBindBuffer(GL_ARRAY_BUFFER, quad_vertex_buffer); + glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_quadcorner, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); + glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_texcoord, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (GLvoid *)(2 * sizeof(float))); + glBindBuffer(GL_ARRAY_BUFFER, PositionBuffer); + glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_pos, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), 0); + glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_lf, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid *)(3 * sizeof(float))); + glVertexAttribPointer(ParticleShader::FlipParticleRender::attrib_sz, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid *)(7 * sizeof(float))); - glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_lf, 1); - glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_pos, 1); - glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_sz, 1); - glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_rotationvec, 1); - glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_anglespeed, 1); + glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_lf, 1); + glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_pos, 1); + glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_sz, 1); + glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_rotationvec, 1); + glVertexAttribDivisor(ParticleShader::FlipParticleRender::attrib_anglespeed, 1); } void ParticleSystemProxy::SimpleParticleVAOBind(GLuint PositionBuffer) { - glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_pos); - glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_lf); - glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_quadcorner); - glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_texcoord); - glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_sz); + glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_pos); + glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_lf); + glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_quadcorner); + glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_texcoord); + glEnableVertexAttribArray(ParticleShader::SimpleParticleRender::attrib_sz); - glBindBuffer(GL_ARRAY_BUFFER, quad_vertex_buffer); - glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_quadcorner, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); - glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_texcoord, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (GLvoid *)(2 * sizeof(float))); - glBindBuffer(GL_ARRAY_BUFFER, PositionBuffer); - glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_pos, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), 0); - glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_lf, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid *)(3 * sizeof(float))); - glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_sz, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid *)(7 * sizeof(float))); + glBindBuffer(GL_ARRAY_BUFFER, quad_vertex_buffer); + glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_quadcorner, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0); + glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_texcoord, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (GLvoid *)(2 * sizeof(float))); + glBindBuffer(GL_ARRAY_BUFFER, PositionBuffer); + glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_pos, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), 0); + glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_lf, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid *)(3 * sizeof(float))); + glVertexAttribPointer(ParticleShader::SimpleParticleRender::attrib_sz, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid *)(7 * sizeof(float))); - glVertexAttribDivisor(ParticleShader::SimpleParticleRender::attrib_lf, 1); - glVertexAttribDivisor(ParticleShader::SimpleParticleRender::attrib_pos, 1); - glVertexAttribDivisor(ParticleShader::SimpleParticleRender::attrib_sz, 1); + glVertexAttribDivisor(ParticleShader::SimpleParticleRender::attrib_lf, 1); + glVertexAttribDivisor(ParticleShader::SimpleParticleRender::attrib_pos, 1); + glVertexAttribDivisor(ParticleShader::SimpleParticleRender::attrib_sz, 1); } void ParticleSystemProxy::SimpleSimulationBind(GLuint PositionBuffer, GLuint InitialValuesBuffer) { - glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_position); - glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_lifetime); - glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_velocity); - glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_size); - glBindBuffer(GL_ARRAY_BUFFER, PositionBuffer); - glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_position, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)0); - glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_lifetime, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(3 * sizeof(float))); - glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_velocity, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(4 * sizeof(float))); - glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_size, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(7 * sizeof(float))); - glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_initial_position); - glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_initial_lifetime); - glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_initial_velocity); - glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_initial_size); - glBindBuffer(GL_ARRAY_BUFFER, InitialValuesBuffer); - glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_initial_position, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)0); - glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_initial_lifetime, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(3 * sizeof(float))); - glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_initial_velocity, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(4 * sizeof(float))); - glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_initial_size, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(7 * sizeof(float))); + glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_position); + glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_lifetime); + glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_velocity); + glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_size); + glBindBuffer(GL_ARRAY_BUFFER, PositionBuffer); + glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_position, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)0); + glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_lifetime, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(3 * sizeof(float))); + glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_velocity, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(4 * sizeof(float))); + glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_size, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(7 * sizeof(float))); + glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_initial_position); + glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_initial_lifetime); + glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_initial_velocity); + glEnableVertexAttribArray(ParticleShader::SimpleSimulationShader::attrib_initial_size); + glBindBuffer(GL_ARRAY_BUFFER, InitialValuesBuffer); + glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_initial_position, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)0); + glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_initial_lifetime, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(3 * sizeof(float))); + glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_initial_velocity, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(4 * sizeof(float))); + glVertexAttribPointer(ParticleShader::SimpleSimulationShader::attrib_initial_size, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(7 * sizeof(float))); } void ParticleSystemProxy::HeightmapSimulationBind(GLuint PositionBuffer, GLuint InitialValuesBuffer) { - glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_position); - glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_lifetime); - glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_velocity); - // glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_size); - glBindBuffer(GL_ARRAY_BUFFER, PositionBuffer); - glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_position, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)0); - glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_lifetime, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(3 * sizeof(float))); - glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_velocity, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(4 * sizeof(float))); - //glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_size, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(7 * sizeof(float))); - glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_initial_position); - glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_initial_lifetime); - glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_initial_velocity); - glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_initial_size); - glBindBuffer(GL_ARRAY_BUFFER, InitialValuesBuffer); - glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_initial_position, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)0); - glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_initial_lifetime, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(3 * sizeof(float))); - glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_initial_velocity, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(4 * sizeof(float))); - glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_initial_size, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(7 * sizeof(float))); + glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_position); + glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_lifetime); + glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_velocity); + // glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_size); + glBindBuffer(GL_ARRAY_BUFFER, PositionBuffer); + glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_position, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)0); + glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_lifetime, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(3 * sizeof(float))); + glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_velocity, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(4 * sizeof(float))); + //glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_size, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(7 * sizeof(float))); + glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_initial_position); + glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_initial_lifetime); + glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_initial_velocity); + glEnableVertexAttribArray(ParticleShader::HeightmapSimulationShader::attrib_initial_size); + glBindBuffer(GL_ARRAY_BUFFER, InitialValuesBuffer); + glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_initial_position, 3, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)0); + glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_initial_lifetime, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(3 * sizeof(float))); + glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_initial_velocity, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(4 * sizeof(float))); + glVertexAttribPointer(ParticleShader::HeightmapSimulationShader::attrib_initial_size, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(7 * sizeof(float))); } void ParticleSystemProxy::setEmitter(scene::IParticleEmitter* emitter) { - CParticleSystemSceneNode::setEmitter(emitter); - if (!emitter || !isGPUParticleType(emitter->getType())) - return; - has_height_map = false; - flip = false; + CParticleSystemSceneNode::setEmitter(emitter); + if (!emitter || !isGPUParticleType(emitter->getType())) + return; + has_height_map = false; + flip = false; - count = emitter->getMaxParticlesPerSecond() * emitter->getMaxLifeTime() / 1000; - switch (emitter->getType()) - { - case scene::EPET_POINT: - generateParticlesFromPointEmitter(emitter); - break; - case scene::EPET_BOX: - generateParticlesFromBoxEmitter(static_cast(emitter)); - break; - case scene::EPET_SPHERE: - generateParticlesFromSphereEmitter(static_cast(emitter)); - break; - default: - assert(0 && "Wrong particle type"); - } + count = emitter->getMaxParticlesPerSecond() * emitter->getMaxLifeTime() / 1000; + switch (emitter->getType()) + { + case scene::EPET_POINT: + generateParticlesFromPointEmitter(emitter); + break; + case scene::EPET_BOX: + generateParticlesFromBoxEmitter(static_cast(emitter)); + break; + case scene::EPET_SPHERE: + generateParticlesFromSphereEmitter(static_cast(emitter)); + break; + default: + assert(0 && "Wrong particle type"); + } - glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(current_rendering_vao); - SimpleParticleVAOBind(tfb_buffers[0]); + glBindVertexArray(current_rendering_vao); + SimpleParticleVAOBind(tfb_buffers[0]); - glBindVertexArray(non_current_rendering_vao); - SimpleParticleVAOBind(tfb_buffers[1]); + glBindVertexArray(non_current_rendering_vao); + SimpleParticleVAOBind(tfb_buffers[1]); - glGenVertexArrays(1, ¤t_simulation_vao); - glBindVertexArray(current_simulation_vao); - SimpleSimulationBind(tfb_buffers[0], initial_values_buffer); + glGenVertexArrays(1, ¤t_simulation_vao); + glBindVertexArray(current_simulation_vao); + SimpleSimulationBind(tfb_buffers[0], initial_values_buffer); - glGenVertexArrays(1, &non_current_simulation_vao); - glBindVertexArray(non_current_simulation_vao); - SimpleSimulationBind(tfb_buffers[1], initial_values_buffer); + glGenVertexArrays(1, &non_current_simulation_vao); + glBindVertexArray(non_current_simulation_vao); + SimpleSimulationBind(tfb_buffers[1], initial_values_buffer); - glBindVertexArray(0); + glBindVertexArray(0); - texture = getTextureGLuint(getMaterial(0).getTexture(0)); + texture = getTextureGLuint(getMaterial(0).getTexture(0)); } void ParticleSystemProxy::simulateHeightmap() { - int timediff = int(GUIEngine::getLatestDt() * 1000.f); - int active_count = getEmitter()->getMaxLifeTime() * getEmitter()->getMaxParticlesPerSecond() / 1000; - core::matrix4 matrix = getAbsoluteTransformation(); - glUseProgram(ParticleShader::HeightmapSimulationShader::Program); - glEnable(GL_RASTERIZER_DISCARD); + int timediff = int(GUIEngine::getLatestDt() * 1000.f); + int active_count = getEmitter()->getMaxLifeTime() * getEmitter()->getMaxParticlesPerSecond() / 1000; + core::matrix4 matrix = getAbsoluteTransformation(); + glUseProgram(ParticleShader::HeightmapSimulationShader::Program); + glEnable(GL_RASTERIZER_DISCARD); - glUniform1i(ParticleShader::HeightmapSimulationShader::uniform_dt, timediff); - glUniform1i(ParticleShader::HeightmapSimulationShader::uniform_level, active_count); - glUniformMatrix4fv(ParticleShader::HeightmapSimulationShader::uniform_sourcematrix, 1, GL_FALSE, matrix.pointer()); - glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_size_increase_factor, size_increase_factor); - glActiveTexture(GL_TEXTURE2); - glBindTexture(GL_TEXTURE_BUFFER, heightmaptexture); - glUniform1i(ParticleShader::HeightmapSimulationShader::uniform_heightmap, 2); - glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_track_x, track_x); - glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_track_z, track_z); - glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_track_x_len, track_x_len); - glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_track_z_len, track_z_len); + glUniform1i(ParticleShader::HeightmapSimulationShader::uniform_dt, timediff); + glUniform1i(ParticleShader::HeightmapSimulationShader::uniform_level, active_count); + glUniformMatrix4fv(ParticleShader::HeightmapSimulationShader::uniform_sourcematrix, 1, GL_FALSE, matrix.pointer()); + glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_size_increase_factor, size_increase_factor); + glActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_BUFFER, heightmaptexture); + glUniform1i(ParticleShader::HeightmapSimulationShader::uniform_heightmap, 2); + glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_track_x, track_x); + glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_track_z, track_z); + glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_track_x_len, track_x_len); + glUniform1f(ParticleShader::HeightmapSimulationShader::uniform_track_z_len, track_z_len); - glBindVertexArray(current_hm_simulation_vao); - glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfb_buffers[1]); + glBindVertexArray(current_hm_simulation_vao); + glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfb_buffers[1]); - glBeginTransformFeedback(GL_POINTS); - glDrawArrays(GL_POINTS, 0, count); - glEndTransformFeedback(); - glBindVertexArray(0); + glBeginTransformFeedback(GL_POINTS); + glDrawArrays(GL_POINTS, 0, count); + glEndTransformFeedback(); + glBindVertexArray(0); - glDisable(GL_RASTERIZER_DISCARD); - std::swap(tfb_buffers[0], tfb_buffers[1]); - std::swap(current_rendering_flip_vao, non_current_rendering_flip_vao); - std::swap(current_hm_simulation_vao, non_currenthm__simulation_vao); + glDisable(GL_RASTERIZER_DISCARD); + std::swap(tfb_buffers[0], tfb_buffers[1]); + std::swap(current_rendering_flip_vao, non_current_rendering_flip_vao); + std::swap(current_hm_simulation_vao, non_currenthm__simulation_vao); } void ParticleSystemProxy::simulateNoHeightmap() { - int timediff = int(GUIEngine::getLatestDt() * 1000.f); - int active_count = getEmitter()->getMaxLifeTime() * getEmitter()->getMaxParticlesPerSecond() / 1000; - core::matrix4 matrix = getAbsoluteTransformation(); - glUseProgram(ParticleShader::SimpleSimulationShader::Program); - glEnable(GL_RASTERIZER_DISCARD); + int timediff = int(GUIEngine::getLatestDt() * 1000.f); + int active_count = getEmitter()->getMaxLifeTime() * getEmitter()->getMaxParticlesPerSecond() / 1000; + core::matrix4 matrix = getAbsoluteTransformation(); + glUseProgram(ParticleShader::SimpleSimulationShader::Program); + glEnable(GL_RASTERIZER_DISCARD); - glUniform1i(ParticleShader::SimpleSimulationShader::uniform_dt, timediff); - glUniform1i(ParticleShader::SimpleSimulationShader::uniform_level, active_count); - glUniformMatrix4fv(ParticleShader::SimpleSimulationShader::uniform_sourcematrix, 1, GL_FALSE, matrix.pointer()); - glUniform1f(ParticleShader::SimpleSimulationShader::uniform_size_increase_factor, size_increase_factor); + glUniform1i(ParticleShader::SimpleSimulationShader::uniform_dt, timediff); + glUniform1i(ParticleShader::SimpleSimulationShader::uniform_level, active_count); + glUniformMatrix4fv(ParticleShader::SimpleSimulationShader::uniform_sourcematrix, 1, GL_FALSE, matrix.pointer()); + glUniform1f(ParticleShader::SimpleSimulationShader::uniform_size_increase_factor, size_increase_factor); - glBindVertexArray(current_simulation_vao); - glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfb_buffers[1]); + glBindVertexArray(current_simulation_vao); + glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfb_buffers[1]); - glBeginTransformFeedback(GL_POINTS); - glDrawArrays(GL_POINTS, 0, count); - glEndTransformFeedback(); - glBindVertexArray(0); + glBeginTransformFeedback(GL_POINTS); + glDrawArrays(GL_POINTS, 0, count); + glEndTransformFeedback(); + glBindVertexArray(0); - glDisable(GL_RASTERIZER_DISCARD); - std::swap(tfb_buffers[0], tfb_buffers[1]); - std::swap(current_rendering_vao, non_current_rendering_vao); - std::swap(current_simulation_vao, non_current_simulation_vao); + glDisable(GL_RASTERIZER_DISCARD); + std::swap(tfb_buffers[0], tfb_buffers[1]); + std::swap(current_rendering_vao, non_current_rendering_vao); + std::swap(current_simulation_vao, non_current_simulation_vao); } void ParticleSystemProxy::simulate() { - if (has_height_map) - simulateHeightmap(); - else - simulateNoHeightmap(); + if (has_height_map) + simulateHeightmap(); + else + simulateNoHeightmap(); } void ParticleSystemProxy::drawFlip() { - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glUseProgram(ParticleShader::FlipParticleRender::Program); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glUseProgram(ParticleShader::FlipParticleRender::Program); - float screen[2] = { - (float)UserConfigParams::m_width, - (float)UserConfigParams::m_height - }; + float screen[2] = { + (float)UserConfigParams::m_width, + (float)UserConfigParams::m_height + }; - setTexture(0, texture, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); - setTexture(1, static_cast(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH))->DepthBufferTexture, GL_NEAREST, GL_NEAREST); + setTexture(0, texture, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(1, static_cast(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH))->DepthBufferTexture, GL_NEAREST, GL_NEAREST); - ParticleShader::FlipParticleRender::setUniforms(irr_driver->getViewMatrix(), irr_driver->getProjMatrix(), irr_driver->getInvProjMatrix(), screen[0], screen[1], 0, 1); + ParticleShader::FlipParticleRender::setUniforms(irr_driver->getViewMatrix(), irr_driver->getProjMatrix(), irr_driver->getInvProjMatrix(), screen[0], screen[1], 0, 1); - glBindVertexArray(current_rendering_flip_vao); - glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, count); + glBindVertexArray(current_rendering_flip_vao); + glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, count); } void ParticleSystemProxy::drawNotFlip() { - if (m_alpha_additive) - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - else - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glUseProgram(ParticleShader::SimpleParticleRender::Program); + if (m_alpha_additive) + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + else + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glUseProgram(ParticleShader::SimpleParticleRender::Program); - float screen[2] = { - (float)UserConfigParams::m_width, - (float)UserConfigParams::m_height - }; + float screen[2] = { + (float)UserConfigParams::m_width, + (float)UserConfigParams::m_height + }; - setTexture(0, texture, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); - setTexture(1, static_cast(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH))->DepthBufferTexture, GL_NEAREST, GL_NEAREST); + setTexture(0, texture, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(1, static_cast(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH))->DepthBufferTexture, GL_NEAREST, GL_NEAREST); - ParticleShader::SimpleParticleRender::setUniforms(irr_driver->getViewMatrix(), irr_driver->getProjMatrix(), irr_driver->getInvProjMatrix(), screen[0], screen[1], 0, 1); + ParticleShader::SimpleParticleRender::setUniforms(irr_driver->getViewMatrix(), irr_driver->getProjMatrix(), irr_driver->getInvProjMatrix(), screen[0], screen[1], 0, 1); - glBindVertexArray(current_rendering_vao); - glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, count); + glBindVertexArray(current_rendering_vao); + glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, count); } void ParticleSystemProxy::draw() { - if (flip) - drawFlip(); - else - drawNotFlip(); + if (flip) + drawFlip(); + else + drawNotFlip(); } void ParticleSystemProxy::render() { - if (!getEmitter() || !isGPUParticleType(getEmitter()->getType())) - { - CParticleSystemSceneNode::render(); - return; - } - simulate(); - draw(); + if (!getEmitter() || !isGPUParticleType(getEmitter()->getType())) + { + CParticleSystemSceneNode::render(); + return; + } + simulate(); + draw(); } void ParticleSystemProxy::OnRegisterSceneNode() { - doParticleSystem(os::Timer::getTime()); + doParticleSystem(os::Timer::getTime()); - if (IsVisible && (Particles.size() != 0)) - { - SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT_EFFECT); - ISceneNode::OnRegisterSceneNode(); - } + if (IsVisible && (Particles.size() != 0)) + { + SceneManager->registerNodeForRendering(this, scene::ESNRP_TRANSPARENT_EFFECT); + ISceneNode::OnRegisterSceneNode(); + } } RainNode::RainNode(scene::ISceneManager* mgr, ITexture *tex) - : GPUParticle(0, mgr, tex) +: GPUParticle(0, mgr, tex) { - RenderProgram = LoadProgram(file_manager->getAsset("shaders/rain.vert").c_str(), file_manager->getAsset("shaders/rain.frag").c_str()); - loc_screenw = glGetUniformLocation(RenderProgram, "screenw"); - loc_screen = glGetUniformLocation(RenderProgram, "screen"); - loc_invproj = glGetUniformLocation(RenderProgram, "invproj"); - texloc_tex = glGetUniformLocation(RenderProgram, "tex"); - texloc_normal_and_depths = glGetUniformLocation(RenderProgram, "normals_and_depth"); + RenderProgram = LoadProgram(file_manager->getAsset("shaders/rain.vert").c_str(), file_manager->getAsset("shaders/rain.frag").c_str()); + loc_screenw = glGetUniformLocation(RenderProgram, "screenw"); + loc_screen = glGetUniformLocation(RenderProgram, "screen"); + loc_invproj = glGetUniformLocation(RenderProgram, "invproj"); + texloc_tex = glGetUniformLocation(RenderProgram, "tex"); + texloc_normal_and_depths = glGetUniformLocation(RenderProgram, "normals_and_depth"); - const char *varyings[] = { "currentPosition" }; - SimulationProgram = LoadTFBProgram(file_manager->getAsset("shaders/rainsim.vert").c_str(), varyings, 1); - loc_campos = glGetUniformLocation(SimulationProgram, "campos"); - loc_viewm = glGetUniformLocation(SimulationProgram, "viewm"); - loc_time = glGetUniformLocation(SimulationProgram, "time"); - count = 2500; - area = 3500; + const char *varyings[] = { "currentPosition" }; + SimulationProgram = LoadTFBProgram(file_manager->getAsset("shaders/rainsim.vert").c_str(), varyings, 1); + loc_campos = glGetUniformLocation(SimulationProgram, "campos"); + loc_viewm = glGetUniformLocation(SimulationProgram, "viewm"); + loc_time = glGetUniformLocation(SimulationProgram, "time"); + count = 2500; + area = 3500; - u32 i; - float x, y, z, vertices[7500]; - for (i = 0; i < count; i++) - { - x = ((rand() % area) - area / 2) / 100.0f; - y = ((rand() % 2400)) / 100.0f; - z = ((rand() % area) - area / 2) / 100.0f; + u32 i; + float x, y, z, vertices[7500]; + for (i = 0; i < count; i++) + { + x = ((rand() % area) - area / 2) / 100.0f; + y = ((rand() % 2400)) / 100.0f; + z = ((rand() % area) - area / 2) / 100.0f; - vertices[3 * i] = x; - vertices[3 * i + 1] = y; - vertices[3 * i + 2] = z; - } - - texture = getTextureGLuint(tex); - normal_and_depth = getTextureGLuint(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH)); - glGenBuffers(2, tfb_vertex_buffer); - glBindBuffer(GL_ARRAY_BUFFER, tfb_vertex_buffer[0]); - glBufferData(GL_ARRAY_BUFFER, 3 * count * sizeof(float), vertices, GL_STREAM_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, tfb_vertex_buffer[1]); - glBufferData(GL_ARRAY_BUFFER, 3 * count * sizeof(float), 0, GL_STREAM_DRAW); + vertices[3 * i] = x; + vertices[3 * i + 1] = y; + vertices[3 * i + 2] = z; + } - box.addInternalPoint(vector3df((float)(-area / 2))); - box.addInternalPoint(vector3df((float)(area / 2))); + texture = getTextureGLuint(tex); + normal_and_depth = getTextureGLuint(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH)); + glGenBuffers(2, tfb_vertex_buffer); + glBindBuffer(GL_ARRAY_BUFFER, tfb_vertex_buffer[0]); + glBufferData(GL_ARRAY_BUFFER, 3 * count * sizeof(float), vertices, GL_STREAM_DRAW); + glBindBuffer(GL_ARRAY_BUFFER, tfb_vertex_buffer[1]); + glBufferData(GL_ARRAY_BUFFER, 3 * count * sizeof(float), 0, GL_STREAM_DRAW); + + box.addInternalPoint(vector3df((float)(-area / 2))); + box.addInternalPoint(vector3df((float)(area / 2))); } void RainNode::simulate() { - glUseProgram(SimulationProgram); - const float time = irr_driver->getDevice()->getTimer()->getTime() / 90.0f; - const irr::core::matrix4 viewm = irr_driver->getVideoDriver()->getTransform(irr::video::ETS_VIEW); - const irr::core::vector3df campos = irr_driver->getSceneManager()->getActiveCamera()->getPosition(); + glUseProgram(SimulationProgram); + const float time = irr_driver->getDevice()->getTimer()->getTime() / 90.0f; + const irr::core::matrix4 viewm = irr_driver->getVideoDriver()->getTransform(irr::video::ETS_VIEW); + const irr::core::vector3df campos = irr_driver->getSceneManager()->getActiveCamera()->getPosition(); - glEnable(GL_RASTERIZER_DISCARD); - glEnableVertexAttribArray(0); - glBindBuffer(GL_ARRAY_BUFFER, tfb_vertex_buffer[0]); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); - glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfb_vertex_buffer[1]); + glEnable(GL_RASTERIZER_DISCARD); + glEnableVertexAttribArray(0); + glBindBuffer(GL_ARRAY_BUFFER, tfb_vertex_buffer[0]); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); + glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfb_vertex_buffer[1]); - glUniformMatrix4fv(loc_viewm, 1, GL_FALSE, viewm.pointer()); - glUniform1f(loc_time, time); - glUniform3f(loc_campos, campos.X, campos.Y, campos.Z); - glBeginTransformFeedback(GL_POINTS); - glDrawArrays(GL_POINTS, 0, count); - glEndTransformFeedback(); - glDisable(GL_RASTERIZER_DISCARD); + glUniformMatrix4fv(loc_viewm, 1, GL_FALSE, viewm.pointer()); + glUniform1f(loc_time, time); + glUniform3f(loc_campos, campos.X, campos.Y, campos.Z); + glBeginTransformFeedback(GL_POINTS); + glDrawArrays(GL_POINTS, 0, count); + glEndTransformFeedback(); + glDisable(GL_RASTERIZER_DISCARD); } void RainNode::draw() { - const float screenw = (float)UserConfigParams::m_width; + const float screenw = (float)UserConfigParams::m_width; - glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); - glEnable(GL_POINT_SPRITE); - glUseProgram(RenderProgram); - glEnableVertexAttribArray(0); - glBindBuffer(GL_ARRAY_BUFFER, tfb_vertex_buffer[1]); - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); + glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); + glEnable(GL_POINT_SPRITE); + glUseProgram(RenderProgram); + glEnableVertexAttribArray(0); + glBindBuffer(GL_ARRAY_BUFFER, tfb_vertex_buffer[1]); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); - float screen[2] = { - (float)UserConfigParams::m_width, - (float)UserConfigParams::m_height - }; - irr::core::matrix4 invproj = irr_driver->getVideoDriver()->getTransform(irr::video::ETS_PROJECTION); - invproj.makeInverse(); + float screen[2] = { + (float)UserConfigParams::m_width, + (float)UserConfigParams::m_height + }; + irr::core::matrix4 invproj = irr_driver->getVideoDriver()->getTransform(irr::video::ETS_PROJECTION); + invproj.makeInverse(); - bindUniformToTextureUnit(texloc_tex, texture, 0); - bindUniformToTextureUnit(texloc_normal_and_depths, normal_and_depth, 1); + bindUniformToTextureUnit(texloc_tex, texture, 0); + bindUniformToTextureUnit(texloc_normal_and_depths, normal_and_depth, 1); - glUniformMatrix4fv(loc_invproj, 1, GL_FALSE, invproj.pointer()); - glUniform2f(loc_screen, screen[0], screen[1]); - glUniform1f(loc_screenw, screenw); - glDrawArrays(GL_POINTS, 0, count); - glDisableVertexAttribArray(0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glActiveTexture(GL_TEXTURE0); - glDisable(GL_VERTEX_PROGRAM_POINT_SIZE); + glUniformMatrix4fv(loc_invproj, 1, GL_FALSE, invproj.pointer()); + glUniform2f(loc_screen, screen[0], screen[1]); + glUniform1f(loc_screenw, screenw); + glDrawArrays(GL_POINTS, 0, count); + glDisableVertexAttribArray(0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glActiveTexture(GL_TEXTURE0); + glDisable(GL_VERTEX_PROGRAM_POINT_SIZE); } const core::aabbox3d& RainNode::getBoundingBox() const { - return box; + return box; } diff --git a/src/graphics/gpuparticles.h b/src/graphics/gpuparticles.h deleted file mode 100644 index 4c9c7d03f..000000000 --- a/src/graphics/gpuparticles.h +++ /dev/null @@ -1,98 +0,0 @@ -#ifndef GPUPARTICLES_H -#define GPUPARTICLES_H - -#include "graphics/glwrap.hpp" - -#include "../lib/irrlicht/source/Irrlicht/CParticleSystemSceneNode.h" -#include -#include - -namespace irr { namespace video{ class ITexture; } } - -GLuint getTextureGLuint(irr::video::ITexture *tex); - -class GPUParticle : public scene::ISceneNode -{ -protected: - video::SMaterial fakemat; - virtual void simulate() = 0; - virtual void draw() = 0; -public: - GPUParticle(scene::ISceneNode *parent, scene::ISceneManager* mgr, - video::ITexture *tex); - virtual void render(); - virtual void OnRegisterSceneNode(); -}; - -class ParticleSystemProxy : public scene::CParticleSystemSceneNode { -protected: - video::SMaterial fakemat; - GLuint tfb_buffers[2], initial_values_buffer, heighmapbuffer, heightmaptexture, quaternionsbuffer; - GLuint current_simulation_vao, non_current_simulation_vao; - GLuint current_hm_simulation_vao, non_currenthm__simulation_vao; - GLuint current_rendering_vao, non_current_rendering_vao; - GLuint current_rendering_flip_vao, non_current_rendering_flip_vao; - bool m_alpha_additive, has_height_map, flip; - float size_increase_factor, track_x, track_z, track_x_len, track_z_len; - - static GLuint quad_vertex_buffer; - - GLuint texture; - unsigned count; - static void SimpleParticleVAOBind(GLuint PositionBuffer); - static void FlipParticleVAOBind(GLuint PositionBuffer, GLuint QuaternionBuffer); - static void SimpleSimulationBind(GLuint PositionBuffer, GLuint InitialValuesBuffer); - static void HeightmapSimulationBind(GLuint PositionBuffer, GLuint InitialValuesBuffer); - - void simulateHeightmap(); - void simulateNoHeightmap(); - void drawFlip(); - void drawNotFlip(); - virtual void simulate(); - virtual void draw(); - void generateParticlesFromPointEmitter(scene::IParticlePointEmitter *); - void generateParticlesFromBoxEmitter(scene::IParticleBoxEmitter *); - void generateParticlesFromSphereEmitter(scene::IParticleSphereEmitter *); -public: - static IParticleSystemSceneNode *addParticleNode( - bool withDefaultEmitter = true, ISceneNode* parent = 0, s32 id = -1, - const core::vector3df& position = core::vector3df(0, 0, 0), - const core::vector3df& rotation = core::vector3df(0, 0, 0), - const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f)); - - ParticleSystemProxy(bool createDefaultEmitter, - ISceneNode* parent, scene::ISceneManager* mgr, s32 id, - const core::vector3df& position, - const core::vector3df& rotation, - const core::vector3df& scale); - ~ParticleSystemProxy(); - - virtual void setEmitter(scene::IParticleEmitter* emitter); - virtual void render(); - virtual void OnRegisterSceneNode(); - void setAlphaAdditive(bool); - void setIncreaseFactor(float); - void setHeightmap(const std::vector >&, float, float, float, float); - void setFlip(); -}; - -class RainNode : public GPUParticle -{ -protected: - GLuint SimulationProgram, RenderProgram, tfb_vertex_buffer[2]; - unsigned count; - GLuint texture, normal_and_depth; - GLuint loc_campos, loc_viewm, loc_time; - GLuint loc_screenw, loc_screen, loc_invproj, texloc_tex, texloc_normal_and_depths; - s32 area; - core::aabbox3d box; - - virtual void simulate(); - virtual void draw(); -public: - RainNode(scene::ISceneManager* mgr, video::ITexture *tex); - virtual const core::aabbox3d& getBoundingBox() const; - virtual u32 getMaterialCount() const { return 1; } -}; - -#endif // GPUPARTICLES_H diff --git a/src/graphics/gpuparticles.hpp b/src/graphics/gpuparticles.hpp new file mode 100644 index 000000000..5228ed0e1 --- /dev/null +++ b/src/graphics/gpuparticles.hpp @@ -0,0 +1,98 @@ +#ifndef GPUPARTICLES_H +#define GPUPARTICLES_H + +#include "graphics/glwrap.hpp" + +#include "../lib/irrlicht/source/Irrlicht/CParticleSystemSceneNode.h" +#include +#include + +namespace irr { namespace video{ class ITexture; } } + +GLuint getTextureGLuint(irr::video::ITexture *tex); + +class GPUParticle : public scene::ISceneNode +{ +protected: + video::SMaterial fakemat; + virtual void simulate() = 0; + virtual void draw() = 0; +public: + GPUParticle(scene::ISceneNode *parent, scene::ISceneManager* mgr, + video::ITexture *tex); + virtual void render(); + virtual void OnRegisterSceneNode(); +}; + +class ParticleSystemProxy : public scene::CParticleSystemSceneNode { +protected: + video::SMaterial fakemat; + GLuint tfb_buffers[2], initial_values_buffer, heighmapbuffer, heightmaptexture, quaternionsbuffer; + GLuint current_simulation_vao, non_current_simulation_vao; + GLuint current_hm_simulation_vao, non_currenthm__simulation_vao; + GLuint current_rendering_vao, non_current_rendering_vao; + GLuint current_rendering_flip_vao, non_current_rendering_flip_vao; + bool m_alpha_additive, has_height_map, flip; + float size_increase_factor, track_x, track_z, track_x_len, track_z_len; + + static GLuint quad_vertex_buffer; + + GLuint texture; + unsigned count; + static void SimpleParticleVAOBind(GLuint PositionBuffer); + static void FlipParticleVAOBind(GLuint PositionBuffer, GLuint QuaternionBuffer); + static void SimpleSimulationBind(GLuint PositionBuffer, GLuint InitialValuesBuffer); + static void HeightmapSimulationBind(GLuint PositionBuffer, GLuint InitialValuesBuffer); + + void simulateHeightmap(); + void simulateNoHeightmap(); + void drawFlip(); + void drawNotFlip(); + virtual void simulate(); + virtual void draw(); + void generateParticlesFromPointEmitter(scene::IParticlePointEmitter *); + void generateParticlesFromBoxEmitter(scene::IParticleBoxEmitter *); + void generateParticlesFromSphereEmitter(scene::IParticleSphereEmitter *); +public: + static IParticleSystemSceneNode *addParticleNode( + bool withDefaultEmitter = true, ISceneNode* parent = 0, s32 id = -1, + const core::vector3df& position = core::vector3df(0, 0, 0), + const core::vector3df& rotation = core::vector3df(0, 0, 0), + const core::vector3df& scale = core::vector3df(1.0f, 1.0f, 1.0f)); + + ParticleSystemProxy(bool createDefaultEmitter, + ISceneNode* parent, scene::ISceneManager* mgr, s32 id, + const core::vector3df& position, + const core::vector3df& rotation, + const core::vector3df& scale); + ~ParticleSystemProxy(); + + virtual void setEmitter(scene::IParticleEmitter* emitter); + virtual void render(); + virtual void OnRegisterSceneNode(); + void setAlphaAdditive(bool); + void setIncreaseFactor(float); + void setHeightmap(const std::vector >&, float, float, float, float); + void setFlip(); +}; + +class RainNode : public GPUParticle +{ +protected: + GLuint SimulationProgram, RenderProgram, tfb_vertex_buffer[2]; + unsigned count; + GLuint texture, normal_and_depth; + GLuint loc_campos, loc_viewm, loc_time; + GLuint loc_screenw, loc_screen, loc_invproj, texloc_tex, texloc_normal_and_depths; + s32 area; + core::aabbox3d box; + + virtual void simulate(); + virtual void draw(); +public: + RainNode(scene::ISceneManager* mgr, video::ITexture *tex); + virtual const core::aabbox3d& getBoundingBox() const; + virtual u32 getMaterialCount() const { return 1; } +}; + +#endif // GPUPARTICLES_H diff --git a/src/graphics/irr_driver.cpp b/src/graphics/irr_driver.cpp index b4ae1bf59..9141dc725 100644 --- a/src/graphics/irr_driver.cpp +++ b/src/graphics/irr_driver.cpp @@ -945,17 +945,6 @@ scene::IMeshSceneNode *IrrDriver::addMesh(scene::IMesh *mesh, // ---------------------------------------------------------------------------- -PerCameraNode *IrrDriver::addPerCameraMesh(scene::IMesh* mesh, - scene::ICameraSceneNode* camera, - scene::ISceneNode *parent) -{ - scene::ISceneNode *node = m_scene_manager->addMeshSceneNode(mesh); - - return new PerCameraNode((parent ? parent - : m_scene_manager->getRootSceneNode()), - m_scene_manager, -1, camera, node); -} // addMesh - PerCameraNode *IrrDriver::addPerCameraNode(scene::ISceneNode* node, scene::ICameraSceneNode* camera, scene::ISceneNode *parent) @@ -1457,15 +1446,15 @@ void IrrDriver::setAmbientLight(const video::SColor &light) */ void IrrDriver::displayFPS() { - gui::IGUIFont* font = GUIEngine::getFont(); + gui::IGUIFont* font = GUIEngine::getSmallFont(); if(UserConfigParams::m_artist_debug_mode) { - GL32_draw2DRectangle(video::SColor(150, 96, 74, 196),core::rect< s32 >(75,0,1100,50),NULL); + GL32_draw2DRectangle(video::SColor(150, 96, 74, 196),core::rect< s32 >(75,0,1100,40),NULL); } else { - GL32_draw2DRectangle(video::SColor(150, 96, 74, 196),core::rect< s32 >(75,0,900,50),NULL); + GL32_draw2DRectangle(video::SColor(150, 96, 74, 196),core::rect< s32 >(75,0,900,40),NULL); } // We will let pass some time to let things settle before trusting FPS counter // even if we also ignore fps = 1, which tends to happen in first checks @@ -1520,7 +1509,9 @@ void IrrDriver::displayFPS() { sprintf(buffer, "FPS: %i/%i/%i - Objects (P1:%d P2:%d T:%d) KTris - LightDst : ~%d", min, fps, max, object_count[SOLID_NORMAL_AND_DEPTH_PASS], object_count[SOLID_NORMAL_AND_DEPTH_PASS], object_count[TRANSPARENT_PASS], m_last_light_bucket_distance); - object_count[SOLID_NORMAL_AND_DEPTH_PASS] = object_count[SOLID_NORMAL_AND_DEPTH_PASS] = object_count[TRANSPARENT_PASS] = 0; + object_count[SOLID_NORMAL_AND_DEPTH_PASS] = 0; + object_count[SOLID_NORMAL_AND_DEPTH_PASS] = 0; + object_count[TRANSPARENT_PASS] = 0; } else { diff --git a/src/graphics/irr_driver.hpp b/src/graphics/irr_driver.hpp index db936bba3..9a2fbda5c 100644 --- a/src/graphics/irr_driver.hpp +++ b/src/graphics/irr_driver.hpp @@ -102,6 +102,7 @@ private: RTT *m_rtts; /** Shadow importance. */ ShadowImportance *m_shadow_importance; + core::matrix4 sun_ortho_matrix; /** Additional details to be shown in case that a texture is not found. * This is used to specify details like: "while loading kart '...'" */ @@ -111,7 +112,7 @@ private: core::array m_mrt; /** Matrixes used in several places stored here to avoid recomputation. */ - core::matrix4 m_ViewMatrix, m_ProjMatrix, m_InvProjMatrix, m_ProjViewMatrix, m_InvProjViewMatrix; + core::matrix4 m_ViewMatrix, m_InvViewMatrix, m_ProjMatrix, m_InvProjMatrix, m_ProjViewMatrix, m_InvProjViewMatrix; std::vector SkyboxTextures; @@ -203,9 +204,9 @@ private: void renderFixed(float dt); void renderGLSL(float dt); - void renderShadows(ShadowImportanceProvider * const sicb, + void renderShadows(//ShadowImportanceProvider * const sicb, scene::ICameraSceneNode * const camnode, - video::SOverrideMaterial &overridemat, + //video::SOverrideMaterial &overridemat, Camera * const camera); void renderGlow(video::SOverrideMaterial &overridemat, std::vector& glows, @@ -260,9 +261,6 @@ public: const video::SColor &color=video::SColor(128, 255, 255, 255)); scene::IMeshSceneNode*addMesh(scene::IMesh *mesh, scene::ISceneNode *parent=NULL); - PerCameraNode *addPerCameraMesh(scene::IMesh* mesh, - scene::ICameraSceneNode* node, - scene::ISceneNode *parent = NULL); PerCameraNode *addPerCameraNode(scene::ISceneNode* node, scene::ICameraSceneNode* cam, scene::ISceneNode *parent = NULL); @@ -495,8 +493,9 @@ public: // ------------------------------------------------------------------------ scene::IMeshSceneNode *getSunInterposer() { return m_sun_interposer; } // ------------------------------------------------------------------------ - void setViewMatrix(core::matrix4 matrix) { m_ViewMatrix = matrix; } + void setViewMatrix(core::matrix4 matrix) { m_ViewMatrix = matrix; matrix.getInverse(m_InvViewMatrix); } const core::matrix4 &getViewMatrix() const { return m_ViewMatrix; } + const core::matrix4 &getInvViewMatrix() const { return m_InvViewMatrix; } void setProjMatrix(core::matrix4 matrix) { m_ProjMatrix = matrix; matrix.getInverse(m_InvProjMatrix); } const core::matrix4 &getProjMatrix() const { return m_ProjMatrix; } const core::matrix4 &getInvProjMatrix() const { return m_InvProjMatrix; } diff --git a/src/graphics/light.hpp b/src/graphics/light.hpp index c649bc495..1f17c5aad 100644 --- a/src/graphics/light.hpp +++ b/src/graphics/light.hpp @@ -66,8 +66,6 @@ public: protected: static core::aabbox3df box; - class ScreenQuad *sq; - //float m_radius; float m_color[3]; float m_energy; diff --git a/src/graphics/particle_emitter.cpp b/src/graphics/particle_emitter.cpp index 2d17796e0..d96bb310b 100644 --- a/src/graphics/particle_emitter.cpp +++ b/src/graphics/particle_emitter.cpp @@ -28,7 +28,7 @@ #include "tracks/track.hpp" #include "utils/constants.hpp" #include "utils/helpers.hpp" -#include "graphics/gpuparticles.h" +#include "graphics/gpuparticles.hpp" #include #include diff --git a/src/graphics/post_processing.cpp b/src/graphics/post_processing.cpp index e02352216..27415cbf2 100644 --- a/src/graphics/post_processing.cpp +++ b/src/graphics/post_processing.cpp @@ -57,7 +57,11 @@ PostProcessing::PostProcessing(IVideoDriver* video_driver) io::IReadFile *areamap = irr_driver->getDevice()->getFileSystem()-> createMemoryReadFile((void *) AreaMap33, sizeof(AreaMap33), "AreaMap33", false); - if (!areamap) Log::fatal("postprocessing", "Failed to load the areamap"); + if (!areamap) + { + Log::fatal("postprocessing", "Failed to load the areamap"); + return; + } m_areamap = irr_driver->getVideoDriver()->getTexture(areamap); areamap->drop(); @@ -342,55 +346,25 @@ void PostProcessing::renderSunlight() glBindVertexArray(0); } -void PostProcessing::renderLightbBlend(ITexture *diffuse, ITexture *specular, ITexture *ao, ITexture *specmap, bool debug) +void PostProcessing::renderShadowedSunlight(const core::matrix4 &sun_ortho_matrix) { - const SColorf s = irr_driver->getSceneManager()->getAmbientLight(); - glStencilFunc(GL_EQUAL, 1, ~0); - glEnable(GL_STENCIL_TEST); - glEnable(GL_BLEND); - glBlendEquation(GL_FUNC_ADD); - if (debug) - glBlendFunc(GL_ONE, GL_ZERO); - else - glBlendFunc(GL_DST_COLOR, GL_ZERO); - glDisable(GL_DEPTH_TEST); + SunLightProvider * const cb = (SunLightProvider *)irr_driver->getCallback(ES_SUNLIGHT); - glUseProgram(FullScreenShader::LightBlendShader::Program); - glBindVertexArray(FullScreenShader::LightBlendShader::vao); + glEnable(GL_BLEND); + glDisable(GL_DEPTH_TEST); + glBlendFunc(GL_ONE, GL_ONE); + glBlendEquation(GL_FUNC_ADD); - glUniform3f(FullScreenShader::LightBlendShader::uniform_ambient, s.r, s.g, s.b); - - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, static_cast(diffuse)->getOpenGLTextureName()); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glUniform1i(FullScreenShader::LightBlendShader::uniform_diffuse, 0); - glActiveTexture(GL_TEXTURE1); - glBindTexture(GL_TEXTURE_2D, static_cast(specular)->getOpenGLTextureName()); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glUniform1i(FullScreenShader::LightBlendShader::uniform_specular, 1); - glActiveTexture(GL_TEXTURE2); - glBindTexture(GL_TEXTURE_2D, static_cast(ao)->getOpenGLTextureName()); - glUniform1i(FullScreenShader::LightBlendShader::uniform_ambient_occlusion, 2); - glActiveTexture(GL_TEXTURE3); - if (!UserConfigParams::m_ssao) - { - GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ONE}; - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } - glBindTexture(GL_TEXTURE_2D, static_cast(specmap)->getOpenGLTextureName()); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glUniform1i(FullScreenShader::LightBlendShader::uniform_specular_map, 3); - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - glBindVertexArray(0); - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - glEnable(GL_DEPTH_TEST); - glDisable(GL_BLEND); - glDisable(GL_STENCIL_TEST); + glUseProgram(FullScreenShader::ShadowedSunLightShader::Program); + glBindVertexArray(FullScreenShader::ShadowedSunLightShader::vao); + setTexture(0, static_cast(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH))->getOpenGLTextureName(), GL_NEAREST, GL_NEAREST); + setTexture(1, static_cast(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH))->DepthBufferTexture, GL_NEAREST, GL_NEAREST); + setTexture(2, static_cast(irr_driver->getRTT(RTT_SHADOW))->DepthBufferTexture, GL_LINEAR, GL_LINEAR); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); + FullScreenShader::ShadowedSunLightShader::setUniforms(sun_ortho_matrix, cb->getPosition(), irr_driver->getInvProjMatrix(), cb->getRed(), cb->getGreen(), cb->getBlue(), 0, 1, 2); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glBindVertexArray(0); } @@ -495,6 +469,27 @@ void PostProcessing::renderPassThrough(ITexture *tex) glDisable(GL_BLEND); } +void PostProcessing::renderPassThrough(GLuint tex) +{ + glDisable(GL_DEPTH_TEST); + + glUseProgram(FullScreenShader::PassThroughShader::Program); + glBindVertexArray(FullScreenShader::PassThroughShader::vao); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, tex); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glUniform1i(FullScreenShader::PassThroughShader::uniform_texture, 0); + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glBindVertexArray(0); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + glEnable(GL_DEPTH_TEST); + glDisable(GL_BLEND); +} + void PostProcessing::renderGlow(ITexture *tex) { glDisable(GL_DEPTH_TEST); @@ -542,7 +537,7 @@ void PostProcessing::renderSSAO(const core::matrix4 &invprojm, const core::matri glEnable(GL_DEPTH_TEST); } -void PostProcessing::renderFog(const core::vector3df &campos, const core::matrix4 &ipvmat) +void PostProcessing::renderFog(const core::matrix4 &ipvmat) { irr_driver->getVideoDriver()->setRenderTarget(irr_driver->getRTT(RTT_COLOR), false, false); const Track * const track = World::getWorld()->getTrack(); @@ -568,7 +563,7 @@ void PostProcessing::renderFog(const core::vector3df &campos, const core::matrix glBindVertexArray(FullScreenShader::FogShader::vao); setTexture(0, static_cast(irr_driver->getRTT(RTT_NORMAL_AND_DEPTH))->DepthBufferTexture, GL_NEAREST, GL_NEAREST); - FullScreenShader::FogShader::setUniforms(ipvmat, fogmax, startH, endH, start, end, col, campos, 0); + FullScreenShader::FogShader::setUniforms(ipvmat, fogmax, startH, endH, start, end, col, 0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); @@ -854,7 +849,7 @@ void PostProcessing::render() else if (irr_driver->getSSAOViz()) renderPassThrough(irr_driver->getRTT(RTT_SSAO)); else if (irr_driver->getShadowViz()) - renderPassThrough(irr_driver->getRTT(RTT_SHADOW)); + renderPassThrough(static_cast(irr_driver->getRTT(RTT_SHADOW))->DepthBufferTexture); else renderColorLevel(in); } diff --git a/src/graphics/post_processing.hpp b/src/graphics/post_processing.hpp index c4b90cac2..b6c83a792 100644 --- a/src/graphics/post_processing.hpp +++ b/src/graphics/post_processing.hpp @@ -75,10 +75,9 @@ public: /** Generate diffuse and specular map */ void renderPointlight(const std::vector &positions, const std::vector &colors, const std::vector &energy); void renderSunlight(); - /** Blend all light related map */ - void renderLightbBlend(video::ITexture *diffuse, video::ITexture *specular, video::ITexture *ao, video::ITexture *specmap, bool debug); + void renderShadowedSunlight(const core::matrix4 &sun_ortho_matrix); - void renderFog(const core::vector3df &campos, const core::matrix4 &ipvmat); + void renderFog(const core::matrix4 &ipvmat); void renderSSAO(const core::matrix4 &invprojm, const core::matrix4 &projm); /** Blur the in texture */ @@ -87,6 +86,7 @@ public: /** Render tex. Used for blit/texture resize */ void renderPassThrough(video::ITexture *tex); + void renderPassThrough(unsigned tex); void renderGlow(video::ITexture *tex); diff --git a/src/graphics/rain.cpp b/src/graphics/rain.cpp index 091025f72..f71d2f956 100644 --- a/src/graphics/rain.cpp +++ b/src/graphics/rain.cpp @@ -20,7 +20,7 @@ #include "audio/sfx_manager.hpp" #include "graphics/camera.hpp" #include "graphics/glwrap.hpp" -#include "graphics/gpuparticles.h" +#include "graphics/gpuparticles.hpp" #include "graphics/irr_driver.hpp" #include "graphics/material_manager.hpp" #include "graphics/material.hpp" @@ -42,7 +42,7 @@ using namespace core; // The rain manager -Rain::Rain(Camera *camera, irr::scene::ISceneNode* parent) +Rain::Rain(Camera *camera, irr::scene::ISceneNode* parent) : m_thunder_sound(0) { m_lightning = camera->getIndex()==0; diff --git a/src/graphics/render.cpp b/src/graphics/render.cpp index 52f1a2cd9..b937b4cfd 100644 --- a/src/graphics/render.cpp +++ b/src/graphics/render.cpp @@ -215,10 +215,10 @@ void IrrDriver::renderGLSL(float dt) const core::aabbox3df cambox = camnode->getViewFrustum()->getBoundingBox(); // Shadows - if (!m_mipviz && !m_wireframe && UserConfigParams::m_shadows && - World::getWorld()->getTrack()->hasShadows()) + if (!m_mipviz && !m_wireframe && UserConfigParams::m_shadows) + //&& World::getWorld()->getTrack()->hasShadows()) { - //renderShadows(sicb, camnode, overridemat, camera); + renderShadows(camnode, camera); } @@ -242,7 +242,7 @@ void IrrDriver::renderGLSL(float dt) if (World::getWorld()->getTrack()->isFogEnabled()) { PROFILER_PUSH_CPU_MARKER("- Fog", 0xFF, 0x00, 0x00); - m_post_processing->renderFog(camnode->getAbsolutePosition(), irr_driver->getInvProjViewMatrix()); + m_post_processing->renderFog(irr_driver->getInvProjMatrix()); PROFILER_POP_CPU_MARKER(); } @@ -268,7 +268,7 @@ void IrrDriver::renderGLSL(float dt) // Is the lens flare enabled & visible? Check last frame's query. const bool hasflare = World::getWorld()->getTrack()->hasLensFlare(); const bool hasgodrays = World::getWorld()->getTrack()->hasGodRays(); - if (hasflare | hasgodrays) + if (hasflare || hasgodrays) { irr::video::COpenGLDriver* gl_driver = (irr::video::COpenGLDriver*)m_device->getVideoDriver(); @@ -464,9 +464,9 @@ void IrrDriver::renderFixed(float dt) // ---------------------------------------------------------------------------- -void IrrDriver::renderShadows(ShadowImportanceProvider * const sicb, +void IrrDriver::renderShadows(//ShadowImportanceProvider * const sicb, scene::ICameraSceneNode * const camnode, - video::SOverrideMaterial &overridemat, + //video::SOverrideMaterial &overridemat, Camera * const camera) { m_scene_manager->setCurrentRendertime(scene::ESNRP_SOLID); @@ -486,7 +486,6 @@ void IrrDriver::renderShadows(ShadowImportanceProvider * const sicb, camnode->render(); // Set up a nice ortho projection that contains our camera frustum - core::matrix4 ortho; core::aabbox3df box = smallcambox; box = box.intersect(trackbox); @@ -518,16 +517,16 @@ void IrrDriver::renderShadows(ShadowImportanceProvider * const sicb, if (up == down) down += 0.1f; if (z == 30) z += 0.1f; - ortho.buildProjectionMatrixOrthoLH(left, right, + sun_ortho_matrix.buildProjectionMatrixOrthoLH(left, right, up, down, 30, z); - m_suncam->setProjectionMatrix(ortho, true); + m_suncam->setProjectionMatrix(sun_ortho_matrix, true); m_scene_manager->setActiveCamera(m_suncam); m_suncam->render(); - ortho *= m_suncam->getViewMatrix(); - ((SunLightProvider *) m_shaders->m_callbacks[ES_SUNLIGHT])->setShadowMatrix(ortho); + //sun_ortho_matrix *= m_suncam->getViewMatrix(); +/* ((SunLightProvider *) m_shaders->m_callbacks[ES_SUNLIGHT])->setShadowMatrix(ortho); sicb->setShadowMatrix(ortho); overridemat.Enabled = 0; @@ -563,7 +562,7 @@ void IrrDriver::renderShadows(ShadowImportanceProvider * const sicb, m_rtts->getRTT(RTT_WARPV)->getSize().Height, m_rtts->getRTT(RTT_WARPV)->getSize().Height); -/* sq.setMaterialType(m_shaders->getShader(ES_GAUSSIAN6H)); + sq.setMaterialType(m_shaders->getShader(ES_GAUSSIAN6H)); sq.setTexture(m_rtts->getRTT(RTT_WARPH)); sq.render(m_rtts->getRTT(curh)); @@ -577,7 +576,7 @@ void IrrDriver::renderShadows(ShadowImportanceProvider * const sicb, // calculating the min, max, and total, it's several hundred us // faster to do that than to do it once in a separate shader // (shader switch overhead, measured). - colcb->setResolution(m_rtts->getRTT(RTT_WARPV)->getSize().Height, + /*colcb->setResolution(m_rtts->getRTT(RTT_WARPV)->getSize().Height, m_rtts->getRTT(RTT_WARPV)->getSize().Height); sq.setMaterialType(m_shaders->getShader(ES_SHADOW_WARPH)); @@ -586,11 +585,12 @@ void IrrDriver::renderShadows(ShadowImportanceProvider * const sicb, sq.setMaterialType(m_shaders->getShader(ES_SHADOW_WARPV)); sq.setTexture(m_rtts->getRTT(curv)); - sq.render(m_rtts->getRTT(RTT_WARPV)); + sq.render(m_rtts->getRTT(RTT_WARPV));*/ // Actual shadow map - m_video_driver->setRenderTarget(m_rtts->getRTT(RTT_SHADOW), true, true); - overridemat.Material.MaterialType = m_shaders->getShader(ES_SHADOWPASS); + + +/* overridemat.Material.MaterialType = m_shaders->getShader(ES_SHADOWPASS); overridemat.EnableFlags = video::EMF_MATERIAL_TYPE | video::EMF_TEXTURE1 | video::EMF_TEXTURE2; overridemat.EnablePasses = scene::ESNRP_SOLID; @@ -607,19 +607,22 @@ void IrrDriver::renderShadows(ShadowImportanceProvider * const sicb, overridemat.Material.TextureLayer[1].AnisotropicFilter = overridemat.Material.TextureLayer[2].AnisotropicFilter = 0; overridemat.Material.Wireframe = 1; - overridemat.Enabled = true; - + overridemat.Enabled = true;*/ + sun_ortho_matrix = getVideoDriver()->getTransform(video::ETS_PROJECTION); + sun_ortho_matrix *= getVideoDriver()->getTransform(video::ETS_VIEW); + irr_driver->setPhase(SHADOW_PASS); + glDisable(GL_BLEND); + glEnable(GL_CULL_FACE); + glCullFace(GL_FRONT); + m_video_driver->setRenderTarget(m_rtts->getRTT(RTT_SHADOW), true, true); + glDrawBuffer(GL_NONE); m_scene_manager->drawAll(scene::ESNRP_SOLID); + glCullFace(GL_BACK); - if (m_shadowviz) - { - overridemat.EnableFlags |= video::EMF_WIREFRAME; - m_scene_manager->drawAll(scene::ESNRP_SOLID); - } - - overridemat.EnablePasses = 0; - overridemat.Enabled = false; +// overridemat.EnablePasses = 0; +// overridemat.Enabled = false; camera->activate(); + m_scene_manager->drawAll(scene::ESNRP_CAMERA); tick++; tick %= 2; @@ -640,10 +643,6 @@ void IrrDriver::renderGlow(video::SOverrideMaterial &overridemat, const u32 glowcount = glows.size(); ColorizeProvider * const cb = (ColorizeProvider *) m_shaders->m_callbacks[ES_COLORIZE]; - GlowProvider * const glowcb = (GlowProvider *) m_shaders->m_callbacks[ES_GLOW]; - glowcb->setResolution(UserConfigParams::m_width, - UserConfigParams::m_height); - /* overridemat.Material.MaterialType = m_shaders->getShader(ES_COLORIZE); overridemat.EnableFlags = video::EMF_MATERIAL_TYPE; overridemat.EnablePasses = scene::ESNRP_SOLID; @@ -732,6 +731,7 @@ void IrrDriver::renderLights(const core::aabbox3df& cambox, video::SOverrideMaterial &overridemat, int cam, float dt) { + sun_ortho_matrix *= getInvViewMatrix(); core::array rtts; // Diffuse rtts.push_back(m_rtts->getRTT(RTT_TMP1)); @@ -753,7 +753,10 @@ void IrrDriver::renderLights(const core::aabbox3df& cambox, if (!m_lights[i]->isPointLight()) { m_lights[i]->render(); - m_post_processing->renderSunlight(); + if (UserConfigParams::m_shadows) + m_post_processing->renderShadowedSunlight(sun_ortho_matrix); + else + m_post_processing->renderSunlight(); continue; } const core::vector3df &lightpos = (m_lights[i]->getAbsolutePosition() - campos); diff --git a/src/graphics/rtts.cpp b/src/graphics/rtts.cpp index 2696bebb7..288dc63b6 100644 --- a/src/graphics/rtts.cpp +++ b/src/graphics/rtts.cpp @@ -36,7 +36,7 @@ RTT::RTT() const dimension2du ssaosize = UserConfigParams::m_ssao == 2 ? res : quarter; - const u16 shadowside = UserConfigParams::m_shadows == 2 ? 2048 : 512; + const u16 shadowside = 8192; const dimension2du shadowsize(shadowside, shadowside); const dimension2du warpvsize(1, 512); const dimension2du warphsize(512, 1); diff --git a/src/graphics/shaders.cpp b/src/graphics/shaders.cpp index be5d31c3e..7ab06e31e 100644 --- a/src/graphics/shaders.cpp +++ b/src/graphics/shaders.cpp @@ -40,8 +40,6 @@ Shaders::Shaders() m_callbacks[ES_GAUSSIAN3V] = m_callbacks[ES_GAUSSIAN3H] = new GaussianBlurProvider(); m_callbacks[ES_MIPVIZ] = new MipVizProvider(); m_callbacks[ES_COLORIZE] = new ColorizeProvider(); - m_callbacks[ES_GLOW] = new GlowProvider(); - m_callbacks[ES_OBJECTPASS] = new ObjectPassProvider(); m_callbacks[ES_SUNLIGHT] = new SunLightProvider(); m_callbacks[ES_MLAA_COLOR1] = new MLAAColor1Provider(); m_callbacks[ES_MLAA_BLEND2] = new MLAABlend2Provider(); @@ -108,29 +106,24 @@ void Shaders::loadShaders() memcpy(saved_shaders, m_shaders, sizeof(m_shaders)); // Ok, go - m_shaders[ES_NORMAL_MAP] = glslmat(dir + "normalmap.vert", dir + "normalmap.frag", - m_callbacks[ES_NORMAL_MAP], EMT_SOLID_2_LAYER); - - m_shaders[ES_NORMAL_MAP_LIGHTMAP] = glslmat(dir + "normalmap.vert", dir + "normalmap.frag", - m_callbacks[ES_NORMAL_MAP_LIGHTMAP], EMT_SOLID_2_LAYER); + m_shaders[ES_NORMAL_MAP] = glsl_noinput(dir + "normalmap.vert", dir + "normalmap.frag"); + m_shaders[ES_NORMAL_MAP_LIGHTMAP] = glsl_noinput(dir + "normalmap.vert", dir + "normalmap.frag"); m_shaders[ES_SKYBOX] = glslmat(dir + "skybox.vert", dir + "skybox.frag", m_callbacks[ES_SKYBOX], EMT_TRANSPARENT_ALPHA_CHANNEL); - m_shaders[ES_SPLATTING] = glslmat(dir + "splatting.vert", dir + "splatting.frag", - m_callbacks[ES_SPLATTING], EMT_SOLID); + m_shaders[ES_SPLATTING] = glsl_noinput(dir + "splatting.vert", dir + "splatting.frag"); m_shaders[ES_WATER] = glslmat(dir + "water.vert", dir + "water.frag", m_callbacks[ES_WATER], EMT_TRANSPARENT_ALPHA_CHANNEL); m_shaders[ES_WATER_SURFACE] = glsl(dir + "water.vert", dir + "pass.frag", m_callbacks[ES_WATER]); - m_shaders[ES_SPHERE_MAP] = glslmat(dir + "objectpass.vert", dir + "objectpass_spheremap.frag", - m_callbacks[ES_OBJECTPASS], EMT_SOLID); + m_shaders[ES_SPHERE_MAP] = glsl_noinput(dir + "objectpass.vert", dir + "objectpass_spheremap.frag"); - m_shaders[ES_GRASS] = glslmat(dir + "grass.vert", dir + "grass.frag", + m_shaders[ES_GRASS] = glslmat(std::string(""), dir + "pass.frag", m_callbacks[ES_GRASS], EMT_TRANSPARENT_ALPHA_CHANNEL); - m_shaders[ES_GRASS_REF] = glslmat(dir + "grass.vert", dir + "grass.frag", + m_shaders[ES_GRASS_REF] = glslmat(std::string(""), dir + "pass.frag", m_callbacks[ES_GRASS], EMT_TRANSPARENT_ALPHA_CHANNEL_REF); m_shaders[ES_BUBBLES] = glslmat(dir + "bubble.vert", dir + "bubble.frag", @@ -155,22 +148,13 @@ void Shaders::loadShaders() m_shaders[ES_COLORIZE_REF] = glslmat(std::string(""), dir + "colorize_ref.frag", m_callbacks[ES_COLORIZE], EMT_SOLID); - m_shaders[ES_GLOW] = glslmat(std::string(""), dir + "glow.frag", - m_callbacks[ES_GLOW], EMT_TRANSPARENT_ALPHA_CHANNEL); + m_shaders[ES_OBJECTPASS] = glsl_noinput(dir + "objectpass.vert", dir + "objectpass.frag"); + m_shaders[ES_OBJECT_UNLIT] = glsl_noinput(dir + "objectpass.vert", dir + "objectpass.frag"); + m_shaders[ES_OBJECTPASS_REF] = glsl_noinput(dir + "objectpass.vert", dir + "objectpass_ref.frag"); + m_shaders[ES_OBJECTPASS_RIMLIT] = glsl_noinput(dir + "objectpass_rimlit.vert", dir + "objectpass_rimlit.frag"); - m_shaders[ES_OBJECTPASS] = glslmat(dir + "objectpass.vert", dir + "objectpass.frag", - m_callbacks[ES_OBJECTPASS], EMT_SOLID); - m_shaders[ES_OBJECT_UNLIT] = glslmat(dir + "objectpass.vert", dir + "objectpass.frag", - m_callbacks[ES_OBJECTPASS], EMT_SOLID); - m_shaders[ES_OBJECTPASS_REF] = glslmat(dir + "objectpass.vert", dir + "objectpass_ref.frag", - m_callbacks[ES_OBJECTPASS], EMT_SOLID); - m_shaders[ES_OBJECTPASS_RIMLIT] = glslmat(dir + "objectpass_rimlit.vert", dir + "objectpass_rimlit.frag", - m_callbacks[ES_OBJECTPASS], EMT_SOLID); - - m_shaders[ES_SUNLIGHT] = glslmat(std::string(""), dir + "sunlight.frag", - m_callbacks[ES_SUNLIGHT], EMT_SOLID); - m_shaders[ES_SUNLIGHT_SHADOW] = glslmat(dir + "pass.vert", dir + "sunlightshadow.frag", - m_callbacks[ES_SUNLIGHT], EMT_SOLID); + m_shaders[ES_SUNLIGHT] = glsl_noinput(std::string(""), dir + "sunlight.frag"); + m_shaders[ES_SUNLIGHT_SHADOW] = glsl_noinput(dir + "pass.vert", dir + "pass.frag"); m_shaders[ES_MLAA_COLOR1] = glsl(dir + "mlaa_offset.vert", dir + "mlaa_color1.frag", m_callbacks[ES_MLAA_COLOR1]); @@ -249,12 +233,12 @@ void Shaders::loadShaders() FullScreenShader::Gaussian6HBlurShader::init(); FullScreenShader::Gaussian6VBlurShader::init(); FullScreenShader::GlowShader::init(); - FullScreenShader::LightBlendShader::init(); FullScreenShader::PassThroughShader::init(); FullScreenShader::PointLightShader::init(); FullScreenShader::PPDisplaceShader::init(); FullScreenShader::SSAOShader::init(); FullScreenShader::SunLightShader::init(); + FullScreenShader::ShadowedSunLightShader::init(); MeshShader::ColorizeShader::init(); MeshShader::NormalMapShader::init(); MeshShader::ObjectPass1Shader::init(); @@ -271,8 +255,12 @@ void Shaders::loadShaders() MeshShader::GrassPass2Shader::init(); MeshShader::BubbleShader::init(); MeshShader::TransparentShader::init(); + MeshShader::TransparentFogShader::init(); MeshShader::BillboardShader::init(); MeshShader::DisplaceShader::init(); + MeshShader::ShadowShader::init(); + MeshShader::RefShadowShader::init(); + MeshShader::GrassShadowShader::init(); ParticleShader::FlipParticleRender::init(); ParticleShader::HeightmapSimulationShader::init(); ParticleShader::SimpleParticleRender::init(); @@ -794,6 +782,51 @@ namespace MeshShader glUniformMatrix4fv(uniform_MVP, 1, GL_FALSE, ModelViewProjectionMatrix.pointer()); glUniform1i(uniform_tex, TU_tex); } + + GLuint TransparentFogShader::Program; + GLuint TransparentFogShader::attrib_position; + GLuint TransparentFogShader::attrib_texcoord; + GLuint TransparentFogShader::uniform_MVP; + GLuint TransparentFogShader::uniform_tex; + GLuint TransparentFogShader::uniform_fogmax; + GLuint TransparentFogShader::uniform_startH; + GLuint TransparentFogShader::uniform_endH; + GLuint TransparentFogShader::uniform_start; + GLuint TransparentFogShader::uniform_end; + GLuint TransparentFogShader::uniform_col; + GLuint TransparentFogShader::uniform_screen; + GLuint TransparentFogShader::uniform_ipvmat; + + void TransparentFogShader::init() + { + Program = LoadProgram(file_manager->getAsset("shaders/transparent.vert").c_str(), file_manager->getAsset("shaders/transparentfog.frag").c_str()); + attrib_position = glGetAttribLocation(Program, "Position"); + attrib_texcoord = glGetAttribLocation(Program, "Texcoord"); + uniform_MVP = glGetUniformLocation(Program, "ModelViewProjectionMatrix"); + uniform_tex = glGetUniformLocation(Program, "tex"); + uniform_fogmax = glGetUniformLocation(Program, "fogmax"); + uniform_startH = glGetUniformLocation(Program, "startH"); + uniform_endH = glGetUniformLocation(Program, "endH"); + uniform_start = glGetUniformLocation(Program, "start"); + uniform_end = glGetUniformLocation(Program, "end"); + uniform_col = glGetUniformLocation(Program, "col"); + uniform_screen = glGetUniformLocation(Program, "screen"); + uniform_ipvmat = glGetUniformLocation(Program, "ipvmat"); + } + + void TransparentFogShader::setUniforms(const core::matrix4 &ModelViewProjectionMatrix, const core::matrix4 &ipvmat, float fogmax, float startH, float endH, float start, float end, const core::vector3df &col, const core::vector3df &campos, unsigned TU_tex) + { + glUniformMatrix4fv(uniform_MVP, 1, GL_FALSE, ModelViewProjectionMatrix.pointer()); + glUniform1f(uniform_fogmax, fogmax); + glUniform1f(uniform_startH, startH); + glUniform1f(uniform_endH, endH); + glUniform1f(uniform_start, start); + glUniform1f(uniform_end, end); + glUniform3f(uniform_col, col.X, col.Y, col.Z); + glUniform2f(uniform_screen, UserConfigParams::m_width, UserConfigParams::m_height); + glUniformMatrix4fv(uniform_ipvmat, 1, GL_FALSE, ipvmat.pointer()); + glUniform1i(uniform_tex, TU_tex); + } GLuint BillboardShader::Program; GLuint BillboardShader::attrib_corner; @@ -814,7 +847,6 @@ namespace MeshShader uniform_Position = glGetUniformLocation(Program, "Position"); uniform_Size = glGetUniformLocation(Program, "Size"); uniform_tex = glGetUniformLocation(Program, "tex"); - printf("TUTex is %d, Texcoord is %d\n", uniform_tex, attrib_texcoord); } void BillboardShader::setUniforms(const core::matrix4 &ModelViewMatrix, const core::matrix4 &ProjectionMatrix, const core::vector3df &Position, const core::dimension2d &size, unsigned TU_tex) @@ -845,6 +877,69 @@ namespace MeshShader glUniform3f(uniform_col, r, g, b); } + GLuint ShadowShader::Program; + GLuint ShadowShader::attrib_position; + GLuint ShadowShader::uniform_MVP; + + void ShadowShader::init() + { + Program = LoadProgram(file_manager->getAsset("shaders/object_pass2.vert").c_str(), file_manager->getAsset("shaders/white.frag").c_str()); + attrib_position = glGetAttribLocation(Program, "Position"); + uniform_MVP = glGetUniformLocation(Program, "ModelViewProjectionMatrix"); + } + + void ShadowShader::setUniforms(const core::matrix4 &ModelViewProjectionMatrix) + { + glUniformMatrix4fv(uniform_MVP, 1, GL_FALSE, ModelViewProjectionMatrix.pointer()); + } + + GLuint RefShadowShader::Program; + GLuint RefShadowShader::attrib_position; + GLuint RefShadowShader::attrib_texcoord; + GLuint RefShadowShader::uniform_MVP; + GLuint RefShadowShader::uniform_tex; + + void RefShadowShader::init() + { + Program = LoadProgram(file_manager->getAsset("shaders/object_pass2.vert").c_str(), file_manager->getAsset("shaders/object_unlit.frag").c_str()); + attrib_position = glGetAttribLocation(Program, "Position"); + attrib_texcoord = glGetAttribLocation(Program, "Texcoord"); + uniform_MVP = glGetUniformLocation(Program, "ModelViewProjectionMatrix"); + uniform_tex = glGetUniformLocation(Program, "tex"); + } + + void RefShadowShader::setUniforms(const core::matrix4 &ModelViewProjectionMatrix, unsigned TU_tex) + { + glUniformMatrix4fv(uniform_MVP, 1, GL_FALSE, ModelViewProjectionMatrix.pointer()); + glUniform1i(uniform_tex, TU_tex); + } + + GLuint GrassShadowShader::Program; + GLuint GrassShadowShader::attrib_position; + GLuint GrassShadowShader::attrib_texcoord; + GLuint GrassShadowShader::attrib_color; + GLuint GrassShadowShader::uniform_MVP; + GLuint GrassShadowShader::uniform_tex; + GLuint GrassShadowShader::uniform_windDir; + + void GrassShadowShader::init() + { + Program = LoadProgram(file_manager->getAsset("shaders/grass_pass2.vert").c_str(), file_manager->getAsset("shaders/object_unlit.frag").c_str()); + attrib_position = glGetAttribLocation(Program, "Position"); + attrib_texcoord = glGetAttribLocation(Program, "Texcoord"); + uniform_MVP = glGetUniformLocation(Program, "ModelViewProjectionMatrix"); + uniform_tex = glGetUniformLocation(Program, "tex"); + attrib_color = glGetAttribLocation(Program, "Color"); + uniform_windDir = glGetUniformLocation(Program, "windDir"); + } + + void GrassShadowShader::setUniforms(const core::matrix4 &ModelViewProjectionMatrix, const core::vector3df &windDirection, unsigned TU_tex) + { + glUniformMatrix4fv(uniform_MVP, 1, GL_FALSE, ModelViewProjectionMatrix.pointer()); + glUniform1i(uniform_tex, TU_tex); + glUniform3f(uniform_windDir, windDirection.X, windDirection.Y, windDirection.Z); + } + GLuint DisplaceShader::Program; GLuint DisplaceShader::attrib_position; GLuint DisplaceShader::attrib_texcoord; @@ -1180,7 +1275,6 @@ namespace FullScreenShader uniform_col = glGetUniformLocation(Program, "col"); uniform_invproj = glGetUniformLocation(Program, "invproj"); vao = createVAO(Program); - printf("uniform %d\n", uniform_ntex); } void SunLightShader::setUniforms(const core::vector3df &direction, const core::matrix4 &InvProjMatrix, float r, float g, float b, unsigned TU_ntex, unsigned TU_dtex) @@ -1192,23 +1286,39 @@ namespace FullScreenShader glUniform1i(uniform_dtex, TU_dtex); } - GLuint LightBlendShader::Program; - GLuint LightBlendShader::uniform_diffuse; - GLuint LightBlendShader::uniform_specular; - GLuint LightBlendShader::uniform_ambient_occlusion; - GLuint LightBlendShader::uniform_specular_map; - GLuint LightBlendShader::uniform_ambient; - GLuint LightBlendShader::vao; - void LightBlendShader::init() - { - Program = LoadProgram(file_manager->getAsset("shaders/screenquad.vert").c_str(), file_manager->getAsset("shaders/lightblend.frag").c_str()); - uniform_diffuse = glGetUniformLocation(Program, "diffuse"); - uniform_specular = glGetUniformLocation(Program, "specular"); - uniform_ambient_occlusion = glGetUniformLocation(Program, "ambient_occlusion"); - uniform_specular_map = glGetUniformLocation(Program, "specular_map"); - uniform_ambient = glGetUniformLocation(Program, "ambient"); - vao = createVAO(Program); - } + GLuint ShadowedSunLightShader::Program; + GLuint ShadowedSunLightShader::uniform_ntex; + GLuint ShadowedSunLightShader::uniform_dtex; + GLuint ShadowedSunLightShader::uniform_shadowtex; + GLuint ShadowedSunLightShader::uniform_shadowmat; + GLuint ShadowedSunLightShader::uniform_direction; + GLuint ShadowedSunLightShader::uniform_col; + GLuint ShadowedSunLightShader::uniform_invproj; + GLuint ShadowedSunLightShader::vao; + + void ShadowedSunLightShader::init() + { + Program = LoadProgram(file_manager->getAsset("shaders/screenquad.vert").c_str(), file_manager->getAsset("shaders/sunlightshadow.frag").c_str()); + uniform_ntex = glGetUniformLocation(Program, "ntex"); + uniform_dtex = glGetUniformLocation(Program, "dtex"); + uniform_shadowtex = glGetUniformLocation(Program, "shadowtex"); + uniform_shadowmat = glGetUniformLocation(Program, "shadowmat"), + uniform_direction = glGetUniformLocation(Program, "direction"); + uniform_col = glGetUniformLocation(Program, "col"); + uniform_invproj = glGetUniformLocation(Program, "invproj"); + vao = createVAO(Program); + } + + void ShadowedSunLightShader::setUniforms(const core::matrix4 &shadowmat, const core::vector3df &direction, const core::matrix4 &InvProjMatrix, float r, float g, float b, unsigned TU_ntex, unsigned TU_dtex, unsigned TU_shadowtex) + { + glUniformMatrix4fv(uniform_shadowmat, 1, GL_FALSE, shadowmat.pointer()); + glUniformMatrix4fv(uniform_invproj, 1, GL_FALSE, InvProjMatrix.pointer()); + glUniform3f(uniform_direction, direction.X, direction.Y, direction.Z); + glUniform3f(uniform_col, r, g, b); + glUniform1i(uniform_ntex, TU_ntex); + glUniform1i(uniform_dtex, TU_dtex); + glUniform1i(uniform_shadowtex, TU_shadowtex); + } GLuint Gaussian6HBlurShader::Program; GLuint Gaussian6HBlurShader::uniform_tex; @@ -1432,7 +1542,6 @@ namespace FullScreenShader GLuint FogShader::uniform_start; GLuint FogShader::uniform_end; GLuint FogShader::uniform_col; - GLuint FogShader::uniform_campos; GLuint FogShader::uniform_ipvmat; GLuint FogShader::vao; @@ -1446,22 +1555,20 @@ namespace FullScreenShader uniform_start = glGetUniformLocation(Program, "start"); uniform_end = glGetUniformLocation(Program, "end"); uniform_col = glGetUniformLocation(Program, "col"); - uniform_campos = glGetUniformLocation(Program, "campos"); uniform_ipvmat = glGetUniformLocation(Program, "ipvmat"); vao = createVAO(Program); } - void FogShader::setUniforms(const core::matrix4 &ipvmat, float fogmax, float startH, float endH, float start, float end, const core::vector3df &col, const core::vector3df &campos, unsigned TU_ntex) + void FogShader::setUniforms(const core::matrix4 &ipvmat, float fogmax, float startH, float endH, float start, float end, const core::vector3df &col, unsigned TU_ntex) { - glUniform1f(FullScreenShader::FogShader::uniform_fogmax, fogmax); - glUniform1f(FullScreenShader::FogShader::uniform_startH, startH); - glUniform1f(FullScreenShader::FogShader::uniform_endH, endH); - glUniform1f(FullScreenShader::FogShader::uniform_start, start); - glUniform1f(FullScreenShader::FogShader::uniform_end, end); - glUniform3f(FullScreenShader::FogShader::uniform_col, col.X, col.Y, col.Z); - glUniform3f(FullScreenShader::FogShader::uniform_campos, campos.X, campos.Y, campos.Z); - glUniformMatrix4fv(FullScreenShader::FogShader::uniform_ipvmat, 1, GL_FALSE, ipvmat.pointer()); - glUniform1i(FullScreenShader::FogShader::uniform_tex, TU_ntex); + glUniform1f(uniform_fogmax, fogmax); + glUniform1f(uniform_startH, startH); + glUniform1f(uniform_endH, endH); + glUniform1f(uniform_start, start); + glUniform1f(uniform_end, end); + glUniform3f(uniform_col, col.X, col.Y, col.Z); + glUniformMatrix4fv(uniform_ipvmat, 1, GL_FALSE, ipvmat.pointer()); + glUniform1i(uniform_tex, TU_ntex); } } diff --git a/src/graphics/shaders.hpp b/src/graphics/shaders.hpp index f2babad85..75172cd6e 100644 --- a/src/graphics/shaders.hpp +++ b/src/graphics/shaders.hpp @@ -191,6 +191,17 @@ public: static void setUniforms(const core::matrix4 &ModelViewProjectionMatrix, unsigned TU_tex); }; +class TransparentFogShader +{ +public: + static GLuint Program; + static GLuint attrib_position, attrib_texcoord; + static GLuint uniform_MVP, uniform_tex, uniform_fogmax, uniform_startH, uniform_endH, uniform_start, uniform_end, uniform_col, uniform_screen, uniform_ipvmat; + + static void init(); + static void setUniforms(const core::matrix4 &ModelViewProjectionMatrix, const core::matrix4 &ipvmat, float fogmax, float startH, float endH, float start, float end, const core::vector3df &col, const core::vector3df &campos, unsigned TU_tex); +}; + class BillboardShader { public: @@ -214,6 +225,39 @@ public: static void setUniforms(const core::matrix4 &ModelViewProjectionMatrix, float r, float g, float b); }; +class ShadowShader +{ +public: + static GLuint Program; + static GLuint attrib_position; + static GLuint uniform_MVP; + + static void init(); + static void setUniforms(const core::matrix4 &ModelViewProjectionMatrix); +}; + +class RefShadowShader +{ +public: + static GLuint Program; + static GLuint attrib_position, attrib_texcoord; + static GLuint uniform_MVP, uniform_tex; + + static void init(); + static void setUniforms(const core::matrix4 &ModelViewProjectionMatrix, unsigned TU_tex); +}; + +class GrassShadowShader +{ +public: + static GLuint Program; + static GLuint attrib_position, attrib_texcoord, attrib_color; + static GLuint uniform_MVP, uniform_tex, uniform_windDir; + + static void init(); + static void setUniforms(const core::matrix4 &ModelViewProjectionMatrix, const core::vector3df &windDirection, unsigned TU_tex); +}; + class DisplaceShader { public: @@ -341,14 +385,15 @@ public: static void setUniforms(const core::vector3df &direction, const core::matrix4 &InvProjMatrix, float r, float g, float b, unsigned TU_ntex, unsigned TU_dtex); }; -class LightBlendShader +class ShadowedSunLightShader { public: - static GLuint Program; - static GLuint uniform_diffuse, uniform_specular, uniform_ambient_occlusion, uniform_specular_map, uniform_ambient; - static GLuint vao; + static GLuint Program; + static GLuint uniform_ntex, uniform_dtex, uniform_shadowtex, uniform_shadowmat, uniform_direction, uniform_col, uniform_invproj; + static GLuint vao; - static void init(); + static void init(); + static void setUniforms(const core::matrix4 &shadowmat, const core::vector3df &direction, const core::matrix4 &InvProjMatrix, float r, float g, float b, unsigned TU_ntex, unsigned TU_dtex, unsigned TU_shadowtex); }; class Gaussian6HBlurShader @@ -427,11 +472,11 @@ class FogShader { public: static GLuint Program; - static GLuint uniform_tex, uniform_fogmax, uniform_startH, uniform_endH, uniform_start, uniform_end, uniform_col, uniform_campos, uniform_ipvmat; + static GLuint uniform_tex, uniform_fogmax, uniform_startH, uniform_endH, uniform_start, uniform_end, uniform_col, uniform_ipvmat; static GLuint vao; static void init(); - static void setUniforms(const core::matrix4 &ipvmat, float fogmax, float startH, float endH, float start, float end, const core::vector3df &col, const core::vector3df &campos, unsigned TU_ntex); + static void setUniforms(const core::matrix4 &ipvmat, float fogmax, float startH, float endH, float start, float end, const core::vector3df &col, unsigned TU_ntex); }; } @@ -494,7 +539,6 @@ public: ACT(ES_MIPVIZ) \ ACT(ES_COLORIZE) \ ACT(ES_COLORIZE_REF) \ - ACT(ES_GLOW) \ ACT(ES_OBJECT_UNLIT) \ ACT(ES_OBJECTPASS) \ ACT(ES_OBJECTPASS_REF) \ diff --git a/src/graphics/stkanimatedmesh.cpp b/src/graphics/stkanimatedmesh.cpp index 377db0bb9..07bb167bc 100644 --- a/src/graphics/stkanimatedmesh.cpp +++ b/src/graphics/stkanimatedmesh.cpp @@ -4,6 +4,8 @@ #include #include "graphics/irr_driver.hpp" #include "config/user_config.hpp" +#include "modes/world.hpp" +#include "tracks/track.hpp" using namespace irr; @@ -30,7 +32,10 @@ void STKAnimatedMesh::drawTransparent(const GLMesh &mesh, video::E_MATERIAL_TYPE computeMVP(ModelViewProjectionMatrix); - drawTransparentObject(mesh, ModelViewProjectionMatrix); + if (World::getWorld()->getTrack()->isFogEnabled()) + drawTransparentFogObject(mesh, ModelViewProjectionMatrix); + else + drawTransparentObject(mesh, ModelViewProjectionMatrix); return; } @@ -89,6 +94,20 @@ isObjectPass(video::E_MATERIAL_TYPE type) return false; } +void STKAnimatedMesh::drawShadow(const GLMesh &mesh) +{ + GLenum ptype = mesh.PrimitiveType; + GLenum itype = mesh.IndexType; + size_t count = mesh.IndexCount; + assert(irr_driver->getPhase() == SHADOW_PASS); + core::matrix4 ShadowMVP; + computeMVP(ShadowMVP); + glUseProgram(MeshShader::ShadowShader::Program); + MeshShader::ShadowShader::setUniforms(ShadowMVP); + glBindVertexArray(mesh.vao_shadow_pass); + glDrawElements(ptype, count, itype, 0); +} + void STKAnimatedMesh::render() { video::IVideoDriver* driver = SceneManager->getVideoDriver(); @@ -106,9 +125,8 @@ void STKAnimatedMesh::render() } else { -#ifdef _DEBUG - os::Printer::log("Animated Mesh returned no mesh to render.", Mesh->getDebugName(), ELL_WARNING); -#endif + Log::error("animated mesh", "Animated Mesh returned no mesh to render."); + return; } driver->setTransform(video::ETS_WORLD, AbsoluteTransformation); @@ -147,7 +165,9 @@ void STKAnimatedMesh::render() glBindBuffer(GL_ARRAY_BUFFER, GLmeshes[i].vertex_buffer); glBufferSubData(GL_ARRAY_BUFFER, 0, mb->getVertexCount() * GLmeshes[i].Stride, mb->getVertices()); } - if (isTransparentPass) + if (irr_driver->getPhase() == SHADOW_PASS) + drawShadow(GLmeshes[i]); + else if (isTransparentPass) drawTransparent(GLmeshes[i], material.MaterialType); else drawSolid(GLmeshes[i], material.MaterialType); diff --git a/src/graphics/stkanimatedmesh.hpp b/src/graphics/stkanimatedmesh.hpp index e97a30215..1df7fc005 100644 --- a/src/graphics/stkanimatedmesh.hpp +++ b/src/graphics/stkanimatedmesh.hpp @@ -15,6 +15,7 @@ protected: core::matrix4 ModelViewProjectionMatrix, TransposeInverseModelView; void drawSolid(const GLMesh &mesh, video::E_MATERIAL_TYPE type); void drawTransparent(const GLMesh &mesh, video::E_MATERIAL_TYPE type); + void drawShadow(const GLMesh &mesh); public: STKAnimatedMesh(irr::scene::IAnimatedMesh* mesh, irr::scene::ISceneNode* parent, irr::scene::ISceneManager* mgr, irr::s32 id, diff --git a/src/graphics/stkmesh.cpp b/src/graphics/stkmesh.cpp index 6c76cde31..34dfc14d8 100644 --- a/src/graphics/stkmesh.cpp +++ b/src/graphics/stkmesh.cpp @@ -1,10 +1,13 @@ #include "stkmesh.hpp" #include "graphics/irr_driver.hpp" +#include "tracks/track.hpp" #include #include #include "config/user_config.hpp" #include "graphics/callbacks.hpp" #include "utils/helpers.hpp" +#include "graphics/camera.hpp" +#include "modes/world.hpp" GLuint createVAO(GLuint vbo, GLuint idx, GLuint attrib_position, GLuint attrib_texcoord, GLuint attrib_second_texcoord, GLuint attrib_normal, GLuint attrib_tangent, GLuint attrib_bitangent, GLuint attrib_color, size_t stride) @@ -222,18 +225,20 @@ void drawObjectPass1(const GLMesh &mesh, const core::matrix4 & ModelViewProjecti void drawObjectRefPass1(const GLMesh &mesh, const core::matrix4 & ModelViewProjectionMatrix, const core::matrix4 &TransposeInverseModelView) { + glDisable(GL_CULL_FACE); GLenum ptype = mesh.PrimitiveType; GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); glUseProgram(MeshShader::ObjectRefPass1Shader::Program); MeshShader::ObjectRefPass1Shader::setUniforms(ModelViewProjectionMatrix, TransposeInverseModelView, 0); glBindVertexArray(mesh.vao_first_pass); glDrawElements(ptype, count, itype, 0); + glEnable(GL_CULL_FACE); } static @@ -258,7 +263,7 @@ void drawGrassPass1(const GLMesh &mesh, const core::matrix4 & ModelViewProjectio GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); glUseProgram(MeshShader::GrassPass1Shader::Program); MeshShader::GrassPass1Shader::setUniforms(ModelViewProjectionMatrix, TransposeInverseModelView, windDir, 0); @@ -274,7 +279,7 @@ void drawNormalPass(const GLMesh &mesh, const core::matrix4 & ModelViewProjectio size_t count = mesh.IndexCount; assert(mesh.textures[1]); - setTexture(0, mesh.textures[1], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[1], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); glUseProgram(MeshShader::NormalMapShader::Program); MeshShader::NormalMapShader::setUniforms(ModelViewProjectionMatrix, TransposeInverseModelView, 0); @@ -289,7 +294,7 @@ void drawSphereMap(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionM GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); glUseProgram(MeshShader::SphereMapShader::Program); MeshShader::SphereMapShader::setUniforms(ModelViewProjectionMatrix, TransposeInverseModelView, 0); @@ -305,7 +310,7 @@ void drawSplatting(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionM size_t count = mesh.IndexCount; // Texlayout - setTexture(0, mesh.textures[1], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[1], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA}; @@ -317,7 +322,7 @@ void drawSplatting(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionM glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); } //Tex detail0 - setTexture(1, mesh.textures[2], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(1, mesh.textures[2], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA}; @@ -329,7 +334,7 @@ void drawSplatting(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionM glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); } //Tex detail1 - setTexture(2, mesh.textures[3], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(2, mesh.textures[3], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA}; @@ -341,7 +346,7 @@ void drawSplatting(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionM glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); } //Tex detail2 - setTexture(3, mesh.textures[4], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(3, mesh.textures[4], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA}; @@ -353,7 +358,7 @@ void drawSplatting(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionM glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); } //Tex detail3 - setTexture(4, mesh.textures[5], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(4, mesh.textures[5], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA}; @@ -387,11 +392,12 @@ void drawSplatting(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionM void drawObjectRefPass2(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionMatrix) { + glDisable(GL_CULL_FACE); GLenum ptype = mesh.PrimitiveType; GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA}; @@ -416,6 +422,7 @@ void drawObjectRefPass2(const GLMesh &mesh, const core::matrix4 &ModelViewProjec glBindVertexArray(mesh.vao_second_pass); glDrawElements(ptype, count, itype, 0); + glEnable(GL_CULL_FACE); } void drawGrassPass2(const GLMesh &mesh, const core::matrix4 & ModelViewProjectionMatrix, core::vector3df windDir) @@ -424,7 +431,7 @@ void drawGrassPass2(const GLMesh &mesh, const core::matrix4 & ModelViewProjectio GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA}; @@ -480,7 +487,7 @@ void drawObjectRimLimit(const GLMesh &mesh, const core::matrix4 &ModelViewProjec GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = { GL_ONE, GL_ONE, GL_ONE, GL_ALPHA }; @@ -514,7 +521,7 @@ void drawObjectUnlit(const GLMesh &mesh, const core::matrix4 &ModelViewProjectio GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = { GL_ONE, GL_ONE, GL_ONE, GL_ALPHA }; @@ -540,7 +547,7 @@ void drawDetailledObjectPass2(const GLMesh &mesh, const core::matrix4 &ModelView GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = {GL_ONE, GL_ONE, GL_ONE, GL_ALPHA}; @@ -552,7 +559,7 @@ void drawDetailledObjectPass2(const GLMesh &mesh, const core::matrix4 &ModelView glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); } - setTexture(1, mesh.textures[1], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(1, mesh.textures[1], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); setTexture(2, static_cast(irr_driver->getRTT(RTT_TMP1))->getOpenGLTextureName(), GL_NEAREST, GL_NEAREST); setTexture(3, static_cast(irr_driver->getRTT(RTT_TMP2))->getOpenGLTextureName(), GL_NEAREST, GL_NEAREST); @@ -576,7 +583,7 @@ void drawObjectPass2(const GLMesh &mesh, const core::matrix4 &ModelViewProjectio GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); if (irr_driver->getLightViz()) { GLint swizzleMask[] = { GL_ONE, GL_ONE, GL_ONE, GL_ALPHA }; @@ -610,7 +617,7 @@ void drawTransparentObject(const GLMesh &mesh, const core::matrix4 &ModelViewPro GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); glUseProgram(MeshShader::TransparentShader::Program); MeshShader::TransparentShader::setUniforms(ModelViewProjectionMatrix, 0); @@ -619,6 +626,35 @@ void drawTransparentObject(const GLMesh &mesh, const core::matrix4 &ModelViewPro glDrawElements(ptype, count, itype, 0); } +void drawTransparentFogObject(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionMatrix) +{ + GLenum ptype = mesh.PrimitiveType; + GLenum itype = mesh.IndexType; + size_t count = mesh.IndexCount; + + const Track * const track = World::getWorld()->getTrack(); + + // This function is only called once per frame - thus no need for setters. + const float fogmax = track->getFogMax(); + const float startH = track->getFogStartHeight(); + const float endH = track->getFogEndHeight(); + const float start = track->getFogStart(); + const float end = track->getFogEnd(); + const video::SColor tmpcol = track->getFogColor(); + + core::vector3df col(tmpcol.getRed() / 255.0f, + tmpcol.getGreen() / 255.0f, + tmpcol.getBlue() / 255.0f); + + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); + + glUseProgram(MeshShader::TransparentFogShader::Program); + MeshShader::TransparentFogShader::setUniforms(ModelViewProjectionMatrix, irr_driver->getInvProjMatrix(), fogmax, startH, endH, start, end, col, Camera::getCamera(0)->getCameraSceneNode()->getAbsolutePosition(), 0); + + glBindVertexArray(mesh.vao_first_pass); + glDrawElements(ptype, count, itype, 0); +} + void drawBubble(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionMatrix) { const float time = irr_driver->getDevice()->getTimer()->getTime() / 1000.0f; @@ -628,7 +664,7 @@ void drawBubble(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionMatr GLenum itype = mesh.IndexType; size_t count = mesh.IndexCount; - setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR); + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); glUseProgram(MeshShader::BubbleShader::Program); MeshShader::BubbleShader::setUniforms(ModelViewProjectionMatrix, 0, time, transparency); @@ -664,7 +700,7 @@ void STKMesh::drawDisplace(const GLMesh &mesh) computeMVP(ModelViewProjectionMatrix); core::matrix4 ModelViewMatrix = irr_driver->getVideoDriver()->getTransform(video::ETS_VIEW); ModelViewMatrix *= irr_driver->getVideoDriver()->getTransform(video::ETS_WORLD); - setTexture(0, static_cast(irr_driver->getTexture(FileManager::TEXTURE, "displace.png"))->getOpenGLTextureName(), GL_LINEAR, GL_LINEAR); + setTexture(0, static_cast(irr_driver->getTexture(FileManager::TEXTURE, "displace.png"))->getOpenGLTextureName(), GL_LINEAR, GL_LINEAR, true); glUseProgram(MeshShader::DisplaceShader::Program); MeshShader::DisplaceShader::setUniforms(ModelViewProjectionMatrix, ModelViewMatrix, cb->getDirX(), cb->getDirY(), cb->getDir2X(), cb->getDir2Y(), 0); @@ -678,13 +714,47 @@ void STKMesh::drawTransparent(const GLMesh &mesh, video::E_MATERIAL_TYPE type) computeMVP(ModelViewProjectionMatrix); - if (type == irr_driver->getShader(ES_BUBBLES)) - drawBubble(mesh, ModelViewProjectionMatrix); + if (type == irr_driver->getShader(ES_BUBBLES)) + drawBubble(mesh, ModelViewProjectionMatrix); + else if (World::getWorld()->getTrack()->isFogEnabled()) + drawTransparentFogObject(mesh, ModelViewProjectionMatrix); else drawTransparentObject(mesh, ModelViewProjectionMatrix); return; } +void STKMesh::drawShadow(const GLMesh &mesh, video::E_MATERIAL_TYPE type) +{ + + GLenum ptype = mesh.PrimitiveType; + GLenum itype = mesh.IndexType; + size_t count = mesh.IndexCount; + + + core::matrix4 ShadowMVP; + computeMVP(ShadowMVP); + + if (type == irr_driver->getShader(ES_OBJECTPASS_REF)) + { + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); + glUseProgram(MeshShader::RefShadowShader::Program); + MeshShader::RefShadowShader::setUniforms(ShadowMVP, 0); + } + else if (type == irr_driver->getShader(ES_GRASS) || type == irr_driver->getShader(ES_GRASS_REF)) + { + setTexture(0, mesh.textures[0], GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, true); + glUseProgram(MeshShader::GrassShadowShader::Program); + MeshShader::GrassShadowShader::setUniforms(ShadowMVP, windDir, 0); + } + else + { + glUseProgram(MeshShader::ShadowShader::Program); + MeshShader::ShadowShader::setUniforms(ShadowMVP); + } + glBindVertexArray(mesh.vao_shadow_pass); + glDrawElements(ptype, count, itype, 0); +} + void STKMesh::drawSolid(const GLMesh &mesh, video::E_MATERIAL_TYPE type) { switch (irr_driver->getPhase()) @@ -856,6 +926,11 @@ void initvaostate(GLMesh &mesh, video::E_MATERIAL_TYPE type) mesh.vao_first_pass = createVAO(mesh.vertex_buffer, mesh.index_buffer, MeshShader::BubbleShader::attrib_position, MeshShader::BubbleShader::attrib_texcoord, -1, -1, -1, -1, -1, mesh.Stride); } + else if (World::getWorld()->getTrack()->isFogEnabled()) + { + mesh.vao_first_pass = createVAO(mesh.vertex_buffer, mesh.index_buffer, + MeshShader::TransparentFogShader::attrib_position, MeshShader::TransparentFogShader::attrib_texcoord, -1, -1, -1, -1, -1, mesh.Stride); + } else { mesh.vao_first_pass = createVAO(mesh.vertex_buffer, mesh.index_buffer, @@ -867,6 +942,22 @@ void initvaostate(GLMesh &mesh, video::E_MATERIAL_TYPE type) return; mesh.vao_displace_pass = createVAO(mesh.vertex_buffer, mesh.index_buffer, MeshShader::DisplaceShader::attrib_position, MeshShader::DisplaceShader::attrib_texcoord, MeshShader::DisplaceShader::attrib_second_texcoord, -1, -1, -1, -1, mesh.Stride); return; + case SHADOW_PASS: + if (mesh.vao_shadow_pass) + return; + if (type == irr_driver->getShader(ES_OBJECTPASS_REF)) + { + mesh.vao_shadow_pass = createVAO(mesh.vertex_buffer, mesh.index_buffer, MeshShader::RefShadowShader::attrib_position, MeshShader::RefShadowShader::attrib_texcoord, -1, -1, -1, -1, -1, mesh.Stride); + } + else if (type == irr_driver->getShader(ES_GRASS) || type == irr_driver->getShader(ES_GRASS_REF)) + { + mesh.vao_shadow_pass = createVAO(mesh.vertex_buffer, mesh.index_buffer, MeshShader::GrassShadowShader::attrib_position, MeshShader::GrassShadowShader::attrib_texcoord, -1, -1, -1, -1, MeshShader::GrassShadowShader::attrib_color, mesh.Stride); + } + else + { + mesh.vao_shadow_pass = createVAO(mesh.vertex_buffer, mesh.index_buffer, MeshShader::ShadowShader::attrib_position, -1, -1, -1, -1, -1, -1, mesh.Stride); + } + return; } } @@ -918,6 +1009,11 @@ void STKMesh::render() initvaostate(GLmeshes[i], material.MaterialType); drawGlow(GLmeshes[i]); } + else if (irr_driver->getPhase() == SHADOW_PASS) + { + initvaostate(GLmeshes[i], material.MaterialType); + drawShadow(GLmeshes[i], material.MaterialType); + } else { irr_driver->IncreaseObjectCount(); diff --git a/src/graphics/stkmesh.hpp b/src/graphics/stkmesh.hpp index 9a54dc53a..74cde2358 100644 --- a/src/graphics/stkmesh.hpp +++ b/src/graphics/stkmesh.hpp @@ -13,6 +13,7 @@ struct GLMesh { GLuint vao_second_pass; GLuint vao_glow_pass; GLuint vao_displace_pass; + GLuint vao_shadow_pass; GLuint vertex_buffer; GLuint index_buffer; GLuint textures[6]; @@ -47,6 +48,7 @@ void drawObjectUnlit(const GLMesh &mesh, const core::matrix4 &ModelViewProjectio // Forward pass (for transparents meshes) void drawTransparentObject(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionMatrix); +void drawTransparentFogObject(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionMatrix); void drawBubble(const GLMesh &mesh, const core::matrix4 &ModelViewProjectionMatrix); class STKMesh : public irr::scene::CMeshSceneNode @@ -61,6 +63,7 @@ protected: // Misc passes shaders (glow, displace...) void drawGlow(const GLMesh &mesh); void drawDisplace(const GLMesh &mesh); + void drawShadow(const GLMesh &mesh, video::E_MATERIAL_TYPE type); void createGLMeshes(); void cleanGLMeshes(); public: diff --git a/src/input/device_manager.cpp b/src/input/device_manager.cpp index 64afddcbd..b0330a97a 100644 --- a/src/input/device_manager.cpp +++ b/src/input/device_manager.cpp @@ -24,11 +24,13 @@ #include "config/player.hpp" #include "config/user_config.hpp" #include "graphics/irr_driver.hpp" +#include "input/wiimote_manager.hpp" #include "io/file_manager.hpp" #include "states_screens/kart_selection.hpp" #include "states_screens/state_manager.hpp" +#include "utils/log.hpp" #include "utils/translation.hpp" -#include "input/wiimote_manager.hpp" + #define INPUT_MODE_DEBUG 0 @@ -56,18 +58,18 @@ bool DeviceManager::initialize() if(UserConfigParams::logMisc()) { - printf("Initializing Device Manager\n"); - printf("---------------------------\n"); + Log::info("Device manager","Initializing Device Manager"); + Log::info("-","---------------------------"); } deserialize(); // Assign a configuration to the keyboard, or create one if we haven't yet - if(UserConfigParams::logMisc()) printf("Initializing keyboard support.\n"); + if(UserConfigParams::logMisc()) Log::info("Device manager","Initializing keyboard support."); if (m_keyboard_configs.size() == 0) { if(UserConfigParams::logMisc()) - printf("No keyboard configuration exists, creating one.\n"); + Log::info("Device manager","No keyboard configuration exists, creating one."); m_keyboard_configs.push_back(new KeyboardConfig()); created = true; } @@ -79,13 +81,13 @@ bool DeviceManager::initialize() } if(UserConfigParams::logMisc()) - printf("Initializing gamepad support.\n"); + Log::info("Device manager","Initializing gamepad support."); irr_driver->getDevice()->activateJoysticks(m_irrlicht_gamepads); int num_gamepads = m_irrlicht_gamepads.size(); if(UserConfigParams::logMisc()) { - printf("Irrlicht reports %d gamepads are attached to the system.\n", + Log::info("Device manager","Irrlicht reports %d gamepads are attached to the system.", num_gamepads); } @@ -109,19 +111,19 @@ bool DeviceManager::initialize() if (UserConfigParams::logMisc()) { - printf("#%d: %s detected...", id, name.c_str()); + Log::info("Device manager","#%d: %s detected...", id, name.c_str()); } // Returns true if new configuration was created if (getConfigForGamepad(id, name, &gamepadConfig) == true) { if(UserConfigParams::logMisc()) - printf("creating new configuration.\n"); + Log::info("Device manager","creating new configuration."); created = true; } else { if(UserConfigParams::logMisc()) - printf("using existing configuration.\n"); + Log::info("Device manager","using existing configuration."); } gamepadConfig->setPlugged(); @@ -440,12 +442,12 @@ bool DeviceManager::deserialize() static std::string filepath = file_manager->getUserConfigFile(INPUT_FILE_NAME); if(UserConfigParams::logMisc()) - printf("Deserializing input.xml...\n"); + Log::info("Device manager","Deserializing input.xml..."); if(!file_manager->fileExists(filepath)) { if(UserConfigParams::logMisc()) - printf("Warning: no configuration file exists.\n"); + Log::warn("Device manager","No configuration file exists."); } else { @@ -499,15 +501,15 @@ bool DeviceManager::deserialize() { if(keyboard_config != NULL) if(!keyboard_config->deserializeAction(xml)) - std::cerr << "Ignoring an ill-formed keyboard action in input config.\n"; + Log::error("Device manager","Ignoring an ill-formed keyboard action in input config."); } else if(reading_now == GAMEPAD) { if(gamepad_config != NULL) if(!gamepad_config->deserializeAction(xml)) - std::cerr << "Ignoring an ill-formed gamepad action in input config.\n"; + Log::error("Device manager","Ignoring an ill-formed gamepad action in input config."); } - else std::cerr << "Warning: An action is placed in an unexpected area in the input config file.\n"; + else Log::warn("Device manager","An action is placed in an unexpected area in the input config file."); } } break; @@ -534,7 +536,7 @@ bool DeviceManager::deserialize() if(UserConfigParams::logMisc()) { - printf("Found %d keyboard and %d gamepad configurations.\n", + Log::info("Device manager","Found %d keyboard and %d gamepad configurations.", m_keyboard_configs.size(), m_gamepad_configs.size()); } @@ -557,7 +559,7 @@ bool DeviceManager::deserialize() void DeviceManager::serialize() { static std::string filepath = file_manager->getUserConfigFile(INPUT_FILE_NAME); - if(UserConfigParams::logMisc()) printf("Serializing input.xml...\n"); + if(UserConfigParams::logMisc()) Log::info("Device manager","Serializing input.xml..."); std::ofstream configfile; @@ -565,8 +567,7 @@ void DeviceManager::serialize() if(!configfile.is_open()) { - std::cerr << "Failed to open " << filepath.c_str() - << " for writing, controls won't be saved\n"; + Log::error("Device manager","Failed to open %s for writing, controls won't be saved",filepath.c_str()); return; } @@ -584,7 +585,7 @@ void DeviceManager::serialize() configfile << "\n"; configfile.close(); - if(UserConfigParams::logMisc()) printf("Serialization complete.\n\n"); + if(UserConfigParams::logMisc()) Log::info("Device manager","Serialization complete."); } // serialize // ----------------------------------------------------------------------------- diff --git a/src/io/file_manager.cpp b/src/io/file_manager.cpp index 12db2079c..37bf5c1e1 100644 --- a/src/io/file_manager.cpp +++ b/src/io/file_manager.cpp @@ -64,7 +64,7 @@ std::vector FileManager::m_root_dirs; bool macSetBundlePathIfRelevant(std::string& data_dir) { - Log::debug("FileManager", "Checking whether we are using an app bundle... "); + Log::debug("[FileManager]", "Checking whether we are using an app bundle... "); // the following code will enable STK to find its data when placed in an // app bundle on mac OS X. // returns true if path is set, returns false if path was not set @@ -82,14 +82,14 @@ bool macSetBundlePathIfRelevant(std::string& data_dir) std::string contents = std::string(path) + std::string("/Contents"); if(contents.find(".app") != std::string::npos) { - Log::debug("FileManager", "yes\n"); + Log::debug("[FileManager]", "yes"); // executable is inside an app bundle, use app bundle-relative paths data_dir = contents + std::string("/Resources/"); return true; } else { - Log::debug("FileManager", "no\n"); + Log::debug("[FileManager]", "no"); return false; } } @@ -197,13 +197,13 @@ FileManager::FileManager() // We can't use _() here, since translations will only be initalised // after the filemanager (to get the path to the tranlsations from it) for(unsigned int i=0; iexistFile(io::path(path.c_str()))) return true; - std::cout << "[FileManager] Creating directory(ies) '" << path << "'.\n"; + Log::info("[FileManager]", "Creating directory(ies) '%s'", path.c_str()); std::vector split = StringUtils::split(path,'/'); std::string current_path = ""; for (unsigned int i=0; iexistFile(io::path(current_path.c_str()))) { if (!checkAndCreateDirectory(current_path)) { - Log::error("FileManager", "Can't create dir '%s'", + Log::error("[FileManager]", "Can't create dir '%s'", current_path.c_str()); break; } @@ -684,8 +684,8 @@ void FileManager::checkAndCreateConfigDir() m_user_config_dir = getenv("APPDATA"); if(!checkAndCreateDirectory(m_user_config_dir)) { - std::cerr << "[FileManager] Can't create config dir '" - << m_user_config_dir << "', falling back to '.'.\n"; + Log::error("[FileManager]", "Can't create config dir '%s" + ", falling back to '.'.", m_user_config_dir); m_user_config_dir = "."; } } @@ -702,8 +702,8 @@ void FileManager::checkAndCreateConfigDir() } else { - std::cerr << - "[FileManager] No home directory, this should NOT happen!\n"; + Log::error("[FileManager]", + "No home directory, this should NOT happen!"); // Fall back to system-wide app data (rather than // user-specific data), but should not happen anyway. m_user_config_dir = ""; @@ -721,9 +721,9 @@ void FileManager::checkAndCreateConfigDir() } else if (!getenv("HOME")) { - std::cerr - << "[FileManager] No home directory, this should NOT happen " - << "- trying '.' for config files!\n"; + Log::error("[FileManager]", + "No home directory, this should NOT happen " + "- trying '.' for config files!"); m_user_config_dir = "."; } else @@ -733,9 +733,9 @@ void FileManager::checkAndCreateConfigDir() if(!checkAndCreateDirectory(m_user_config_dir)) { // If $HOME/.config can not be created: - std::cerr << "[FileManager] Cannot create directory '" - << m_user_config_dir <<"', falling back to use '" - << getenv("HOME")<< "'.\n"; + Log::error("[FileManager]", + "Cannot create directory '%s', falling back to use '%s'", + m_user_config_dir.c_str(), getenv("HOME")); m_user_config_dir = getenv("HOME"); } } diff --git a/src/io/xml_node.cpp b/src/io/xml_node.cpp index 153327b3a..092dde423 100644 --- a/src/io/xml_node.cpp +++ b/src/io/xml_node.cpp @@ -56,8 +56,8 @@ XMLNode::XMLNode(const std::string &filename) { if(!is_first_element) { - fprintf(stderr, - "More than one root element in '%s' - ignored.\n", + Log::warn("[XMLNode]", + "More than one root element in '%s' - ignored.", filename.c_str()); } readXML(xml); @@ -223,8 +223,8 @@ int XMLNode::get(const std::string &attribute, Vec3 *value) const std::vector v = StringUtils::split(s,' '); if (v.size() != 3) { - fprintf(stderr, "[XMLNode] WARNING: Expected 3 floating-point values, but found '%s' in file %s\n", - s.c_str(), m_file_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected 3 floating-point values, but found '%s' in file %s", + s.c_str(), m_file_name.c_str()); return 0; } @@ -240,8 +240,8 @@ int XMLNode::get(const std::string &attribute, Vec3 *value) const } else { - fprintf(stderr, "[XMLNode] WARNING: Expected 3 floating-point values, but found '%s' in file %s\n", - s.c_str(), m_file_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected 3 floating-point values, but found '%s' in file %s", + s.c_str(), m_file_name.c_str()); return 0; } @@ -305,8 +305,8 @@ int XMLNode::get(const std::string &attribute, int32_t *value) const if (!StringUtils::parseString(s, value)) { - fprintf(stderr, "[XMLNode] WARNING: Expected int but found '%s' for attribute '%s' of node '%s' in file %s\n", - s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected int but found '%s' for attribute '%s' of node '%s' in file %s", + s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); return 0; } @@ -321,8 +321,8 @@ int XMLNode::get(const std::string &attribute, int64_t *value) const if (!StringUtils::parseString(s, value)) { - fprintf(stderr, "[XMLNode] WARNING: Expected int but found '%s' for attribute '%s' of node '%s' in file %s\n", - s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected int but found '%s' for attribute '%s' of node '%s' in file %s", + s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); return 0; } @@ -338,8 +338,8 @@ int XMLNode::get(const std::string &attribute, uint16_t *value) const if (!StringUtils::parseString(s, value)) { - fprintf(stderr, "[XMLNode] WARNING: Expected uint but found '%s' for attribute '%s' of node '%s' in file %s\n", - s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected uint but found '%s' for attribute '%s' of node '%s' in file %s", + s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); return 0; } @@ -354,8 +354,8 @@ int XMLNode::get(const std::string &attribute, uint32_t *value) const if (!StringUtils::parseString(s, value)) { - fprintf(stderr, "[XMLNode] WARNING: Expected uint but found '%s' for attribute '%s' of node '%s' in file %s\n", - s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected uint but found '%s' for attribute '%s' of node '%s' in file %s", + s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); return 0; } @@ -370,8 +370,8 @@ int XMLNode::get(const std::string &attribute, float *value) const if (!StringUtils::parseString(s, value)) { - fprintf(stderr, "[XMLNode] WARNING: Expected float but found '%s' for attribute '%s' of node '%s' in file %s\n", - s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected float but found '%s' for attribute '%s' of node '%s' in file %s", + s.c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); return 0; } @@ -429,8 +429,8 @@ int XMLNode::get(const std::string &attribute, float curr; if (!StringUtils::parseString(v[i], &curr)) { - fprintf(stderr, "[XMLNode] WARNING: Expected float but found '%s' for attribute '%s' of node '%s' in file %s\n", - v[i].c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected float but found '%s' for attribute '%s' of node '%s' in file %s", + v[i].c_str(), attribute.c_str(), m_name.c_str(), m_file_name.c_str()); return 0; } @@ -460,8 +460,8 @@ int XMLNode::get(const std::string &attribute, std::vector *value) const int val; if (!StringUtils::parseString(v[i], &val)) { - fprintf(stderr, "[XMLNode] WARNING: Expected int but found '%s' for attribute '%s' of node '%s'\n", - v[i].c_str(), attribute.c_str(), m_name.c_str()); + Log::warn("[XMLNode]", "WARNING: Expected int but found '%s' for attribute '%s' of node '%s'", + v[i].c_str(), attribute.c_str(), m_name.c_str()); return 0; } @@ -490,22 +490,22 @@ int XMLNode::get(const std::string &attribute, InterpolationArray *value) const std::vector pair = StringUtils::split(pairs[i],':'); if(pair.size()!=2) { - printf("Incorrect interpolation pair '%s' in '%s'.\n", - pairs[i].c_str(), attribute.c_str()); - printf("Must be x:y.\n"); + Log::fatal("[XMLNode]", "Incorrect interpolation pair '%s' in '%s'.", + pairs[i].c_str(), attribute.c_str()); + Log::fatal("[XMLNode]", "Must be x:y."); exit(-1); } float x; if(!StringUtils::fromString(pair[0], x)) { - printf("Incorrect x in pair '%s' of '%s'.\n", + Log::fatal("[XMLNode]", "Incorrect x in pair '%s' of '%s'.", pairs[i].c_str(), attribute.c_str()); exit(-1); } float y; if(!StringUtils::fromString(pair[1], y)) { - printf("Incorrect y in pair '%s' in '%s'.\n", + Log::fatal("[XMLNode]", "Incorrect y in pair '%s' in '%s'.", pair[1].c_str(), attribute.c_str()); exit(-1); } diff --git a/src/items/attachment.cpp b/src/items/attachment.cpp index c3f4e17a6..2689cbd01 100644 --- a/src/items/attachment.cpp +++ b/src/items/attachment.cpp @@ -39,7 +39,6 @@ #include "physics/triangle_mesh.hpp" #include "tracks/track.hpp" #include "utils/constants.hpp" -#include "utils/log.hpp" /** Initialises the attachment each kart has. */ diff --git a/src/items/flyable.cpp b/src/items/flyable.cpp index 9d5525075..4f043a7cd 100644 --- a/src/items/flyable.cpp +++ b/src/items/flyable.cpp @@ -143,9 +143,9 @@ void Flyable::createPhysics(float forw_offset, const Vec3 &velocity, // Just to get some additional information if the assert is triggered if(isnan(v.getX()) || isnan(v.getY()) || isnan(v.getZ())) { - printf("vel %f %f %f v %f %f %f\n", - velocity.getX(),velocity.getY(),velocity.getZ(), - v.getX(),v.getY(),v.getZ()); + Log::debug("[Flyable]", "vel %f %f %f v %f %f %f", + velocity.getX(),velocity.getY(),velocity.getZ(), + v.getX(),v.getY(),v.getZ()); } #endif assert(!isnan(v.getX())); diff --git a/src/items/item_manager.cpp b/src/items/item_manager.cpp index f740088dc..2072b1063 100644 --- a/src/items/item_manager.cpp +++ b/src/items/item_manager.cpp @@ -97,8 +97,8 @@ void ItemManager::loadDefaultItemMeshes() scene::IMesh *mesh = irr_driver->getAnimatedMesh(model_filename); if(!node || model_filename.size()==0 || !mesh) { - fprintf(stderr, "Item model '%s' in items.xml could not be loaded " - "- aborting", name.c_str()); + Log::fatal("[ItemManager]", "Item model '%s' in items.xml could not be loaded " + "- aborting", name.c_str()); exit(-1); } mesh->grab(); diff --git a/src/items/plunger.cpp b/src/items/plunger.cpp index ca7ea56f0..8925ce1b7 100644 --- a/src/items/plunger.cpp +++ b/src/items/plunger.cpp @@ -34,8 +34,6 @@ #include "utils/constants.hpp" #include "utils/string_utils.hpp" -#include "utils/log.hpp" //TODO: remove after debugging is done - // ----------------------------------------------------------------------------- Plunger::Plunger(AbstractKart *kart) : Flyable(kart, PowerupManager::POWERUP_PLUNGER) diff --git a/src/items/powerup_manager.cpp b/src/items/powerup_manager.cpp index defd22a73..e73661388 100644 --- a/src/items/powerup_manager.cpp +++ b/src/items/powerup_manager.cpp @@ -125,8 +125,8 @@ void PowerupManager::loadAllPowerups() LoadPowerup(type, *node); else { - printf("Can't find item '%s' from powerup.xml, entry %d/\n", - name.c_str(), i+1); + Log::fatal("[PowerupManager]", "Can't find item '%s' from powerup.xml, entry %d/", + name.c_str(), i+1); exit(-1); } } @@ -157,7 +157,7 @@ void PowerupManager::LoadPowerup(PowerupType type, const XMLNode &node) #ifdef DEBUG if (icon_file.size() == 0) { - fprintf(stderr, "Cannot load powerup %i, no 'icon' attribute under XML node\n", type); + Log::debug("[PowerupManager]", "Cannot load powerup %i, no 'icon' attribute under XML node", type); assert(false); } #endif @@ -221,8 +221,9 @@ void PowerupManager::loadWeights(const XMLNode &root, if(!node || s=="" || s_multi=="") { - printf("No weights found for class '%s' - probabilities will be incorrect.\n", - class_name.c_str()); + Log::error("[PowerupManager]", "No weights found for class '%s'" + " - probabilities will be incorrect.", + class_name.c_str()); return; } @@ -245,9 +246,9 @@ void PowerupManager::loadWeights(const XMLNode &root, if(weight_list.size()!=2*(int)POWERUP_LAST) { - printf("Incorrect number of weights found in class '%s':\n", + Log::error("[PowerupManager]", "Incorrect number of weights found in class '%s':", class_name.c_str()); - printf("%d instead of %d - probabilities will be incorrect.\n", + Log::error("[PowerupManager]", "%d instead of %d - probabilities will be incorrect.", (int)weight_list.size(), (int)POWERUP_LAST); return; } diff --git a/src/items/rubber_ball.cpp b/src/items/rubber_ball.cpp index b8086a759..36a252636 100644 --- a/src/items/rubber_ball.cpp +++ b/src/items/rubber_ball.cpp @@ -158,7 +158,7 @@ void RubberBall::computeTarget() if(m_target==m_owner && m_delete_timer < 0) { #ifdef PRINT_BALL_REMOVE_INFO - Log::debug("RubberBall", + Log::debug("[RubberBall]", "ball %d removed because owner is target.", m_id); #endif m_delete_timer = m_st_delete_time; @@ -171,7 +171,7 @@ void RubberBall::computeTarget() // aim at the owner (the ball is unlikely to hit it), and // this will trigger the usage of the delete time in updateAndDelete #ifdef PRINT_BALL_REMOVE_INFO - Log::debug("RubberBall" "ball %d removed because no more active target.", + Log::debug("[RubberBall]" "ball %d removed because no more active target.", m_id); #endif m_delete_timer = m_st_delete_time; @@ -312,7 +312,7 @@ bool RubberBall::updateAndDelete(float dt) { hit(NULL); #ifdef PRINT_BALL_REMOVE_INFO - Log::debug("RubberBall", "ball %d deleted.", m_id); + Log::debug("[RubberBall]", "ball %d deleted.", m_id); #endif return true; } @@ -355,7 +355,7 @@ bool RubberBall::updateAndDelete(float dt) float new_y = getHoT()+height; if(UserConfigParams::logFlyable()) - printf("ball %d: %f %f %f height %f new_y %f gethot %f ", + Log::debug("[RubberBall]", "ball %d: %f %f %f height %f new_y %f gethot %f ", m_id, next_xyz.getX(), next_xyz.getY(), next_xyz.getZ(), height, new_y, getHoT()); // No need to check for terrain height if the ball is low to the ground @@ -503,7 +503,7 @@ bool RubberBall::checkTunneling() if(m_tunnel_count > 3) { #ifdef PRINT_BALL_REMOVE_INFO - Log::debug("RubberBall", + Log::debug("[RubberBall]", "Ball %d nearly tunneled at %f %f %f -> %f %f %f", m_id, m_previous_xyz.getX(),m_previous_xyz.getY(), m_previous_xyz.getZ(), @@ -627,7 +627,7 @@ void RubberBall::updateDistanceToTarget() m_distance_to_target += world->getTrack()->getTrackLength(); } if(UserConfigParams::logFlyable()) - printf("ball %d: target %f %f %f distance_2_target %f", + Log::debug("[RubberBall]", "ball %d: target %f %f %f distance_2_target %f", m_id, m_target->getXYZ().getX(),m_target->getXYZ().getY(), m_target->getXYZ().getZ(),m_distance_to_target ); @@ -657,7 +657,7 @@ void RubberBall::updateDistanceToTarget() { m_delete_timer = m_st_delete_time; #ifdef PRINT_BALL_REMOVE_INFO - Log::debug("RubberBall", "ball %d lost target (overtook?).", + Log::debug("[RubberBall]", "ball %d lost target (overtook?).", m_id); #endif @@ -690,7 +690,7 @@ bool RubberBall::hit(AbstractKart* kart, PhysicalObject* object) { #ifdef PRINT_BALL_REMOVE_INFO if(kart) - Log::debug("RuberBall", "ball %d hit kart.", m_id); + Log::debug("[RuberBall]", "ball %d hit kart.", m_id); #endif if(kart && kart!=m_target) { diff --git a/src/karts/abstract_kart.cpp b/src/karts/abstract_kart.cpp index 8024f23f9..c8981ff36 100644 --- a/src/karts/abstract_kart.cpp +++ b/src/karts/abstract_kart.cpp @@ -111,7 +111,7 @@ void AbstractKart::setKartAnimation(AbstractKartAnimation *ka) ka->getName().c_str()); else Log::debug("Abstract_Kart", "Setting kart animation to NULL."); if(m_kart_animation) Log::info("Abstract_Kart", "Current kart" - "animation is '%s'.\n", + "animation is '%s'.", m_kart_animation->getName().c_str()); else Log::debug("Abstract_Kart", "Current kart animation is NULL."); } diff --git a/src/karts/controller/ai_properties.cpp b/src/karts/controller/ai_properties.cpp index c9dc6f655..720fc5a77 100644 --- a/src/karts/controller/ai_properties.cpp +++ b/src/karts/controller/ai_properties.cpp @@ -85,7 +85,7 @@ void AIProperties::load(const XMLNode *ai_node) else { Log::fatal("AIProperties", - "Incorrect nitro-usage '%s' in AI '%s'.\n",s.c_str(), + "Incorrect nitro-usage '%s' in AI '%s'.",s.c_str(), m_ident.c_str()); } // We actually need the square of the distance later @@ -102,7 +102,7 @@ void AIProperties::checkAllSet(const std::string &filename) const { #define CHECK_NEG( a,str_a) if(a<=UNDEFINED) { \ Log::fatal("AIProperties","Missing default value for" \ - " '%s' in '%s' 'for AI '%s'.\n", \ + " '%s' in '%s' 'for AI '%s'.", \ str_a, filename.c_str(), m_ident.c_str()); \ } CHECK_NEG(m_max_item_angle, "max-item-angle" ); @@ -118,17 +118,17 @@ void AIProperties::checkAllSet(const std::string &filename) const if(m_skid_probability.size()==0) { - Log::fatal("AIProperties", "No skid probability defined.\n"); + Log::fatal("AIProperties", "No skid probability defined."); } if(m_speed_cap.size()==0) { - Log::fatal("AIProperties", "No speed cap defined.\n"); + Log::fatal("AIProperties", "No speed cap defined."); } if(m_collect_item_probability.size()==0) { - Log::fatal("AIProperties", "No collect-item-probability defined.\n"); + Log::fatal("AIProperties", "No collect-item-probability defined."); } } // checkAllSet diff --git a/src/karts/controller/end_controller.cpp b/src/karts/controller/end_controller.cpp index 9e4b586d4..693e955fb 100644 --- a/src/karts/controller/end_controller.cpp +++ b/src/karts/controller/end_controller.cpp @@ -218,7 +218,7 @@ void EndController::handleSteering(float dt) const int next = m_next_node_index[m_track_node]; target_point = QuadGraph::get()->getQuadOfNode(next).getCenter(); #ifdef AI_DEBUG - Log::debug("end_controller.cpp", "- Outside of road: steer to center point.\n"); + Log::debug("end_controller.cpp", "- Outside of road: steer to center point."); #endif } else diff --git a/src/karts/controller/network_player_controller.cpp b/src/karts/controller/network_player_controller.cpp index b408727ec..84ebc105e 100644 --- a/src/karts/controller/network_player_controller.cpp +++ b/src/karts/controller/network_player_controller.cpp @@ -255,7 +255,7 @@ void NetworkPlayerController::update(float dt) { // Print a dividing line so that it's easier to see which events // get received in which order in the one frame. - Log::debug("PlayerController", "irr_driver", "-------------------------------------\n"); + Log::debug("PlayerController", "irr_driver", "-------------------------------------"); } // Don't do steering if it's replay. In position only replay it doesn't diff --git a/src/karts/controller/player_controller.cpp b/src/karts/controller/player_controller.cpp index 9886dcf81..776db3b81 100644 --- a/src/karts/controller/player_controller.cpp +++ b/src/karts/controller/player_controller.cpp @@ -311,7 +311,7 @@ void PlayerController::update(float dt) { // Print a dividing line so that it's easier to see which events // get received in which order in the one frame. - Log::debug("PlayerController", "irr_driver", "-------------------------------------\n"); + Log::debug("PlayerController", "irr_driver", "-------------------------------------"); } // Don't do steering if it's replay. In position only replay it doesn't diff --git a/src/karts/controller/skidding_ai.cpp b/src/karts/controller/skidding_ai.cpp index fcb1521ad..5db0c83c3 100644 --- a/src/karts/controller/skidding_ai.cpp +++ b/src/karts/controller/skidding_ai.cpp @@ -198,7 +198,7 @@ void SkiddingAI::reset() { Log::error("SkiddingAI", "Invalid starting position for '%s' - not on track" - " - can be ignored.\n", + " - can be ignored.", m_kart->getIdent().c_str()); m_track_node = QuadGraph::get()->findOutOfRoadSector(m_kart->getXYZ()); } @@ -401,7 +401,7 @@ void SkiddingAI::handleBraking() { #ifdef DEBUG if(m_ai_debug) - Log::debug("SkiddingAI", "braking: %s ahead of leader.\n", + Log::debug("SkiddingAI", "braking: %s ahead of leader.", m_kart->getIdent().c_str()); #endif @@ -421,7 +421,7 @@ void SkiddingAI::handleBraking() { #ifdef DEBUG if(m_ai_debug) - Log::debug("SkiddingAI", "%s not aligned with track.\n", + Log::debug("SkiddingAI", "%s not aligned with track.", m_kart->getIdent().c_str()); #endif m_controls->m_brake = true; @@ -486,7 +486,7 @@ void SkiddingAI::handleSteering(float dt) #ifdef AI_DEBUG m_debug_sphere[0]->setPosition(QuadGraph::get()->getQuadOfNode(next) .getCenter().toIrrVector()); - Log::debug("skidding_ai","-Outside of road: steer to center point.\n"); + Log::debug("skidding_ai","-Outside of road: steer to center point."); #endif } //If we are going to crash against a kart, avoid it if it doesn't @@ -522,7 +522,7 @@ void SkiddingAI::handleSteering(float dt) #ifdef AI_DEBUG Log::debug("skidding_ai", "- Velocity vector crashes with kart " "and doesn't crashes with road : steer 90 " - "degrees away from kart.\n"); + "degrees away from kart."); #endif } @@ -701,7 +701,7 @@ void SkiddingAI::handleItemCollectionAndAvoidance(Vec3 *aim_point, } if(m_ai_debug) - Log::debug("SkiddingAI", "%s unselects item.\n", + Log::debug("SkiddingAI", "%s unselects item.", m_kart->getIdent().c_str()); // Otherwise remove the pre-selected item (and start // looking for a new item). @@ -771,7 +771,7 @@ void SkiddingAI::handleItemCollectionAndAvoidance(Vec3 *aim_point, .toIrrVector()); #endif if(m_ai_debug) - Log::debug("SkiddingAI", "%s selects item type '%d'.\n", + Log::debug("SkiddingAI", "%s selects item type '%d'.", m_kart->getIdent().c_str(), item_to_collect->getType()); m_item_to_collect = item_to_collect; @@ -795,7 +795,7 @@ void SkiddingAI::handleItemCollectionAndAvoidance(Vec3 *aim_point, #endif if(m_ai_debug) Log::debug("SkiddingAI", - "%s adjusts to hit type %d angle %f.\n", + "%s adjusts to hit type %d angle %f.", m_kart->getIdent().c_str(), item_to_collect->getType(), angle); } @@ -803,7 +803,7 @@ void SkiddingAI::handleItemCollectionAndAvoidance(Vec3 *aim_point, { if(m_ai_debug) Log::debug("SkiddingAI", - "%s won't hit '%d', angle %f.\n", + "%s won't hit '%d', angle %f.", m_kart->getIdent().c_str(), item_to_collect->getType(), angle); } @@ -1378,7 +1378,7 @@ void SkiddingAI::handleItems(const float dt) break; default: Log::error("SkiddingAI", - "Invalid or unhandled powerup '%d' in default AI.\n", + "Invalid or unhandled powerup '%d' in default AI.", m_kart->getPowerup()->getType()); assert(false); } @@ -1699,7 +1699,7 @@ void SkiddingAI::checkCrashes(const Vec3& pos ) if(steps<1 || steps>1000) { Log::warn("SkiddingAI", - "Incorrect STEPS=%d. kart_length %f velocity %f\n", + "Incorrect STEPS=%d. kart_length %f velocity %f", steps, m_kart_length, m_kart->getVelocityLC().getZ()); steps=1000; } @@ -2181,7 +2181,7 @@ bool SkiddingAI::doSkid(float steer_fraction) if(m_ai_debug) { if(fabsf(steer_fraction)>=2.5f) - Log::debug("SkiddingAI", "%s stops skidding (%f).\n", + Log::debug("SkiddingAI", "%s stops skidding (%f).", m_kart->getIdent().c_str(), steer_fraction); } #endif @@ -2201,7 +2201,7 @@ bool SkiddingAI::doSkid(float steer_fraction) #ifdef DEBUG if(m_controls->m_skid && m_ai_debug) { - Log::debug("SkiddingAI", "%s stops skidding on straight.\n", + Log::debug("SkiddingAI", "%s stops skidding on straight.", m_kart->getIdent().c_str()); } #endif @@ -2238,7 +2238,7 @@ bool SkiddingAI::doSkid(float steer_fraction) if(m_controls->m_skid && duration < 1.0f) { if(m_ai_debug) - Log::debug("SkiddingAI", "'%s' too short, stop skid.\n", + Log::debug("SkiddingAI", "'%s' too short, stop skid.", m_kart->getIdent().c_str()); return false; } @@ -2254,7 +2254,7 @@ bool SkiddingAI::doSkid(float steer_fraction) #ifdef DEBUG if(m_controls->m_skid && m_ai_debug) Log::debug("SkiddingAI", - "%s skidding against track direction.\n", + "%s skidding against track direction.", m_kart->getIdent().c_str()); #endif return false; @@ -2265,7 +2265,7 @@ bool SkiddingAI::doSkid(float steer_fraction) { #ifdef DEBUG if(!m_controls->m_skid && m_ai_debug) - Log::debug("SkiddingAI", "%s start skid, duration %f.\n", + Log::debug("SkiddingAI", "%s start skid, duration %f.", m_kart->getIdent().c_str(), duration); #endif return true; @@ -2274,7 +2274,7 @@ bool SkiddingAI::doSkid(float steer_fraction) #ifdef DEBUG if(m_controls->m_skid && m_ai_debug) - Log::debug("SkiddingAI", "%s has no reasons to skid anymore.\n", + Log::debug("SkiddingAI", "%s has no reasons to skid anymore.", m_kart->getIdent().c_str()); #endif return false; @@ -2353,7 +2353,7 @@ void SkiddingAI::setSteering(float angle, float dt) m_controls->m_skid = KartControl::SC_NONE; #ifdef DEBUG if(m_ai_debug) - Log::info("SkiddingAI", "'%s' wrong steering, stop skid.\n", + Log::info("SkiddingAI", "'%s' wrong steering, stop skid.", m_kart->getIdent().c_str()); #endif } @@ -2368,7 +2368,7 @@ void SkiddingAI::setSteering(float angle, float dt) { #ifdef DEBUG if(m_ai_debug) - Log::info("SkiddingAI", "%s steering too much (%f).\n", + Log::info("SkiddingAI", "%s steering too much (%f).", m_kart->getIdent().c_str(), steer_fraction); #endif m_controls->m_skid = KartControl::SC_NONE; diff --git a/src/karts/explosion_animation.cpp b/src/karts/explosion_animation.cpp index 37656b295..53cb0e198 100644 --- a/src/karts/explosion_animation.cpp +++ b/src/karts/explosion_animation.cpp @@ -26,7 +26,6 @@ #include "karts/kart_properties.hpp" #include "modes/world.hpp" #include "tracks/track.hpp" -#include "utils/log.hpp" //TODO: remove after debugging is done /** A static create function that does only create an explosion if * the explosion happens to be close enough to affect the kart. diff --git a/src/karts/kart.cpp b/src/karts/kart.cpp index 7be299fb0..1e249ad60 100644 --- a/src/karts/kart.cpp +++ b/src/karts/kart.cpp @@ -199,7 +199,7 @@ void Kart::init(RaceManager::KartType type) if(!m_engine_sound) { - Log::error("Kart","Could not allocate a sfx object for the kart. Further errors may ensue!\n"); + Log::error("Kart","Could not allocate a sfx object for the kart. Further errors may ensue!"); } @@ -257,7 +257,7 @@ Kart::~Kart() if(m_slipstream) delete m_slipstream; if(m_sky_particles_emitter) delete m_sky_particles_emitter; if(m_attachment) delete m_attachment; - if (m_stars_effect) delete m_stars_effect; + if(m_stars_effect) delete m_stars_effect; delete m_shadow; @@ -1261,7 +1261,7 @@ void Kart::update(float dt) #ifdef DEBUG if(UserConfigParams::m_material_debug) { - Log::info("Kart","%s\tfraction %f\ttime %f.\n", + Log::info("Kart","%s\tfraction %f\ttime %f.", material->getTexFname().c_str(), material->getMaxSpeedFraction(), material->getSlowDownTime() ); @@ -1728,7 +1728,7 @@ void Kart::crashed(const Material *m, const Vec3 &normal) // Add a counter to make it easier to see if a new line of // output was added. static int counter=0; - Log::info("Kart","Kart %s hit track: %d material %s.\n", + Log::info("Kart","Kart %s hit track: %d material %s.", getIdent().c_str(), counter++, m ? m->getTexFname().c_str() : "None"); } @@ -2062,7 +2062,7 @@ void Kart::updatePhysics(float dt) updateEngineSFX(); #ifdef XX - Log::info("Kart","forward %f %f %f %f side %f %f %f %f angVel %f %f %f heading %f\n" + Log::info("Kart","forward %f %f %f %f side %f %f %f %f angVel %f %f %f heading %f" ,m_vehicle->m_forwardImpulse[0] ,m_vehicle->m_forwardImpulse[1] ,m_vehicle->m_forwardImpulse[2] diff --git a/src/karts/kart_gfx.cpp b/src/karts/kart_gfx.cpp index fa04661f9..42a5c94f6 100644 --- a/src/karts/kart_gfx.cpp +++ b/src/karts/kart_gfx.cpp @@ -27,6 +27,7 @@ #include "karts/kart_properties.hpp" #include "karts/skidding.hpp" #include "physics/btKart.hpp" +#include "utils/log.hpp" #include @@ -122,7 +123,7 @@ void KartGFX::addEffect(KartGFXType type, const std::string &file_name, // by adding a NULL to the list (which is tested for in all // cases). C++ guarantees that all memory allocated in the // constructor is properly freed. - std::cerr << e.what() << std::endl; + Log::error("[KartGFX]", "%s",e.what()); kind = NULL; emitter = NULL; } diff --git a/src/karts/kart_properties.cpp b/src/karts/kart_properties.cpp index 3ac459622..8cd676fe1 100644 --- a/src/karts/kart_properties.cpp +++ b/src/karts/kart_properties.cpp @@ -201,9 +201,9 @@ void KartProperties::load(const std::string &filename, const std::string &node) } catch(std::exception& err) { - Log::error("KartProperties", "Error while parsing KartProperties '%s':\n", + Log::error("[KartProperties]", "Error while parsing KartProperties '%s':", filename.c_str()); - Log::error("KartProperties", "%s\n", err.what()); + Log::error("[KartProperties]", "%s", err.what()); } if(root) delete root; @@ -392,15 +392,15 @@ void KartProperties::getAllData(const XMLNode * root) engine_node->get("power", &m_engine_power); if(m_engine_power.size()!=RaceManager::DIFFICULTY_COUNT) { - Log::fatal("KartProperties", - "Incorrect engine-power specifications for kart '%s'\n", + Log::fatal("[KartProperties]", + "Incorrect engine-power specifications for kart '%s'", getIdent().c_str()); } engine_node->get("max-speed", &m_max_speed); if(m_max_speed.size()!=RaceManager::DIFFICULTY_COUNT) { - Log::fatal("KartProperties", - "Incorrect max-speed specifications for kart '%s'\n", + Log::fatal("[KartProperties]", + "Incorrect max-speed specifications for kart '%s'", getIdent().c_str()); } } // if getNode("engine") @@ -477,8 +477,8 @@ void KartProperties::getAllData(const XMLNode * root) m_terrain_impulse_type = IMPULSE_TO_DRIVELINE; else { - Log::fatal("KartProperties", - "Missing or incorrect value for impulse-type: '%s'.\n", + Log::fatal("[KartProperties]", + "Missing or incorrect value for impulse-type: '%s'.", s.c_str()); } } @@ -560,7 +560,7 @@ void KartProperties::getAllData(const XMLNode * root) else if (s == "small") m_engine_sfx_type = "engine_small"; else { - Log::warn("KartProperties", "Kart '%s' has invalid engine '%s'.", + Log::warn("[KartProperties]", "Kart '%s' has invalid engine '%s'.", m_name.c_str(), s.c_str()); m_engine_sfx_type = "engine_small"; } @@ -603,32 +603,32 @@ void KartProperties::checkAllSet(const std::string &filename) { if(m_gear_switch_ratio.size()==0) { - Log::fatal("KartProperties", - "Missing default value for 'gear-switch-ratio' in '%s'.\n", + Log::fatal("[KartProperties]", + "Missing default value for 'gear-switch-ratio' in '%s'.", filename.c_str()); } if(m_gear_power_increase.size()==0) { - Log::fatal("KartProperties", - "Missing default value for 'gear-power-increase' in '%s'.\n", + Log::fatal("[KartProperties]", + "Missing default value for 'gear-power-increase' in '%s'.", filename.c_str()); } if(m_gear_switch_ratio.size()!=m_gear_power_increase.size()) { Log::error("KartProperties", "Number of entries for 'gear-switch-ratio' and " - "'gear-power-increase\n"); - Log::fatal("KartProperties", "in '%s' must be equal.\n", + "'gear-power-increase"); + Log::fatal("KartProperties", "in '%s' must be equal.", filename.c_str()); } if(m_startup_boost.size()!=m_startup_times.size()) { - Log::error("KartProperties", - "Number of entried for 'startup times' and 'startup-boost\n"); - Log::fatal("KartProperties", "must be identical.\n"); + Log::error("[KartProperties]", + "Number of entried for 'startup times' and 'startup-boost"); + Log::fatal("KartProperties", "must be identical."); } #define CHECK_NEG( a,strA) if(a<=UNDEFINED) { \ - Log::fatal("KartProperties", \ - "Missing default value for '%s' in '%s'.\n", \ + Log::fatal("[KartProperties]", \ + "Missing default value for '%s' in '%s'.", \ strA,filename.c_str()); \ } diff --git a/src/karts/kart_properties_manager.cpp b/src/karts/kart_properties_manager.cpp index 5b07afbee..8381e10ac 100644 --- a/src/karts/kart_properties_manager.cpp +++ b/src/karts/kart_properties_manager.cpp @@ -191,8 +191,8 @@ bool KartPropertiesManager::loadKart(const std::string &dir) } catch (std::runtime_error& err) { - std::cerr << "Giving up loading '" << config_filename.c_str() - << "' : " << err.what() << std::endl; + Log::error("[Kart_Properties_Manager]","Giving up loading '%s': %s", + config_filename.c_str(), err.what()); return false; } @@ -201,7 +201,7 @@ bool KartPropertiesManager::loadKart(const std::string &dir) if (kart_properties->getVersion() < stk_config->m_min_kart_version || kart_properties->getVersion() > stk_config->m_max_kart_version) { - Log::warn("Kart_Properties_Manager", "Warning: kart '%s' is not " + Log::warn("[Kart_Properties_Manager]", "Warning: kart '%s' is not " "supported by this binary, ignored.", kart_properties->getIdent().c_str()); delete kart_properties; @@ -306,7 +306,7 @@ void KartPropertiesManager::setUnavailableKarts(std::vector karts) { m_kart_available[i] = false; - Log::error("Kart_Properties_Manager", + Log::error("[Kart_Properties_Manager]", "Kart '%s' not available on all clients, disabled.", m_karts_properties[i].getIdent().c_str()); } // kart not in list @@ -428,10 +428,8 @@ void KartPropertiesManager::getRandomKartList(int count, catch (std::runtime_error& ex) { (void)ex; - std::cerr << - "[KartPropertiesManager] getRandomKartList : WARNING, " - "can't find kart '" - << existing_karts[i].getKartName() << "'\n"; + Log::error("[KartPropertiesManager]", "getRandomKartList : WARNING, " + "can't find kart '%s'", existing_karts[i].getKartName().c_str()); } } for(unsigned int i=0; isize(); i++) @@ -444,10 +442,8 @@ void KartPropertiesManager::getRandomKartList(int count, catch (std::runtime_error &ex) { (void)ex; - std::cerr << - "[KartPropertiesManager] getRandomKartList : WARNING, " - "can't find kart '" - << (*ai_list)[i] << "'\n"; + Log::error("[KartPropertiesManager]", "getRandomKartList : WARNING, " + "can't find kart '%s'",(*ai_list)[i].c_str()); } } diff --git a/src/modes/cutscene_world.cpp b/src/modes/cutscene_world.cpp index 4213caaf8..6ba63c3b1 100644 --- a/src/modes/cutscene_world.cpp +++ b/src/modes/cutscene_world.cpp @@ -97,7 +97,7 @@ void CutsceneWorld::init() if (!StringUtils::fromString(frameStr, frame)) { - fprintf(stderr, "[CutsceneWorld] Invalid condition '%s'\n", + Log::error("[CutsceneWorld]", "Invalid condition '%s'", condition.c_str()); continue; } @@ -117,7 +117,7 @@ void CutsceneWorld::init() if (!StringUtils::fromString(frameStr, frame)) { - fprintf(stderr, "[CutsceneWorld] Invalid condition '%s'\n", + Log::error("[CutsceneWorld]", "Invalid condition '%s'", condition.c_str()); continue; } @@ -132,7 +132,7 @@ void CutsceneWorld::init() if (!StringUtils::fromString(frameStr, frame)) { - fprintf(stderr, "[CutsceneWorld] Invalid condition '%s'\n", + Log::error("[CutsceneWorld]", "Invalid condition '%s'", condition.c_str()); continue; } @@ -152,7 +152,7 @@ void CutsceneWorld::init() if (m_duration <= 0.0f) { - fprintf(stderr, "[CutsceneWorld] WARNING: cutscene has no duration\n"); + Log::error("[CutsceneWorld]", "WARNING: cutscene has no duration"); } } // CutsceneWorld diff --git a/src/modes/demo_world.cpp b/src/modes/demo_world.cpp index 6f0fbdf10..c6dad061c 100644 --- a/src/modes/demo_world.cpp +++ b/src/modes/demo_world.cpp @@ -120,7 +120,7 @@ bool DemoWorld::updateIdleTimeAndStartDemo(float dt) && m_demo_tracks.size() > 0) { if(!track) - printf("Invalid demo track identifier '%s'.\n", + Log::warn("[DemoWorld]", "Invalid demo track identifier '%s'.", m_demo_tracks[0].c_str()); m_demo_tracks.erase(m_demo_tracks.begin()); track = track_manager->getTrack(m_demo_tracks[0]); @@ -130,7 +130,7 @@ bool DemoWorld::updateIdleTimeAndStartDemo(float dt) // be filled up with all the tracks. if(m_demo_tracks.size()==0) { - printf("No valid tracks found, no demo started.\n"); + Log::warn("[DemoWorld]", "No valid tracks found, no demo started."); return false; } diff --git a/src/modes/easter_egg_hunt.cpp b/src/modes/easter_egg_hunt.cpp index 4d44192cb..5afe05f6f 100644 --- a/src/modes/easter_egg_hunt.cpp +++ b/src/modes/easter_egg_hunt.cpp @@ -42,7 +42,7 @@ void EasterEggHunt::init() // check for possible problems if AI karts were incorrectly added if(getNumKarts() > race_manager->getNumPlayers()) { - fprintf(stderr, "No AI exists for this game mode\n"); + Log::error("EasterEggHunt]", "No AI exists for this game mode"); exit(1); } @@ -70,7 +70,7 @@ void EasterEggHunt::readData(const std::string &filename) if(easter->getName()!="EasterEggHunt") { - printf("Can't load easter egg file '%s' - no EasterEggHunt element.", + Log::error("[EasterEggHunt]", "Can't load easter egg file '%s' - no EasterEggHunt element.", filename.c_str()); delete easter; return; @@ -121,7 +121,7 @@ void EasterEggHunt::readData(const std::string &filename) const XMLNode *egg = data->getNode(i); if(egg->getName()!="easter-egg") { - printf("Unknown node '%s' in easter egg level '%s' - ignored.\n", + Log::warn("[EasterEggHunt]", "Unknown node '%s' in easter egg level '%s' - ignored.", egg->getName().c_str(), race_manager->getDifficultyAsString(act_difficulty).c_str()); continue; diff --git a/src/modes/follow_the_leader.cpp b/src/modes/follow_the_leader.cpp index 005b937ae..f9c4b2f94 100644 --- a/src/modes/follow_the_leader.cpp +++ b/src/modes/follow_the_leader.cpp @@ -108,19 +108,19 @@ void FollowTheLeaderRace::countdownReachedZero() AbstractKart *kart = getKartAtPosition(position_to_remove); if(!kart || kart->isEliminated()) { - fprintf(stderr,"Problem with removing leader: position %d not found\n", + Log::error("[FTL]", "Problem with removing leader: position %d not found", position_to_remove); for(unsigned int i=0; iisEliminated(), m_karts[i]->getPosition()); + Log::error("[FTL]", "kart %u: eliminated %d position %d", + i, m_karts[i]->isEliminated(), m_karts[i]->getPosition()); } // for i } // else { if(UserConfigParams::m_ftl_debug) { - printf("[ftl] Eliminiating kart '%s' at position %d.\n", + Log::debug("[FTL", "Eliminiating kart '%s' at position %d.", kart->getIdent().c_str(), position_to_remove); } eliminateKart(kart->getWorldKartId()); diff --git a/src/modes/linear_world.cpp b/src/modes/linear_world.cpp index b96d7ac98..d4d7b09a8 100644 --- a/src/modes/linear_world.cpp +++ b/src/modes/linear_world.cpp @@ -208,10 +208,10 @@ void LinearWorld::update(float dt) { if(pos_used[m_karts[i]->getPosition()]!=-99) { - for(unsigned int j =0; jgetPosition(), m_karts[j]->hasFinishedRace(), m_kart_info[j].m_race_lap, @@ -553,9 +553,9 @@ float LinearWorld::estimateFinishTimeForKart(AbstractKart* kart) #ifdef DEBUG if(kart_info.m_overall_distance > full_distance) { - printf("WARNING: full distance < distance covered for kart '%s':\n", + Log::debug("[LinearWorld]", "Full distance < distance covered for kart '%s':", kart->getIdent().c_str()); - printf("%f < %f\n", full_distance, kart_info.m_overall_distance); + Log::debug("[LinearWorld]", "%f < %f", full_distance, kart_info.m_overall_distance); } #endif // Avoid potential problems (floating point issues, coding bug?) if a @@ -699,29 +699,29 @@ void LinearWorld::updateRacePosition() rank_changed |= kart->getPosition()!=p; if (!setKartPosition(i,p)) { - std::cerr << "ERROR, same rank used twice!!\n"; + Log::error("[LinearWorld]", "Same rank used twice!!"); - std::cerr << "Info used to decide ranking :\n"; + Log::debug("[LinearWorld]", "Info used to decide ranking :"); for (unsigned int d=0; dgetIdent() - << " has finished(" << m_karts[d]->hasFinishedRace() - << "), is at lap (" << getLapForKart(d) - << "), is at distance(" - << m_kart_info[d].m_overall_distance - << "), is eliminated(" << m_karts[d]->isEliminated() - << ")" << std::endl; + Log::debug("[LinearWorld]", "Kart %s has finished (%d), is at lap (%u)," + "is at distance (%u), is eliminated(%d)", + m_karts[d]->getIdent().c_str(), + m_karts[d]->hasFinishedRace(), + getLapForKart(d), + m_kart_info[d].m_overall_distance, + m_karts[d]->isEliminated()); } - std::cerr << "Who has each ranking so far :\n"; + Log::debug("[LinearWorld]", "Who has each ranking so far :"); for (unsigned int d=0; dgetIdent() << " has rank " - << m_karts[d]->getPosition() << std::endl; + Log::debug("[LinearWorld]", "%s has rank %d", m_karts[d]->getIdent().c_str(), + m_karts[d]->getPosition()); } - std::cerr << " --> And " << kart->getIdent() - << " is being set at rank " << p << std::endl; + Log::debug("[LinearWorld]", " --> And %s is being set at rank %d", + kart->getIdent().c_str(), p); history->Save(); assert(false); } @@ -749,17 +749,18 @@ void LinearWorld::updateRacePosition() #ifdef DEBUG_KART_RANK if(rank_changed) { - std::cout << "Counting laps at "<getIdent() - << " (laps " << m_kart_info[i].m_race_lap - << ", progress " << m_kart_info[i].m_overall_distance - << " finished " << kart->hasFinishedRace() - << " eliminated " << kart->isEliminated() - << " initial position "<< kart->getInitialPosition() - << ").\n"; + Log::debug("[LinearWorld]", "counting karts ahead of %s (laps %u," + " progress %u, finished %d, eliminated %d, initial position %u.", + kart->getIdent().c_str(), + m_kart_info[i].m_race_lap, + m_kart_info[i].m_overall_distance, + kart->hasFinishedRace(), + kart->isEliminated(), + kart->getInitialPosition()); // Karts that are either eliminated or have finished the // race already have their (final) position assigned. If // these karts would get their rank updated, it could happen @@ -776,36 +777,36 @@ void LinearWorld::updateRacePosition() if(j == my_id) continue; if(m_karts[j]->isEliminated()) { - std::cout << " " << p << " : " << m_karts[j]->getIdent() - << " because it is eliminated.\n"; + Log::debug("[LinearWorld]", " %u: %s because it is eliminated.", + p, m_karts[j]->getIdent().c_str()); continue; } if(!kart->hasFinishedRace() && m_karts[j]->hasFinishedRace()) { p++; - std::cout << " " << p << " : " << m_karts[j]->getIdent() - << " because it has finished the race.\n"; + Log::debug("[LinearWorld]", " %u: %s because it has finished the race.", + p, m_karts[j]->getIdent().c_str()); continue; } if(m_kart_info[j].m_overall_distance > my_distance) { p++; - std::cout << " " << p << " : " << m_karts[j]->getIdent() - << " because it is ahead " - << m_kart_info[j].m_overall_distance <<".\n"; + Log::debug("[LinearWorld]", " %u: %s because it is ahead %u.", + p, m_karts[j]->getIdent().c_str(), + m_kart_info[j].m_overall_distance); continue; } if(m_kart_info[j].m_overall_distance == my_distance && m_karts[j]->getInitialPosition()getInitialPosition()) { p++; - std::cout << " " << p << " : " << m_karts[j]->getIdent() - << " has same distance, but started ahead " - << m_karts[j]->getInitialPosition()<<".\n"; + Log::debug("[LinearWorld]"," %u: %s has same distance, but started ahead %d", + p, m_karts[j]->getIdent().c_str(), + m_karts[j]->getInitialPosition()); } } // next kart j } // for igetKart(UserConfigParams::m_default_kart)) { - Log::warn("overworld", "cannot find kart '%s', " - "will revert to default\n", + Log::warn("[overworld]", "cannot find kart '%s', " + "will revert to default", UserConfigParams::m_default_kart.c_str()); UserConfigParams::m_default_kart.revertToDefaults(); diff --git a/src/modes/soccer_world.cpp b/src/modes/soccer_world.cpp index e3e8f8d8d..4331ab500 100644 --- a/src/modes/soccer_world.cpp +++ b/src/modes/soccer_world.cpp @@ -76,7 +76,7 @@ void SoccerWorld::init() // check for possible problems if AI karts were incorrectly added if(getNumKarts() > race_manager->getNumPlayers()) { - fprintf(stderr, "No AI exists for this game mode\n"); + Log::error("[SoccerWorld]", "No AI exists for this game mode"); exit(1); } m_goal_target = race_manager->getMaxGoal(); @@ -85,7 +85,7 @@ void SoccerWorld::init() } // init //----------------------------------------------------------------------------- -/** Called then a battle is restarted. +/** Called when a battle is restarted. */ void SoccerWorld::reset() { @@ -391,8 +391,8 @@ void SoccerWorld::moveKartAfterRescue(AbstractKart* kart) } else { - fprintf(stderr, "WARNING: invalid position after rescue for kart %s on track %s.\n", - (kart->getIdent().c_str()), m_track->getIdent().c_str()); + Log::warn("[SoccerWorld]", " Invalid position after rescue for kart %s on track %s.", + kart->getIdent().c_str(), m_track->getIdent().c_str()); } } // moveKartAfterRescue diff --git a/src/modes/three_strikes_battle.cpp b/src/modes/three_strikes_battle.cpp index c449fea52..185c74598 100644 --- a/src/modes/three_strikes_battle.cpp +++ b/src/modes/three_strikes_battle.cpp @@ -61,7 +61,7 @@ void ThreeStrikesBattle::init() // check for possible problems if AI karts were incorrectly added if(getNumKarts() > race_manager->getNumPlayers()) { - Log::fatal("Three Strikes Battle", "No AI exists for this game mode"); + Log::fatal("[Three Strikes Battle]", "No AI exists for this game mode"); } m_kart_info.resize(m_karts.size()); } // ThreeStrikesBattle diff --git a/src/modes/world.cpp b/src/modes/world.cpp index a2ae337c6..def30338f 100644 --- a/src/modes/world.cpp +++ b/src/modes/world.cpp @@ -334,7 +334,7 @@ Controller* World::loadAIController(AbstractKart *kart) controller = new SkiddingAI(kart); break; default: - Log::warn("World", "Unknown AI, using default."); + Log::warn("[World]", "Unknown AI, using default."); controller = new SkiddingAI(kart); break; } @@ -531,12 +531,12 @@ void World::resetAllKarts() if (!kart_over_ground) { - Log::error("World", + Log::error("[World]", "No valid starting position for kart %d on track %s.", (int)(i-m_karts.begin()), m_track->getIdent().c_str()); if (UserConfigParams::m_artist_debug_mode) { - Log::warn("World", "Activating fly mode."); + Log::warn("[World]", "Activating fly mode."); (*i)->flyUp(); continue; } @@ -582,14 +582,14 @@ void World::resetAllKarts() &normal); if(!material) { - Log::error("World", + Log::error("[World]", "No valid starting position for kart %d " "on track %s.", (int)(i-m_karts.begin()), m_track->getIdent().c_str()); if (UserConfigParams::m_artist_debug_mode) { - Log::warn("World", "Activating fly mode."); + Log::warn("[World]", "Activating fly mode."); (*i)->flyUp(); continue; } @@ -757,7 +757,7 @@ void World::updateWorld(float dt) if (!kart_properties_manager->getKart(UserConfigParams::m_default_kart)) { - Log::warn("World", + Log::warn("[World]", "Cannot find kart '%s', will revert to default.", UserConfigParams::m_default_kart.c_str()); UserConfigParams::m_default_kart.revertToDefaults(); @@ -932,10 +932,10 @@ void World::updateHighscores(int* best_highscore_rank, int* best_finish_time, // the kart location data is wrong #ifdef DEBUG - Log::error("World", "Incorrect kart positions:"); + Log::error("[World]", "Incorrect kart positions:"); for (unsigned int i=0; igetPosition()); } #endif @@ -948,7 +948,6 @@ void World::updateHighscores(int* best_highscore_rank, int* best_finish_time, continue; if (!m_karts[index[pos]]->hasFinishedRace()) continue; - assert(index[pos] >= 0); assert(index[pos] < m_karts.size()); Kart *k = (Kart*)m_karts[index[pos]]; diff --git a/src/modes/world_with_rank.cpp b/src/modes/world_with_rank.cpp index 7db5f6047..ef9ddfce1 100644 --- a/src/modes/world_with_rank.cpp +++ b/src/modes/world_with_rank.cpp @@ -21,6 +21,7 @@ #include "karts/kart_properties.hpp" #include "race/history.hpp" #include "tracks/track.hpp" +#include "utils/log.hpp" #include @@ -85,22 +86,22 @@ bool WorldWithRank::setKartPosition(unsigned int kart_id, assert(m_position_setting_initialised); if(m_position_used[position-1]) { - std::cerr << "== TWO KARTS ARE BEING GIVEN THE SAME POSITION!! ==\n"; + Log::error("[WorldWithRank]", "== TWO KARTS ARE BEING GIVEN THE SAME POSITION!! =="); for (unsigned int j=0; j < m_position_index.size(); j++) { if (!m_position_used[j]) { - std::cout << " No kart is yet set at position " << j+1 - << std::endl; + Log::warn("WorldWithRank]", "No kart is yet set at position %u", j+1); } else { - std::cout << " Kart " << m_position_index[j] - << " is at position " << j << std::endl; + Log::warn("WorldWithRank]", "Kart %u is at position %u", + m_position_index[j], j); } } - std::cout << "Kart " << kart_id << " is being given position " - << position << ", but this position is already taken\n"; + Log::warn("WorldWithRank]", "Kart %u is being given position %u," + "but this position is already taken", + kart_id, position); return false; } m_position_used[position-1] = true; diff --git a/src/network/network_manager.cpp b/src/network/network_manager.cpp index a3d5d801c..234bb5913 100644 --- a/src/network/network_manager.cpp +++ b/src/network/network_manager.cpp @@ -123,7 +123,7 @@ void NetworkManager::notifyEvent(Event* event) ((addr>>24)&0xff), ((addr>>16)&0xff), ((addr>>8)&0xff), - (addr&0xff), event->data().c_str()); + (addr & 0xff), event->data().std_string().c_str()); } diff --git a/src/network/network_string.hpp b/src/network/network_string.hpp index fe6e018e8..b1616f430 100644 --- a/src/network/network_string.hpp +++ b/src/network/network_string.hpp @@ -146,16 +146,20 @@ class NetworkString return *this; } - const char* c_str() const + const std::string std_string() const { std::string str(m_string.begin(), m_string.end()); - return str.c_str(); + return str; } + int size() const { return m_string.size(); } + uint8_t* getBytes() { return &m_string[0]; }; + const uint8_t* getBytes() const { return &m_string[0]; }; + template T get(int pos) const { diff --git a/src/network/protocol_manager.cpp b/src/network/protocol_manager.cpp index 06cf9a415..967540a71 100644 --- a/src/network/protocol_manager.cpp +++ b/src/network/protocol_manager.cpp @@ -144,7 +144,7 @@ void ProtocolManager::notifyEvent(Event* event) pthread_mutex_unlock(&m_protocols_mutex); if (searchedProtocol == PROTOCOL_NONE) // no protocol was aimed, show the msg to debug { - Log::debug("ProtocolManager", "NO PROTOCOL : Message is \"%s\"", event2->data().c_str()); + Log::debug("ProtocolManager", "NO PROTOCOL : Message is \"%s\"", event2->data().std_string().c_str()); } if (protocols_ids.size() != 0) diff --git a/src/network/stk_host.cpp b/src/network/stk_host.cpp index a74a47620..a6d82edfc 100644 --- a/src/network/stk_host.cpp +++ b/src/network/stk_host.cpp @@ -73,7 +73,7 @@ void* STKHost::receive_data(void* self) } } myself->m_listening = false; - delete myself->m_listening_thread; + free(myself->m_listening_thread); myself->m_listening_thread = NULL; Log::info("STKHost", "Listening has been stopped"); return NULL; @@ -302,7 +302,7 @@ uint8_t* STKHost::receiveRawPacket(TransportAddress sender, int max_tries) void STKHost::broadcastPacket(const NetworkString& data, bool reliable) { - ENetPacket* packet = enet_packet_create(data.c_str(), data.size()+1, + ENetPacket* packet = enet_packet_create(data.getBytes(), data.size() + 1, (reliable ? ENET_PACKET_FLAG_RELIABLE : ENET_PACKET_FLAG_UNSEQUENCED)); enet_host_broadcast(m_host, 0, packet); STKHost::logPacket(data, false); diff --git a/src/network/stk_peer.cpp b/src/network/stk_peer.cpp index a68a647a9..39badb8c4 100644 --- a/src/network/stk_peer.cpp +++ b/src/network/stk_peer.cpp @@ -95,7 +95,7 @@ void STKPeer::sendPacket(NetworkString const& data, bool reliable) data.size(), (m_peer->address.host>>0)&0xff, (m_peer->address.host>>8)&0xff,(m_peer->address.host>>16)&0xff, (m_peer->address.host>>24)&0xff,m_peer->address.port); - ENetPacket* packet = enet_packet_create(data.c_str(), data.size()+1, + ENetPacket* packet = enet_packet_create(data.getBytes(), data.size() + 1, (reliable ? ENET_PACKET_FLAG_RELIABLE : ENET_PACKET_FLAG_UNSEQUENCED)); /* to debug the packet output printf("STKPeer: "); @@ -126,7 +126,7 @@ uint16_t STKPeer::getPort() const bool STKPeer::isConnected() const { - Log::info("STKPeer", "The peer state is %i\n", m_peer->state); + Log::info("STKPeer", "The peer state is %i", m_peer->state); return (m_peer->state == ENET_PEER_STATE_CONNECTED); } diff --git a/src/physics/physics.hpp b/src/physics/physics.hpp index 2ef4a94d8..47b3e874f 100644 --- a/src/physics/physics.hpp +++ b/src/physics/physics.hpp @@ -87,7 +87,7 @@ private: // -------------------------------------------------------------------- const UserPointer *getUserPointer(unsigned int n) const { - assert(n>=0 && n<=1); + assert(n<=1); return m_up[n]; } // getUserPointer // -------------------------------------------------------------------- diff --git a/src/race/race_manager.cpp b/src/race/race_manager.cpp index 2355d02f2..29c36eeb2 100644 --- a/src/race/race_manager.cpp +++ b/src/race/race_manager.cpp @@ -143,7 +143,7 @@ void RaceManager::setLocalKartInfo(unsigned int player_id, const std::string& kart) { assert(kart.size() > 0); - assert(0<=player_id && player_id getKart(kart) != NULL); const PlayerProfile* profile = StateManager::get()->getActivePlayerProfile(player_id); @@ -157,7 +157,7 @@ void RaceManager::setLocalKartInfo(unsigned int player_id, */ void RaceManager::setLocalKartSoccerTeam(unsigned int player_id, SoccerTeam team) { - assert(0<=player_id && player_id getWidget("tracks"); assert( tracks_widget != NULL ); - tracks_widget->setItemCountHint(num_of_arenas); //set the item hint to that number to prevent weird formatting + tracks_widget->setItemCountHint(num_of_arenas+1); //set the item hint to that number to prevent weird formatting } // ----------------------------------------------------------------------------- diff --git a/src/states_screens/dialogs/addons_loading.cpp b/src/states_screens/dialogs/addons_loading.cpp index ad918f13b..6878193c2 100644 --- a/src/states_screens/dialogs/addons_loading.cpp +++ b/src/states_screens/dialogs/addons_loading.cpp @@ -305,7 +305,6 @@ void AddonsLoading::onUpdate(float delta) **/ void AddonsLoading::startDownload() { - std::string file = m_addon.getZipFileName(); std::string save = "tmp/" + StringUtils::getBasename(m_addon.getZipFileName()); m_download_request = new Online::HTTPRequest(save, /*manage mem*/false, diff --git a/src/states_screens/easter_egg_screen.cpp b/src/states_screens/easter_egg_screen.cpp index c58534520..18ade0b41 100644 --- a/src/states_screens/easter_egg_screen.cpp +++ b/src/states_screens/easter_egg_screen.cpp @@ -176,7 +176,7 @@ void EasterEggScreen::beforeAddingWidget() DynamicRibbonWidget* tracks_widget = this->getWidget("tracks"); assert( tracks_widget != NULL ); - tracks_widget->setItemCountHint(num_of_arenas); //set the item hint to that number to prevent weird formatting + tracks_widget->setItemCountHint(num_of_arenas+1); //set the item hint to that number to prevent weird formatting } // ----------------------------------------------------------------------------- diff --git a/src/states_screens/kart_selection.cpp b/src/states_screens/kart_selection.cpp index 8f9e06c8b..6b71448e0 100644 --- a/src/states_screens/kart_selection.cpp +++ b/src/states_screens/kart_selection.cpp @@ -43,6 +43,7 @@ #include "online/profile.hpp" #include "states_screens/race_setup_screen.hpp" #include "states_screens/state_manager.hpp" +#include "utils/log.hpp" #include "utils/translation.hpp" #include "utils/random_generator.hpp" #include "utils/string_utils.hpp" @@ -393,9 +394,9 @@ void PlayerKartWidget::setPlayerID(const int newPlayerID) if (StateManager::get()->getActivePlayer(newPlayerID) != m_associated_player) { - std::cerr << "[KartSelectionScreen] WARNING: Internal " + Log::warn("[KartSelectionScreen]", "Internal " "inconsistency, PlayerKartWidget has IDs and " - "pointers that do not correspond to one player\n"; + "pointers that do not correspond to one player"); fprintf(stderr, " Player: %p - Index: %d - m_associated_player: %p\n", StateManager::get()->getActivePlayer(newPlayerID), @@ -692,12 +693,11 @@ GUIEngine::EventPropagation PlayerKartWidget::transmitEvent( { if(UserConfigParams::logGUI()) { - std::cout << "[KartSelectionScreen] Identity changed " - "for player " << m_player_id - << " : " << irr::core::stringc( + Log::info("[KartSelectionScreen]", "Identity changed " + "for player %s : %s",m_player_id, + irr::core::stringc( m_player_ident_spinner->getStringValue() - .c_str()).c_str() - << std::endl; + .c_str()).c_str()); } if (m_parent_screen->m_multiplayer) @@ -1062,7 +1062,7 @@ void KartSelectionScreen::unloaded() bool KartSelectionScreen::playerJoin(InputDevice* device, bool firstPlayer) { if (UserConfigParams::logGUI()) - std::cout << "[KartSelectionScreen] playerJoin() invoked\n"; + Log::info("[KartSelectionScreen]", "playerJoin() invoked"); if (!m_multiplayer && !firstPlayer) return false; assert (g_dispatcher != NULL); @@ -1070,21 +1070,21 @@ bool KartSelectionScreen::playerJoin(InputDevice* device, bool firstPlayer) DynamicRibbonWidget* w = getWidget("karts"); if (w == NULL) { - std::cerr << "[KartSelectionScreen] playerJoin(): Called outside of " - "kart selection screen.\n"; + Log::error("[KartSelectionScreen]", "playerJoin(): Called outside of " + "kart selection screen."); return false; } else if (device == NULL) { - std::cerr << "[KartSelectionScreen] playerJoin(): Received null " - "device pointer\n"; + Log::error("[KartSelectionScreen]", "playerJoin(): Received null " + "device pointer"); return false; } if (StateManager::get()->activePlayerCount() >= MAX_PLAYER_COUNT) { - std::cerr << "[KartSelectionScreen] Maximum number of players " - "reached\n"; + Log::error("[KartSelectionScreen]", "Maximum number of players " + "reached"); sfx_manager->quickSound( "anvil" ); return false; } @@ -1214,10 +1214,10 @@ bool KartSelectionScreen::playerQuit(StateManager::ActivePlayer* player) DynamicRibbonWidget* w = getWidget("karts"); if (w == NULL) { - std::cerr << "[KartSelectionScreen] ERROR: playerQuit() called " + Log::error("[KartSelectionScreen]", "ERROR: playerQuit() called " "outside of kart selection screen, " - << "or the XML file for this screen was changed without " - "adapting the code accordingly\n"; + "or the XML file for this screen was changed without " + "adapting the code accordingly"); return false; } @@ -1249,12 +1249,12 @@ bool KartSelectionScreen::playerQuit(StateManager::ActivePlayer* player) } if (playerID == -1) { - std::cerr << "[KartSelectionScreen] WARNING: playerQuit cannot find " - "passed player\n"; + Log::warn("[KartSelectionScreen]", " playerQuit cannot find " + "passed player"); return false; } if(UserConfigParams::logGUI()) - std::cout << "playerQuit( " << playerID << " )\n"; + Log::info("[KartSelectionScreen]", "playerQuit(%s)",playerID); // Just a cheap way to check if there is any discrepancy // between m_kart_widgets and the active player array @@ -1291,8 +1291,8 @@ bool KartSelectionScreen::playerQuit(StateManager::ActivePlayer* player) // update selections - const int amount = m_kart_widgets.size(); - for (int n=0; n 0) @@ -1303,9 +1303,8 @@ bool KartSelectionScreen::playerQuit(StateManager::ActivePlayer* player) const bool success = w->setSelection(selectedKart, n, true); if (!success) { - std::cerr << "[KartSelectionScreen] Failed to select kart " - << selectedKart << " for player " << n - << ", what's going on??\n"; + Log::warn("[KartSelectionScreen]", "Failed to select kart %s" + " for player %u, what's going on??", selectedKart.c_str(),n); } } } @@ -1313,7 +1312,7 @@ bool KartSelectionScreen::playerQuit(StateManager::ActivePlayer* player) // check if all players are ready bool allPlayersReady = true; - for (int n=0; nquickSound( "anvil" ); return; @@ -1571,8 +1570,8 @@ void KartSelectionScreen::eventCallback(Widget* widget, // if we get here, it means one player "lost" his kart in // the tab switch if (UserConfigParams::logGUI()) - std::cout << "[KartSelectionScreen] Player " << n - << " lost their selection when switching tabs!!!\n"; + Log::info("[KartSelectionScreen]", "Player %u" + " lost their selection when switching tabs!!!",n); // Select a random kart in this case const int count = w->getItems().size(); @@ -1589,14 +1588,13 @@ void KartSelectionScreen::eventCallback(Widget* widget, w->setSelection( randomID, n, n != PLAYER_ID_GAME_MASTER ); if (!success) - std::cerr << "[KartSelectionScreen] WARNING: " - "setting kart of player " << n - << " failed :(\n"; + Log::warn("[KartSelectionScreen]", + "setting kart of player %u failed"); } else { - std::cerr << "[KartSelectionScreen] WARNING : 0 items " - "in the ribbon\n"; + Log::warn("[KartSelectionScreen]", " 0 items " + "in the ribbon"); } } } @@ -1689,14 +1687,14 @@ void KartSelectionScreen::allPlayersDone() // ---- Print selection (for debugging purposes) if(UserConfigParams::logGUI()) { - std::cout << "[KartSelectionScreen] " << players.size() - << " players :\n"; + Log::info("[KartSelectionScreen]", "players : %d",players.size()); + for (unsigned int n=0; ngetName().c_str()).c_str() - << " on " << players[n].getDevice()->m_name << std::endl; + Log::info("[KartSelectionScreen]", " Player %u is %s on %s",n, + core::stringc( + players[n].getConstProfile()->getName().c_str()).c_str(), + players[n].getDevice()->m_name.c_str()); } } @@ -1886,10 +1884,10 @@ bool KartSelectionScreen::validateKartChoices() { bool ok = true; - const int amount = m_kart_widgets.size(); + const unsigned int amount = m_kart_widgets.size(); // reset all marks, we'll re-add them next if errors are still there - for (int n=0; nunsetBadge(BAD_BADGE); } @@ -1898,26 +1896,24 @@ bool KartSelectionScreen::validateKartChoices() // players than karts then just allow duplicates DynamicRibbonWidget* w = getWidget("karts"); assert( w != NULL ); - const int availableKartCount = w->getItems().size(); + const unsigned int availableKartCount = w->getItems().size(); if (amount > availableKartCount) return true; // Check everyone for duplicates - for (int n=0; n Setting red badge on player " - << n << std::endl; + Log::info("[KartSelectionScreen]", " --> Setting red badge on player %u", n); // player m is ready, so player n should not choose // this name @@ -1936,8 +1931,7 @@ bool KartSelectionScreen::validateKartChoices() !m_kart_widgets[m].isReady()) { if (UserConfigParams::logGUI()) - std::cout << " --> Setting red badge on player " - << m << std::endl; + Log::info("[KartSelectionScreen]", " --> Setting red badge on player %u",m); // player n is ready, so player m should not // choose this name @@ -2089,8 +2083,8 @@ EventPropagation FocusDispatcher::focused(const int playerID) if (!m_is_initialised) return EVENT_LET; if(UserConfigParams::logGUI()) - std::cout << "[KartSelectionScreen] FocusDispatcher focused by player " - << playerID << std::endl; + Log::info("[KartSelectionScreen]", "FocusDispatcher focused by player %u", + playerID); // since this screen is multiplayer, redirect focus to the right widget const int amount = m_parent->m_kart_widgets.size(); diff --git a/src/states_screens/race_gui_overworld.cpp b/src/states_screens/race_gui_overworld.cpp index 88c85b8d7..f906d612e 100644 --- a/src/states_screens/race_gui_overworld.cpp +++ b/src/states_screens/race_gui_overworld.cpp @@ -486,6 +486,15 @@ void RaceGUIOverworld::drawGlobalMiniMap() gui::ScalableFont* font = GUIEngine::getTitleFont(); font->draw(gp->getName(), pos, video::SColor(255,255,255,255), false, true /* vcenter */, NULL); + + core::rect pos(15, + 20 + GUIEngine::getTitleFontHeight(), + 15 + UserConfigParams::m_width/2, + 20 + 2*GUIEngine::getTitleFontHeight()); + + //just below GP name + font->draw(_("Type: Grand Prix"), pos, video::SColor(255,255,255,255), + false, true /* vcenter */, NULL); } else { diff --git a/src/states_screens/tracks_screen.cpp b/src/states_screens/tracks_screen.cpp index f03e85ce7..ddf293651 100644 --- a/src/states_screens/tracks_screen.cpp +++ b/src/states_screens/tracks_screen.cpp @@ -192,7 +192,7 @@ void TracksScreen::beforeAddingWidget() DynamicRibbonWidget* tracks_widget = this->getWidget("tracks"); assert( tracks_widget != NULL ); - tracks_widget->setItemCountHint( track_manager->getNumberOfTracks() ); + tracks_widget->setItemCountHint( track_manager->getNumberOfTracks()+1 ); } // ----------------------------------------------------------------------------- diff --git a/src/tracks/track.cpp b/src/tracks/track.cpp index 0ee428a24..f5d7a525f 100644 --- a/src/tracks/track.cpp +++ b/src/tracks/track.cpp @@ -151,6 +151,29 @@ Track::~Track() #endif } // ~Track +//----------------------------------------------------------------------------- +/** Returns number of completed challenges */ +unsigned int Track::getNumOfCompletedChallenges() +{ + unsigned int unlocked_challenges = 0; + GameSlot* slot = unlock_manager->getCurrentSlot(); + for (unsigned int i=0; igetChallenge(m_challenges[i].m_challenge_id) + ->isSolvedAtAnyDifficulty()) + { + unlocked_challenges++; + } + } + + return unlocked_challenges; +} // getNumOfCompletedChallenges + //----------------------------------------------------------------------------- /** Removes all cached data structures. This is called before the resolution * is changed. @@ -963,6 +986,7 @@ bool Track::loadMainTrack(const XMLNode &root) } else if (condition == "allchallenges") { +<<<<<<< HEAD unsigned int unlocked_challenges = 0; PlayerProfile *player = PlayerManager::get()->getCurrentPlayer(); for (unsigned int c=0; c>>>>>> upstream/master // allow ONE unsolved challenge : the last one - if (unlocked_challenges < m_challenges.size() - 1) continue; + if (getNumOfCompletedChallenges() < m_challenges.size() - 1) + continue; } else if (condition.size() > 0) { @@ -995,6 +1022,7 @@ bool Track::loadMainTrack(const XMLNode &root) } else if (neg_condition == "allchallenges") { +<<<<<<< HEAD unsigned int unlocked_challenges = 0; PlayerProfile *player = PlayerManager::get()->getCurrentPlayer(); for (unsigned int c=0; c>>>>>> upstream/master // allow ONE unsolved challenge : the last one - if (unlocked_challenges >= m_challenges.size() - 1) continue; + if (getNumOfCompletedChallenges() >= m_challenges.size() - 1) + continue; } else if (neg_condition.size() > 0) { diff --git a/src/tracks/track.hpp b/src/tracks/track.hpp index 6c6c0e91f..a4eb87989 100644 --- a/src/tracks/track.hpp +++ b/src/tracks/track.hpp @@ -206,6 +206,7 @@ private: /** True if this track (textures and track data) should be cached. Used * for the overworld. */ bool m_cache_track; + #ifdef DEBUG /** A list of textures that were cached before the track is loaded. @@ -527,6 +528,9 @@ public: /** Returns the number of modes available for this track. */ unsigned int getNumberOfModes() const { return m_all_modes.size(); } // ------------------------------------------------------------------------ + /** Returns number of completed challenges. */ + unsigned int getNumOfCompletedChallenges(); + // ------------------------------------------------------------------------ /** Returns the name of the i-th. mode. */ const std::string &getModeName(unsigned int i) const { return m_all_modes[i].m_name; } diff --git a/src/tracks/track_object_presentation.cpp b/src/tracks/track_object_presentation.cpp index 763cae3c7..e697226bc 100644 --- a/src/tracks/track_object_presentation.cpp +++ b/src/tracks/track_object_presentation.cpp @@ -20,6 +20,7 @@ #include "audio/sfx_base.hpp" #include "audio/sfx_buffer.hpp" +#include "challenges/unlock_manager.hpp" #include "graphics/irr_driver.hpp" #include "graphics/material_manager.hpp" #include "graphics/particle_emitter.hpp" @@ -674,6 +675,21 @@ void TrackObjectPresentationActionTrigger::onTriggerItemApproached(Item* who) new RacePausedDialog(0.8f, 0.6f); //dynamic_cast(World::getWorld())->scheduleSelectKart(); } + //action trigger near big doors in the overword to notify players that they'll open once they finish all the challenges + else if (m_action == "big_door") + { + m_action_active = false; + + Track* m_track = World::getWorld()->getTrack(); + unsigned int unlocked_challenges = m_track->getNumOfCompletedChallenges(); + std::vector m_challenges = m_track->getChallengeList(); + + // allow ONE unsolved challenge : the last one + if (unlocked_challenges < m_challenges.size() - 1) + { + new TutorialMessageDialog(_("Complete all challenges to unlock the big door!"), true); + } + } else if (m_action == "tutorial_drive") { //if (World::getWorld()->getPhase() == World::RACE_PHASE) diff --git a/src/utils/debug.cpp b/src/utils/debug.cpp index 52e4bb4f9..871c4ae9a 100644 --- a/src/utils/debug.cpp +++ b/src/utils/debug.cpp @@ -167,7 +167,7 @@ bool onEvent(const SEvent &event) { if(cmdID == DEBUG_GRAPHICS_RELOAD_SHADERS) { - Log::info("Debug", "Reloading shaders...\n"); + Log::info("Debug", "Reloading shaders..."); irr_driver->updateShaders(); } else if (cmdID == DEBUG_GRAPHICS_RESET) diff --git a/src/utils/helpers.cpp b/src/utils/helpers.cpp index 76ec6283c..fba721f6f 100644 --- a/src/utils/helpers.cpp +++ b/src/utils/helpers.cpp @@ -26,39 +26,6 @@ float clampf(float in, float low, float high) { return in > high ? high : in < low ? low : in; } -float smootherstep(float e0, float e1, float x) { - x = clampf((x - e0)/(e1 - e0), 0, 1); - - return x*x*x*(x*(x*6 - 15) + 10); -} - -void savetex(ITexture *tex, const char *name) { - - using namespace core; - using namespace video; - - IVideoDriver * const drv = irr_driver->getVideoDriver(); - - IImage * const tmp = drv->createImage(tex, position2di(0,0), tex->getSize()); - - if (!name) - { - stringc namec = tex->getName().getPath(); - namec += ".png"; - drv->writeImageToFile(tmp, namec.c_str()); - } - else - { - drv->writeImageToFile(tmp, name); - } - - tmp->drop(); -} - -float mix(float x, float y, float a) { - return x * (1 - a) + y * a; -} - unsigned ispow(const unsigned in) { if (in < 2) return 0; @@ -66,19 +33,6 @@ unsigned ispow(const unsigned in) { return !(in & (in - 1)); } -unsigned npow(unsigned in) { - - if (ispow(in)) return in; - - in |= in >> 1; - in |= in >> 2; - in |= in >> 4; - in |= in >> 8; - in |= in >> 16; - - return in + 1; -} - // Simple 8-bit hash u8 shash8(const u8 * const data, const u16 size) { diff --git a/src/utils/helpers.hpp b/src/utils/helpers.hpp index c13028666..bdb10a1e9 100644 --- a/src/utils/helpers.hpp +++ b/src/utils/helpers.hpp @@ -23,15 +23,9 @@ using irr::video::ITexture; -float smootherstep(float, float, float); float clampf(float, float, float); -float mix(float x, float y, float a); - unsigned ispow(const unsigned in); -unsigned npow(unsigned in); - -void savetex(ITexture *tex, const char *name = NULL); float noise2d(float v1, float v2 = 0); diff --git a/src/utils/string_utils.hpp b/src/utils/string_utils.hpp index ee46848ea..084140589 100644 --- a/src/utils/string_utils.hpp +++ b/src/utils/string_utils.hpp @@ -72,7 +72,7 @@ namespace StringUtils // ------------------------------------------------------------------------ /** Specialisiation for bools to return 'true' or 'false'*/ - inline std::string toString(bool &b) + inline std::string toString(const bool& b) { return (b ? "true" : "false"); } // toString(bool)