Subversion Repository Public Repository

Divide-Framework

This repository has no backups
This repository's network speed is throttled to 100KB/sec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#include "Headers/Water.h"

#include "Core/Headers/ParamHandler.h"
#include "Core/Math/Headers/Transform.h"
#include "Managers/Headers/SceneManager.h"
#include "Hardware/Video/Headers/RenderStateBlock.h"
#include "Geometry/Material/Headers/Material.h"


WaterPlane::WaterPlane() : SceneNode(TYPE_WATER), Reflector(TYPE_WATER_SURFACE,vec2<U16>(1024,1024)),
                           _plane(nullptr),  _planeTransform(nullptr), _node(nullptr), _planeSGN(nullptr), _waterLevel(0), _waterDepth(0), _refractionPlaneID(ClipPlaneIndex_PLACEHOLDER), 
                           _reflectionPlaneID(ClipPlaneIndex_PLACEHOLDER), _reflectionRendering(false), _refractionRendering(false), _refractionTexture(nullptr), _dirty(true), _cameraUnderWater(false),
                           _cameraMgr(Application::getInstance().getKernel()->getCameraMgr())
{
    //Set water plane to be single-sided
    P32 quadMask;
    quadMask.i = 0;
    quadMask.b.b0 = true;
    ResourceDescriptor waterPlane("waterPlane");
    waterPlane.setFlag(true); //No default material
    waterPlane.setBoolMask(quadMask);
    _plane = CreateResource<Quad3D>(waterPlane);
    
}

void WaterPlane::postLoad(SceneGraphNode* const sgn){
    _node = sgn;

    ShaderProgram* shader = getMaterial()->getShaderInfo(FINAL_STAGE).getProgram();

    _farPlane = 2.0f * GET_ACTIVE_SCENE()->state().getRenderState().getCameraConst().getZPlanes().y;
    _plane->setCorner(Quad3D::TOP_LEFT,     vec3<F32>(-_farPlane * 1.5f, 0, -_farPlane * 1.5f));
    _plane->setCorner(Quad3D::TOP_RIGHT,    vec3<F32>( _farPlane * 1.5f, 0, -_farPlane * 1.5f));
    _plane->setCorner(Quad3D::BOTTOM_LEFT,  vec3<F32>(-_farPlane * 1.5f, 0,  _farPlane * 1.5f));
    _plane->setCorner(Quad3D::BOTTOM_RIGHT, vec3<F32>( _farPlane * 1.5f, 0,  _farPlane * 1.5f));
    _plane->setNormal(Quad3D::CORNER_ALL, WORLD_Y_AXIS);
    _plane->getSceneNodeRenderState().setDrawState(false);
    _planeSGN = _node->addNode(_plane);
    _planeTransform = _planeSGN->getTransform();
    //The water doesn't cast shadows, doesn't need ambient occlusion and doesn't have real "depth"
    getSceneNodeRenderState().addToDrawExclusionMask(SHADOW_STAGE);

    shader->UniformTexture("texWaterNoiseNM", 0);
    shader->UniformTexture("texWaterReflection", 1);
    shader->UniformTexture("texWaterRefraction", 2);
    shader->UniformTexture("texWaterNoiseDUDV", 3);
    _dirty = true;

    PRINT_FN(Locale::get("REFRACTION_INIT_FB"), _resolution.x, _resolution.y);
    SamplerDescriptor refractionSampler;
    refractionSampler.setWrapMode(TEXTURE_CLAMP_TO_EDGE);
    refractionSampler.toggleMipMaps(false);

    TextureDescriptor refractionDescriptor(TEXTURE_2D, RGBA8, UNSIGNED_BYTE); //Less precision for reflections
    refractionDescriptor.setSampler(refractionSampler);

    _refractionTexture = GFX_DEVICE.newFB();
    _refractionTexture->AddAttachment(refractionDescriptor, TextureDescriptor::Color0);
    _refractionTexture->toggleDepthBuffer(true);
    _refractionTexture->Create(_resolution.x, _resolution.y);

    //getMaterial()->addCustomTexture(_refractionTexture->GetAttachment(TextureDescriptor::Color0), Material::TEXTURE_UNIT1);
    SceneNode::postLoad(sgn);
}

bool WaterPlane::computeBoundingBox(SceneGraphNode* const sgn){
    BoundingBox& bb = _node->getBoundingBox();

    if(bb.isComputed())
        return true;

    _waterLevel = GET_ACTIVE_SCENE()->state().getWaterLevel();
    _waterDepth = GET_ACTIVE_SCENE()->state().getWaterDepth();
    _planeTransform->setPositionY(_waterLevel);
    _planeDirty = true;
    bb.set(vec3<F32>(-_farPlane,_waterLevel - _waterDepth, -_farPlane), vec3<F32>(_farPlane, _waterLevel, _farPlane));
    _planeSGN->getBoundingBox().Add(bb);
    PRINT_FN(Locale::get("WATER_CREATE_DETAILS_1"), bb.getMax().y)
    PRINT_FN(Locale::get("WATER_CREATE_DETAILS_2"), bb.getMin().y);
    _dirty = true;
    return SceneNode::computeBoundingBox(sgn);
}

