History: Dof shader in Mogre
Source of version: 5 (current)
Copy to clipboard
The "depth of field" (DOF) is the distance between the nearest and farthest objects in a scene that appear acceptably sharp in an image" [http://en.wikipedia.org/wiki/Depth_of_field|(Wikipedia)]. It is a quite impressive technique. It bases on this [http://www.ogre3d.org/forums/viewtopic.php?t=18074|c++ implementation] and the slightly [http://www.ogre3d.org/forums/viewtopic.php?f=11&t=18074&sid=83092bc20e4daab5f1d054cd451334ea&start=100#p367396|modified version of Polygon9].
%info% For questions, bug reports, etc. use this [http://www.ogre3d.org/addonforums/viewtopic.php?f=8&t=15042|Mogre forum topic] or if it's shader related [http://www.ogre3d.org/forums/viewtopic.php?t=18074|Ogre forum topic].
{maketoc}
!Showcase and demo
The demo download link (external, c++ version, may not work with dx9)
http://dword.dk/blog/software/ogre/dof/
!Screenshots
{DIV()}{IMG(fileId="2115", thumb="y", rel="box[g]", width="800", align="left", stylebox="border", desc="click for image mode ..... and then ..... click again to switch to the next pictures")}{IMG}{DIV}
{DIV()}{IMG(fileId="2118", thumb="y", rel="box[g]", width="390", align="left", stylebox="border", desc="click to enlarge")}{IMG}{DIV}
{DIV()}{IMG(fileId="2117", thumb="y", rel="box[g]", width="390", align="left", stylebox="border", desc="click to enlarge")}{IMG}{DIV}
%clear%
!Implementation
First copy and paste the code below in two code files (you could create an empty code files in VS). There is a VB.Net and a C# version.
The "DepthOfFieldEffect.vb" or "DepthOfFieldEffect.cs" file:
{VERSIONS(nav="y",default="C#")}
{CODE(wrap="1", colors="c#")}
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using Mogre;
public class DepthOfFieldEffect : RenderQueue.RenderableListener
{
// Inherits CompositorInstance.Listener, RenderTargetListener, RenderQueue.RenderableListener
private RenderTargetListener RenderTargetListener;
private CompositorInstance.Listener Listener;
private RenderQueue.RenderableListener RenderableListenerBackup;
private uint mWidth;
private uint mHeight;
private Viewport mViewPort;
private Camera mCamera;
private Viewport mDepthViewport;
private RenderTexture mDepthTarget;
private TexturePtr mDepthTexture;
private MaterialPtr mDepthMaterial;
private Technique mDepthTechnique;
private CompositorInstance mCompositor;
private float mNearDepth;
private float mFocalDepth;
private float mFarDepth;
private float mFarBlurCutoff;
private const int BLUR_DIVISOR = 4;
public DepthOfFieldEffect(Viewport Viewport, Camera Camera)
{
mViewPort = Viewport;
mCamera = Camera;
mNearDepth = 10.0;
mFocalDepth = 100.0;
mFarDepth = 190.0;
mFarBlurCutoff = 1.0;
mWidth = Convert.ToUInt32(Viewport.ActualWidth());
mHeight = Convert.ToUInt32(Viewport.ActualHeight());
mCompositor = null;
mDepthTechnique = null;
mDepthTarget = null;
mDepthViewport = null;
mDepthTexture = null;
mDepthMaterial = null;
createDepthRenderTexture();
addCompositor();
}
public void Destroy()
{
removeCompositor();
destroyDepthRenderTexture();
}
//C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
//ORIGINAL LINE: Single getNearDepth() const
public float getNearDepth()
{
return mNearDepth;
}
//C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
//ORIGINAL LINE: Single getFocalDepth() const
public float getFocalDepth()
{
return mFocalDepth;
}
//C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
//ORIGINAL LINE: Single getFarDepth() const
public float getFarDepth()
{
return mFarDepth;
}
public void setFocalDepths(float nearDepth, float focalDepth, float farDepth)
{
mNearDepth = nearDepth;
mFocalDepth = focalDepth;
mFarDepth = farDepth;
}
//C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
//ORIGINAL LINE: Single getFarBlurCutoff() const
public float getFarBlurCutoff()
{
return mFarBlurCutoff;
}
public void setFarBlurCutoff(float cutoff)
{
mFarBlurCutoff = cutoff;
}
//C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
//ORIGINAL LINE: Boolean getEnabled() const
public bool getEnabled()
{
return mCompositor.Enabled();
}
public void setEnabled(bool value)
{
mCompositor.Enabled = value;
}
// Implementation of Ogre::CompositorInstance::Listener
private void notifyMaterialSetup(UInt32 passId, MaterialPtr material)
{
switch ((PassId)passId) {
case DepthOfFieldEffect.PassId.BlurPass:
//float pixelSize[2] = {
// 1.0f / (mViewport->getActualWidth() / BLUR_DIVISOR),
// 1.0f / (mViewport->getActualHeight() / BLUR_DIVISOR)};
// Adjust fragment program parameters
Vector3 ps = new Vector3(1f / (mWidth / BLUR_DIVISOR), 1f / (mHeight / BLUR_DIVISOR), 1f);
float[] pixelSize = {
ps.x,
ps.y,
ps.z
};
GpuProgramParametersSharedPtr fragParams = material.GetBestTechnique().GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters();
if ((((fragParams != null))) && (!fragParams._findNamedConstantDefinition("pixelSize").IsNull)) {
fragParams.SetNamedConstant("pixelSize", ps);
}
break; // TODO: might not be correct. Was : Exit Select
break;
case DepthOfFieldEffect.PassId.OutputPass:
float[] pixelSizeScene = {
1f / mWidth,
1f / mHeight,
0
};
Vector3 pixelSizeSceneV = new Vector3(pixelSizeScene[0], pixelSizeScene[1], pixelSizeScene[2]);
float[] pixelSizeBlur = {
1f / (mWidth / BLUR_DIVISOR),
1f / (mHeight / BLUR_DIVISOR),
0
};
Vector3 pixelSizeBlurV = new Vector3(pixelSizeBlur[0], pixelSizeBlur[1], pixelSizeBlur[2]);
// Adjust fragment program parameters
GpuProgramParametersSharedPtr fragParams = material.GetBestTechnique().GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters();
if ((((fragParams != null))) && (!fragParams._findNamedConstantDefinition("pixelSizeScene").IsNull)) {
fragParams.SetNamedConstant("pixelSizeScene", pixelSizeSceneV);
}
if ((((fragParams != null))) && (!fragParams._findNamedConstantDefinition("pixelSizeBlur").IsNull)) {
fragParams.SetNamedConstant("pixelSizeBlur", pixelSizeBlurV);
}
break; // TODO: might not be correct. Was : Exit Select
break;
}
}
// Implementation of Ogre::RenderTargetListener
private void preViewportUpdate(RenderTargetViewportEvent_NativePtr evt)
{
float[] dofParams = {
mNearDepth,
mFocalDepth,
mFarDepth,
mFarBlurCutoff
};
Vector4 dofParamsM = new Vector4(dofParams[0], dofParams[1], dofParams[2], dofParams[3]);
// Adjust fragment program parameters for depth pass
GpuProgramParametersSharedPtr fragParams = mDepthTechnique.GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters();
if ((((fragParams != null))) && !(fragParams._findNamedConstantDefinition("dofParams").IsNull)) {
fragParams.SetNamedConstant("dofParams", dofParamsM);
}
// Add 'this' as a RenderableListener to replace the technique for all renderables
RenderQueue queue = evt.source.Camera().SceneManager().RenderQueue();
queue.SetRenderableListener(this);
}
private void postViewportUpdate(RenderTargetViewportEvent_NativePtr evt)
{
// Reset the RenderableListener
RenderQueue queue = evt.source.Camera.SceneManager().RenderQueue();
queue.SetRenderableListener(null);
}
// Implementation of Ogre::RenderQueue::RenderableListener
public override bool RenderableQueued(global::Mogre.IRenderable rend, byte groupID, ushort priority, ref global::Mogre.Technique ppTech, global::Mogre.RenderQueue pQueue)
{
// Replace the technique of all renderables
ppTech = mDepthTechnique;
return true;
}
private enum PassId : uint
{
BlurPass = 666,
OutputPass = 667
}
private void createDepthRenderTexture()
{
// Create the depth render texture
mDepthTexture = TextureManager.Singleton().CreateManual("DoF_Depth", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, TextureType.TEX_TYPE_2D, mWidth, mHeight, 0, PixelFormat.PF_L8, TextureUsage.TU_RENDERTARGET);
// Get its render target and add a viewport to it
mDepthTarget = mDepthTexture.GetBuffer().GetRenderTarget();
mDepthViewport = mDepthTarget.AddViewport(mCamera);
// Register 'this' as a render target listener
mDepthTarget.PreViewportUpdate += preViewportUpdate;
mDepthTarget.PostViewportUpdate += postViewportUpdate;
// Get the technique to use when rendering the depth render texture
mDepthMaterial = MaterialManager.Singleton().GetByName("DoF_Depth");
mDepthMaterial.Load();
// needs to be loaded manually
mDepthTechnique = mDepthMaterial.GetBestTechnique();
// Create a custom render queue invocation sequence for the depth render texture
RenderQueueInvocationSequence invocationSequence = Root.Singleton().CreateRenderQueueInvocationSequence("DoF_Depth");
// Add a render queue invocation to the sequence, and disable shadows for it
RenderQueueInvocation invocation = invocationSequence.Add(Convert.ToByte(RenderQueueGroupID.RENDER_QUEUE_MAIN), "main");
invocation.SuppressShadows = true;
// Set the render queue invocation sequence for the depth render texture viewport
mDepthViewport.RenderQueueInvocationSequenceName = "DoF_Depth";
//re-set texture "DoF_Depth"
MaterialPtr p = MaterialManager.Singleton().GetByName("DoF_DepthOfField");
p.Load();
p.GetBestTechnique().GetPass(Convert.ToUInt16(0)).GetTextureUnitState("depth").SetTextureName("DoF_Depth");
p.Unload();
}
private void destroyDepthRenderTexture()
{
mDepthViewport.RenderQueueInvocationSequenceName = "";
Root.Singleton().DestroyRenderQueueInvocationSequence("DoF_Depth");
mDepthMaterial.Unload();
mDepthTarget.RemoveAllListeners();
mDepthTarget.RemoveAllViewports();
//TextureManager::getSingleton().unload("DoF_Depth");
TextureManager.Singleton().Remove("DoF_Depth");
}
// void createCompositor();
// void destroyCompositor();
private void addCompositor()
{
mCompositor = CompositorManager.Singleton().AddCompositor(mViewPort, "DoF_Compositor_test");
mCompositor.NotifyMaterialSetup += this.notifyMaterialSetup;
mCompositor.Enabled = true;
}
private void removeCompositor()
{
mCompositor.Enabled = false;
mCompositor.NotifyMaterialSetup -= this.notifyMaterialSetup;
CompositorManager.Singleton().RemoveCompositor(mViewPort, "DoF_Compositor_test");
}
}
public class DOFManager
{
private Camera mCamera;
private RenderWindow mWindow;
private SceneManager mSceneManager;
private float cooldown = 0.25;
public delegate float RequestFocalDistance();
public RequestFocalDistance DelegateRequestFocalDistance { get; set; }
/////////////////////////////////////////////////////////////////////////////////////
public DOFManager(Viewport Viewport, Camera Camera, RenderWindow RenderWindow, SceneManager SceneManager)
{
mCamera = Camera;
mWindow = RenderWindow;
mSceneManager = SceneManager;
mFocusMode = FocusMode.Auto;
mAutoSpeed = 999;
mAutoTime = cooldown;
targetFocalDistance = 5;
mDepthOfFieldEffect = new DepthOfFieldEffect(Viewport, Camera);
mLens = new Lens(Camera.FOVy, 1);
mLens.setFocalDistance(5);
//mLens->setFStop(10);
// mDepthOfFieldEffect->setEnabled(false);
Root.Singleton.FrameStarted += frameStarted;
// MaterialPtr material = MaterialManager::getSingleton().getByName("DoF_DepthDebug");
// material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName("DoF_Depth");
// Overlay* overlay = OverlayManager::getSingleton().getByName("DoF_DepthDebugOverlay");
// overlay->show();
}
public void Dispose()
{
cleanup();
}
public void setEnabled(bool enabled)
{
mDepthOfFieldEffect.setEnabled(enabled);
//
// // crashes for some reason
// if(enabled && !mDepthOfFieldEffect->getEnabled())
// {
// // turn on
// mDepthOfFieldEffect->setEnabled(true);
// mRoot->addFrameListener(this);
// } else if(!enabled && mDepthOfFieldEffect->getEnabled())
// {
// // turn off
// mDepthOfFieldEffect->setEnabled(false);
// mRoot->removeFrameListener(this);
// }
//
}
public bool getEnabled()
{
return mDepthOfFieldEffect.getEnabled();
}
// controls
public void setFocusMode(FocusMode mode)
{
mFocusMode = (FocusMode)mode;
}
public void setAutoSpeed(float f)
{
mAutoSpeed = f;
}
public void zoomView(float delta)
{
float fieldOfView = mLens.getFieldOfView().ValueRadians();
fieldOfView += delta;
fieldOfView = Convert.ToSingle(System.Math.Max(0.1, System.Math.Min(fieldOfView, 2.0)));
mLens.setFieldOfView(new Radian(fieldOfView));
mCamera.FOVy = (new Radian(fieldOfView));
}
public void Aperture(float delta)
{
if (mFocusMode == FocusMode.Pinhole) {
return;
}
float fStop = mLens.getFStop();
fStop += delta;
fStop = Convert.ToSingle(System.Math.Max(0.5, System.Math.Min(fStop, 12.0)));
mLens.setFStop(fStop);
}
public void moveFocus(float delta)
{
mLens.setFocalDistance(mLens.getFocalDistance() + delta);
}
public void setZoom(float f)
{
float fieldOfView = new Degree(f).ValueRadians();
fieldOfView = Convert.ToSingle(System.Math.Max(0.1, System.Math.Min(fieldOfView, 2.0)));
mLens.setFieldOfView(new Radian(fieldOfView));
mCamera.FOVy = new Radian(fieldOfView);
}
public void setAperture(float f)
{
if (mFocusMode == FocusMode.Pinhole) {
return;
}
float fStop = f;
fStop = Convert.ToSingle(System.Math.Max(0.5, System.Math.Min(fStop, 12.0)));
mLens.setFStop(fStop);
}
public void setFocus(float f)
{
mLens.setFocalDistance(f);
}
//C++ TO VB CONVERTER TODO TASK: The implementation of the following method could not be found:
// virtual Function frameStarted(ByVal evt As Ogre::FrameEvent) As Boolean
protected void cleanup()
{
Root.Singleton.FrameStarted -= frameStarted;
mLens.Dispose();
mLens = null;
mDepthOfFieldEffect.Destroy();
mDepthOfFieldEffect = null;
}
protected DepthOfFieldEffect mDepthOfFieldEffect;
protected Lens mLens;
public enum FocusMode
{
Auto,
Manual,
Pinhole
}
protected FocusMode mFocusMode;
protected float mAutoSpeed;
protected float mAutoTime;
protected float targetFocalDistance = new float();
private class Result
{
public Vector3 Position { get; set; }
public Entity Entity { get; set; }
public float Distance { get; set; }
}
private Result RaycastFromCamera(RenderWindow window, Camera camera, Vector2 point, SceneManager SceneManager, UInt32 queryMask)
{
Result functionReturnValue = null;
float tx = (point.x / Convert.ToSingle(window.Width));
float ty = (point.y / Convert.ToSingle(window.Height));
Ray ray = camera.GetCameraToViewportRay(tx, ty);
RaySceneQuery raySceneQuery = SceneManager.CreateRayQuery(ray, queryMask);
raySceneQuery.SetSortByDistance(true);
raySceneQuery.Execute();
object Results = raySceneQuery.GetLastResults;
if (Results == null || Results.IsEmpty) {
SceneManager.DestroyQuery(raySceneQuery);
raySceneQuery.Dispose();
return null;
} else {
for (int i = 0; i <= Results.Count - 1; i++) {
object obj = Results.Item(i);
if (obj.movable != null && obj.movable is Entity) {
functionReturnValue = new Result {
Distance = obj.distance,
Entity = (Entity)obj.movable,
Position = ray.GetPoint(obj.distance)
};
SceneManager.DestroyQuery(raySceneQuery);
raySceneQuery.Dispose();
return functionReturnValue;
}
}
SceneManager.DestroyQuery(raySceneQuery);
raySceneQuery.Dispose();
return null;
}
return functionReturnValue;
}
public bool frameStarted(FrameEvent evt)
{
Camera camera = mCamera;
// Focusing
if (this.getEnabled() == false)
return true;
switch (mFocusMode) {
case FocusMode.Auto:
// TODO: Replace with accurate ray/triangle collision detection
float currentFocalDistance = mLens.getFocalDistance();
// TODO: Continous AF / triggered
mAutoTime -= evt.timeSinceLastFrame;
if (mAutoTime <= 0f) {
mAutoTime = cooldown;
targetFocalDistance = currentFocalDistance;
//' Ryan Booker's (eyevee99) ray scene query auto focus
//Dim focusRay As New Ray()
//focusRay.Origin = (camera.DerivedPosition())
//focusRay.Direction = (camera.DerivedDirection())
//Dim v As New Vector3()
//Dim vn As New Vector3()
//Dim e As Entity
//Dim d As Single
if (DelegateRequestFocalDistance != null) {
targetFocalDistance = DelegateRequestFocalDistance.Invoke();
} else {
object r = RaycastFromCamera(mWindow, mCamera, new Vector2(Convert.ToSingle(mWindow.Width / 2), Convert.ToSingle(mWindow.Height / 2)), mSceneManager, 1 << 2);
if (r != null) {
targetFocalDistance = r.Distance;
}
}
}
// Slowly adjust the focal distance (emulate auto focus motor)
if (currentFocalDistance < targetFocalDistance) {
mLens.setFocalDistance(System.Math.Min(currentFocalDistance + mAutoSpeed * evt.timeSinceLastFrame, targetFocalDistance));
} else if (currentFocalDistance > targetFocalDistance) {
mLens.setFocalDistance(System.Math.Max(currentFocalDistance - mAutoSpeed * evt.timeSinceLastFrame, targetFocalDistance));
}
break;
case FocusMode.Manual:
break;
//we set the values elsewhere
}
// Update Depth of Field effect
if (mFocusMode != FocusMode.Pinhole) {
mDepthOfFieldEffect.setEnabled(true);
// Calculate and set depth of field using lens
float nearDepth = 0;
float focalDepth = 0;
float farDepth = 0;
mLens.recalculateDepthOfField(nearDepth, focalDepth, farDepth);
mDepthOfFieldEffect.setFocalDepths(nearDepth, focalDepth, farDepth);
} else {
mDepthOfFieldEffect.setEnabled(false);
}
return true;
}
}
{CODE}
---(VB.NET)---
{CODE(wrap="1", colors="vbnet")}
Option Strict On
Imports Mogre
Public Class DepthOfFieldEffect
Inherits RenderQueue.RenderableListener
' Inherits CompositorInstance.Listener, RenderTargetListener, RenderQueue.RenderableListener
Private RenderTargetListener As RenderTargetListener
Private Listener As CompositorInstance.Listener
Private RenderableListenerBackup As RenderQueue.RenderableListener
Private mWidth As UInteger
Private mHeight As UInteger
Private mViewPort As Viewport
Private mCamera As Camera
Private mDepthViewport As Viewport
Private mDepthTarget As RenderTexture
Private mDepthTexture As TexturePtr
Private mDepthMaterial As MaterialPtr
Private mDepthTechnique As Technique
Private mCompositor As CompositorInstance
Private mNearDepth As Single
Private mFocalDepth As Single
Private mFarDepth As Single
Private mFarBlurCutoff As Single
Private Const BLUR_DIVISOR As Integer = 4
Public Sub New(ByVal Viewport As Viewport, ByVal Camera As Camera)
mViewPort = Viewport
mCamera = Camera
mNearDepth = 10.0
mFocalDepth = 100.0
mFarDepth = 190.0
mFarBlurCutoff = 1.0
mWidth = CUInt(Viewport.ActualWidth())
mHeight = CUInt(Viewport.ActualHeight())
mCompositor = Nothing
mDepthTechnique = Nothing
mDepthTarget = Nothing
mDepthViewport = Nothing
mDepthTexture = Nothing
mDepthMaterial = Nothing
createDepthRenderTexture()
addCompositor()
End Sub
Public Sub Destroy()
removeCompositor()
destroyDepthRenderTexture()
End Sub
'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
'ORIGINAL LINE: Single getNearDepth() const
Public Function getNearDepth() As Single
Return mNearDepth
End Function
'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
'ORIGINAL LINE: Single getFocalDepth() const
Public Function getFocalDepth() As Single
Return mFocalDepth
End Function
'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
'ORIGINAL LINE: Single getFarDepth() const
Public Function getFarDepth() As Single
Return mFarDepth
End Function
Public Sub setFocalDepths(ByVal nearDepth As Single, ByVal focalDepth As Single, ByVal farDepth As Single)
mNearDepth = nearDepth
mFocalDepth = focalDepth
mFarDepth = farDepth
End Sub
'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
'ORIGINAL LINE: Single getFarBlurCutoff() const
Public Function getFarBlurCutoff() As Single
Return mFarBlurCutoff
End Function
Public Sub setFarBlurCutoff(ByVal cutoff As Single)
mFarBlurCutoff = cutoff
End Sub
'C++ TO VB CONVERTER WARNING: 'const' methods are not available in VB:
'ORIGINAL LINE: Boolean getEnabled() const
Public Function getEnabled() As Boolean
Return mCompositor.Enabled()
End Function
Public Sub setEnabled(ByVal value As Boolean)
mCompositor.Enabled = value
End Sub
' Implementation of Ogre::CompositorInstance::Listener
Private Sub notifyMaterialSetup(ByVal passId As UInt32, ByVal material As MaterialPtr)
Select Case DirectCast(passId, PassId)
Case DepthOfFieldEffect.PassId.BlurPass
'float pixelSize[2] = {
' 1.0f / (mViewport->getActualWidth() / BLUR_DIVISOR),
' 1.0f / (mViewport->getActualHeight() / BLUR_DIVISOR)};
' Adjust fragment program parameters
Dim ps As New Vector3(1.0F / (mWidth \ BLUR_DIVISOR), 1.0F / (mHeight \ BLUR_DIVISOR), 1.0F)
Dim pixelSize() As Single = {ps.x, ps.y, ps.z}
Dim fragParams As GpuProgramParametersSharedPtr = material.GetBestTechnique().GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters()
If ((Not fragParams Is Nothing)) AndAlso (Not fragParams._findNamedConstantDefinition("pixelSize").IsNull) Then
fragParams.SetNamedConstant("pixelSize", ps)
End If
Exit Select
Case DepthOfFieldEffect.PassId.OutputPass
Dim pixelSizeScene() As Single = {1.0F / mWidth, 1.0F / mHeight, 0}
Dim pixelSizeSceneV As New Vector3(pixelSizeScene(0), pixelSizeScene(1), pixelSizeScene(2))
Dim pixelSizeBlur() As Single = {1.0F / (mWidth \ BLUR_DIVISOR), 1.0F / (mHeight \ BLUR_DIVISOR), 0}
Dim pixelSizeBlurV As New Vector3(pixelSizeBlur(0), pixelSizeBlur(1), pixelSizeBlur(2))
' Adjust fragment program parameters
Dim fragParams As GpuProgramParametersSharedPtr = material.GetBestTechnique().GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters()
If ((Not fragParams Is Nothing)) AndAlso (Not fragParams._findNamedConstantDefinition("pixelSizeScene").IsNull) Then
fragParams.SetNamedConstant("pixelSizeScene", pixelSizeSceneV)
End If
If ((Not fragParams Is Nothing)) AndAlso (Not fragParams._findNamedConstantDefinition("pixelSizeBlur").IsNull) Then
fragParams.SetNamedConstant("pixelSizeBlur", pixelSizeBlurV)
End If
Exit Select
End Select
End Sub
' Implementation of Ogre::RenderTargetListener
Private Sub preViewportUpdate(ByVal evt As RenderTargetViewportEvent_NativePtr)
Dim dofParams() As Single = {mNearDepth, mFocalDepth, mFarDepth, mFarBlurCutoff}
Dim dofParamsM As New Vector4(dofParams(0), dofParams(1), dofParams(2), dofParams(3))
' Adjust fragment program parameters for depth pass
Dim fragParams As GpuProgramParametersSharedPtr = mDepthTechnique.GetPass(Convert.ToUInt16(0)).GetFragmentProgramParameters()
If ((Not fragParams Is Nothing)) AndAlso Not (fragParams._findNamedConstantDefinition("dofParams").IsNull) Then
fragParams.SetNamedConstant("dofParams", dofParamsM)
End If
' Add 'this' as a RenderableListener to replace the technique for all renderables
Dim queue As RenderQueue = evt.source.Camera().SceneManager().RenderQueue()
queue.SetRenderableListener(Me)
End Sub
Private Sub postViewportUpdate(ByVal evt As RenderTargetViewportEvent_NativePtr)
' Reset the RenderableListener
Dim queue As RenderQueue = evt.source.Camera.SceneManager().RenderQueue()
queue.SetRenderableListener(Nothing)
End Sub
' Implementation of Ogre::RenderQueue::RenderableListener
Public Overrides Function RenderableQueued(ByVal rend As Global.Mogre.IRenderable, ByVal groupID As Byte, ByVal priority As UShort, ByRef ppTech As Global.Mogre.Technique, ByVal pQueue As Global.Mogre.RenderQueue) As Boolean
' Replace the technique of all renderables
ppTech = mDepthTechnique
Return True
End Function
Private Enum PassId As UInteger
BlurPass = 666
OutputPass = 667
End Enum
Private Sub createDepthRenderTexture()
' Create the depth render texture
mDepthTexture = TextureManager.Singleton().CreateManual("DoF_Depth", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME, TextureType.TEX_TYPE_2D, mWidth, mHeight, 0, PixelFormat.PF_L8, TextureUsage.TU_RENDERTARGET)
' Get its render target and add a viewport to it
mDepthTarget = mDepthTexture.GetBuffer().GetRenderTarget()
mDepthViewport = mDepthTarget.AddViewport(mCamera)
' Register 'this' as a render target listener
AddHandler mDepthTarget.PreViewportUpdate, AddressOf preViewportUpdate
AddHandler mDepthTarget.PostViewportUpdate, AddressOf postViewportUpdate
' Get the technique to use when rendering the depth render texture
mDepthMaterial = MaterialManager.Singleton().GetByName("DoF_Depth")
mDepthMaterial.Load() ' needs to be loaded manually
mDepthTechnique = mDepthMaterial.GetBestTechnique()
' Create a custom render queue invocation sequence for the depth render texture
Dim invocationSequence As RenderQueueInvocationSequence = Root.Singleton().CreateRenderQueueInvocationSequence("DoF_Depth")
' Add a render queue invocation to the sequence, and disable shadows for it
Dim invocation As RenderQueueInvocation = invocationSequence.Add(CByte(RenderQueueGroupID.RENDER_QUEUE_MAIN), "main")
invocation.SuppressShadows = True
' Set the render queue invocation sequence for the depth render texture viewport
mDepthViewport.RenderQueueInvocationSequenceName = "DoF_Depth"
're-set texture "DoF_Depth"
Dim p As MaterialPtr = MaterialManager.Singleton().GetByName("DoF_DepthOfField")
p.Load()
p.GetBestTechnique().GetPass(Convert.ToUInt16(0)).GetTextureUnitState("depth").SetTextureName("DoF_Depth")
p.Unload()
End Sub
Private Sub destroyDepthRenderTexture()
mDepthViewport.RenderQueueInvocationSequenceName = ""
Root.Singleton().DestroyRenderQueueInvocationSequence("DoF_Depth")
mDepthMaterial.Unload()
mDepthTarget.RemoveAllListeners()
mDepthTarget.RemoveAllViewports()
'TextureManager::getSingleton().unload("DoF_Depth");
TextureManager.Singleton().Remove("DoF_Depth")
End Sub
' void createCompositor();
' void destroyCompositor();
Private Sub addCompositor()
mCompositor = CompositorManager.Singleton().AddCompositor(mViewPort, "DoF_Compositor_test")
AddHandler mCompositor.NotifyMaterialSetup, AddressOf Me.notifyMaterialSetup
mCompositor.Enabled = True
End Sub
Private Sub removeCompositor()
mCompositor.Enabled = False
RemoveHandler mCompositor.NotifyMaterialSetup, AddressOf Me.notifyMaterialSetup
CompositorManager.Singleton().RemoveCompositor(mViewPort, "DoF_Compositor_test")
End Sub
End Class
Public Class DOFManager
Private mCamera As Camera
Private mWindow As RenderWindow
Private mSceneManager As SceneManager
Private cooldown As Single = 0.25
Public Delegate Function RequestFocalDistance() As Single
Public Property DelegateRequestFocalDistance As RequestFocalDistance
'///////////////////////////////////////////////////////////////////////////////////
Public Sub New(ByVal Viewport As Viewport, ByVal Camera As Camera, ByVal RenderWindow As RenderWindow, ByVal SceneManager As SceneManager)
mCamera = Camera
mWindow = RenderWindow
mSceneManager = SceneManager
mFocusMode = FocusMode.Auto
mAutoSpeed = 999
mAutoTime = cooldown
targetFocalDistance = 5
mDepthOfFieldEffect = New DepthOfFieldEffect(Viewport, Camera)
mLens = New Lens(Camera.FOVy, 1)
mLens.setFocalDistance(5)
'mLens->setFStop(10);
' mDepthOfFieldEffect->setEnabled(false);
AddHandler Root.Singleton.FrameStarted, AddressOf frameStarted
' MaterialPtr material = MaterialManager::getSingleton().getByName("DoF_DepthDebug");
' material->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureName("DoF_Depth");
' Overlay* overlay = OverlayManager::getSingleton().getByName("DoF_DepthDebugOverlay");
' overlay->show();
End Sub
Public Sub Dispose()
cleanup()
End Sub
Public Sub setEnabled(ByVal enabled As Boolean)
mDepthOfFieldEffect.setEnabled(enabled)
'
' // crashes for some reason
' if(enabled && !mDepthOfFieldEffect->getEnabled())
' {
' // turn on
' mDepthOfFieldEffect->setEnabled(true);
' mRoot->addFrameListener(this);
' } else if(!enabled && mDepthOfFieldEffect->getEnabled())
' {
' // turn off
' mDepthOfFieldEffect->setEnabled(false);
' mRoot->removeFrameListener(this);
' }
'
End Sub
Public Function getEnabled() As Boolean
Return mDepthOfFieldEffect.getEnabled()
End Function
' controls
Public Sub setFocusMode(ByVal mode As FocusMode)
mFocusMode = CType(mode, FocusMode)
End Sub
Public Sub setAutoSpeed(ByVal f As Single)
mAutoSpeed = f
End Sub
Public Sub zoomView(ByVal delta As Single)
Dim fieldOfView As Single = mLens.getFieldOfView().ValueRadians()
fieldOfView += delta
fieldOfView = CSng(System.Math.Max(0.1, System.Math.Min(fieldOfView, 2.0)))
mLens.setFieldOfView(New Radian(fieldOfView))
mCamera.FOVy = (New Radian(fieldOfView))
End Sub
Public Sub Aperture(ByVal delta As Single)
If mFocusMode = FocusMode.Pinhole Then
Return
End If
Dim fStop As Single = mLens.getFStop()
fStop += delta
fStop = CSng(System.Math.Max(0.5, System.Math.Min(fStop, 12.0)))
mLens.setFStop(fStop)
End Sub
Public Sub moveFocus(ByVal delta As Single)
mLens.setFocalDistance(mLens.getFocalDistance() + delta)
End Sub
Public Sub setZoom(ByVal f As Single)
Dim fieldOfView As Single = New Degree(f).ValueRadians()
fieldOfView = CSng(System.Math.Max(0.1, System.Math.Min(fieldOfView, 2.0)))
mLens.setFieldOfView(New Radian(fieldOfView))
mCamera.FOVy = New Radian(fieldOfView)
End Sub
Public Sub setAperture(ByVal f As Single)
If mFocusMode = FocusMode.Pinhole Then
Return
End If
Dim fStop As Single = f
fStop = CSng(System.Math.Max(0.5, System.Math.Min(fStop, 12.0)))
mLens.setFStop(fStop)
End Sub
Public Sub setFocus(ByVal f As Single)
mLens.setFocalDistance(f)
End Sub
'C++ TO VB CONVERTER TODO TASK: The implementation of the following method could not be found:
' virtual Function frameStarted(ByVal evt As Ogre::FrameEvent) As Boolean
Protected Sub cleanup()
RemoveHandler Root.Singleton.FrameStarted, AddressOf frameStarted
mLens.Dispose()
mLens = Nothing
mDepthOfFieldEffect.Destroy()
mDepthOfFieldEffect = Nothing
End Sub
Protected mDepthOfFieldEffect As DepthOfFieldEffect
Protected mLens As Lens
Public Enum FocusMode
[Auto]
Manual
Pinhole
End Enum
Protected mFocusMode As FocusMode
Protected mAutoSpeed As Single
Protected mAutoTime As Single
Protected targetFocalDistance As New Single()
Private Class Result
Public Property Position As Vector3
Public Property Entity As Entity
Public Property Distance As Single
End Class
Private Function RaycastFromCamera(ByVal window As RenderWindow, ByVal camera As Camera, ByVal point As Vector2, ByVal SceneManager As SceneManager, ByVal queryMask As UInt32) As Result
Dim tx As Single = (point.x / CSng(window.Width))
Dim ty As Single = (point.y / CSng(window.Height))
Dim ray As Ray = camera.GetCameraToViewportRay(tx, ty)
Dim raySceneQuery As RaySceneQuery = SceneManager.CreateRayQuery(ray, queryMask)
raySceneQuery.SetSortByDistance(True)
raySceneQuery.Execute()
Dim Results = raySceneQuery.GetLastResults
If Results Is Nothing OrElse Results.IsEmpty Then
SceneManager.DestroyQuery(raySceneQuery)
raySceneQuery.Dispose()
Return Nothing
Else
For i As Integer = 0 To Results.Count - 1
Dim obj = Results.Item(i)
If obj.movable IsNot Nothing AndAlso TypeOf obj.movable Is Entity Then
RaycastFromCamera = New Result With {.Distance = obj.distance, .Entity = DirectCast(obj.movable, Entity), .Position = ray.GetPoint(obj.distance)}
SceneManager.DestroyQuery(raySceneQuery)
raySceneQuery.Dispose()
Return RaycastFromCamera
End If
Next
SceneManager.DestroyQuery(raySceneQuery)
raySceneQuery.Dispose()
Return Nothing
End If
End Function
Public Function frameStarted(ByVal evt As FrameEvent) As Boolean
Dim camera As Camera = mCamera
' Focusing
If Me.getEnabled = False Then Return True
Select Case mFocusMode
Case FocusMode.Auto
' TODO: Replace with accurate ray/triangle collision detection
Dim currentFocalDistance As Single = mLens.getFocalDistance()
' TODO: Continous AF / triggered
mAutoTime -= evt.timeSinceLastFrame
If mAutoTime <= 0.0F Then
mAutoTime = cooldown
targetFocalDistance = currentFocalDistance
'' Ryan Booker's (eyevee99) ray scene query auto focus
'Dim focusRay As New Ray()
'focusRay.Origin = (camera.DerivedPosition())
'focusRay.Direction = (camera.DerivedDirection())
'Dim v As New Vector3()
'Dim vn As New Vector3()
'Dim e As Entity
'Dim d As Single
If DelegateRequestFocalDistance IsNot Nothing Then
targetFocalDistance = DelegateRequestFocalDistance.Invoke
Else
Dim r = RaycastFromCamera(mWindow, mCamera, New Vector2(CSng(mWindow.Width / 2), CSng(mWindow.Height / 2)), mSceneManager, 1 << 2)
If r IsNot Nothing Then
targetFocalDistance = r.Distance
End If
End If
End If
' Slowly adjust the focal distance (emulate auto focus motor)
If currentFocalDistance < targetFocalDistance Then
mLens.setFocalDistance(System.Math.Min(currentFocalDistance + mAutoSpeed * evt.timeSinceLastFrame, targetFocalDistance))
ElseIf currentFocalDistance > targetFocalDistance Then
mLens.setFocalDistance(System.Math.Max(currentFocalDistance - mAutoSpeed * evt.timeSinceLastFrame, targetFocalDistance))
End If
Case FocusMode.Manual
'we set the values elsewhere
End Select
' Update Depth of Field effect
If mFocusMode <> FocusMode.Pinhole Then
mDepthOfFieldEffect.setEnabled(True)
' Calculate and set depth of field using lens
Dim nearDepth As Single
Dim focalDepth As Single
Dim farDepth As Single
mLens.recalculateDepthOfField(nearDepth, focalDepth, farDepth)
mDepthOfFieldEffect.setFocalDepths(nearDepth, focalDepth, farDepth)
Else
mDepthOfFieldEffect.setEnabled(False)
End If
Return True
End Function
End Class
{CODE}
{VERSIONS}
The "Lens.vb" or "Lens.cs" file:
{VERSIONS(nav="y",default="C#")}
{CODE(wrap="1", colors="c#")}
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using Mogre;
public class Lens
{
// NOTE: All units must be the same, eg mm, cm or m etc
// Primary attributes
// Film stock/sensor size, arbitrarily selected to help mimic the properties of film, eg 35mm, 3.5cm, 0.035m etc
protected float mFrameSize = new float();
// The area within which the depth of field is clear, it's tied to frame size, eg 0.03mm, 0.003cm, 0.0003m etc
protected float mCircleOfConfusion = new float();
// The distance to the object we are focusing on
protected float mFocalDistance = new float();
// Focal length of the lens, this directly effects field of view, we can do anything from wide angle to telephoto as we don't have the limitations of physical lenses. Focal length is the distance from the optical centre of the lens to the film stock/sensor etc
protected float mFocalLength = new float();
// FStop number, ie aperture, changing the aperture of a lens has an effect of depth of field, the narrower the aperture/higher the fstop number, the greater the depth of field/clearer the picture is.
protected float mFStop = new float();
// Secondary attributes
// The hyperfocal length is the point at which far depth of field is infinite, ie if mFocalDistance is >= to this value everythig will be clear to infinity
protected float mHyperfocalLength = new float();
// Field of view of the lens, directly related to focal length
protected Radian mFieldOfView = new Radian();
public void Dispose()
{
}
public float getFrameSize()
{
return mFrameSize;
}
public float getFocalDistance()
{
return mFocalDistance;
}
public float getFocalLength()
{
return mFocalLength;
}
public Radian getFieldOfView()
{
return mFieldOfView;
}
public float getFStop()
{
return mFStop;
}
public float getHyperfocalLength()
{
return mHyperfocalLength;
}
public void recalculateDepthOfField(ref float _nearDepth, ref float _focalDepth, ref float _farDepth)
{
// Set focalDepth to the current focalDistance
_focalDepth = mFocalDistance;
// Recalculate the Hyperfocal length
recalculateHyperfocalLength();
// Calculate the numerator of the optics equations
float numerator = (mFocalDistance * (mHyperfocalLength - mFocalLength));
float nearClear = Convert.ToSingle(numerator / (mHyperfocalLength + mFocalDistance - (2.0 * mFocalLength)));
// Adjust the nearDepth relative to the aperture. This is an approximation.
_nearDepth = System.Math.Min(nearClear - nearClear * mFStop, Convert.ToSingle(0));
if (mFocalDistance < mHyperfocalLength) {
// Calculate the far clear plane
float farClear = numerator / (mHyperfocalLength - mFocalDistance);
// Adjust the farDepth relative to the aperture. This is an approximation.
_farDepth = farClear + farClear * mFStop;
// Far depth of field should be infinite
} else {
_farDepth = Math.POS_INFINITY;
}
}
public Lens(float _focalLength, float _fStop, float _frameSize = 3.5, float _circleOfConfusion = 0.003)
{
init(_focalLength, _fStop, _frameSize, _circleOfConfusion);
}
public Lens(Radian _fieldOfView, float _fStop, float _frameSize = 3.5, float _circleOfConfusion = 0.003)
{
init(_fieldOfView, _fStop, _frameSize, _circleOfConfusion);
}
public void init(float _focalLength, float _fStop, float _frameSize, float _circleOfConfusion)
{
mFocalLength = _focalLength;
mFStop = _fStop;
mFrameSize = _frameSize;
mCircleOfConfusion = _circleOfConfusion;
recalculateFieldOfView();
}
public void init(Radian _fieldOfView, float _fStop, float _frameSize, float _circleOfConfusion)
{
mFieldOfView = _fieldOfView;
mFStop = _fStop;
mFrameSize = _frameSize;
mCircleOfConfusion = _circleOfConfusion;
recalculateFocalLength();
}
public void setFrameSize(float _frameSize)
{
mFrameSize = _frameSize;
recalculateFieldOfView();
}
public void setFocalDistance(float _focalDistance)
{
mFocalDistance = System.Math.Max(_focalDistance, 0f);
}
public void setFocalLength(float _focalLength)
{
mFocalLength = System.Math.Max(_focalLength, 0.3f);
recalculateFieldOfView();
}
public void setFieldOfView(Radian _fieldOfView)
{
Radian n = new Radian(2.8);
if (n < _fieldOfView) {
mFieldOfView = n;
} else {
mFieldOfView = _fieldOfView;
}
recalculateFocalLength();
}
public void setFStop(float _fStop)
{
mFStop = System.Math.Max(_fStop, 0f);
}
private void recalculateHyperfocalLength()
{
mHyperfocalLength = (mFocalLength * mFocalLength) / (mFStop * mCircleOfConfusion) + mFocalLength;
}
private void recalculateFieldOfView()
{
mFieldOfView = 2.0 * Math.Atan(Convert.ToSingle(mFrameSize / (2.0 * mFocalLength)));
}
private void recalculateFocalLength()
{
mFocalLength = Convert.ToSingle((mFrameSize / System.Math.Tan(mFieldOfView.ValueRadians / 2.0)) / 2.0);
}
}
{CODE}
---(VB.NET)---
{CODE(wrap="1", colors="vbnet")}
Option Strict On
Imports Mogre
Public Class Lens
' NOTE: All units must be the same, eg mm, cm or m etc
' Primary attributes
Protected mFrameSize As New single() ' Film stock/sensor size, arbitrarily selected to help mimic the properties of film, eg 35mm, 3.5cm, 0.035m etc
Protected mCircleOfConfusion As New single() ' The area within which the depth of field is clear, it's tied to frame size, eg 0.03mm, 0.003cm, 0.0003m etc
Protected mFocalDistance As New single() ' The distance to the object we are focusing on
Protected mFocalLength As New single() ' Focal length of the lens, this directly effects field of view, we can do anything from wide angle to telephoto as we don't have the limitations of physical lenses. Focal length is the distance from the optical centre of the lens to the film stock/sensor etc
Protected mFStop As New single() ' FStop number, ie aperture, changing the aperture of a lens has an effect of depth of field, the narrower the aperture/higher the fstop number, the greater the depth of field/clearer the picture is.
' Secondary attributes
Protected mHyperfocalLength As New single() ' The hyperfocal length is the point at which far depth of field is infinite, ie if mFocalDistance is >= to this value everythig will be clear to infinity
Protected mFieldOfView As New Radian() ' Field of view of the lens, directly related to focal length
Public Sub Dispose()
End Sub
Public Function getFrameSize() As single
Return mFrameSize
End Function
Public Function getFocalDistance() As single
Return mFocalDistance
End Function
Public Function getFocalLength() As single
Return mFocalLength
End Function
Public Function getFieldOfView() As Radian
Return mFieldOfView
End Function
Public Function getFStop() As single
Return mFStop
End Function
Public Function getHyperfocalLength() As single
Return mHyperfocalLength
End Function
Public Sub recalculateDepthOfField(ByRef _nearDepth As Single, ByRef _focalDepth As Single, ByRef _farDepth As Single)
' Set focalDepth to the current focalDistance
_focalDepth = mFocalDistance
' Recalculate the Hyperfocal length
recalculateHyperfocalLength()
' Calculate the numerator of the optics equations
Dim numerator As Single = (mFocalDistance * (mHyperfocalLength - mFocalLength))
Dim nearClear As Single = CSng(numerator / (mHyperfocalLength + mFocalDistance - (2.0 * mFocalLength)))
' Adjust the nearDepth relative to the aperture. This is an approximation.
_nearDepth = System.Math.Min(nearClear - nearClear * mFStop, CType(0, Single))
If mFocalDistance < mHyperfocalLength Then
' Calculate the far clear plane
Dim farClear As Single = numerator / (mHyperfocalLength - mFocalDistance)
' Adjust the farDepth relative to the aperture. This is an approximation.
_farDepth = farClear + farClear * mFStop
' Far depth of field should be infinite
Else
_farDepth = Math.POS_INFINITY
End If
End Sub
Public Sub New(ByVal _focalLength As Single, ByVal _fStop As Single, Optional ByVal _frameSize As Single = 3.5, Optional ByVal _circleOfConfusion As Single = 0.003)
init(_focalLength, _fStop, _frameSize, _circleOfConfusion)
End Sub
Public Sub New(ByVal _fieldOfView As Radian, ByVal _fStop As Single, Optional ByVal _frameSize As Single = 3.5, Optional ByVal _circleOfConfusion As Single = 0.003)
init(_fieldOfView, _fStop, _frameSize, _circleOfConfusion)
End Sub
Public Sub init(ByVal _focalLength As Single, ByVal _fStop As Single, ByVal _frameSize As Single, ByVal _circleOfConfusion As Single)
mFocalLength = _focalLength
mFStop = _fStop
mFrameSize = _frameSize
mCircleOfConfusion = _circleOfConfusion
recalculateFieldOfView()
End Sub
Public Sub init(ByVal _fieldOfView As Radian, ByVal _fStop As Single, ByVal _frameSize As Single, ByVal _circleOfConfusion As Single)
mFieldOfView = _fieldOfView
mFStop = _fStop
mFrameSize = _frameSize
mCircleOfConfusion = _circleOfConfusion
recalculateFocalLength()
End Sub
Public Sub setFrameSize(ByVal _frameSize As Single)
mFrameSize = _frameSize
recalculateFieldOfView()
End Sub
Public Sub setFocalDistance(ByVal _focalDistance As Single)
mFocalDistance = System.Math.Max(_focalDistance, 0.0F)
End Sub
Public Sub setFocalLength(ByVal _focalLength As Single)
mFocalLength = System.Math.Max(_focalLength, 0.3F)
recalculateFieldOfView()
End Sub
Public Sub setFieldOfView(ByVal _fieldOfView As Radian)
Dim n As New Radian(2.8)
If n < _fieldOfView Then
mFieldOfView = n
Else
mFieldOfView = _fieldOfView
End If
recalculateFocalLength()
End Sub
Public Sub setFStop(ByVal _fStop As Single)
mFStop = System.Math.Max(_fStop, 0.0F)
End Sub
Private Sub recalculateHyperfocalLength()
mHyperfocalLength = (mFocalLength * mFocalLength) / (mFStop * mCircleOfConfusion) + mFocalLength
End Sub
Private Sub recalculateFieldOfView()
mFieldOfView = 2.0 * Math.ATan(CSng(mFrameSize / (2.0 * mFocalLength)))
End Sub
Private Sub recalculateFocalLength()
mFocalLength = CSng((mFrameSize / System.Math.Tan(mFieldOfView.ValueRadians / 2.0)) / 2.0)
End Sub
End Class
{CODE}
{VERSIONS}
There are three classes:
__DepthOfField__ - This is the class which controls the dof shader and the underlying compositor script.
__Lens__ - This is a class which makes it easier to control the DeathOfField class (makes it more natural)
__Dofmanager__ - This class combines both other classes to an automatic dof shader: create a new instance and set mode=automatic and everything runs out of the box
And now you have to download the material file and the other shader files.
{SPLIT()}
{DIV(class="Bloody_box1")}[http://www.ogre3d.org/tikiwiki/dl2116|__Download link__]{DIV}
---
{BOX(title="%tip% Subfolder",width="30%",class="Layout_box4")}Copy the material file in a new folder called "dof". It improves clarity and makes it easier to find.{BOX}
{BOX(title="%warning% Warning",bg="whiteyellow",width="30%",class="achtung")}Make sure that the material file is in the media folder or in one of it's subfolders and a reference is added to the "resources.cfg" file.{BOX}
{SPLIT}
!How to use - The simplest way
Create a dofmanager instance (and set the values you need)
{VERSIONS(nav="y",default="C#")}
{CODE(wrap="1", colors="c#")}
DOFManager dof = new DOFManager(MyViewport, MyCamera, MyRenderWindow, MySceneManager);
{CODE}
---(VB.NET)---
{CODE(wrap="1", colors="vbnet")}
Dim dof as DofManager = new DOFManager(MyViewport, MyCamera, MyRenderWindow, MySceneManager)
{CODE}
{VERSIONS}
!How to use - The other way
Create instances of Lens and DepthOfField.
{VERSIONS(nav="y",default="C#")}
{CODE(wrap="1", colors="c#")}
DepthOfFieldEffect mDepthOfFieldEffect = new DepthOfFieldEffect(Viewport, Camera);
Lens mLens = new Lens(Camera.FOVy, 1);
{CODE}
---(VB.NET)---
{CODE(wrap="1", colors="vbnet")}
Dim mDepthOfFieldEffect as DepthOfFieldEffect = new DepthOfFieldEffect(Viewport, Camera);
Dim mLens as Lens = new Lens(Camera.FOVy, 1);
{CODE}
{VERSIONS}
But now you have to adjust the values on your own. Look into the DofManager to get an overview.
Don't forget to call "Dispose" if you stop rendering.
!How does the DofManager works
The DofManager hooks into the renderloop (the FrameStarted event) and raycasts each frame from the screen center (You may need to change the query flags). The "DelegateRequestFocalDistance" is delegate which can be used to inect custom focal distances into the manager. If it's null/nothing it will be ignored.
You can stop/resume the manager with getenabled and setenabled.
{BOX(title="Combability issues",class="achtung")}The dofshader somehow prevents other compositors to work.
(Note from Tublii: One example: this happens with the [http://www.ogre3d.org/forums/viewtopic.php?f=11&t=61524|SSAA compositor]){BOX}
!Thanks to
[http://www.ogre3d.org/forums/memberlist.php?mode=viewprofile&u=2213&sid=83092bc20e4daab5f1d054cd451334ea|DWORD]
[http://www.ogre3d.org/forums/memberlist.php?mode=viewprofile&u=10883|polygon9]