protected override void InitializeInternal() { base.InitializeInternal(); _lightRotationAngle = 0; _sceneBounds = new BoundingSphere(new Vector3(), MathF.Sqrt(40 * 40 + 60 * 60)); _dirLights = new[] { new DirectionalLight { Ambient = new Color(0.2f, 0.2f, 0.2f), Diffuse = new Color(0.7f, 0.7f, 0.7f), Specular = new Color(0.8f, 0.8f, 0.8f), Direction = new Vector3(-0.57735f, -0.57735f, 0.57735f) }, new DirectionalLight { Ambient = new Color(0, 0, 0), Diffuse = new Color(0.4f, 0.4f, 0.4f), Specular = new Color(0.2f, 0.2f, 0.2f), Direction = new Vector3(-0.707f, -0.707f, 0) }, new DirectionalLight { Ambient = new Color(0, 0, 0), Diffuse = new Color(0.2f, 0.2f, 0.2f), Specular = new Color(0.2f, 0.2f, 0.2f), Direction = new Vector3(0, 0, -1) } }; _originalLightDirs = _dirLights.Select(l => l.Direction).ToArray(); var device = D3DApp11.I.D3DDevice; _shadowMap = new ShadowMap(device, ShadowMapSize, ShadowMapSize); BuildShapeGeometryBuffers(device); BuildScreenQuadGeometryBuffers(device); var context = D3DApp11.I.ImmediateContext; _randomTex = TextureLoader.CreateRandomTexture1D(device); _flareTexSRV = TextureLoader.CreateTexture2DArray(device, context, new[] { NoireConfiguration.GetFullResourcePath("textures/flare0.png") }); _fire = new ParticleSource(RootContainer, this, device, EffectManager11.Instance.GetEffect <FireParticleEffect11>(), _flareTexSRV, _randomTex, 500); _fire.Initialize(); _fire.Visible = _settings.ParticleFlameVisible; ChildComponents.Add(_fire); _rainTexSRV = TextureLoader.CreateTexture2DArray(device, context, new[] { NoireConfiguration.GetFullResourcePath("textures/raindrop.png") }); _rain = new ParticleSource(RootContainer, this, device, EffectManager11.Instance.GetEffect <RainParticleEffect11>(), _rainTexSRV, _randomTex, 10000); _rain.Initialize(); _rain.Visible = _settings.ParticleRainVisible; ChildComponents.Add(_rain); var basicFx = EffectManager11.Instance.GetEffect <BasicEffect11>(); var normalMapFx = EffectManager11.Instance.GetEffect <NormalMapEffect11>(); var displacementMapFx = EffectManager11.Instance.GetEffect <DisplacementMapEffect11>(); InitializeTechniqueTable(basicFx, normalMapFx, displacementMapFx); }
protected override void CreateShadowMap(EntityLightShadow light) { var shadowMapDesc = light.Light.Shadow as LightShadowMap; // create the shadow map var shadowMap = new ShadowMap { LightDirection = light.Light.Direction, LightPosition = light.Entity.Transformation.Translation, ShadowMapSize = shadowMapDesc.MaxSize, ShadowNearDistance = shadowMapDesc.NearDistance, ShadowFarDistance = shadowMapDesc.FarDistance, CascadeCount = light.Light.Type is LightDirectional ? shadowMapDesc.CascadeCount : 1, // cascades are only supported for directional shadow maps //Fov = light.Light.SpotFieldAngle, Filter = shadowMapDesc.FilterType, Layers = light.Light.Layers }; // find or create the shadow map texture ShadowMapTexture chosenTexture = null; chosenTexture = AllocateOrChooseTexture(shadowMap, shadowMapDesc.FilterType == LightShadowMapFilterType.Variance ? texturesVsm : texturesDefault); shadowMap.Texture = chosenTexture; InternalShadowMaps.Add(shadowMap); light.ShadowMap = shadowMap; }
//TODO: Make this generical for whole pre effects pipeline public void CreateShadowMap(Resolution resolution) { var shadowMap = new ShadowMap(_graphicsDevice, resolution); // TODO: add to correct index - this only correct by chance _childrenPre.Add(shadowMap); }
public ShadowCastingLight(Entity entity, PerspectiveCamera viewPoint, ShadowMap shadowMap, Color color) { this.Entity = entity; this.ViewPoint = viewPoint; this.ShadowMap = shadowMap; this.Color = color; }
protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap) { var anyPartIsVisible = _slices.Aggregate(false, (current, slice) => current | (slice.Visible = camera.BoundingFrustum.Contains(slice.BoundingSphere) != ContainmentType.Disjoint)); if (!anyPartIsVisible) return false; for (var i = 0; i < 9; i++) { var ep = Effect.Parameters["Texture" + (char)(48 + i)]; if (ep != null) ep.SetResource(Textures[i]); } Effect.Parameters["HeightsMap"].SetResource(HeightsMap); Effect.Parameters["NormalsMap"].SetResource(NormalsMap); Effect.Parameters["WeightsMap"].SetResource(WeightsMap); camera.UpdateEffect(Effect); foreach (var slice in _slices.Where(slice => slice.Visible)) { Effect.Parameters["TexOffsetAndScale"].SetValue(slice.TexOffsetAndScale); VContent.TerrainPlane.Draw(camera, slice.World, drawingReason); } return true; }
protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap) { if (_vertexBuffer == null) return false; camera.UpdateEffect(Effect); Effect.World = _world; Effect.Texture = _texture; Effect.GraphicsDevice.SetVertexBuffer(_vertexBuffer); Effect.GraphicsDevice.SetVertexInputLayout(_vertexInputLayout); Effect.Parameters["WindTime"].SetValue(_time); Effect.Parameters["BillboardWidth"].SetValue(_billboardWidth); Effect.Parameters["BillboardHeight"].SetValue(_billboardHeight); //pass one Effect.Parameters["AlphaTestDirection"].SetValue(1f); Effect.Effect.CurrentTechnique.Passes[0].Apply(); Effect.GraphicsDevice.Draw(PrimitiveType.TriangleList, _vertexBuffer.ElementCount); if (drawingReason == DrawingReason.Normal) { //pass two Effect.GraphicsDevice.SetDepthStencilState(Effect.GraphicsDevice.DepthStencilStates.DepthRead); Effect.GraphicsDevice.SetBlendState(Effect.GraphicsDevice.BlendStates.NonPremultiplied); Effect.Parameters["AlphaTestDirection"].SetValue(-1f); Effect.Effect.CurrentTechnique.Passes[0].Apply(); Effect.GraphicsDevice.Draw(PrimitiveType.TriangleList, _vertexBuffer.ElementCount); Effect.GraphicsDevice.SetDepthStencilState(Effect.GraphicsDevice.DepthStencilStates.Default); Effect.GraphicsDevice.SetBlendState(Effect.GraphicsDevice.BlendStates.Default); } return true; }
private static bool BelongToGroup(LightComponent light, ShadowMap shadow, ShadowConfiguration config, int groupCount, Texture groupTexture) { return(light.ShadowMapCascadeCount == config.CascadeCount && light.ShadowMapFilterType == config.FilterType && groupCount < config.ShadowCount && (groupTexture == null || groupTexture == shadow.Texture.ShadowMapDepthTexture)); }
private ShadowMapTexture AllocateOrChooseTexture(ShadowMap newShadowMap, Dictionary <ShadowMapTexture, List <ShadowMap> > shadowMapTextures) { ShadowMapTexture chosenTexture = null; // find best texture foreach (var shadowMapTexture in shadowMapTextures) { var shadowTexture = shadowMapTexture.Key; var shadowMaps = shadowMapTexture.Value; shadowTexture.GuillotinePacker.Clear(shadowTexture.ShadowMapDepthTexture.ViewWidth, shadowTexture.ShadowMapDepthTexture.ViewHeight); var useShadowTexture = true; for (var i = 0; i < shadowMaps.Count && useShadowTexture; ++i) { useShadowTexture = shadowTexture.GuillotinePacker.TryInsert(shadowMaps[i].ShadowMapSize, shadowMaps[i].ShadowMapSize, shadowMaps[i].CascadeCount); } useShadowTexture = useShadowTexture && shadowTexture.GuillotinePacker.TryInsert(newShadowMap.ShadowMapSize, newShadowMap.ShadowMapSize, newShadowMap.CascadeCount); shadowTexture.GuillotinePacker.Clear(); if (useShadowTexture) { chosenTexture = shadowMapTexture.Key; break; } } if (chosenTexture == null) { // allocate a new texture chosenTexture = new ShadowMapTexture(GraphicsDevice, newShadowMap.Filter, 2048); chosenTexture.GuillotinePacker.Clear(chosenTexture.ShadowMapDepthTexture.ViewWidth, chosenTexture.ShadowMapDepthTexture.ViewHeight); // TODO: choose texture size based on the shadow map. For now throw exception if (!chosenTexture.GuillotinePacker.TryInsert(newShadowMap.ShadowMapSize, newShadowMap.ShadowMapSize, newShadowMap.CascadeCount)) { var message = new StringBuilder(); message.AppendFormat("Unable to allocate shadow map texture. The default size (2048 x 2048) is too small for the shadow map ({0} cascade(s) with size {1}).", newShadowMap.CascadeCount, newShadowMap.ShadowMapSize); throw new Exception(message.ToString()); } chosenTexture.GuillotinePacker.Clear(); InternalShadowMapTextures.Add(chosenTexture); var shadowMaps = new List <ShadowMap> { newShadowMap }; shadowMapTextures.Add(chosenTexture, shadowMaps); } else { shadowMapTextures[chosenTexture].Add(newShadowMap); } return(chosenTexture); }
public LightComponent() { var size = 20f; var farPlane = 200f; ProjMatrix = Matrix4x4.CreateOrthographicOffCenter(-size, size, -size, size, 0.1f, farPlane); ViewMatrix = Matrix4x4.Identity; ShadowMap = new ShadowMap(4096, 4096); }
public override bool Init() { if (!base.Init()) { return(false); } Effects.InitAll(Device); InputLayouts.InitAll(Device); RenderStates.InitAll(Device); Patch.InitPatchData(Terrain.CellsPerPatch, Device); _sky = new Sky(Device, "Textures/grasscube1024.dds", 5000.0f); var tii = new InitInfo { HeightMapFilename = null, LayerMapFilename0 = "textures/grass.dds", LayerMapFilename1 = "textures/darkdirt.dds", LayerMapFilename2 = "textures/stone.dds", LayerMapFilename3 = "Textures/lightdirt.dds", LayerMapFilename4 = "textures/snow.dds", BlendMapFilename = null, HeightScale = 50.0f, HeightMapWidth = 2049, HeightMapHeight = 2049, CellSpacing = 0.5f, Seed = 0, NoiseSize1 = 3.0f, Persistence1 = 0.7f, Octaves1 = 7, NoiseSize2 = 2.5f, Persistence2 = 0.8f, Octaves2 = 3, }; _terrain = new Terrain(); _terrain.Init(Device, ImmediateContext, tii); _camera.Height = _terrain.Height; AddUIElements(); _camera.SetLens(0.25f * MathF.PI, AspectRatio, 1.0f, 1000.0f); _ssao = new Ssao(Device, ImmediateContext, ClientWidth, ClientHeight, _camera.FovY, _camera.FarZ); _whiteTex = ShaderResourceView.FromFile(Device, "Textures/white.dds"); _sMap = new ShadowMap(Device, SMapSize, SMapSize); _sceneBounds = new BoundingSphere(new Vector3(), MathF.Sqrt(_terrain.Width * _terrain.Width + _terrain.Depth * _terrain.Depth) / 2); _minimap = new Minimap(Device, ImmediateContext, MinimapSize, MinimapSize, _terrain, _camera); return(true); }
protected override void OnEntityAdded(Entity entity, AssociatedData associatedData) { if (associatedData.LightComponent.Deferred) { associatedData.EffectMesh = new EffectMesh(lightEffect); associatedData.EffectMesh.AddReference(); renderSystem.GlobalMeshes.AddMesh(associatedData.EffectMesh); } else { if (associatedData.LightComponent.Type == LightType.Directional) { associatedData.Light = new DirectionalLight(); } else { throw new NotImplementedException(); } associatedData.LightComponent.Set(LightKey, associatedData.Light); } associatedData.CurrentShadowMap = associatedData.LightComponent.ShadowMap; associatedData.CurrentType = associatedData.LightComponent.Type; ShadowMapPermutation shadowMap = null; if (associatedData.LightComponent.ShadowMap) { shadowMap = new ShadowMap((DirectionalLight)associatedData.Light) { Level = CascadeShadowMapLevel.X2, ShadowMapSize = 1024, ShadowDistance = associatedData.LightComponent.DecayStart } .SetFilter(sm => new ShadowMapFilterVsm(sm)); lightingPlugin.AddShadowMap(shadowMap.ShadowMap); associatedData.ShadowMapPermutation = shadowMap; associatedData.LightComponent.Set(ShadowMapKey, associatedData.ShadowMapPermutation); } if (enableIcons) { throw new NotImplementedException(); associatedData.IconMesh = new EffectMesh(lightIconEffect /*, iconMeshData, null*/); associatedData.IconMesh.AddReference(); renderPassEnumerator.AddMesh(associatedData.IconMesh); associatedData.IconMesh.Tags.Set(PickingPlugin.AssociatedEntity, entity); } if (LightComponentAdded != null) { LightComponentAdded(this, associatedData.LightComponent); } }
public void CreateBasicShadowMap() { //Given ShadowMap map = new ShadowMap(GraphicsDevice.New(DeviceCreationFlags.Debug), 1, 1); //When //Then Assert.IsTrue(map.ResourceView != null); map.Dispose(); }
protected override void PreRender(VoxelSystemScene scene) { Camera.ViewMatrix = scene.Player.ViewMatrix; ShadowMap.SetLightDirection(scene.SunDirection); var center = scene.Player.Transform.WorldPosition; center.Floor(); ShadowMap.SetCenter(center); VoxelBodyRenderer.SetCamera(Camera); VoxelBodyRenderer.SetShadowMap(ShadowMap); }
protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap) { camera.UpdateEffect(Effect); Effect.World = World; if (drawingReason != DrawingReason.ShadowDepthMap) { Effect.Texture = _texture; //TODO Effect.Parameters["BumpMap"].SetResource(_bumpMap); } _cube.Draw(Effect); return true; }
protected override void SetShadowValues(Shader shader, string name, ref int shadowMapUnit) { shader.SetBool(name + ".shadowsEnabled", ShadowsEnabled); if (!ShadowsEnabled) { return; } shader.SetMat4(name + ".lightSpace", LightSpace); shader.SetInt("shadowCube", shadowMapUnit + 8); ShadowMap.BindToUnit(shadowMapUnit + 8); shadowMapUnit += 1; }
void createTile(int x, int y, Texture texture, ShadowMap shadow) { // creates the tile gameobject based from the prefab and positions it GameObject tileObject = Instantiate(tilePrefab, new Vector3(-x, 0, -y), Quaternion.identity, mapParentTransform); // sets the primary texture of each tile Renderer rend = tileObject.GetComponentsInChildren <Renderer>()[1]; rend.material.SetTexture("_BaseColorMap", texture); //if necessary, sets the underlay texture of a tile if (!CompareColours(mapUnderlay.texture.GetPixel(x, y), blankUnderlayColour)) { for (int i = 0; i < colours.Length; i++) { Color c = colours[i]; if (CompareColours(c, mapUnderlay.texture.GetPixel(x, y))) { Renderer rend2 = tileObject.GetComponentsInChildren <Renderer>()[2]; rend2.material.SetTexture("_BaseColorMap", textures[i]); } } } if (shadow != ShadowMap.None) { Instantiate(shadowPrefabs[(int)shadow], new Vector3(-x, 0, -y), Quaternion.identity, tileObject.transform); } // hooks the gameobject tile up to the tile system utilised by the pathfinding algorithm Tile.tileMap[x, y] = new Tile(x, y, tileObject); //tileObject.AddComponent<TileObserver>().INIT(x,y); // is the tile walkable? if (CompareColours(mapWalkable.texture.GetPixel(x, y), Color.black)) { Tile.tileMap[x, y].isWalkable = false; } // is the tile placeable? if (CompareColours(mapWalkable.texture.GetPixel(x, y), placeableColour)) { //Debug.Log("placeable"); Tile.tileMap[x, y].isPlaceable = true; } }
public override void OnInspectorGUI() { ShadowMap shadowMap = (ShadowMap)target; DrawDefaultInspector(); //if (shadowMap.m_CullingMask < 0) { options.Clear(); for (int i = 0; i < 32; i++) { string name = LayerMask.LayerToName(i); if (!string.IsNullOrEmpty(name) && !options.Contains(name)) { options.Add(name); } } } shadowMap.m_CullingMaskSelection = EditorGUILayout.MaskField("Culling Mask", shadowMap.m_CullingMaskSelection, options.ToArray()); if (shadowMap.m_CullingMaskSelection >= 0) { shadowMap.m_CullingMask = 0; var myBitArray = new BitArray(BitConverter.GetBytes(shadowMap.m_CullingMaskSelection)); for (int i = myBitArray.Count - 1; i >= 0; i--) { if (myBitArray[i] == true) { if (shadowMap.m_CullingMask > 0) { shadowMap.m_CullingMask |= 1 << LayerMask.NameToLayer(options[i]); } else { shadowMap.m_CullingMask = 1 << LayerMask.NameToLayer(options[i]); } } } Debug.Log(""); } else { shadowMap.m_CullingMask = shadowMap.m_CullingMaskSelection; } Debug.Log("shadowMap.m_CullingMaskSelection :" + shadowMap.m_CullingMaskSelection); }
public virtual void SetShadowsEnabled(bool shadows) { ShadowsEnabled = shadows; if (!shadows) { ShadowMap?.Dispose(); ShadowMap = null; } else { CreateShadowMap(); CalculateLightSpace(); } }
protected virtual void SetShadowValues(Shader shader, string name, ref int shadowMapUnit) { shader.SetBool(name + ".shadowsEnabled", ShadowsEnabled); if (!ShadowsEnabled) { return; } shader.SetMat4(name + ".lightSpace", LightSpace); shader.SetInt(name + ".shadowIndex", shadowMapUnit); shader.SetInt("shadowMaps[" + shadowMapUnit + "]", shadowMapUnit + 8); ShadowMap.BindToUnit(shadowMapUnit + 8); shadowMapUnit += 1; }
public virtual void LoadShadowMap() { Camera lightView = new Camera(); // lighth view to initialize the shadow map. can be changed. lightView.Position = new Vector3(-125.5173f, -112.2577f, -1.61722f); //lightView.Rotate(new Vector3(lightView.CameraUVW.Row0), MathHelper.PiOver2); //lightView.Rotate(new Vector3(Vector3.UnitZ), MathHelper.PiOver6); //lightView.LevelU2XZ(0.9998470f); //V: (0,2715916; -0,6443541; -0,2702386), W: 0,6618307 lightView.Quaternion = new Quaternion(0.2715916f, -0.6443541f, -0.2702386f, 0.6618307f); lightView.Update(); ShadowMap = new ShadowMap(lightView); }
protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap) { camera.UpdateEffect(Effect); if (drawingReason == DrawingReason.ShadowDepthMap) Effect.CameraPosition = shadowMap.RealCamera.Position; Effect.World = World; Effect.Parameters["WindTime"].SetValue(Time); Effect.Parameters["BillboardWidth"].SetValue(Width); Effect.Parameters["BillboardHeight"].SetValue(Height); Effect.Texture = _treeTexture; Effect.GraphicsDevice.SetVertexInputLayout(_vertexInputLayout); Effect.GraphicsDevice.SetVertexBuffer(_vertexBuffer); Effect.Effect.CurrentTechnique.Passes[0].Apply(); Effect.GraphicsDevice.Draw(PrimitiveType.TriangleList, _vertexBuffer.ElementCount); return true; }
public static void DrawWaterSurfaceGrid( WaterSurface waterSurface, Camera camera, ShadowMap shadow, int nisse, int surfaceSize, int surfaceScale) { const int waterW = 64; const int waterH = 64; const int worldW = 32; const int worldH = 32; var boundingFrustum = camera.BoundingFrustum; waterSurface.Effect.SetShadowMapping(shadow); var gridStartX = (int) camera.Position.X/waterW - worldW/2; var gridStartY = (int) camera.Position.Z/waterH - worldH/2; Array.Clear(RenderedWaterPlanes, 0, RenderedWaterPlanes.Length); var drawDetails = camera.Position.Y < -1; // fix the sea water some time if (drawDetails) for (var y = 0; y <= worldH; y++) for (var x = 0; x <= worldW; x++) { var pos1 = new Vector3((gridStartX + x) * waterW, 0, (gridStartY + y) * waterH); var pos2 = pos1 + new Vector3(waterW, 1, waterH); var bb = new BoundingBox(pos1, pos2); if (boundingFrustum.Contains(bb) == ContainmentType.Disjoint) continue; waterSurface.Draw( camera, pos1, Vector3.Distance(camera.Position, pos1 - new Vector3(-32, 0, -32)), x % 8, y % 8, 1 << surfaceScale); } var raise = 0.5f + camera.Position.Y/500; var q = (int)camera.ZFar & ~(waterW - 1); var pos = new Vector3(gridStartX * waterW - q, raise, gridStartY * waterH - q); waterSurface.Draw(camera, pos, -1, 0, 0, 1 << surfaceScale); }
protected override void CreateShadowMap(EntityLightShadow light) { // create the shadow map var shadowMap = new ShadowMap { LightDirection = light.Light.LightDirection, ShadowMapSize = light.Light.ShadowMapMinSize, ShadowNearDistance = light.Light.ShadowNearDistance, ShadowFarDistance = light.Light.ShadowFarDistance, CascadeCount = light.Light.ShadowMapCascadeCount, Filter = light.Light.ShadowMapFilterType, Layers = light.Light.Layers }; InternalShadowMaps.Add(shadowMap); light.ShadowMap = shadowMap; }
protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap) { camera.UpdateEffect(Effect); Effect.World = World; //if (drawingReason != DrawingReason.ShadowDepthMap) // Effect.Texture = _texture; //Effect.Apply(); //foreach (var mesh in _model.Meshes) // mesh.Draw(Effect.GraphicsDevice); //Effect.World = World*Matrix.Translation(21.68f, 0, 0); //foreach (var mesh in _model.Meshes) // mesh.Draw(Effect.GraphicsDevice); return true; }
private void RenderShadowMap(ShadowMap shadowMap) { var modelBatchList = this.ModelSystem.ComputeBatches(shadowMap.ViewPoint, this.NullSkybox); this.MeterRegistry.StartGauge(ShadowMapStep); { // First compute the shadow maps this.Device.SetRenderTarget(shadowMap.DepthMap, shadowMap.Index); this.Device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.White, 1.0f, 0); this.Device.ShadowMapState(); modelBatchList.OpaqueBatch.Draw(RenderEffectTechniques.ShadowMap); } this.MeterRegistry.StopGauge(ShadowMapStep, "opaque"); // TODO: Color maps need to be redone // - If an occluder is between the light and the transparent object, it will also get the transparent object painted on it // - They are hard to mix with particles in the current state // - Expensive since we draw so much double? // - Might benefit from better filtering // TODO: since this doesn't use the depth map, will it sometimes show colors that should not be visible? // for example those that are in front of a thing? this.MeterRegistry.StartGauge(ShadowMapStep); { // Read the depth buffer and render objects that are partially // occluding, like a stained glass window this.Device.SetRenderTarget(shadowMap.ColorMap, shadowMap.Index); this.Device.Clear(ClearOptions.Target, Color.White, 1.0f, 0); this.Device.AlphaBlendOccluderState(); for (var iBatch = 0; iBatch < modelBatchList.TransparentBatches.Count; iBatch++) { var batch = modelBatchList.TransparentBatches[iBatch]; batch.Draw(RenderEffectTechniques.Textured); } } this.MeterRegistry.StopGauge(ShadowMapStep, "transparent"); }
protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap) { if (drawingReason != DrawingReason.Normal) return true; camera.UpdateEffect(Effect); foreach (var item in Items) { Effect.World = Matrix.BillboardRH(item.Target.Position + item.GetOffset(item), camera.Position, -camera.Up, camera.Front); Effect.DiffuseColor = item.GetColor(item); SpriteBatch.Begin(SpriteSortMode.Deferred, Effect.GraphicsDevice.BlendStates.NonPremultiplied, null, Effect.GraphicsDevice.DepthStencilStates.DepthRead, null, Effect.Effect); SpriteBatch.DrawString(Font, item.Text, Vector2.Zero, Color.Black, 0, Font.MeasureString(item.Text) / 2, item.GetSize(item), 0, 0); SpriteBatch.End(); } Effect.GraphicsDevice.SetDepthStencilState(Effect.GraphicsDevice.DepthStencilStates.Default); Effect.GraphicsDevice.SetBlendState(Effect.GraphicsDevice.BlendStates.Opaque); return true; }
public void DrawToShadowMap(DeviceContext dc, ShadowMap sMap, Matrix viewProj) { sMap.BindDsvAndSetNullRenderTarget(dc); dc.InputAssembler.PrimitiveTopology = PrimitiveTopology.PatchListWith4ControlPoints; dc.InputAssembler.InputLayout = InputLayouts.TerrainCP; var stride = TerrainCP.Stride; const int offset = 0; dc.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_quadPatchVB, stride, offset)); dc.InputAssembler.SetIndexBuffer(_quadPatchIB, Format.R16_UInt, 0); var frustum = Frustum.FromViewProj(viewProj); var planes = frustum.Planes; Effects.TerrainFX.SetViewProj(viewProj); Effects.TerrainFX.SetEyePosW(new Vector3(viewProj.M41, viewProj.M42, viewProj.M43)); Effects.TerrainFX.SetMinDist(MinDist); Effects.TerrainFX.SetMaxDist(MaxDist); Effects.TerrainFX.SetMinTess(MinTess); Effects.TerrainFX.SetMaxTess(MaxTess); Effects.TerrainFX.SetWorldCellSpace(_terrain.Info.CellSpacing); Effects.TerrainFX.SetWorldFrustumPlanes(planes); Effects.TerrainFX.SetHeightMap(_heightMapSRV); var tech = Effects.TerrainFX.TessBuildShadowMapTech; for (var p = 0; p < tech.Description.PassCount; p++) { var pass = tech.GetPassByIndex(p); pass.Apply(dc); dc.DrawIndexed(_numPatchQuadFaces * 4, 0, 0); } dc.HullShader.Set(null); dc.DomainShader.Set(null); }
public VoxelSystemSceneRenderer() { // terrain material var terrainMaterial = new VoxelTerrainMaterial(); terrainMaterial.DiffuseIntensity = 0.1f; terrainMaterial.AmbientIntensity = 0.8f; terrainMaterial.MainTexture = G.Assets.VoxelTextureAtlas.AtlasTexture; terrainMaterial.SunlightColor = new Color(255, 255, 192); terrainMaterial.StarlightColor = new Color(0, 20, 70); VoxelBodyRenderer = new VoxelBodyRenderer(terrainMaterial); Camera.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(90), G.Graphics.Viewport.AspectRatio, 0.01f, 1000); // selection wireframe _selectionWireframe = new SelectionWireframe(new BasicEffect(G.Graphics)); _selectionWireframe.Effect.DiffuseColor = Vector3.Zero; _selectionWireframe.Effect.Projection = Camera.ProjectionMatrix; ShadowMap = new ShadowMap(4096 * 4); ShadowMap.SetCenter(Vector3.Zero); ShadowMap.SetRadius(100); }
public override bool Init() { if (!base.Init()) { return(false); } Effects.InitAll(Device); InputLayouts.InitAll(Device); RenderStates.InitAll(Device); _sky = new Sky(Device, "Textures/desertcube1024.dds", 5000.0f); _sMap = new ShadowMap(Device, SMapSize, SMapSize); BuildShapeGeometryBuffers(); BuildSkullGeometryBuffers(); BuildScreenQuadGeometryBuffers(); return(true); }
/// <summary> /// /// </summary> public GameScene() { viewModel_ = new MainWindowViewModel(); viewModel_.LightCount = 2048; lightMgr_ = new LightManager(viewModel_.LightCount); toneMap_ = new ToneMap(); shadowMap_ = new ShadowMap(1024, 1024, ShadowMap.Type.VSM); csMgr_ = new ComputeManager(); csMgr_.ShadowMap = shadowMap_; csMgr_.LightManager = lightMgr_; // シャドウマップの撮影設定 Vector3 lightPos = -lightMgr_.DirectionalLightDir * 50; shadowMap_.Camera.SetPosition(ref lightPos); shadowMap_.Camera.Update(); // カメラ操作 GraphicsCore.Camera3D.SetAt(ref camera_at_); cameraCtrl_ = new CameraController(GraphicsCore.Camera3D); // キューブマップ撮影 cubeMapRendered_ = false; cubeMapInfo_ = new CubeMapGenInfo() { numX = 4, numY = 16, numZ = 9, boundingMin = new Vector3(-28, 1, -12), boundingMax = new Vector3(28, 30, 12), }; cubeMapRenderEnable_ = true; csMgr_.CubeMapInfo = cubeMapInfo_; InitializeTarget(); InitialzeSceneObject(); }
public override bool Init() { if (!base.Init()) { return(false); } Effects.InitAll(Device); InputLayouts.InitAll(Device); RenderStates.InitAll(Device); _sky = new Sky(Device, "Textures/desertcube1024.dds", 5000.0f); _sMap = new ShadowMap(Device, SMapSize, SMapSize); _camera.SetLens(0.25f * MathF.PI, AspectRatio, 1.0f, 1000.0f); _ssao = new Ssao(Device, ImmediateContext, ClientWidth, ClientHeight, _camera.FovY, _camera.FarZ); BuildShapeGeometryBuffers(); BuildSkullGeometryBuffers(); BuildScreenQuadGeometryBuffers(); return(true); }
public void SetShadowMapping(ShadowMap shadow) { }
public void DrawToShadowMap(DeviceContext dc, ShadowMap sMap, Matrix viewProj) { sMap.BindDsvAndSetNullRenderTarget(dc); dc.InputAssembler.PrimitiveTopology = PrimitiveTopology.PatchListWith4ControlPoints; dc.InputAssembler.InputLayout = InputLayouts.TerrainCP; var stride = TerrainCP.Stride; const int offset = 0; dc.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(_quadPatchVB, stride, offset)); dc.InputAssembler.SetIndexBuffer(_quadPatchIB, Format.R16_UInt, 0); var frustum = Frustum.FromViewProj(viewProj); var planes = frustum.Planes; Effects.TerrainFX.SetViewProj(viewProj); Effects.TerrainFX.SetEyePosW(new Vector3(viewProj.M41, viewProj.M42, viewProj.M43)); Effects.TerrainFX.SetMinDist(MinDist); Effects.TerrainFX.SetMaxDist(MaxDist); Effects.TerrainFX.SetMinTess(MinTess); Effects.TerrainFX.SetMaxTess(MaxTess); Effects.TerrainFX.SetWorldCellSpace(Info.CellSpacing); Effects.TerrainFX.SetWorldFrustumPlanes(planes); Effects.TerrainFX.SetHeightMap(_heightMapSRV); var tech = Effects.TerrainFX.TessBuildShadowMapTech; for (int p = 0; p < tech.Description.PassCount; p++) { var pass = tech.GetPassByIndex(p); pass.Apply(dc); dc.DrawIndexed(_numPatchQuadFaces * 4, 0, 0); } dc.HullShader.Set(null); dc.DomainShader.Set(null); }
public void AddShadowMap(ShadowMap shadowMap) { shadowMaps.Add(shadowMap); shadowMap.Passes = new RenderPass[shadowMap.LevelCount]; shadowMap.Plugins = new RenderTargetsPlugin[shadowMap.LevelCount]; for (int i = 0; i < shadowMap.Passes.Length; i++) { shadowMap.Passes[i] = new RenderPass(string.Format("Pass {0}", i)) { Parameters = new ParameterCollection(string.Format("Parameters ShadowMap {0}", i)) }; shadowMap.Passes[i].Parameters.AddSources(MainPlugin.ViewParameters); shadowMap.Passes[i].Parameters.AddSources(shadowMap.CasterParameters); unsafe { int currentPassIndex = i; shadowMap.Passes[i].Parameters.AddDynamic(TransformationKeys.ViewProjection, ParameterDynamicValue.New(LightingPlugin.ViewProjectionArray, (ref ShadowMapData input, ref Matrix output) => { fixed (Matrix* vpPtr = &input.ViewProjCaster0) { output = vpPtr[currentPassIndex]; } })); shadowMap.Passes[i].Parameters.AddDynamic(LightingPlugin.ShadowLightOffset, ParameterDynamicValue.New(LightingPlugin.ViewProjectionArray, (ref ShadowMapData input, ref Vector3 output) => { fixed (Vector3* vpPtr = &input.Offset0) { output = vpPtr[currentPassIndex]; } })); } shadowMap.Plugins[i] = new RenderTargetsPlugin { Services = Services, EnableClearTarget = false, EnableClearDepth = false, RenderPass = shadowMap.Passes[i], RenderTarget = null, }; shadowMap.Plugins[i].Apply(); } RenderPass.Passes.InsertRange(0, shadowMap.Passes); // Dynamic value used for ViewProjectionArray key var dynamicViewProjectionArray = ParameterDynamicValue.New( TransformationKeys.View, TransformationKeys.Projection, LightKeys.LightDirection, LightKeys.LightColor, LightingPlugin.Offsets, (ref Matrix view, ref Matrix projection, ref Vector3 lightDirection, ref Color3 lightColor, ref Vector3[] offsets, ref ShadowMapData result) => { if (projections == null) { // Preallocates temporary variables (thread static) projections = new Matrix[4]; views = new Matrix[4]; shadowsViewProj = new Matrix[8]; points = new Vector3[8]; directions = new Vector3[4]; } Matrix inverseView, inverseProjection; Matrix.Invert(ref projection, out inverseProjection); Matrix.Invert(ref view, out inverseView); // Frustum in World Space for (int i = 0; i < 8; ++i) Vector3.TransformCoordinate(ref FrustrumBasePoints[i], ref inverseProjection, out points[i]); for (int i = 0; i < 4; i++) { directions[i] = Vector3.Normalize(points[i + 4] - points[i]); } // TODO Make these factors configurable. They need also to be correctly tweaked. float shadowDistribute = 1.0f / shadowMap.LevelCount; float znear = 1.0f; float zfar = shadowMap.ShadowDistance; var shadowOffsets = new Vector3[shadowMap.LevelCount]; var boudingBoxVectors = new Vector3[shadowMap.LevelCount * 2]; var direction = Vector3.Normalize(lightDirection); // Fake value // It will be setup by next loop Vector3 side = Vector3.UnitX; Vector3 up = Vector3.UnitX; // Select best Up vector foreach (var vectorUp in VectorUps) { if (Vector3.Dot(direction, vectorUp) < (1.0 - 0.0001)) { side = Vector3.Normalize(Vector3.Cross(vectorUp, direction)); up = Vector3.Normalize(Vector3.Cross(direction, side)); break; } } for (int cascadeLevel = 0; cascadeLevel < shadowMap.LevelCount; ++cascadeLevel) { float k0 = (float)(cascadeLevel + 0) / shadowMap.LevelCount; float k1 = (float)(cascadeLevel + 1) / shadowMap.LevelCount; float min = (float)(znear * Math.Pow(zfar / znear, k0)) * (1.0f - shadowDistribute) + (znear + (zfar - znear) * k0) * shadowDistribute; float max = (float)(znear * Math.Pow(zfar / znear, k1)) * (1.0f - shadowDistribute) + (znear + (zfar - znear) * k1) * shadowDistribute; for (int j = 0; j < shadowMap.LevelCount; j++) { boudingBoxVectors[j] = points[j] + directions[j] * min; boudingBoxVectors[j + shadowMap.LevelCount] = points[j] + directions[j] * max; } var boundingBox = BoundingBox.FromPoints(boudingBoxVectors); var radius = (boundingBox.Maximum - boundingBox.Minimum).Length() * 0.5f; var target = Vector3.TransformCoordinate(boundingBox.Center, inverseView); // Snap camera to texel units (so that shadow doesn't jitter) var shadowMapHalfSize = shadowMap.ShadowMapSize * 0.5f; float x = (float)Math.Ceiling(Vector3.Dot(target, up) * shadowMapHalfSize / radius) * radius / shadowMapHalfSize; float y = (float)Math.Ceiling(Vector3.Dot(target, side) * shadowMapHalfSize / radius) * radius / shadowMapHalfSize; float z = Vector3.Dot(target, direction); //target = up * x + side * y + direction * R32G32B32_Float.Dot(target, direction); target = up * x + side * y + direction * z; views[cascadeLevel] = Matrix.LookAtLH(target - direction * zfar * 0.5f, target + direction * zfar * 0.5f, up); // View; projections[cascadeLevel] = Matrix.OrthoOffCenterLH(-radius, radius, -radius, radius, znear / zfar, zfar); // Projection //float leftX = shadowMap.Level == CascadeShadowMapLevel.X1 ? 0.5f : 0.25f; //float leftY = shadowMap.Level == CascadeShadowMapLevel.X4 ? 0.25f : 0.5f; //float centerX = 0.5f * (cascadeLevel % 2) + leftX; //float centerY = 0.5f * (cascadeLevel / 2) + leftY; var cascadeTextureCoords = shadowMap.TextureCoordsBorder[cascadeLevel]; float leftX = (float)shadowMap.ShadowMapSize / (float)AtlasSize * 0.5f; float leftY = (float)shadowMap.ShadowMapSize / (float)AtlasSize * 0.5f; float centerX = 0.5f * (cascadeTextureCoords.X + cascadeTextureCoords.Z); float centerY = 0.5f * (cascadeTextureCoords.Y + cascadeTextureCoords.W); shadowsViewProj[cascadeLevel] = views[cascadeLevel] * projections[cascadeLevel]; shadowsViewProj[cascadeLevel + 4] = shadowsViewProj[cascadeLevel] * Matrix.Scaling(leftX, -leftY, 0.5f) // Texture0 mapping offsets/scaling * Matrix.Translation(centerX, centerY, 0.5f); var shadowVInverse = Matrix.Invert(views[cascadeLevel]); shadowOffsets[cascadeLevel] = new Vector3(shadowVInverse.M41, shadowVInverse.M42, shadowVInverse.M43); } result.LightColor = lightColor; unsafe { fixed (Matrix* resultPtr = &result.ViewProjCaster0) Utilities.Write((IntPtr)resultPtr, shadowsViewProj, 0, shadowsViewProj.Length); fixed (Vector3* resultPtr = &result.Offset0) Utilities.Write((IntPtr)resultPtr, shadowOffsets, 0, shadowOffsets.Length); } }); shadowMap.Parameters.SetDefault(LightKeys.LightDirection); shadowMap.Parameters.SetDefault(Offsets); shadowMap.Parameters.SetDefault(ViewProjectionArray); shadowMap.Parameters.AddDynamic(ViewProjectionArray, dynamicViewProjectionArray); shadowMap.CasterParameters.Set(EffectPlugin.RasterizerStateKey, null); shadowMap.Texture = shadowMap.Filter is ShadowMapFilterVsm ? ShadowMapVsm : ShadowMapDepth.Texture; }
public void SetShadowMapping(ShadowMap shadow) { if (_epDoShadowMapping == null) return; //this effect cannot do shadow mapping if (shadow != null) { _epDoShadowMapping.SetValue(true); _epShadowMap.SetResource(shadow.ShadowDepthTarget); _epShadowViewProjection.SetValue(shadow.Camera.View*shadow.Camera.Projection); _epShadowMult.SetValue(shadow.ShadowMult); } else { _epShadowMap.SetResource((Texture2D)null); _epDoShadowMapping.SetValue(false); } }
public static async Task Run(EngineContext engineContext) { var renderingSetup = RenderingSetup.Singleton; renderingSetup.Initialize(engineContext); renderingSetup.RegisterLighting(engineContext); #if XENKO_YEBIS YebisPlugin yebisPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin)) { yebisPlugin.Glare.Enable = true; yebisPlugin.ToneMap.Exposure = 1.0f; yebisPlugin.ToneMap.Gamma = 2.2f; } #endif var lightPrepassPlugin = (LightingPrepassPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPrepassPlugin"); var gbufferPlugin = (GBufferPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GBufferPlugin"); EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleCube") .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("AlbedoSpecularBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("AlbedoDiffuseBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("NormalVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("SpecularPowerPerMesh") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("PositionVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("BRDFDiffuseLambert") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream")) }) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColorSynthetic")) }) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new GBufferShaderPlugin { RenderPassPlugin = gbufferPlugin }) .Using(new DeferredLightingShaderPlugin() { RenderPassPlugin = lightPrepassPlugin }) .Using(new LightingShaderPlugin() { RenderPassPlugin = (LightingPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPlugin") }) .Using(new BasicShaderPlugin("LightDirectionalShading") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) ; var shadowMap1 = new ShadowMap(new DirectionalLight() { LightColor = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(1.0f, 1.0f, 1.0f) }); effect.Permutations.Set(ShadowMapPermutationArray.Key, new ShadowMapPermutationArray { ShadowMaps = { shadowMap1 } }); var r = new Random(0); VirtualFileSystem.MountFileSystem("/global_data", "..\\..\\deps\\data\\"); VirtualFileSystem.MountFileSystem("/global_data2", "..\\..\\data\\"); SkyBoxPlugin skyBoxPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("SkyBoxPlugin", out skyBoxPlugin)) { var skyBoxTexture = (Texture2D)await engineContext.AssetManager.LoadAsync <Texture>("/global_data/gdc_demo/bg/GDC2012_map_sky.dds"); skyBoxPlugin.Texture = skyBoxTexture; } var effectMeshGroup = new RenderPassListEnumerator(); engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup); var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(10000, 10000, 1, Color.White)); groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effectMeshGroup.AddMesh(groundMesh); groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new Vector3(0, 0, 0))); // Lights for (int i = 0; i < 1024; ++i) { Color3 color = (Color3)Color.White; switch (i % 4) { case 0: color = (Color3)Color.DarkOrange; break; case 1: color = (Color3)Color.DarkGoldenrod; break; case 2: color = (Color3)Color.DarkSalmon; break; case 3: color = (Color3)Color.DarkRed; break; } var effectMesh = new EffectMesh(lightPrepassPlugin.Lights); effectMesh.Parameters.Set(LightKeys.LightRadius, (float)r.NextDouble() * 200 + 200.0f); effectMesh.Parameters.Set(LightKeys.LightColor, color); effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effectMeshGroup.AddMesh(effectMesh); } EffectOld effectLight = lightPrepassPlugin.Lights; var lightInfo = new LightInfo[effectLight != null ? effectLight.Meshes.Count : 0]; for (int i = 0; i < lightInfo.Length; ++i) { lightInfo[i].Radius = (float)r.NextDouble() * 7000.0f + 500.0f; lightInfo[i].Phase = (float)(r.NextDouble() * Math.PI * 2.0); lightInfo[i].Z = (float)r.NextDouble() * 3000.0f;; } float time = 0.0f; // Meshes (quad) that will later be generated by the engine (light pre pass, SSAO, etc...) // Lights //var effectMesh = new EffectMesh(setup.LightingPrepassPlugin.Lights); //effectMesh.Parameters.Set(LightKeys.LightRadius, 1000.0f); //effectMesh.Parameters.Set(LightKeys.LightColor, new R32G32B32_Float(1.0f, 1.0f, 1.0f)); //effectMesh.Parameters.Set(LightKeys.LightPosition, new R32G32B32_Float(0, 0, 1200)); //effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); //effectMeshGroup.AddMesh(effectMesh); //var boxMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(300, R8G8B8A8.LightBlue)); //boxMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); //boxMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new R32G32B32_Float(0, 0, 200))); //effectMeshGroup.AddMesh(boxMesh); var clock = new Stopwatch(); clock.Start(); int sizeX = 10; int sizeY = 10; var spheres = new Sphere[sizeY, sizeX]; Random random = new Random(0); int size = 200; var meshData = MeshDataHelper.CreateSphere(size, 30, 30, Color.Gray); for (int iy = 0; iy < sizeY; iy++) { for (int ix = 0; ix < sizeX; ix++) { var sphere = new Sphere(); sphere.Mesh = new EffectMesh(effect, meshData); sphere.Phase = (float)random.NextDouble(); sphere.Speed = (float)random.NextDouble(); spheres[iy, ix] = sphere; effectMeshGroup.AddMesh(sphere.Mesh); } } while (true) { await Scheduler.Current.NextFrame(); for (int iy = 0; iy < sizeY; iy++) { for (int ix = 0; ix < sizeX; ix++) { var iFactor = (float)(iy * sizeY + ix) / (sizeX * sizeY); var sphere = spheres[iy, ix]; var sphereMesh = sphere.Mesh; var specularColor = Color.SmoothStep(Color.GreenYellow, Color.Gray, iFactor); // Matrix.RotationX((float)Math.PI/2.0f) * M sphereMesh.Parameters.Set( TransformationKeys.World, Matrix.Translation( new Vector3( (ix - sizeX / 2) * (size * 1.2f) * 2.0f, (iy - sizeY / 2) * (size * 1.2f) * 2.0f, (float)(2000 * (0.5 + 0.5 * Math.Sin(clock.ElapsedMilliseconds / 1000.0f * sphere.Speed * 0.5f + Math.PI * sphere.Phase)))))); sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, iFactor * 0.9f); sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, specularColor); } } time = clock.ElapsedMilliseconds / 1000.0f; if (lightInfo.Length > 0) { int index = 0; foreach (var mesh in effectLight.Meshes) { mesh.Parameters.Set(LightKeys.LightPosition, new Vector3(lightInfo[index].Radius * (float)Math.Cos(-time * 0.17f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(-time * 0.05f + lightInfo[index].Phase), lightInfo[index].Z * (0.5f + 0.5f * (float)Math.Sin(-time * 0.1f + lightInfo[index].Phase * 2.0f)))); index++; } } } }
private ShadowMapTexture AllocateOrChooseTexture(ShadowMap newShadowMap, Dictionary<ShadowMapTexture, List<ShadowMap>> shadowMapTextures) { ShadowMapTexture chosenTexture = null; // find best texture foreach (var shadowMapTexture in shadowMapTextures) { var shadowTexture = shadowMapTexture.Key; var shadowMaps = shadowMapTexture.Value; shadowTexture.GuillotinePacker.Clear(shadowTexture.ShadowMapDepthTexture.ViewWidth, shadowTexture.ShadowMapDepthTexture.ViewHeight); var useShadowTexture = true; for (var i = 0; i < shadowMaps.Count && useShadowTexture; ++i) useShadowTexture = shadowTexture.GuillotinePacker.TryInsert(shadowMaps[i].ShadowMapSize, shadowMaps[i].ShadowMapSize, shadowMaps[i].CascadeCount); useShadowTexture = useShadowTexture && shadowTexture.GuillotinePacker.TryInsert(newShadowMap.ShadowMapSize, newShadowMap.ShadowMapSize, newShadowMap.CascadeCount); shadowTexture.GuillotinePacker.Clear(); if (useShadowTexture) { chosenTexture = shadowMapTexture.Key; break; } } if (chosenTexture == null) { // allocate a new texture chosenTexture = new ShadowMapTexture(GraphicsDevice, newShadowMap.Filter, 2048); chosenTexture.GuillotinePacker.Clear(chosenTexture.ShadowMapDepthTexture.ViewWidth, chosenTexture.ShadowMapDepthTexture.ViewHeight); // TODO: choose texture size based on the shadow map. For now throw exception if (!chosenTexture.GuillotinePacker.TryInsert(newShadowMap.ShadowMapSize, newShadowMap.ShadowMapSize, newShadowMap.CascadeCount)) { var message = new StringBuilder(); message.AppendFormat("Unable to allocate shadow map texture. The default size (2048 x 2048) is too small for the shadow map ({0} cascade(s) with size {1}).", newShadowMap.CascadeCount, newShadowMap.ShadowMapSize); throw new Exception(message.ToString()); } chosenTexture.GuillotinePacker.Clear(); InternalShadowMapTextures.Add(chosenTexture); var shadowMaps = new List<ShadowMap> { newShadowMap }; shadowMapTextures.Add(chosenTexture, shadowMaps); } else { shadowMapTextures[chosenTexture].Add(newShadowMap); } return chosenTexture; }
public static async Task Run(EngineContext engineContext) { var renderingSetup = RenderingSetup.Singleton; renderingSetup.Initialize(engineContext); renderingSetup.RegisterLighting(engineContext); #if XENKO_YEBIS YebisPlugin yebisPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin)) { yebisPlugin.Glare.Enable = true; yebisPlugin.ToneMap.Exposure = 1.0f; yebisPlugin.ToneMap.Gamma = 2.2f; } #endif var lightPrepassPlugin = (LightingPrepassPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPrepassPlugin"); var gbufferPlugin = (GBufferPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GBufferPlugin"); EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleCube") .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("AlbedoSpecularBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("AlbedoDiffuseBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("NormalVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("SpecularPowerPerMesh") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("PositionVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("BRDFDiffuseLambert") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream"))}) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColorSynthetic"))}) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new GBufferShaderPlugin { RenderPassPlugin = gbufferPlugin }) .Using(new DeferredLightingShaderPlugin() { RenderPassPlugin = lightPrepassPlugin }) .Using(new LightingShaderPlugin() { RenderPassPlugin = (LightingPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPlugin") }) .Using(new BasicShaderPlugin("LightDirectionalShading") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) ; var shadowMap1 = new ShadowMap(new DirectionalLight() { LightColor = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(1.0f, 1.0f, 1.0f) }); effect.Permutations.Set(ShadowMapPermutationArray.Key, new ShadowMapPermutationArray { ShadowMaps = { shadowMap1 } }); var r = new Random(0); VirtualFileSystem.MountFileSystem("/global_data", "..\\..\\deps\\data\\"); VirtualFileSystem.MountFileSystem("/global_data2", "..\\..\\data\\"); SkyBoxPlugin skyBoxPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("SkyBoxPlugin", out skyBoxPlugin)) { var skyBoxTexture = (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>("/global_data/gdc_demo/bg/GDC2012_map_sky.dds"); skyBoxPlugin.Texture = skyBoxTexture; } var effectMeshGroup = new RenderPassListEnumerator(); engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup); var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(10000, 10000, 1, Color.White)); groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effectMeshGroup.AddMesh(groundMesh); groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new Vector3(0, 0, 0))); // Lights for (int i = 0; i < 1024; ++i) { Color3 color = (Color3)Color.White; switch (i % 4) { case 0: color = (Color3)Color.DarkOrange; break; case 1: color = (Color3)Color.DarkGoldenrod; break; case 2: color = (Color3)Color.DarkSalmon; break; case 3: color = (Color3)Color.DarkRed; break; } var effectMesh = new EffectMesh(lightPrepassPlugin.Lights); effectMesh.Parameters.Set(LightKeys.LightRadius, (float)r.NextDouble() * 200 + 200.0f); effectMesh.Parameters.Set(LightKeys.LightColor, color); effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effectMeshGroup.AddMesh(effectMesh); } EffectOld effectLight = lightPrepassPlugin.Lights; var lightInfo = new LightInfo[effectLight != null ? effectLight.Meshes.Count : 0]; for (int i = 0; i < lightInfo.Length; ++i) { lightInfo[i].Radius = (float)r.NextDouble() * 7000.0f + 500.0f; lightInfo[i].Phase = (float)(r.NextDouble() * Math.PI * 2.0); lightInfo[i].Z = (float)r.NextDouble() * 3000.0f; ; } float time = 0.0f; // Meshes (quad) that will later be generated by the engine (light pre pass, SSAO, etc...) // Lights //var effectMesh = new EffectMesh(setup.LightingPrepassPlugin.Lights); //effectMesh.Parameters.Set(LightKeys.LightRadius, 1000.0f); //effectMesh.Parameters.Set(LightKeys.LightColor, new R32G32B32_Float(1.0f, 1.0f, 1.0f)); //effectMesh.Parameters.Set(LightKeys.LightPosition, new R32G32B32_Float(0, 0, 1200)); //effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); //effectMeshGroup.AddMesh(effectMesh); //var boxMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(300, R8G8B8A8.LightBlue)); //boxMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); //boxMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new R32G32B32_Float(0, 0, 200))); //effectMeshGroup.AddMesh(boxMesh); var clock = new Stopwatch(); clock.Start(); int sizeX = 10; int sizeY = 10; var spheres = new Sphere[sizeY,sizeX]; Random random = new Random(0); int size = 200; var meshData = MeshDataHelper.CreateSphere(size, 30, 30, Color.Gray); for (int iy = 0; iy < sizeY; iy++) { for (int ix = 0; ix < sizeX; ix++) { var sphere = new Sphere(); sphere.Mesh = new EffectMesh(effect, meshData); sphere.Phase = (float)random.NextDouble(); sphere.Speed = (float)random.NextDouble(); spheres[iy, ix] = sphere; effectMeshGroup.AddMesh(sphere.Mesh); } } while (true) { await Scheduler.Current.NextFrame(); for (int iy = 0; iy < sizeY; iy++) { for (int ix = 0; ix < sizeX; ix++) { var iFactor = (float)(iy * sizeY + ix) / (sizeX * sizeY); var sphere = spheres[iy, ix]; var sphereMesh = sphere.Mesh; var specularColor = Color.SmoothStep(Color.GreenYellow, Color.Gray, iFactor); // Matrix.RotationX((float)Math.PI/2.0f) * M sphereMesh.Parameters.Set( TransformationKeys.World, Matrix.Translation( new Vector3( (ix - sizeX / 2) * (size * 1.2f) * 2.0f, (iy - sizeY / 2) * (size * 1.2f) * 2.0f, (float)(2000 * (0.5 + 0.5 * Math.Sin(clock.ElapsedMilliseconds / 1000.0f * sphere.Speed * 0.5f + Math.PI * sphere.Phase)))))); sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, iFactor * 0.9f); sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, specularColor); } } time = clock.ElapsedMilliseconds / 1000.0f; if (lightInfo.Length > 0) { int index = 0; foreach (var mesh in effectLight.Meshes) { mesh.Parameters.Set(LightKeys.LightPosition, new Vector3(lightInfo[index].Radius * (float)Math.Cos(-time * 0.17f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(-time * 0.05f + lightInfo[index].Phase), lightInfo[index].Z * (0.5f + 0.5f * (float)Math.Sin(-time * 0.1f + lightInfo[index].Phase * 2.0f)))); index++; } } } }
protected ShadowMapFilter(ShadowMap shadowMap) { this.shadowMap = shadowMap; }
public static async Task Run(EngineContext engineContext) { var renderingSetup = RenderingSetup.Singleton; renderingSetup.Initialize(engineContext); renderingSetup.RegisterLighting(engineContext); #if PARADOX_YEBIS YebisPlugin yebisPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin)) { yebisPlugin.Glare.Enable = true; yebisPlugin.ToneMap.Exposure = 1.0f; yebisPlugin.ToneMap.Gamma = 2.2f; } #endif EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleCube") .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("AlbedoSpecularBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("AlbedoDiffuseBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("NormalVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("SpecularPowerPerMesh") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("PositionVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("BRDFDiffuseLambert") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream")) }) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColorSynthetic")) }) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new GBufferShaderPlugin { RenderPassPlugin = (GBufferPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GBufferPlugin") }) .Using(new LightingShaderPlugin() { RenderPassPlugin = (LightingPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPlugin") }) .Using(new BasicShaderPlugin("LightDirectionalShading") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) ; var shadowMap1 = new ShadowMap(new DirectionalLight() { LightColor = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(1.0f, 1.0f, 1.0f) }); effect.Permutations.Set(ShadowMapPermutationArray.Key, new ShadowMapPermutationArray { ShadowMaps = { shadowMap1 } }); var r = new Random(0); VirtualFileSystem.MountFileSystem("/global_data", "..\\..\\deps\\data\\"); VirtualFileSystem.MountFileSystem("/global_data2", "..\\..\\data\\"); SkyBoxPlugin skyBoxPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("SkyBoxPlugin", out skyBoxPlugin)) { var skyBoxTexture = (Texture2D)await engineContext.AssetManager.LoadAsync <Texture>("/global_data/gdc_demo/bg/GDC2012_map_sky.dds"); skyBoxPlugin.Texture = skyBoxTexture; } var effectMeshGroup = new RenderPassListEnumerator(); engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup); var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(10000, 10000, 1, Color.White)); groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effectMeshGroup.AddMesh(groundMesh); groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new Vector3(0, 0, 0))); var meshData = MeshDataHelper.CreateSphere(200, 30, 30, Color.Gray); var sphereMesh = new EffectMesh(effect, meshData); sphereMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new Vector3(0, 0, 50))); sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, 0f); sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, Color.White); effectMeshGroup.AddMesh(sphereMesh); //while (true) //{ // await Scheduler.Current.WaitFrame(); // for (int iy = 0; iy < sizeY; iy++) // { // for (int ix = 0; ix < sizeX; ix++) // { // var iFactor = (float)(iy * sizeY + ix) / (sizeX * sizeY); // var sphere = spheres[iy, ix]; // var sphereMesh = sphere.Mesh; // var specularColor = R8G8B8A8.SmoothStep(R8G8B8A8.GreenYellow, R8G8B8A8.Gray, iFactor); // // Matrix.RotationX((float)Math.PI/2.0f) * M // sphereMesh.Parameters.Set( // TransformationKeys.World, // Matrix.Translation( // new R32G32B32_Float( // (ix - sizeX / 2) * (size * 1.2f) * 2.0f, // (iy - sizeY / 2) * (size * 1.2f) * 2.0f, // (float)(2000 * (0.5 + 0.5 * Math.Sin(clock.ElapsedMilliseconds / 1000.0f * sphere.Speed * 0.5f + Math.PI * sphere.Phase)))))); // sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, iFactor * 0.9f); // sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, specularColor); // } // } // time = clock.ElapsedMilliseconds / 1000.0f; // if (lightInfo.Length > 0) // { // int index = 0; // foreach (var mesh in effectLight.Meshes) // { // mesh.Parameters.Set(LightKeys.LightPosition, new R32G32B32_Float(lightInfo[index].Radius * (float)Math.Cos(-time * 0.17f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(-time * 0.05f + lightInfo[index].Phase), lightInfo[index].Z * (0.5f + 0.5f * (float)Math.Sin(-time * 0.1f + lightInfo[index].Phase * 2.0f)))); // index++; // } // } //} }
public ShadowMapPermutation(ShadowMap shadowMap) { ShadowMap = shadowMap; }
public static async Task Run(EngineContext engineContext) { var renderingSetup = RenderingSetup.Singleton; renderingSetup.Initialize(engineContext); renderingSetup.RegisterLighting(engineContext); #if PARADOX_YEBIS YebisPlugin yebisPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("YebisPlugin", out yebisPlugin)) { yebisPlugin.Glare.Enable = true; yebisPlugin.ToneMap.Exposure = 1.0f; yebisPlugin.ToneMap.Gamma = 2.2f; } #endif EffectOld effect = engineContext.RenderContext.BuildEffect("SimpleCube") .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("AlbedoSpecularBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("AlbedoDiffuseBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("NormalVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("SpecularPowerPerMesh") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("PositionVSGBuffer") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("BRDFDiffuseLambert") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("BRDFSpecularBlinnPhong") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream"))}) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColorSynthetic"))}) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new GBufferShaderPlugin { RenderPassPlugin = (GBufferPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("GBufferPlugin") }) .Using(new LightingShaderPlugin() { RenderPassPlugin = (LightingPlugin)engineContext.DataContext.RenderPassPlugins.TryGetValue("LightingPlugin") }) .Using(new BasicShaderPlugin("LightDirectionalShading") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) ; var shadowMap1 = new ShadowMap(new DirectionalLight() { LightColor = new Color3(1.0f, 1.0f, 1.0f), LightDirection = new Vector3(1.0f, 1.0f, 1.0f) }); effect.Permutations.Set(ShadowMapPermutationArray.Key, new ShadowMapPermutationArray { ShadowMaps = { shadowMap1 } }); var r = new Random(0); VirtualFileSystem.MountFileSystem("/global_data", "..\\..\\deps\\data\\"); VirtualFileSystem.MountFileSystem("/global_data2", "..\\..\\data\\"); SkyBoxPlugin skyBoxPlugin; if (engineContext.DataContext.RenderPassPlugins.TryGetValueCast("SkyBoxPlugin", out skyBoxPlugin)) { var skyBoxTexture = (Texture2D)await engineContext.AssetManager.LoadAsync<Texture>("/global_data/gdc_demo/bg/GDC2012_map_sky.dds"); skyBoxPlugin.Texture = skyBoxTexture; } var effectMeshGroup = new RenderPassListEnumerator(); engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup); var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(10000, 10000, 1, Color.White)); groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effectMeshGroup.AddMesh(groundMesh); groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(new Vector3(0, 0, 0))); var meshData = MeshDataHelper.CreateSphere(200, 30, 30, Color.Gray); var sphereMesh = new EffectMesh(effect, meshData); sphereMesh.Parameters.Set(TransformationKeys.World,Matrix.Translation(new Vector3(0, 0, 50))); sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, 0f); sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, Color.White); effectMeshGroup.AddMesh(sphereMesh); //while (true) //{ // await Scheduler.Current.WaitFrame(); // for (int iy = 0; iy < sizeY; iy++) // { // for (int ix = 0; ix < sizeX; ix++) // { // var iFactor = (float)(iy * sizeY + ix) / (sizeX * sizeY); // var sphere = spheres[iy, ix]; // var sphereMesh = sphere.Mesh; // var specularColor = R8G8B8A8.SmoothStep(R8G8B8A8.GreenYellow, R8G8B8A8.Gray, iFactor); // // Matrix.RotationX((float)Math.PI/2.0f) * M // sphereMesh.Parameters.Set( // TransformationKeys.World, // Matrix.Translation( // new R32G32B32_Float( // (ix - sizeX / 2) * (size * 1.2f) * 2.0f, // (iy - sizeY / 2) * (size * 1.2f) * 2.0f, // (float)(2000 * (0.5 + 0.5 * Math.Sin(clock.ElapsedMilliseconds / 1000.0f * sphere.Speed * 0.5f + Math.PI * sphere.Phase)))))); // sphereMesh.Parameters.Set(MaterialKeys.SpecularPower, iFactor * 0.9f); // sphereMesh.Parameters.Set(MaterialKeys.SpecularColor, specularColor); // } // } // time = clock.ElapsedMilliseconds / 1000.0f; // if (lightInfo.Length > 0) // { // int index = 0; // foreach (var mesh in effectLight.Meshes) // { // mesh.Parameters.Set(LightKeys.LightPosition, new R32G32B32_Float(lightInfo[index].Radius * (float)Math.Cos(-time * 0.17f + lightInfo[index].Phase), lightInfo[index].Radius * (float)Math.Sin(-time * 0.05f + lightInfo[index].Phase), lightInfo[index].Z * (0.5f + 0.5f * (float)Math.Sin(-time * 0.1f + lightInfo[index].Phase * 2.0f)))); // index++; // } // } //} }
protected override void CreateShadowMap(EntityLightShadow light) { var shadowMapDesc = (LightShadowMap)light.Light.Shadow; // create the shadow map var shadowMap = new ShadowMap { LightDirection = light.Light.Direction, ShadowMapSize = shadowMapDesc.MinSize, ShadowNearDistance = shadowMapDesc.NearDistance, ShadowFarDistance = shadowMapDesc.FarDistance, CascadeCount = shadowMapDesc.CascadeCount, Filter = shadowMapDesc.FilterType, Layers = light.Light.Layers }; InternalShadowMaps.Add(shadowMap); light.ShadowMap = shadowMap; }
public ShadowMapFilterDefault(ShadowMap shadowMap) : base(shadowMap) { }
public void RemoveShadowMap(ShadowMap shadowMap) { shadowMaps.Remove(shadowMap); RenderPass.Passes.RemoveAll(shadowMap.Passes.Contains); }
public static async Task Run(EngineContext engineContext) { var renderingSetup = RenderingSetup.Singleton; //engineContext.RenderContext.Register(renderingSetup.LightingPlugin); //renderingSetup.RegisterLighting(engineContext); var shadowMapPlugin = new LightingPlugin { MainPlugin = renderingSetup.MainPlugin, RenderPass = engineContext.DataContext.RenderPasses.TryGetValue("ShadowMapPass") }; shadowMapPlugin.RenderContext = engineContext.RenderContext; var shadowMap1 = new ShadowMap(new DirectionalLight()) { Level = CascadeShadowMapLevel.X1, ShadowMapSize = 1024, ShadowDistance = 2000.0f } .SetFilter(sm => new ShadowMapFilterDefault(sm)); var shadowMap2 = new ShadowMap(new DirectionalLight()) { Level = CascadeShadowMapLevel.X2, ShadowMapSize = 1024, ShadowDistance = 2000.0f } .SetFilter(sm => new ShadowMapFilterVsm(sm)); shadowMapPlugin.AddShadowMap(shadowMap1); shadowMapPlugin.AddShadowMap(shadowMap2); shadowMap1.DirectionalLight.LightDirection = new Vector3(-1.0f, -1.0f, -1.0f); shadowMap1.DirectionalLight.LightColor = new Color3(1.0f, 0.5f, 0.5f); shadowMap2.DirectionalLight.LightDirection = new Vector3(-1.0f, 1.0f, -1.0f); shadowMap2.DirectionalLight.LightColor = new Color3(0.5f, 0.5f, 1.0f); engineContext.RenderContext.Register(shadowMapPlugin); EffectOld effect = engineContext.RenderContext.BuildEffect("Permutation") .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { "NormalVSStream", "PositionVSStream", new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream")), new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")), // TODO: Default values! "BRDFDiffuseLambert", "BRDFSpecularBlinnPhong", "ShadingBase", }) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new LightingShaderPlugin() { RenderPassPlugin = shadowMapPlugin }) ; var sphereMeshData = MeshDataHelper.CreateSphere(10.0f, 20, 20, Color.White); var effectMeshGroup = new RenderPassListEnumerator(); engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup); int objectSqrtCount = 1; int meshCount = objectSqrtCount * objectSqrtCount * objectSqrtCount; var shadowMapPermutation1 = new ShadowMapPermutationArray { ShadowMaps = { shadowMap1 } }; var shadowMapPermutation2 = new ShadowMapPermutationArray { ShadowMaps = { shadowMap2 } }; var shadowMapPermutation3 = new ShadowMapPermutationArray { ShadowMaps = { shadowMap1, shadowMap2 } }; effect.Permutations.Set(ShadowMapPermutationArray.Key, shadowMapPermutation1); var groups2 = new[] { shadowMapPermutation1, shadowMapPermutation2, shadowMapPermutation3 }; int groupIndex2 = 0; var effectMeshes = new List<EffectMesh>(); for (int j = 0; j < meshCount; ++j) { var effectMesh = new EffectMesh(effect, sphereMeshData); effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effect.Permutations.Set(ShadowMapPermutationArray.Key, groups2[2]); var w2 = Matrix.Scaling(1.0f) * Matrix.Translation(new Vector3( (j % objectSqrtCount - objectSqrtCount / 2) * 30.0f - 30.0f, (((j / objectSqrtCount) % objectSqrtCount) - objectSqrtCount / 2) * 30.0f - 30.0f, (j / (objectSqrtCount * objectSqrtCount)) * 30.0f + 30.0f)); effectMesh.Parameters.Set(TransformationKeys.World, w2); effectMeshes.Add(effectMesh); } var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(1000, 1000, 1, Color.White)); groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effectMeshGroup.AddMesh(groundMesh); groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(0.0f, 0.0f, 0.0f)); var groups = new[] { new int[] { 0, 1 }, new int[] { 0 }, new int[] { 1 } }; int groupIndex = 0; await TaskEx.Delay(1000); foreach (var effectMesh in effectMeshes) effectMeshGroup.AddMesh(effectMesh); while (true) { await engineContext.Scheduler.NextFrame(); if (engineContext.InputManager.IsKeyPressed(Keys.F8)) { var permutation = new LightingPermutation { LightBindings = { new Light() } }; effect.Permutations.Set(LightingPermutation.Key, permutation); } if (engineContext.InputManager.IsKeyPressed(Keys.F9)) { effect.Permutations.Set(ShadowMapPermutationArray.Key, groups2[(groupIndex2++) % groups2.Length]); } } }
public static async Task Run(EngineContext engineContext) { var renderingSetup = RenderingSetup.Singleton; //engineContext.RenderContext.Register(renderingSetup.LightingPlugin); //renderingSetup.RegisterLighting(engineContext); var shadowMapPlugin = new LightingPlugin { MainPlugin = renderingSetup.MainPlugin, RenderPass = engineContext.DataContext.RenderPasses.TryGetValue("ShadowMapPass") }; shadowMapPlugin.RenderContext = engineContext.RenderContext; var shadowMap1 = new ShadowMap(new DirectionalLight()) { Level = CascadeShadowMapLevel.X1, ShadowMapSize = 1024, ShadowDistance = 2000.0f } .SetFilter(sm => new ShadowMapFilterDefault(sm)); var shadowMap2 = new ShadowMap(new DirectionalLight()) { Level = CascadeShadowMapLevel.X2, ShadowMapSize = 1024, ShadowDistance = 2000.0f } .SetFilter(sm => new ShadowMapFilterVsm(sm)); shadowMapPlugin.AddShadowMap(shadowMap1); shadowMapPlugin.AddShadowMap(shadowMap2); shadowMap1.DirectionalLight.LightDirection = new Vector3(-1.0f, -1.0f, -1.0f); shadowMap1.DirectionalLight.LightColor = new Color3(1.0f, 0.5f, 0.5f); shadowMap2.DirectionalLight.LightDirection = new Vector3(-1.0f, 1.0f, -1.0f); shadowMap2.DirectionalLight.LightColor = new Color3(0.5f, 0.5f, 1.0f); engineContext.RenderContext.Register(shadowMapPlugin); EffectOld effect = engineContext.RenderContext.BuildEffect("Permutation") .Using(new BasicShaderPlugin("ShaderBase") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin("TransformationWVP") { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new BasicShaderPlugin(new ShaderMixinSource() { "NormalVSStream", "PositionVSStream", new ShaderComposition("albedoDiffuse", new ShaderClassSource("ComputeColorStream")), new ShaderComposition("albedoSpecular", new ShaderClassSource("ComputeColor")), // TODO: Default values! "BRDFDiffuseLambert", "BRDFSpecularBlinnPhong", "ShadingBase", }) { RenderPassPlugin = renderingSetup.MainTargetPlugin }) .Using(new LightingShaderPlugin() { RenderPassPlugin = shadowMapPlugin }) ; var sphereMeshData = MeshDataHelper.CreateSphere(10.0f, 20, 20, Color.White); var effectMeshGroup = new RenderPassListEnumerator(); engineContext.RenderContext.RenderPassEnumerators.Add(effectMeshGroup); int objectSqrtCount = 1; int meshCount = objectSqrtCount * objectSqrtCount * objectSqrtCount; var shadowMapPermutation1 = new ShadowMapPermutationArray { ShadowMaps = { shadowMap1 } }; var shadowMapPermutation2 = new ShadowMapPermutationArray { ShadowMaps = { shadowMap2 } }; var shadowMapPermutation3 = new ShadowMapPermutationArray { ShadowMaps = { shadowMap1, shadowMap2 } }; effect.Permutations.Set(ShadowMapPermutationArray.Key, shadowMapPermutation1); var groups2 = new[] { shadowMapPermutation1, shadowMapPermutation2, shadowMapPermutation3 }; int groupIndex2 = 0; var effectMeshes = new List <EffectMesh>(); for (int j = 0; j < meshCount; ++j) { var effectMesh = new EffectMesh(effect, sphereMeshData); effectMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effect.Permutations.Set(ShadowMapPermutationArray.Key, groups2[2]); var w2 = Matrix.Scaling(1.0f) * Matrix.Translation(new Vector3( (j % objectSqrtCount - objectSqrtCount / 2) * 30.0f - 30.0f, (((j / objectSqrtCount) % objectSqrtCount) - objectSqrtCount / 2) * 30.0f - 30.0f, (j / (objectSqrtCount * objectSqrtCount)) * 30.0f + 30.0f)); effectMesh.Parameters.Set(TransformationKeys.World, w2); effectMeshes.Add(effectMesh); } var groundMesh = new EffectMesh(effect, MeshDataHelper.CreateBox(1000, 1000, 1, Color.White)); groundMesh.KeepAliveBy(engineContext.SimpleComponentRegistry); effectMeshGroup.AddMesh(groundMesh); groundMesh.Parameters.Set(TransformationKeys.World, Matrix.Translation(0.0f, 0.0f, 0.0f)); var groups = new[] { new int[] { 0, 1 }, new int[] { 0 }, new int[] { 1 } }; int groupIndex = 0; await TaskEx.Delay(1000); foreach (var effectMesh in effectMeshes) { effectMeshGroup.AddMesh(effectMesh); } while (true) { await engineContext.Scheduler.NextFrame(); if (engineContext.InputManager.IsKeyPressed(Keys.F8)) { var permutation = new LightingPermutation { LightBindings = { new Light() } }; effect.Permutations.Set(LightingPermutation.Key, permutation); } if (engineContext.InputManager.IsKeyPressed(Keys.F9)) { effect.Permutations.Set(ShadowMapPermutationArray.Key, groups2[(groupIndex2++) % groups2.Length]); } } }
public void Initialize() { //---------------------------------------------------------------- // グラフィックス設定 GraphicsSettings = LoadAsset <GraphicsSettings>("title:Resources/GraphicsSettings.json"); //---------------------------------------------------------------- // シーン設定 // TODO: ワールド設定としてどうするか再検討。 // いずれにせよ、SceneSettings はワールド設定と一対一。 SceneSettings = LoadAsset <SceneSettings>("title:Resources/SceneSettings.json"); //---------------------------------------------------------------- // シーン マネージャ設定 // TODO: リソースから取得する。 SceneManagerSettings = new SceneManager.Settings(); //---------------------------------------------------------------- // シーン マネージャ SceneManager = new SceneManager(SceneManagerSettings, GraphicsDevice); // 太陽と月をディレクショナル ライトとして登録。 SceneManager.DirectionalLights.Add(SceneSettings.Sunlight); SceneManager.DirectionalLights.Add(SceneSettings.Moonlight); // シャドウ マップ if (GraphicsSettings.ShadowMapEnabled) { var shadowMapEffect = LoadAsset <Effect>("content:Effects/ShadowMap"); var blurEffect = LoadAsset <Effect>("content:Effects/GaussianBlur"); ShadowMap = new ShadowMap(GraphicsDevice, GraphicsSettings.ShadowMap, spriteBatch, shadowMapEffect, blurEffect); SceneManager.ShadowMap = ShadowMap; } // レンズ フレア if (GraphicsSettings.LensFlareEnabled) { var glowSpite = LoadAsset <Texture2D>("content:Textures/LensFlare/Glow"); Texture2D[] flareSprites = { LoadAsset <Texture2D>("content:Textures/LensFlare/Flare1"), LoadAsset <Texture2D>("content:Textures/LensFlare/Flare2"), LoadAsset <Texture2D>("content:Textures/LensFlare/Flare3") }; LensFlare = new LensFlare(GraphicsDevice, spriteBatch, glowSpite, flareSprites); SceneManager.LensFlare = LensFlare; } // スクリーン スペース シャドウ マッピング if (GraphicsSettings.SssmEnabled) { // スクリーン スペース シャドウ マッピング モジュール var shadowSceneEffect = LoadAsset <Effect>("content:Effects/ShadowScene"); var sssmEffect = LoadAsset <Effect>("content:Effects/Sssm"); var blurEffect = LoadAsset <Effect>("content:Effects/GaussianBlur"); Sssm = new Sssm(spriteBatch, GraphicsSettings.ShadowMap, GraphicsSettings.Sssm, shadowSceneEffect, sssmEffect, blurEffect); Sssm.ShadowColor = SceneSettings.ShadowColor; SceneManager.PostProcessors.Add(Sssm); // SSSM は直接的なシャドウ描画を回避しなければならないため明示。 SceneManager.SssmEnabled = true; } // スクリーン スペース アンビエント オクルージョン if (GraphicsSettings.SsaoEnabled) { var normalDepthMapEffect = LoadAsset <Effect>("content:Effects/NormalDepthMap"); var ssaoMapEffect = LoadAsset <Effect>("content:Effects/SsaoMap"); var blurEffect = LoadAsset <Effect>("content:Effects/SsaoMapBlur"); var ssaoEffect = LoadAsset <Effect>("content:Effects/Ssao"); var randomNormalMap = LoadAsset <Texture2D>("content:Textures/RandomNormal"); Ssao = new Ssao(spriteBatch, GraphicsSettings.Ssao, normalDepthMapEffect, ssaoMapEffect, blurEffect, ssaoEffect, randomNormalMap); SceneManager.PostProcessors.Add(Ssao); } // エッジ強調 if (GraphicsSettings.EdgeEnabled) { var normalDepthMapEffect = LoadAsset <Effect>("content:Effects/NormalDepthMap"); var edgeEffect = LoadAsset <Effect>("content:Effects/Edge"); Edge = new Edge(spriteBatch, GraphicsSettings.Edge, normalDepthMapEffect, edgeEffect); SceneManager.PostProcessors.Add(Edge); } // ブルーム if (GraphicsSettings.BloomEnabled) { var bloomExtractEffect = LoadAsset <Effect>("content:Effects/BloomExtract"); var bloomEffect = LoadAsset <Effect>("content:Effects/Bloom"); var blurEffect = LoadAsset <Effect>("content:Effects/GaussianBlur"); Bloom = new Bloom(spriteBatch, GraphicsSettings.Bloom, bloomExtractEffect, bloomEffect, blurEffect); SceneManager.PostProcessors.Add(Bloom); } // 被写界深度 if (GraphicsSettings.DofEnabled) { var depthMapEffect = LoadAsset <Effect>("content:Effects/DepthMap"); var dofEffect = LoadAsset <Effect>("content:Effects/Dof"); var blurEffect = LoadAsset <Effect>("content:Effects/GaussianBlur"); Dof = new Dof(spriteBatch, GraphicsSettings.Dof, depthMapEffect, dofEffect, blurEffect); SceneManager.PostProcessors.Add(Dof); } // カラー オーバラップ if (GraphicsSettings.ColorOverlapEnabled) { ColorOverlap = new ColorOverlap(spriteBatch); SceneManager.PostProcessors.Add(ColorOverlap); } // モノクローム if (GraphicsSettings.MonochromeEnabled) { var monochromeEffect = LoadAsset <Effect>("content:Effects/Monochrome"); Monochrome = new Monochrome(spriteBatch, monochromeEffect); SceneManager.PostProcessors.Add(Monochrome); } // 走査線 if (GraphicsSettings.ScanlineEnabled) { var effect = LoadAsset <Effect>("content:Effects/Scanline"); Scanline = new Scanline(spriteBatch, effect); SceneManager.PostProcessors.Add(Scanline); } //---------------------------------------------------------------- // リージョン マネージャ RegionManager = new RegionManager(serviceProvider, SceneManager); RegionManager.Initialize(SceneSettings); // イベント ハンドラ // シャドウ マップ更新にあわせて、リージョン マネージャで管理しているエフェクトを準備する。 SceneManager.ShadowMapUpdated += RegionManager.OnShadowMapUpdated; //---------------------------------------------------------------- // チャンク マネージャ var chunkSettings = LoadAsset <ChunkSettings>("title:Resources/ChunkSettings.json"); ChunkManager = new ChunkManager(chunkSettings, GraphicsDevice, RegionManager, SceneManager); //---------------------------------------------------------------- // デフォルト カメラ //camera.View.Position = new Vector3(0, 16 * 18, 0); defaultCamera.View.Position = new Vector3(0, 16 * 16, 0); //camera.View.Position = new Vector3(0, 16 * 3, 0); //camera.View.Position = new Vector3(0, 16 * 2, 0); //defaultCamera.Projection.Fov = MathHelper.ToRadians(90); defaultCamera.Projection.AspectRatio = GraphicsDevice.Viewport.AspectRatio; // 最大アクティブ範囲を超えない位置へ FarPlaneDistance を設定。 // パーティション (チャンク) のサイズを掛けておく。 var minChunkSize = Math.Min(chunkSettings.ChunkSize.X, chunkSettings.ChunkSize.Y); minChunkSize = Math.Min(minChunkSize, chunkSettings.ChunkSize.Z); defaultCamera.Projection.FarPlaneDistance = (chunkSettings.MaxActiveVolume - 1) * minChunkSize; // 念のためここで一度更新。 defaultCamera.Update(); // シーン マネージャへ登録してアクティブ化。 SceneManager.Cameras.Add(defaultCamera); SceneManager.ActiveCameraName = defaultCamera.Name; }
public override bool Init() { if (!base.Init()) { return(false); } Effects.InitAll(Device); InputLayouts.InitAll(Device); RenderStates.InitAll(Device); Patch.InitPatchData(Terrain.CellsPerPatch, Device); _sky = new Sky(Device, "Textures/grasscube1024.dds", 5000.0f); var tii = new InitInfo { HeightMapFilename = null, LayerMapFilename0 = "textures/grass.dds", LayerMapFilename1 = "textures/darkdirt.dds", LayerMapFilename2 = "textures/stone.dds", LayerMapFilename3 = "Textures/lightdirt.dds", LayerMapFilename4 = "textures/snow.dds", BlendMapFilename = null, HeightScale = 50.0f, HeightMapWidth = 2049, HeightMapHeight = 2049, CellSpacing = 0.5f, Seed = 0, NoiseSize1 = 3.0f, Persistence1 = 0.7f, Octaves1 = 7, NoiseSize2 = 2.5f, Persistence2 = 0.8f, Octaves2 = 3, }; _terrain = new Terrain(); //_terrain.DebugQuadTree = true; _terrain.Init(Device, ImmediateContext, tii); _camera.Height = _terrain.Height; _camera.SetLens(0.25f * MathF.PI, AspectRatio, 1.0f, 1000.0f); _ssao = new Ssao(Device, ImmediateContext, ClientWidth, ClientHeight, _camera.FovY, _camera.FarZ); _whiteTex = ShaderResourceView.FromFile(Device, "Textures/white.dds"); _sMap = new ShadowMap(Device, SMapSize, SMapSize); _sceneBounds = new BoundingSphere(new Vector3(), MathF.Sqrt(_terrain.Width * _terrain.Width + _terrain.Depth * _terrain.Depth) / 2); _minimap = new Minimap(Device, ImmediateContext, MinimapSize, MinimapSize, _terrain, _camera); _sphereModel = new BasicModel(); _sphereModel.CreateSphere(Device, 0.25f, 10, 10); _sphereModel.Materials[0] = new Material { Ambient = Color.Red, Diffuse = Color.Red, Specular = new Color4(32, 1.0f, 1.0f, 1.0f) }; _sphereModel.DiffuseMapSRV[0] = _whiteTex; _sphere = new BasicModelInstance(_sphereModel); _spherePos = new Vector3(float.MaxValue); _path = null; return(true); }
protected override bool draw(Camera camera, DrawingReason drawingReason, ShadowMap shadowMap) { //if (camera.BoundingFrustum.Intersects(ref _boundingSphere)) // return false; var anyPartIsVisible = _slices.Aggregate(false, (current, slice) => current | (slice.Visible = camera.BoundingFrustum.Contains(slice.BoundingSphere) != ContainmentType.Disjoint)); if (!anyPartIsVisible) return false; for (var i = 0; i < 9; i++) Effect.Parameters["Texture" + (char) (48 + i)].SetResource(Textures[i]); Effect.Parameters["HeightsMap"].SetResource(HeightsMap); Effect.Parameters["NormalsMap"].SetResource(NormalsMap); Effect.Parameters["WeightsMap"].SetResource(WeightsMap); camera.UpdateEffect(Effect); foreach (var slice in _slices.Where(slice => slice.Visible)) { Effect.Parameters["TexOffsetAndScale"].SetValue(slice.TexOffsetAndScale); TerrainPlane.Draw(camera, slice.World, drawingReason); //DrawableBox.World = slice.World * Matrix.Translation(0,10,0); //DrawableBox.Draw(camera, drawingReason, shadowMap); } return true; }
public ShadowMapFilterVsm(ShadowMap shadowMap) : base(shadowMap) { MinVariance = 0.0000001f; BleedingFactor = 0.38f; }