The "depth of field" (DOF) is the distance between the nearest and farthest objects in a scene that appear acceptably sharp in an image" (Wikipedia). It is a quite impressive technique. It bases on this c++ implementation and the slightly modified version of Polygon9.
For questions, bug reports, etc. use this Mogre forum topic or if it's shader related Ogre forum topic.
Table of contents
Showcase and demo
The demo download link (external, c++ version, may not work with dx9)
http://dword.dk/blog/software/ogre/dof/
Screenshots
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:
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
The "Lens.vb" or "Lens.cs" file:
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
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.
|
Subfolder Copy the material file in a new folder called "dof". It improves clarity and makes it easier to find. Warning 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. |
How to use - The simplest way
Create a dofmanager instance (and set the values you need)
Dim dof as DofManager = new DOFManager(MyViewport, MyCamera, MyRenderWindow, MySceneManager)
How to use - The other way
Create instances of Lens and DepthOfField.
Dim mDepthOfFieldEffect as DepthOfFieldEffect = new DepthOfFieldEffect(Viewport, Camera); Dim mLens as Lens = new Lens(Camera.FOVy, 1);
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.
Thanks to
<HR>
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
1. Definitions
- "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with a number of other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.
- "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.
- "Licensor" means the individual or entity that offers the Work under the terms of this License.
- "Original Author" means the individual or entity who created the Work.
- "Work" means the copyrightable work of authorship offered under the terms of this License.
- "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.
- "License Elements" means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike.
2. Fair Use Rights
Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.
3. License Grant
Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
- to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works;
- to create and reproduce Derivative Works;
- to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission the Work including as incorporated in Collective Works;
- to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a digital audio transmission Derivative Works.
- For the avoidance of doubt, where the work is a musical composition:
- Performance Royalties Under Blanket Licenses. Licensor waives the exclusive right to collect, whether individually or via a performance rights society (e.g. ASCAP, BMI, SESAC), royalties for the public performance or public digital performance (e.g. webcast) of the Work.
- Mechanical Rights and Statutory Royalties. Licensor waives the exclusive right to collect, whether individually or via a music rights society or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions).
- Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor waives the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions).
The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. All rights not expressly granted by Licensor are hereby reserved.
4. Restrictions
The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
- You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by clause 4(c), as requested. If You create a Derivative Work, upon notice from any Licensor You must, to the extent practicable, remove from the Derivative Work any credit as required by clause 4(c), as requested.
- You may distribute, publicly display, publicly perform, or publicly digitally perform a Derivative Work only under the terms of this License, a later version of this License with the same License Elements as this License, or a Creative Commons iCommons license that contains the same License Elements as this License (e.g. Attribution-ShareAlike 2.5 Japan). You must include a copy of, or the Uniform Resource Identifier for, this License or other license specified in the previous sentence with every copy or phonorecord of each Derivative Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Derivative Works that alter or restrict the terms of this License or the recipients' exercise of the rights granted hereunder, and You must keep intact all notices that refer to this License and to the disclaimer of warranties. You may not distribute, publicly display, publicly perform, or publicly digitally perform the Derivative Work with any technological measures that control access or use of the Work in a manner inconsistent with the terms of this License Agreement. The above applies to the Derivative Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Derivative Work itself to be made subject to the terms of this License.
- If you distribute, publicly display, publicly perform, or publicly digitally perform the Work or any Derivative Works or Collective Works, You must keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity, journal) for attribution in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and in the case of a Derivative Work, a credit identifying the use of the Work in the Derivative Work (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). Such credit may be implemented in any reasonable manner; provided, however, that in the case of a Derivative Work or Collective Work, at a minimum such credit will appear where any other comparable authorship credit appears and in a manner at least as prominent as such other comparable authorship credit.
5. Representations, Warranties and Disclaimer
UNLESS OTHERWISE AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MATERIALS, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
6. Limitation on Liability.
EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. Termination
- This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Derivative Works or Collective Works from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.
- Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.
8. Miscellaneous
- Each time You distribute or publicly digitally perform the Work or a Collective Work, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.
- Each time You distribute or publicly digitally perform a Derivative Work, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License.
- If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
- No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
- This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You.