bool WaterPlane::unload(){
    bool state = false;
    state = SceneNode::unload();
    return state;
}

void WaterPlane::setParams(F32 shininess, const vec2<F32>& noiseTile, const vec2<F32>& noiseFactor, F32 transparency){
    ShaderProgram* shader = getMaterial()->getShaderInfo(FINAL_STAGE).getProgram();
    shader->Uniform("_waterShininess",   shininess   );
    shader->Uniform("_noiseFactor",      noiseFactor );
    shader->Uniform("_noiseTile",        noiseTile   );
    shader->Uniform("_transparencyBias", transparency);
}

void WaterPlane::sceneUpdate(const U64 deltaTime, SceneGraphNode* const sgn, SceneState& sceneState){
    _cameraUnderWater = isPointUnderWater(sceneState.getRenderState().getCamera().getEye());
    if(_dirty){
       _node->getBoundingSphere().fromBoundingBox(sgn->getBoundingBoxConst());
       _dirty = false;
    }
}

bool WaterPlane::onDraw(SceneGraphNode* const sgn, const RenderStage& currentStage){

    return true;
}

void WaterPlane::postDraw(SceneGraphNode* const sgn, const RenderStage& currentStage){
}

void WaterPlane::render(SceneGraphNode* const sgn, const SceneRenderState& sceneRenderState, const RenderStage& currentRenderStage){
    if(!_plane->onDraw(nullptr, currentRenderStage))
        return;

    bool depthPass = bitCompare(DEPTH_STAGE, currentRenderStage);

    if(!depthPass){
        _reflectedTexture->Bind(1);
        if (!_cameraUnderWater)
            _refractionTexture->Bind(2);
    }

    ShaderProgram* drawShader = getDrawShader(depthPass ? Z_PRE_PASS_STAGE : FINAL_STAGE);
    drawShader->Uniform("underwater", _cameraUnderWater);
    GenericDrawCommand cmd(TRIANGLE_STRIP, 0, 0);
    cmd.setStateHash(getMaterial()->getRenderStateBlock(FINAL_STAGE));
    cmd.setDrawIDs(GFX_DEVICE.getDrawIDs(sgn->getGUID()));
    cmd.setShaderProgram(drawShader);
    GFX_DEVICE.submitRenderCommand(_plane->getGeometryVB(), cmd);
}

bool WaterPlane::getDrawState(const RenderStage& currentStage) {
    // Wait for the Reflector to update
    if(!_createdFB) return false;

    // Make sure we are not drawing our self unless this is desired
    if((currentStage == REFLECTION_STAGE || _reflectionRendering || _refractionRendering) && !_updateSelf)	return false;

    // Else, process normal exclusion
    return SceneNode::getDrawState(currentStage);
}

/// update water refraction
void WaterPlane::updateRefraction(){
   
    if (_cameraUnderWater)
        return;

    // Early out check for render callback
    if(_renderCallback.empty()) return;

    _refractionRendering = true;
    // If we are above water, process the plane's reflection. If we are below, we render the scene normally
    RenderStage prevRenderStage = GFX_DEVICE.setRenderStage(FINAL_STAGE);
    GFX_DEVICE.enableClipPlane(_refractionPlaneID);
    _cameraMgr.getActiveCamera()->renderLookAt();
    // bind the refractive texture
    _refractionTexture->Begin(Framebuffer::defaultPolicy());
        // render to the reflective texture
        _refractionCallback();
    _refractionTexture->End();

    GFX_DEVICE.disableClipPlane(_refractionPlaneID);
    GFX_DEVICE.setRenderStage(prevRenderStage);

    _refractionRendering = false;
}

/// Update water reflections
void WaterPlane::updateReflection(){
   
    // Early out check for render callback
    if (!_renderCallback.empty()){
        //ToDo: this will cause problems later with multiple reflectors. Fix it! -Ionut
        _reflectionRendering = true;
    
        RenderStage prevRenderStage = GFX_DEVICE.setRenderStage(_cameraUnderWater ? FINAL_STAGE : REFLECTION_STAGE);
        GFX_DEVICE.enableClipPlane(_reflectionPlaneID);

        _cameraUnderWater ? _cameraMgr.getActiveCamera()->renderLookAt() : _cameraMgr.getActiveCamera()->renderLookAtReflected(getReflectionPlane());

        _reflectedTexture->Begin(Framebuffer::defaultPolicy());
            _renderCallback(); //< render to the reflective texture
        _reflectedTexture->End();

        GFX_DEVICE.disableClipPlane(_reflectionPlaneID);
        GFX_DEVICE.setRenderStage(prevRenderStage);
    
        _reflectionRendering = false;
    }
    updateRefraction();
}

void WaterPlane::updatePlaneEquation(){
    const Quaternion<F32>& orientation = _planeTransform->getOrientation();
    vec3<F32> reflectionNormal(orientation * WORLD_Y_AXIS);
    reflectionNormal.normalize();
    vec3<F32> refractionNormal(orientation * WORLD_Y_NEG_AXIS);
    refractionNormal.normalize();
    _reflectionPlane.set(reflectionNormal, -_waterLevel);
    _reflectionPlane.active(false);
    _refractionPlane.set(refractionNormal, -_waterLevel);
    _refractionPlane.active(false);
    _reflectionPlaneID = CLIP_PLANE_0;
    _refractionPlaneID = CLIP_PLANE_1;

    GFX_DEVICE.setClipPlane(_reflectionPlaneID, _reflectionPlane);
    GFX_DEVICE.setClipPlane(_refractionPlaneID, _refractionPlane);
    
    _dirty = true;
}

bool WaterPlane::previewReflection(){

    if (_previewReflection) {
        F32 height = _resolution.y * 0.333f;
        _previewReflectionShader->bind();
        _refractionTexture->Bind();
        GFX_DEVICE.renderInViewport(vec4<I32>(_resolution.x  * 0.333f, Application::getInstance().getResolution().y - height, _resolution.x  * 0.666f, height), 
                                    DELEGATE_BIND(&GFXDevice::drawPoints, DELEGATE_REF(GFX_DEVICE), 1, GFX_DEVICE.getDefaultStateBlock(true)));
    }

    return Reflector::previewReflection();
}

Commits for Divide-Framework/trunk/Source Code/Environment/Water/Water.cpp

Diff revisions: vs.
Revision Author Commited Message
286 Diff Diff IonutCava picture IonutCava Fri 18 Jul, 2014 16:32:03 +0000

[Ionut] [[BR]]

    • very buggy commit ** [[BR]]

- New rendering pipeline: [[BR]]
— Bumped OpenGL version to 4.4 [[BR]]
— Command based rendering. GFXDevice dispatches rendering commands to their respective buffers [[BR]]
— State changing is exclusively controlled by the GFXDevice class [[BR]]
— Material properties and transform matrices are stored in shader storage buffers that are updated after culling and uploaded once per RenderPass. Objects use drawIDs to index data in shaders [[BR]]
— Removed all custom matrices and other, per shader, bind data [[BR]]
— Removed per node light data. Light culling and shader buffers will replace the old light management system [[BR]]
— Framebuffers now use the Texture class for attachments [[BR]]
— Sampler objects now work like RenderStateBlocks. GL_API handles them and stores them in a hash indexed map [[BR]]
— Removed “prepareMaterial” calls. Pre-draw material setup is now only limited to texture binding [[BR]]
— Moved immediate mode emulation and primitive rendering from API level to GFXDevice level [[BR]]
— Framebuffer rendering must be completed with a call to end() to ensure proper MSAA resolve (asserts, otherwise) [[BR]]
- Fixed hash code generation for RenderStateBlock (and now, glSamplerObject) using boost::hash_combine [[BR]]
- Temporarily disabled XML caching for materials [[BR]]

284 Diff Diff IonutCava picture IonutCava Tue 01 Jul, 2014 20:54:08 +0000

[Ionut][[BR]]
- Per SGN shader data implementation part 1 / 2 [[BR]]
— Gather node info and transforms into custom struct for visible nodes and store them in a GFXDevice local vector [[BR]]
- Removed “prepareDepthMaterial” and added depthPass flag to “prepareMaterial” [[BR]]

280 Diff Diff IonutCava picture IonutCava Sat 28 Jun, 2014 19:11:37 +0000

[Ionut] [[BR]]
- Improve ClipPlane management (bunch equations into the matrix shader buffer) [[BR]]
- Immediate mode emulation primitives set their own state based on specified hash instead of relying on state functions to be defined [[BR]]
- updateStates() function is now called right before the actual draw call to facilitate future batching work [[BR]]
- added tracked bool values (similar to those in ShaderInfo) to SGN class to fix selection bug. [[BR]]
— will probably create a “stateTracker” class to allow multiple classes to use tracked variables without all of the code duplication [[BR]]

279 Diff Diff IonutCava picture IonutCava Sat 28 Jun, 2014 16:20:46 +0000

[Ionut][[BR]]
- Unified draw command system into GenericDrawCommand [[BR]]
- Fixed double VB creation in Object3D [[BR]]
- Reworked triangle data computation (now Object3D’s responsibility) [[BR]]
- VertexArrays can now render using the primitive type specified in the draw command instead of the fixed type specified at creation [[BR]]
- Optimized terrain shader [[BR]]

274 Diff Diff IonutCava picture IonutCava Fri 13 Jun, 2014 12:56:03 +0000

[Ionut] [[BR]]
- Simplified buffer based rendering (VertexBuffer & GenericVertexData are now exclusively command based) [[BR]]
- Update bone buffer to persistent mapped-SSBO system with double-buffering [[BR]]
- Simplified sky rendering and (finally) reduced the sun’s radius [[BR]]

273 Diff Diff IonutCava picture IonutCava Wed 11 Jun, 2014 20:34:00 +0000

[Ionut] [[BR]]
- Improved batching part2: [[BR]]
— Moved all bone transformation matrices upload from uniform functions in SceneNode to Shader Storage Buffers in AnimationController class with updates controlled by SceneGraphNode’s AnimationComponent [[BR]]
-— No double-buffering or efficient mapping of data yet. Just raw buffer updates [[BR]]
— Replaced all RenderStateBlock* pointers with I64 hash values [[BR]]
-— Will be used later in draw commands as per-shader state hash [[BR]]
— Moved getShaderProgram from Material to Material::ShaderInfo [[BR]]
-— Improved redundant uniform checks [[BR]]
— Improved texture unit changing in case of redundant texture bind case (i.e. skip changing the texture unit) [[BR]]
[[BR]]
- Improved float and double comparison functions using algorithms described in http://randomascii.wordpress.com/2012/02/13/dont-store-that-in-a-float/ [[BR]]
- Added a new utility function, DIVIDE_ASSERT, to more easily bind an assert check with a specific message [[BR]]
- Added missing files from Forward+ renderer’s initial code [[BR]]

270 Diff Diff IonutCava picture IonutCava Thu 05 Jun, 2014 19:08:07 +0000

[Ionut][[BR]]
- SubMeshes now use a single vertex buffer (owned by the parent mesh) with proper offsetting and querying [[BR]]
— Implementation not optimal yet [[BR]]
- Cleaned up VertexBuffer related classes [[BR]]

269 Diff Diff IonutCava picture IonutCava Wed 04 Jun, 2014 12:56:45 +0000

[Ionut] [[BR]]
- All texture objects now properly allocate storage using glTextureStorage*D(w-w/o Multisampled) [[BR]]
- Removed useless “format” element from TextureDescriptor. Format is deduced from the internal format specified (RGBA8 uses RGBA. RG32F uses RG) [[BR]]
- Use GLM only with radians [[BR]]

268 Diff Diff IonutCava picture IonutCava Wed 04 Jun, 2014 10:20:27 +0000

[IonutCava] [[BR]]
- Terrain and vegetation updates: [[BR]]
— Use standard phong lighting model [[BR]]
— Separate grass patches per chunk [[BR]]
— Reduce number of required texture bind points for terrain by adding both textures and normal maps in a single texture array [[BR]]
— Draw terrain with 2 drawcalls (using glMultiDrawElements twice, once for LoD == 0 and once for LoD > 0) [[BR]]
[[BR]]
- Buffer management updates: [[BR]]
— Unified buffer binding system [[BR]]
— Made Uniform buffer objects visible to all classes and moved lightUBO to LightManager, matricesUBO to GFXDevice etc [[BR]]
— Added initial support for Shader Buffer Objects [[BR]]
— Moved viewport management to GFXDevice class [[BR]]
[[BR]]
- Rendering improvements: [[BR]]
— Added Hi-Z occlusion culling to instanceCull shader (using Hi-Z depth buffer constructed in GFXDevice class) [[BR]]
— Resolved issues with shadow maps overriding texture bind locations [[[BR]]
— Improved shader and shader program loading [[BR]]
— Improved material transparency support [[BR]]
— Added buffer lock manager class from “Approaching Zero Driver Overhead in OpenGL (Presented by NVIDIA)” speech at GDC14 [[BR]]

267 k1ngp1n picture k1ngp1n Wed 28 May, 2014 11:08:12 +0000

[Ionut] [[BR]]
- Improved texture handling: [[BR]]
— No more texture unbind (except when clearing the frame state) [[BR]]
— Moved texture bind checking to the GL_API class [[BR]]
- Fixed a crash related to vegetation loading due to compiler optimizations [[BR]]
- removed all “releaseMaterial” functions as they are no longer needed [[BR]]