protected color Sprite(float player, data d, unit u, vec2 pos, float frame, TextureSampler Texture, float selection_blend, float selection_size, bool solid_blend_flag, float solid_blend) { if (pos.x > 1 || pos.y > 1 || pos.x < 0 || pos.y < 0) { return(color.TransparentBlack); } bool draw_selected = u.player == player && fake_selected(d) && pos.y > selection_size; pos.x += floor(frame); pos.y += Dir.Num(d) + 4 * Player.Num(u) + 4 * 4 * UnitType.UnitIndex(u); pos *= UnitSpriteSheet.SpriteSize; var clr = Texture[pos]; //if (draw_selected) //{ // float a = clr.a * selection_blend; // clr = a * clr + (1 - a) * SelectedUnitColor.Get(u.player); //} if (solid_blend_flag) { clr = solid_blend * clr + (1 - solid_blend) * SolidColor(player, d, u); } return(clr); }
protected color ShadowSprite(float player, data d, unit u, vec2 pos, TextureSampler Texture, float selection_blend, float selection_size, bool solid_blend_flag, float solid_blend) { if (pos.x > 1 || pos.y > 1 || pos.x < 0 || pos.y < 0) { return(color.TransparentBlack); } //bool draw_selected = u.player == player && show_selected(d) && pos.y > selection_size; bool draw_selected = u.player == player && fake_selected(d); var clr = Texture[pos]; if (draw_selected) { if (clr.a > 0) { float a = clr.a; clr = SelectedUnitColor.Get(u.player); clr.a = a; } //float a = clr.a * selection_blend; //clr = a * clr + (1 - a) * SelectedUnitColor.Get(u.player); } //if (solid_blend_flag) //{ // clr = solid_blend * clr + (1 - solid_blend) * SolidColor(player, d, u); //} return(clr); }
public TextureSampler SetSampler(int index, Bitmap texture) { var sampler = TextureSampler.Create(texture); _samplers[index] = sampler; return(sampler); }
private void LoadEnvMap() { if (mTutorial < 5) { return; } string texturePath = Path.GetFullPath(EnvMapPath); Bitmap image = new Bitmap(Image.FromFile(texturePath)); if (image == null) { return; } var imgData = image.LockBits(new System.DrawingCore.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat); BufferDesc bufferDesc = new BufferDesc() { Width = (uint)image.Width, Height = (uint)image.Height, Format = Format.UByte4, Type = BufferType.Input }; Buffer textureBuffer = new Buffer(OptixContext, bufferDesc); int stride = imgData.Stride; int numChannels = 4; unsafe { byte *src = (byte *)imgData.Scan0.ToPointer(); BufferStream stream = textureBuffer.Map(); for (int h = 0; h < image.Height; h++) { for (int w = 0; w < image.Width; w++) { UByte4 color = new UByte4(src[(image.Height - h - 1) * stride + w * numChannels + 2], src[(image.Height - h - 1) * stride + w * numChannels + 1], src[(image.Height - h - 1) * stride + w * numChannels + 0], 255); stream.Write <UByte4>(color); } } textureBuffer.Unmap(); } image.UnlockBits(imgData); TextureSampler texture = new TextureSampler(OptixContext, TextureSamplerDesc.GetDefault(WrapMode.Repeat)); texture.SetBuffer(textureBuffer); OptixContext["envmap"].Set(texture); }
public static VrmProtobuf.Sampler ToGltf(this TextureSampler src) { return(new VrmProtobuf.Sampler { WrapS = (int)src.WrapS, WrapT = (int)src.WrapT, MinFilter = (int)src.MinFilter, MagFilter = (int)src.MagFilter, }); }
color FragmentShader(VertexOut vertex, TextureSampler <Clamp, Linear> Texture) { color output; output = Texture[vertex.TexCoords]; output *= vertex.Color; output.rgb *= vertex.Color.a; return(output); }
color FragmentShader(VertexOut vertex, TextureSampler <Clamp, Point> Texture, color clr) { color output; output = Texture[vertex.TexCoords]; output *= vertex.Color * clr; output.rgb *= vertex.Color.a; return(output); }
public static glTFTextureSampler ToGltf(this TextureSampler src) { return(new glTFTextureSampler { wrapS = (glWrap)src.WrapS, wrapT = (glWrap)src.WrapT, minFilter = (glFilter)src.MinFilter, magFilter = (glFilter)src.MagFilter, }); }
private void ApplySampler(TextureSampler sampler) { TextureMinFilter minFilter = TypeConverterGL3x.To(sampler.MinificationFilter); TextureMagFilter magFilter = TypeConverterGL3x.To(sampler.MagnificationFilter); TextureWrapMode wrapS = TypeConverterGL3x.To(sampler.WrapS); TextureWrapMode wrapT = TypeConverterGL3x.To(sampler.WrapT); GL.TexParameter(_target, TextureParameterName.TextureMinFilter, (int)minFilter); GL.TexParameter(_target, TextureParameterName.TextureMagFilter, (int)magFilter); GL.TexParameter(_target, TextureParameterName.TextureWrapS, (int)wrapS); GL.TexParameter(_target, TextureParameterName.TextureWrapT, (int)wrapT); }
public VirtualMachine(BytecodeContainer bytecode, int numContexts) { if (bytecode.Shader.Version.ProgramType == ProgramType.PixelShader && numContexts % 4 != 0) { throw new ArgumentOutOfRangeException("numContexts", "numContexts must be a multiple of 4 for pixel shaders."); } _bytecode = bytecode; var instructionTokens = bytecode.Shader.Tokens.OfType <InstructionToken>().ToArray(); var branchingInstructions = ExplicitBranchingRewriter.Rewrite(instructionTokens); var controlFlowGraph = ControlFlowGraph.FromInstructions(branchingInstructions); _executableInstructions = ExecutableInstructionRewriter.Rewrite(controlFlowGraph).ToArray(); _requiredRegisters = RequiredRegisters.FromShader(bytecode.Shader); _executionContexts = new ExecutionContext[numContexts]; for (int i = 0; i < _executionContexts.Length; i++) { _executionContexts[i] = new ExecutionContext(this, i, _requiredRegisters); } ConstantBuffers = new Number4[_requiredRegisters.ConstantBuffers.Count][]; for (int i = 0; i < _requiredRegisters.ConstantBuffers.Count; i++) { ConstantBuffers[i] = new Number4[_requiredRegisters.ConstantBuffers[i]]; } TextureSamplers = new TextureSampler[_requiredRegisters.Resources.Count]; for (int i = 0; i < _requiredRegisters.Resources.Count; i++) { TextureSamplers[i] = TextureSamplerFactory.Create(_requiredRegisters.Resources[i]); } Textures = new ITexture[_requiredRegisters.Resources.Count]; Samplers = new SamplerState[_requiredRegisters.Samplers]; }
//Deferred Renderer Rework - New GBuffer - //32:32:32 WorldPos, (16b:SPARE, 16b:materialIdx) //8:8:8 Norm, 8:SPARE //reproject z buffer and recompute chain for culling public DeferredRenderer(Framebuffer[] fbufs, LightManager man) { lMan = man; InfoBindings = new TextureBinding[fbufs.Length]; InfoBindings2 = new TextureBinding[fbufs.Length]; DepthBindings = new TextureBinding[fbufs.Length]; Framebuffers = new Framebuffer[fbufs.Length]; HiZMap = new TextureView[fbufs.Length][]; views = new ViewData[fbufs.Length]; HiZMapUBO = new UniformBuffer(false); unsafe { int off = 0; float *fp = (float *)HiZMapUBO.Update(); fp += 4; for (int i = 0; i < views.Length; i++) { views[i] = new ViewData() { depthBuf = new Texture() { Width = fbufs[i].Width, Height = fbufs[i].Height, Depth = 1, Format = PixelInternalFormat.DepthComponent32f, GenerateMipmaps = false, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(), infoTex = new Texture() { Width = fbufs[i].Width, Height = fbufs[i].Height, Depth = 1, Format = PixelInternalFormat.Rgba32f, GenerateMipmaps = false, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(), infoTex2 = new Texture() { Width = fbufs[i].Width, Height = fbufs[i].Height, Depth = 1, Format = PixelInternalFormat.Rgba8, GenerateMipmaps = false, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(), hiZ = new Texture() { Width = fbufs[i].Width, Height = fbufs[i].Height, Depth = 1, Format = PixelInternalFormat.Rg32f, GenerateMipmaps = false, LayerCount = 1, LevelCount = (int)(MathHelper.Log2((ulong)Math.Max(fbufs[i].Width, fbufs[i].Height)) + 1), Target = TextureTarget.Texture2D }.Build(), gbuffer = new Framebuffer(fbufs[i].Width, fbufs[i].Height), }; views[i].depthView = new TextureView() { BaseLayer = 0, BaseLevel = 0, Format = PixelInternalFormat.DepthComponent32f, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(views[i].depthBuf); views[i].infoView = new TextureView() { BaseLayer = 0, BaseLevel = 0, Format = PixelInternalFormat.Rgba32f, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(views[i].infoTex); views[i].infoView2 = new TextureView() { BaseLayer = 0, BaseLevel = 0, Format = PixelInternalFormat.Rgba8, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D }.Build(views[i].infoTex2); views[i].hiZView = new TextureView[views[i].hiZ.LevelCount]; for (int j = 0; j < views[i].hiZView.Length; j++) { views[i].hiZView[j] = new TextureView() { BaseLayer = 0, BaseLevel = j, Format = PixelInternalFormat.Rg32f, LayerCount = 1, LevelCount = 1, Target = TextureTarget.Texture2D, }.Build(views[i].hiZ); var f_arr = (float[])views[i].hiZView[j].GetImageHandle().SetResidency(Residency.Resident, AccessMode.ReadWrite); for (int q = 0; q < f_arr.Length; q++) { *(fp++) = f_arr[q]; } fp += 2; } views[i].hiZTex = new TextureView() { BaseLayer = 0, BaseLevel = 0, Format = PixelInternalFormat.Rg32f, LayerCount = 1, LevelCount = views[i].hiZView.Length, Target = TextureTarget.Texture2D }.Build(views[i].hiZ); var sampler = new TextureSampler(); sampler.SetEnableLinearFilter(false, true, false); sampler.MinReadLevel = 0; sampler.MaxReadLevel = views[i].hiZView.Length; sampler.SetTileMode(TileMode.ClampToBorder, TileMode.ClampToBorder); views[i].hiZBinding = new TextureBinding() { View = views[i].hiZTex, Sampler = sampler }; var f_arr_ = (float[])views[i].hiZBinding.GetTextureHandle().SetResidency(Residency.Resident); for (int q = 0; q < f_arr_.Length; q++) { *(fp++) = f_arr_[q]; } fp += 2; views[i].gbuffer[FramebufferAttachment.DepthAttachment] = views[i].depthView; views[i].gbuffer[FramebufferAttachment.ColorAttachment0] = views[i].infoView; views[i].gbuffer[FramebufferAttachment.ColorAttachment1] = views[i].infoView2; Framebuffers[i] = views[i].gbuffer; views[i].program = new ShaderProgram( ShaderSource.Load(ShaderType.VertexShader, "Shaders/RenderToTexture/FrameBufferTriangle/vertex.glsl"), ShaderSource.Load(ShaderType.FragmentShader, "Shaders/RenderToTexture/FrameBufferTriangle/fragment.glsl") ); views[i].copy = new ShaderProgram( ShaderSource.Load(ShaderType.ComputeShader, "Shaders/HiZ/copy.glsl", $"#define MIP_COUNT {views[i].hiZView.Length}") ); views[i].copyState = new RenderState(null, views[i].copy, null, new UniformBuffer[] { Engine.GlobalParameters, HiZMapUBO }, false, false, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.Back); views[i].mipchain = new ShaderProgram( ShaderSource.Load(ShaderType.ComputeShader, "Shaders/HiZ/mipchain.glsl", $"#define MIP_COUNT {views[i].hiZView.Length}") ); views[i].mipchainState = new RenderState(null, views[i].mipchain, null, new UniformBuffer[] { Engine.GlobalParameters, HiZMapUBO }, false, false, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.Back); views[i].state = new RenderState(fbufs[i], views[i].program, null, new UniformBuffer[] { Engine.GlobalParameters }, false, true, DepthFunc.Always, InverseDepth.Far, InverseDepth.Near, BlendFactor.SrcAlpha, BlendFactor.OneMinusSrcAlpha, Vector4.Zero, InverseDepth.ClearDepth, CullFaceMode.None); InfoBindings[i] = new TextureBinding() { View = views[i].infoView, Sampler = TextureSampler.Default }; InfoBindings[i].GetTextureHandle().SetResidency(Residency.Resident); InfoBindings2[i] = new TextureBinding() { View = views[i].infoView2, Sampler = TextureSampler.Default }; InfoBindings2[i].GetTextureHandle().SetResidency(Residency.Resident); DepthBindings[i] = new TextureBinding() { View = views[i].depthView, Sampler = TextureSampler.Default, }; DepthBindings[i].GetTextureHandle().SetResidency(Residency.Resident); HiZMap[i] = views[i].hiZView; views[i].cBuffer = new CommandBuffer(); views[i].cBuffer.SetRenderState(views[i].state); views[i].cBuffer.Draw(PrimitiveType.Triangles, 0, 3, 1, 0); } HiZMapUBO.UpdateDone(); } }
protected override void Initialize() { string rayGenPath = shaderPath; /*----------------------------------------------- * Create the Optix context *-----------------------------------------------*/ OptixContext = new Context(); OptixContext.RayTypeCount = 2; OptixContext.EntryPointCount = 1; OptixContext.SetStackSize(4096); /* Create the ray-generation and exception programs *-----------------------------------------------*/ var rayGen = new OptixProgram(OptixContext, rayGenPath, mTutorial < 11 ? "pinhole_camera" : "env_camera"); var exception = new OptixProgram(OptixContext, rayGenPath, "exception"); var miss = new OptixProgram(OptixContext, rayGenPath, mTutorial < 5 ? "miss" : "envmap_miss"); OptixContext["bg_color"].Set(100 / 255.0f, 149 / 255.0f, 237 / 255.0f); OptixContext["bad_color"].Set(1.0f, 0.0f, 0.0f); OptixContext.SetRayGenerationProgram(0, rayGen); OptixContext.SetExceptionProgram(0, exception); OptixContext.SetRayMissProgram(0, miss); /*----------------------------------------------- * Create lights *-----------------------------------------------*/ BasicLight[] lights = new BasicLight[1]; lights[0].Position = new Vector3(-5.0f, 60.0f, -16.0f); lights[0].Color = new Vector3(1.0f, 1.0f, 1.0f); lights[0].CastsShadow = 1; BufferDesc desc = new BufferDesc() { Width = (uint)lights.Length, Format = Format.User, Type = BufferType.Input, ElemSize = (uint)Marshal.SizeOf(typeof(BasicLight)) }; Buffer lightsBuffer = new Buffer(OptixContext, desc); lightsBuffer.SetData <BasicLight>(lights); OptixContext["lights"].Set(lightsBuffer); /*----------------------------------------------- * Create noise texture *-----------------------------------------------*/ if (mTutorial >= 8) { uint noiseTexDim = 64; desc = new BufferDesc() { Width = noiseTexDim, Height = noiseTexDim, Depth = noiseTexDim, Format = Format.Float, Type = BufferType.Input }; Buffer noiseBuffer = new Buffer(OptixContext, desc); Random rand = new Random(); BufferStream stream = noiseBuffer.Map(); for (int i = 0; i < noiseTexDim * noiseTexDim * noiseTexDim; i++) { stream.Write <float>((float)rand.NextDouble()); } noiseBuffer.Unmap(); TextureSampler noiseTex = new TextureSampler(OptixContext, TextureSamplerDesc.GetDefault(WrapMode.Repeat)); noiseTex.SetBuffer(noiseBuffer); OptixContext["noise_texture"].Set(noiseTex); } /*----------------------------------------------- * Load enivronment map texture *-----------------------------------------------*/ LoadEnvMap(); /*----------------------------------------------- * Load the geometry *-----------------------------------------------*/ CreateGeometry(); /*----------------------------------------------- * Create the output buffer *-----------------------------------------------*/ CreateOutputBuffer(Format.UByte4); OptixContext["output_buffer"].Set(OutputBuffer); /*----------------------------------------------- * Finally compile the optix context, and build the accel tree *-----------------------------------------------*/ SetCamera(); OptixContext["max_depth"].Set(100); OptixContext["radiance_ray_type"].Set(0u); OptixContext["shadow_ray_type"].Set(1u); OptixContext["frame_number"].Set(0u); OptixContext["scene_epsilon"].Set(.001f); OptixContext["importance_cutoff"].Set(0.01f); OptixContext["ambient_light_color"].Set(0.31f, 0.33f, 0.28f); OptixContext.Compile(); OptixContext.BuildAccelTree(); //very loose calculation of number of rays float numSecondaryRays = 0; if (mTutorial >= 9) { numSecondaryRays = 2.5f; //only convex hull casts refraction rays } else if (mTutorial >= 8) { numSecondaryRays = 2; } else if (mTutorial >= 4) { numSecondaryRays = 1.5f; //only the floor casts reflection rays, so give aproximate } else if (mTutorial >= 3) { numSecondaryRays = 1; } RaysTracedPerFrame = (int)(Width * Height * (numSecondaryRays + 1)); }
private static unsafe void MasterThreadStart() { string instDir = Environment.GetCommandLineArgs().Length > 1 ? Environment.GetCommandLineArgs()[1] : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None), @"Egodystonic\Escape Lizards\Inst\"); string dataDir = Environment.GetCommandLineArgs().Length > 2 ? Environment.GetCommandLineArgs()[2] : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.Create), @"Egodystonic\Escape Lizards\Data"); Monitor.Enter(staticMutationLock); LosgapSystem.ApplicationName = "SEL Editor"; LosgapSystem.InstallationDirectory = new DirectoryInfo(instDir); LosgapSystem.MutableDataDirectory = new DirectoryInfo(dataDir); if (!LosgapSystem.IsModuleAdded(typeof(RenderingModule))) { LosgapSystem.AddModule(typeof(RenderingModule)); } if (!LosgapSystem.IsModuleAdded(typeof(InputModule))) { LosgapSystem.AddModule(typeof(InputModule)); } if (!LosgapSystem.IsModuleAdded(typeof(EntityModule))) { LosgapSystem.AddModule(typeof(EntityModule)); } LosgapSystem.MaxThreadCount = 1U; RenderingModule.VSyncEnabled = true; // Just a nice default for an editor I think #region Create window + shaders AssetLocator.MainWindow = new Window("SEL Editor Main Window", (uint)(1920f * 0.75f), (uint)(1080f * 0.75f), WindowFullscreenState.NotFullscreen); AssetLocator.MainWindow.ClearViewports().ForEach(vp => vp.Dispose()); AssetLocator.MainWindow.AddViewport(ViewportAnchoring.Centered, Vector2.ZERO, Vector2.ONE, Config.DisplayWindowNearPlane, Config.DisplayWindowFarPlane); AssetLocator.GameLayer = Scene.CreateLayer("Main Layer"); AssetLocator.SkyLayer = Scene.CreateLayer("Sky Layer"); AssetLocator.HudLayer = Scene.CreateLayer("HUD Layer"); ConstantBuffer <GeomPassProjViewMatrices> vsCameraBuffer = BufferFactory.NewConstantBuffer <GeomPassProjViewMatrices>().WithUsage(ResourceUsage.DiscardWrite); AssetLocator.MainGeometryVertexShader = new VertexShader( Path.Combine(AssetLocator.ShadersDir, "DLGeometryVS.cso"), new VertexInputBinding(0U, "INSTANCE_TRANSFORM"), new ConstantBufferBinding(0U, "CameraTransform", vsCameraBuffer), new VertexInputBinding(1U, "TEXCOORD"), new VertexInputBinding(2U, "POSITION"), new VertexInputBinding(3U, "NORMAL"), new VertexInputBinding(4U, "TANGENT") ); AssetLocator.SkyVertexShader = new VertexShader( Path.Combine(AssetLocator.ShadersDir, "DLGeometryVSSky.cso"), new VertexInputBinding(0U, "INSTANCE_TRANSFORM"), new ConstantBufferBinding(0U, "CameraTransform", vsCameraBuffer), new VertexInputBinding(1U, "TEXCOORD"), new VertexInputBinding(2U, "POSITION"), new VertexInputBinding(3U, "NORMAL"), new VertexInputBinding(4U, "TANGENT") ); ConstantBuffer <Vector4> matPropsBuffer = BufferFactory.NewConstantBuffer <Vector4>().WithUsage(ResourceUsage.DiscardWrite); TextureSampler defaultDiffuseSampler = new TextureSampler( TextureFilterType.Anisotropic, TextureWrapMode.Wrap, AnisotropicFilteringLevel.FourTimes ); TextureSampler shadowSampler = new TextureSampler( TextureFilterType.MinMagMipLinear, TextureWrapMode.Clamp, AnisotropicFilteringLevel.FourTimes ); AssetLocator.GeometryFragmentShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "DLGeometryFS.cso"), new ResourceViewBinding(0U, "DiffuseMap"), new ResourceViewBinding(1U, "NormalMap"), new ResourceViewBinding(2U, "SpecularMap"), new ResourceViewBinding(3U, "EmissiveMap"), new ResourceViewBinding(4U, "ShadowMap"), new TextureSamplerBinding(0U, "DiffuseSampler"), new TextureSamplerBinding(1U, "ShadowSampler"), new ConstantBufferBinding(0U, "MaterialProperties", matPropsBuffer) ); AssetLocator.GeometryFragmentShader.GetBindingByIdentifier("DiffuseSampler").Bind(defaultDiffuseSampler); AssetLocator.GeometryFragmentShader.GetBindingByIdentifier("ShadowSampler").Bind(shadowSampler); AssetLocator.SkyGeometryFragmentShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "DLGeometryFSSky.cso"), new ResourceViewBinding(0U, "DiffuseMap"), new TextureSamplerBinding(0U, "DiffuseSampler"), new ConstantBufferBinding(0U, "MaterialProperties", matPropsBuffer) ); AssetLocator.SkyGeometryFragmentShader.GetBindingByIdentifier("DiffuseSampler").Bind(defaultDiffuseSampler); ConstantBuffer <Vector4> lightVSScalarsBuffer = BufferFactory.NewConstantBuffer <Vector4>().WithUsage(ResourceUsage.DiscardWrite); VertexShader lightVS = new VertexShader( Path.Combine(AssetLocator.ShadersDir, "DLLightingVS.cso"), new VertexInputBinding(0U, "POSITION"), new VertexInputBinding(1U, "TEXCOORD"), new ConstantBufferBinding(0U, "Scalars", lightVSScalarsBuffer) ); ConstantBuffer <Vector4> fsCameraBuffer = BufferFactory.NewConstantBuffer <Vector4>().WithUsage(ResourceUsage.DiscardWrite); ConstantBuffer <Vector4> lightMetaBuffer = BufferFactory.NewConstantBuffer <Vector4>().WithUsage(ResourceUsage.DiscardWrite); FragmentShader lightFS = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "DLLightingFS.cso"), new ResourceViewBinding(0U, "NormalGB"), new ResourceViewBinding(1U, "DiffuseGB"), new ResourceViewBinding(2U, "SpecularGB"), new ResourceViewBinding(3U, "PositionGB"), new ResourceViewBinding(5U, "EmissiveGB"), new ConstantBufferBinding(0U, "CameraProperties", fsCameraBuffer), new ConstantBufferBinding(1U, "LightMeta", lightMetaBuffer), new ResourceViewBinding(4U, "LightBuffer"), new TextureSamplerBinding(0U, "NormalSampler") ); FragmentShader dlFinalizationFS = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "DLFinalFS.cso"), new ResourceViewBinding(1U, "DiffuseGB") ); TextureSampler normalSampler = new TextureSampler( TextureFilterType.Anisotropic, TextureWrapMode.Wrap, AnisotropicFilteringLevel.FourTimes ); Buffer <LightProperties> lightBuffer = BufferFactory.NewBuffer <LightProperties>() .WithLength(DLLightPass.MAX_DYNAMIC_LIGHTS) .WithUsage(ResourceUsage.DiscardWrite) .WithPermittedBindings(GPUBindings.ReadableShaderResource); ShaderBufferResourceView lightBufferView = lightBuffer.CreateView(); ((TextureSamplerBinding)lightFS.GetBindingByIdentifier("NormalSampler")).Bind(normalSampler); ((ResourceViewBinding)lightFS.GetBindingByIdentifier("LightBuffer")).Bind(lightBufferView); FragmentShader outliningShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "Outliner.cso"), new ResourceViewBinding(0U, "NormalGB"), new ResourceViewBinding(1U, "GeomDepthBuffer") ); FragmentShader bloomHShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "BloomH.cso"), new ResourceViewBinding(0U, "PreBloomImage") ); FragmentShader bloomVShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "BloomV.cso"), new ResourceViewBinding(0U, "PreBloomImage") ); FragmentShader glowShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "Glow.cso"), new ResourceViewBinding(0U, "GlowSrc") ); FragmentShader copyShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "Copy.cso"), new ResourceViewBinding(0U, "SourceTex"), new TextureSamplerBinding(0U, "SourceSampler") ); FragmentShader copyReverseShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "CopyReverse.cso"), new ResourceViewBinding(0U, "SourceTex"), new TextureSamplerBinding(0U, "SourceSampler") ); FragmentShader blurShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "Blur.cso"), new ResourceViewBinding(0U, "UnblurredScene") ); ConstantBuffer <Vector4> dofLensPropsBuffer = BufferFactory.NewConstantBuffer <Vector4>() .WithUsage(ResourceUsage.DiscardWrite) .WithInitialData(new Vector4( Config.DisplayWindowNearPlane, Config.DisplayWindowFarPlane, 1000f, 12000f )); FragmentShader dofShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "DoF.cso"), new ResourceViewBinding(0U, "UnblurredScene"), new ResourceViewBinding(1U, "BlurredScene"), new ResourceViewBinding(2U, "SceneDepth"), new TextureSamplerBinding(0U, "SourceSampler"), new ConstantBufferBinding(0U, "LensProperties", dofLensPropsBuffer) ); VertexShader shadowVS = new VertexShader( Path.Combine(AssetLocator.ShadersDir, "ShadowVS.cso"), new VertexInputBinding(0U, "INSTANCE_TRANSFORM"), new ConstantBufferBinding(0U, "CameraTransform", vsCameraBuffer), new VertexInputBinding(1U, "POSITION") ); FragmentShader shadowFS = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "ShadowFS.cso") ); VertexShader unlitVSSky = new VertexShader( Path.Combine(AssetLocator.ShadersDir, "UnlitVSSky.cso"), new VertexInputBinding(0U, "INSTANCE_TRANSFORM"), new ConstantBufferBinding(0U, "CameraTransform", vsCameraBuffer), new VertexInputBinding(1U, "TEXCOORD"), new VertexInputBinding(2U, "POSITION") ); AssetLocator.SkyFragmentShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "UnlitFS.cso"), new TextureSamplerBinding(0U, "DiffuseSampler"), new ResourceViewBinding(0U, "DiffuseMap") ); TextureSampler skyDiffuseSampler = new TextureSampler( TextureFilterType.Anisotropic, TextureWrapMode.Wrap, AnisotropicFilteringLevel.FourTimes ); ((TextureSamplerBinding)AssetLocator.SkyFragmentShader.GetBindingByIdentifier("DiffuseSampler")).Bind(skyDiffuseSampler); ConstantBuffer <Vector4> viewportPropertiesBuffer = BufferFactory.NewConstantBuffer <Vector4>().WithUsage(ResourceUsage.DiscardWrite); VertexShader hudVS = new VertexShader( Path.Combine(AssetLocator.ShadersDir, "HUDVS.cso"), new VertexInputBinding(0U, "INSTANCE_TRANSFORM"), new ConstantBufferBinding(1U, "CameraTransform", vsCameraBuffer), new ConstantBufferBinding(0U, "ViewportProperties", viewportPropertiesBuffer), new VertexInputBinding(1U, "TEXCOORD"), new VertexInputBinding(2U, "POSITION") ); ConstantBuffer <Vector4> hudFSColorBuffer = BufferFactory.NewConstantBuffer <Vector4>().WithUsage(ResourceUsage.DiscardWrite); AssetLocator.HUDFragmentShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "HUDFS.cso"), new ResourceViewBinding(0U, "DiffuseMap"), new TextureSamplerBinding(0U, "DiffuseSampler"), new ConstantBufferBinding(0U, "TextureProperties", hudFSColorBuffer) ); TextureSampler hudFSSampler = new TextureSampler( TextureFilterType.None, TextureWrapMode.Border, AnisotropicFilteringLevel.None, new TexelFormat.RGB32Float() { R = 1f, G = 0f, B = 0f } ); ((TextureSamplerBinding)AssetLocator.HUDFragmentShader.GetBindingByIdentifier("DiffuseSampler")).Bind(hudFSSampler); ConstantBuffer <Vector4> hudFSTextColorBuffer = BufferFactory.NewConstantBuffer <Vector4>().WithUsage(ResourceUsage.DiscardWrite); AssetLocator.HUDTextFragmentShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "HUDFSText.cso"), new ResourceViewBinding(0U, "DiffuseMap"), new TextureSamplerBinding(0U, "DiffuseSampler"), new ConstantBufferBinding(0U, "TextProperties", hudFSTextColorBuffer) ); TextureSampler hudTextSampler = new TextureSampler( TextureFilterType.None, TextureWrapMode.Border, AnisotropicFilteringLevel.None, new TexelFormat.RGB32Float() { R = 1f, G = 0f, B = 0f } ); ((TextureSamplerBinding)AssetLocator.HUDTextFragmentShader.GetBindingByIdentifier("DiffuseSampler")).Bind(hudTextSampler); var simpleFSSampler = new TextureSampler( Config.DefaultSamplingFilterType, TextureWrapMode.Wrap, Config.DefaultSamplingAnisoLevel ); var simpleFSMatPropsBuffer = BufferFactory.NewConstantBuffer <Vector4>().WithUsage(ResourceUsage.DiscardWrite).Create(); AssetLocator.AlphaFragmentShader = new FragmentShader( Path.Combine(AssetLocator.ShadersDir, "SimpleFS.cso"), new TextureSamplerBinding(0U, "DiffuseSampler"), new ResourceViewBinding(0U, "DiffuseMap"), new ConstantBufferBinding(0U, "MaterialProperties", simpleFSMatPropsBuffer) ); ((TextureSamplerBinding)AssetLocator.AlphaFragmentShader.GetBindingByIdentifier("DiffuseSampler")).Bind(simpleFSSampler); #endregion #region Create passes var shadowPass = new ShadowPass("Shadow Pass"); shadowPass.AddLayer(AssetLocator.GameLayer); shadowPass.ShadowVS = shadowVS; shadowPass.ShadowFS = shadowFS; shadowPass.Output = AssetLocator.MainWindow; AssetLocator.MainGeometryPass = new DLGeometryPass("Geometry Pass"); AssetLocator.MainGeometryPass.ClearOutputBeforePass = false; AssetLocator.MainGeometryPass.AddLayer(AssetLocator.GameLayer); AssetLocator.MainGeometryPass.AddLayer(AssetLocator.SkyLayer); AssetLocator.MainGeometryPass.DepthStencilState = new DepthStencilState(); AssetLocator.MainGeometryPass.Output = AssetLocator.MainWindow; AssetLocator.MainGeometryPass.BlendState = new BlendState(BlendOperation.None); AssetLocator.MainGeometryPass.RasterizerState = new RasterizerState(false, TriangleCullMode.BackfaceCulling, false); AssetLocator.MainGeometryPass.ShadowPass = shadowPass; AssetLocator.MainGeometryPass.GeomFSWithShadowSupport = AssetLocator.GeometryFragmentShader; AssetLocator.LightPass = new DLLightPass("Light Pass"); AssetLocator.LightPass.DLLightVertexShader = lightVS; AssetLocator.LightPass.DLLightFragmentShader = lightFS; AssetLocator.LightPass.DLLightFinalizationShader = dlFinalizationFS; AssetLocator.LightPass.BloomHShader = bloomHShader; AssetLocator.LightPass.BloomVShader = bloomVShader; AssetLocator.LightPass.CopyReverseShader = copyReverseShader; AssetLocator.LightPass.CopyShader = copyShader; AssetLocator.LightPass.OutliningShader = outliningShader; AssetLocator.LightPass.BlurShader = blurShader; AssetLocator.LightPass.DoFShader = dofShader; AssetLocator.LightPass.GeometryPass = AssetLocator.MainGeometryPass; AssetLocator.LightPass.PresentAfterPass = false; AssetLocator.LightPass.SetLensProperties(0f, float.MaxValue); HUDPass hudPass = new HUDPass("HUD") { DepthStencilState = new DepthStencilState(false), Input = new Camera(), Output = AssetLocator.MainWindow, PresentAfterPass = true, RasterizerState = new RasterizerState(false, TriangleCullMode.NoCulling, false), VertexShader = hudVS, BlendState = new BlendState(BlendOperation.Additive), GlowShader = glowShader, GlowVS = lightVS, ScaleUpShader = copyReverseShader, ScaleDownShader = copyShader }; hudPass.AddLayer(AssetLocator.HudLayer); ConstantBufferBinding vpPropsBinding = (ConstantBufferBinding)hudVS.GetBindingByIdentifier("ViewportProperties"); hudPass.PrePass += pass => { Vector4 vpSizePx = ((SceneViewport)AssetLocator.MainWindow).SizePixels / 2f; vpPropsBinding.SetValue((byte *)(&vpSizePx)); }; AssetLocator.MainCamera = AssetLocator.MainGeometryPass.Input = new IlluminatingCamera(GameplayConstants.EGG_ILLUMINATION_RADIUS, Vector3.ONE); AssetLocator.ShadowcasterCamera = shadowPass.LightCam = new Camera(); AssetLocator.ShadowcasterCamera.OrthographicDimensions = new Vector3(1000f, 1000f, PhysicsManager.ONE_METRE_SCALED * 100f); RenderingModule.AddRenderPass(shadowPass); RenderingModule.AddRenderPass(AssetLocator.MainGeometryPass); RenderingModule.AddRenderPass(AssetLocator.LightPass); RenderingModule.AddRenderPass(hudPass); #endregion #region HUD AssetLocator.MainFont = Font.Load(Path.Combine(AssetLocator.FontsDir, "mainFont.fnt"), AssetLocator.HUDTextFragmentShader, null, null); AssetLocator.TitleFont = Font.Load(Path.Combine(AssetLocator.FontsDir, "titleFont.fnt"), AssetLocator.HUDTextFragmentShader, null, null); #endregion #region Game Objects GeometryCacheBuilder <DefaultVertex> gameObjectGCB = new GeometryCacheBuilder <DefaultVertex>(); FragmentShader fs = AssetLocator.GeometryFragmentShader; // Load model streams var startFlagModelStream = AssetLoader.LoadModel(Path.Combine(AssetLocator.ModelsDir, "Spawn.obj")); var dynamicLightModelStream = AssetLoader.LoadModel(Path.Combine(AssetLocator.ModelsDir, "Lightbulb.obj")); var introCameraModelStream = AssetLoader.LoadModel(Path.Combine(AssetLocator.ModelsDir, "camera.obj")); var finishingBellModelStream = AssetLoader.LoadModel(Path.Combine(AssetLocator.ModelsDir, "FinishBellBottom.obj")); var vultureEggModelStream = AssetLoader.LoadModel(Path.Combine(AssetLocator.ModelsDir, "Playerball.obj")); var shadowcasterModelStream = AssetLoader.LoadModel(Path.Combine(AssetLocator.ModelsDir, "ScaleArrow.obj")); var coinModelStream = AssetLoader.LoadModel(Path.Combine(AssetLocator.ModelsDir, "LizardCoin.obj")); var finishingBellVerts = finishingBellModelStream.GetVertices <DefaultVertex>(typeof(DefaultVertex).GetConstructor(new[] { typeof(Vector3), typeof(Vector3), typeof(Vector3), typeof(Vector2) })).ToList(); var finishingBellIndices = finishingBellModelStream.GetIndices().ToList(); var vultureEggVerts = vultureEggModelStream.GetVertices <DefaultVertex>(typeof(DefaultVertex).GetConstructor(new[] { typeof(Vector3), typeof(Vector3), typeof(Vector3), typeof(Vector2) })).ToList(); var vultureEggIndices = vultureEggModelStream.GetIndices().ToList(); var coinModelVertices = coinModelStream.GetVertices <DefaultVertex>(typeof(DefaultVertex).GetConstructor(new[] { typeof(Vector3), typeof(Vector3), typeof(Vector3), typeof(Vector2) })); // Load models AssetLocator.StartFlagModel = gameObjectGCB.AddModel( "Game Object: Start Flag", startFlagModelStream.GetVertices <DefaultVertex>(typeof(DefaultVertex).GetConstructor(new[] { typeof(Vector3), typeof(Vector3), typeof(Vector3), typeof(Vector2) })).ToList(), startFlagModelStream.GetIndices().ToList() ); AssetLocator.DynamicLightModel = gameObjectGCB.AddModel( "Game Object: Dynamic Light", dynamicLightModelStream.GetVertices <DefaultVertex>(typeof(DefaultVertex).GetConstructor(new[] { typeof(Vector3), typeof(Vector3), typeof(Vector3), typeof(Vector2) })).ToList(), dynamicLightModelStream.GetIndices().ToList() ); AssetLocator.IntroCameraModel = gameObjectGCB.AddModel( "Game Object: Intro Camera Attracter", introCameraModelStream.GetVertices <DefaultVertex>(typeof(DefaultVertex).GetConstructor(new[] { typeof(Vector3), typeof(Vector3), typeof(Vector3), typeof(Vector2) })).ToList(), introCameraModelStream.GetIndices().ToList() ); AssetLocator.FinishingBellModel = gameObjectGCB.AddModel( "Game Object: Finishing Bell", finishingBellVerts, finishingBellIndices ); AssetLocator.VultureEggModel = gameObjectGCB.AddModel( "Game Object: Vulture Egg", vultureEggVerts, vultureEggIndices ); AssetLocator.ShadowcasterModel = gameObjectGCB.AddModel( "Game Object: Shadowcaster", shadowcasterModelStream.GetVerticesWithoutTangents <DefaultVertex>(typeof(DefaultVertex).GetConstructor(new[] { typeof(Vector3), typeof(Vector3), typeof(Vector2) })).ToList(), shadowcasterModelStream.GetIndices().ToList() ); AssetLocator.LizardCoinModel = gameObjectGCB.AddModel( "Game Object: Lizard Coin", coinModelVertices, coinModelStream.GetIndices() ); // Set materials AssetLocator.StartFlagMaterial = new Material("Game Object Mat: Start Flag", fs); AssetLocator.StartFlagMaterial.SetMaterialResource( (ResourceViewBinding)fs.GetBindingByIdentifier("DiffuseMap"), AssetLocator.LoadTexture("Spawn_bake.jpg").CreateView() ); AssetLocator.StartFlagMaterial.SetMaterialConstantValue( (ConstantBufferBinding)fs.GetBindingByIdentifier("MaterialProperties"), new Vector4(0f, 0f, 0f, 1f) ); AssetLocator.DynamicLightMaterial = new Material("Game Object Mat: Dynamic Light", fs); AssetLocator.DynamicLightMaterial.SetMaterialResource( (ResourceViewBinding)fs.GetBindingByIdentifier("DiffuseMap"), AssetLocator.LoadTexture("Bulb_bake.jpg").CreateView() ); AssetLocator.DynamicLightMaterial.SetMaterialConstantValue( (ConstantBufferBinding)fs.GetBindingByIdentifier("MaterialProperties"), new Vector4(0f, 0f, 0f, 1f) ); AssetLocator.IntroCameraMaterial = new Material("Game Object Mat: Intro Camera", fs); AssetLocator.IntroCameraMaterial.SetMaterialResource( (ResourceViewBinding)fs.GetBindingByIdentifier("DiffuseMap"), AssetLocator.LoadTexture("Camera_colo.png").CreateView() ); AssetLocator.IntroCameraMaterial.SetMaterialConstantValue( (ConstantBufferBinding)fs.GetBindingByIdentifier("MaterialProperties"), new Vector4(0f, 0f, 0f, 1f) ); AssetLocator.FinishingBellMaterial = new Material("Game Object Mat: Finishing Bell", fs); AssetLocator.FinishingBellMaterial.SetMaterialResource( (ResourceViewBinding)fs.GetBindingByIdentifier("DiffuseMap"), AssetLocator.LoadTexture("FinishBellBottom_bake.png").CreateView() ); AssetLocator.FinishingBellMaterial.SetMaterialConstantValue( (ConstantBufferBinding)fs.GetBindingByIdentifier("MaterialProperties"), new Vector4(1f, 1f, 0.8f, 1f) ); AssetLocator.VultureEggMaterial = new Material("Game Object Mat: Vulture Egg", fs); AssetLocator.VultureEggMaterial.SetMaterialResource( (ResourceViewBinding)fs.GetBindingByIdentifier("DiffuseMap"), AssetLocator.LoadTexture("VEggTexture.png").CreateView() ); AssetLocator.VultureEggMaterial.SetMaterialConstantValue( (ConstantBufferBinding)fs.GetBindingByIdentifier("MaterialProperties"), new Vector4(1f, 1f, 0.8f, 1f) ); AssetLocator.ShadowcasterMaterial = new Material("Game Object Mat: Shadowcaster", fs); AssetLocator.ShadowcasterMaterial.SetMaterialResource( (ResourceViewBinding)fs.GetBindingByIdentifier("DiffuseMap"), AssetLocator.LoadTexture("Default_s.bmp").CreateView() ); AssetLocator.ShadowcasterMaterial.SetMaterialConstantValue( (ConstantBufferBinding)fs.GetBindingByIdentifier("MaterialProperties"), new Vector4(0f, 0f, 0f, 1f) ); AssetLocator.LizardCoinMaterial = new Material("Game Object Mat: Lizard Coin", AssetLocator.GeometryFragmentShader); AssetLocator.LizardCoinMaterial.SetMaterialResource( (ResourceViewBinding)AssetLocator.GeometryFragmentShader.GetBindingByIdentifier("DiffuseMap"), AssetLocator.LoadTexture("LizardCoin.png", true).CreateView() ); AssetLocator.LizardCoinMaterial.SetMaterialResource( (ResourceViewBinding)AssetLocator.GeometryFragmentShader.GetBindingByIdentifier("SpecularMap"), AssetLocator.LoadTexture("LizardCoin_s.png", true).CreateView() ); AssetLocator.LizardCoinMaterial.SetMaterialResource( (ResourceViewBinding)AssetLocator.GeometryFragmentShader.GetBindingByIdentifier("NormalMap"), AssetLocator.LoadTexture("LizardCoin_n.png", true).CreateView() ); AssetLocator.LizardCoinMaterial.SetMaterialResource( (ResourceViewBinding)AssetLocator.GeometryFragmentShader.GetBindingByIdentifier("EmissiveMap"), AssetLocator.LoadTexture("LizardCoin_e.png", true).CreateView() ); AssetLocator.LizardCoinMaterial.SetMaterialConstantValue( (ConstantBufferBinding)AssetLocator.GeometryFragmentShader.GetBindingByIdentifier("MaterialProperties"), Vector4.ONE ); AssetLocator.FinishingBellPhysicsShape = PhysicsManager.CreateConcaveHullShape( finishingBellVerts.Select(df => df.Position), finishingBellIndices.Select(i => (int)i), new CollisionShapeOptionsDesc(), AssetLocator.CreateACDFilePath("finishingBell") ); AssetLocator.VultureEggPhysicsShape = PhysicsManager.CreateConcaveHullShape( vultureEggVerts.Select(df => df.Position), vultureEggIndices.Select(i => (int)i), new CollisionShapeOptionsDesc(), AssetLocator.CreateACDFilePath("vultureEgg") ); AssetLocator.LizardCoinShape = PhysicsManager.CreateConvexHullShape( coinModelVertices.Select(v => v.Position), new CollisionShapeOptionsDesc(Vector3.ONE) ); // Build gameObjectCache = gameObjectGCB.Build(); AssetLocator.MainGeometryPass.SetVSForCache(gameObjectCache, AssetLocator.MainGeometryVertexShader); #endregion #region Misc AssetLocator.UnitSphereShape = PhysicsManager.CreateSimpleSphereShape(1f, new CollisionShapeOptionsDesc(Vector3.ONE)); AssetLocator.DefaultNormalMapView = AssetLocator.LoadTexture("Default_n.bmp").CreateView(); AssetLocator.DefaultSpecularMapView = AssetLocator.LoadTexture("Default_s.bmp").CreateView(); AssetLocator.DefaultEmissiveMapView = AssetLocator.LoadTexture("Default_e.bmp").CreateView(); #endregion AssetLocator.MainWindow.WindowClosed += w => LosgapSystem.Exit(); Monitor.Pulse(staticMutationLock); Monitor.Exit(staticMutationLock); LosgapSystem.Start(); #region Disposal AssetLocator.UnitSphereShape.Dispose(); gameObjectCache.Dispose(); AssetLocator.IntroCameraMaterial.Dispose(); AssetLocator.DynamicLightMaterial.Dispose(); AssetLocator.StartFlagMaterial.Dispose(); AssetLocator.MainFont.Dispose(); hudPass.DepthStencilState.Dispose(); hudPass.Input.Dispose(); hudPass.RasterizerState.Dispose(); hudPass.BlendState.Dispose(); hudPass.Dispose(); AssetLocator.LightPass.Dispose(); AssetLocator.MainGeometryPass.DepthStencilState.Dispose(); AssetLocator.MainGeometryPass.RasterizerState.Dispose(); AssetLocator.MainGeometryPass.Dispose(); AssetLocator.MainCamera.Dispose(); hudTextSampler.Dispose(); AssetLocator.HUDFragmentShader.Dispose(); hudVS.Dispose(); shadowVS.Dispose(); shadowFS.Dispose(); viewportPropertiesBuffer.Dispose(); skyDiffuseSampler.Dispose(); AssetLocator.SkyFragmentShader.Dispose(); unlitVSSky.Dispose(); normalSampler.Dispose(); dofShader.Dispose(); blurShader.Dispose(); copyReverseShader.Dispose(); copyShader.Dispose(); glowShader.Dispose(); bloomHShader.Dispose(); bloomVShader.Dispose(); outliningShader.Dispose(); dlFinalizationFS.Dispose(); lightFS.Dispose(); lightBufferView.Dispose(); lightBuffer.Dispose(); lightMetaBuffer.Dispose(); fsCameraBuffer.Dispose(); lightVS.Dispose(); AssetLocator.GeometryFragmentShader.Dispose(); shadowSampler.Dispose(); defaultDiffuseSampler.Dispose(); matPropsBuffer.Dispose(); AssetLocator.MainGeometryVertexShader.Dispose(); AssetLocator.SkyVertexShader.Dispose(); vsCameraBuffer.Dispose(); AssetLocator.HudLayer.Dispose(); AssetLocator.SkyLayer.Dispose(); AssetLocator.GameLayer.Dispose(); GC.KeepAlive(AssetLocator.MainWindow); #endregion }
color FragmentShader(VertexOut vertex, Field <data> CurrentData, Field <data> PreviousData, Field <unit> CurrentUnits, Field <unit> PreviousUnits, TextureSampler UnitTexture, TextureSampler ShadowTexture, [Player.Vals] float player, float s, float t, float selection_blend, float selection_size, [Vals.Bool] bool solid_blend_flag, float solid_blend) { // Calculate shadow pixel color shadow = color.TransparentBlack; vec2 shadow_subcell_pos = get_subcell_pos(vertex, CurrentData.Size, vec(0f, -.5f)); var shadow_here = Here + new RelativeIndex(0, -.5f); data shadow_cur = CurrentData[shadow_here], shadow_pre = PreviousData[shadow_here]; unit shadow_cur_unit = CurrentUnits[shadow_here], shadow_pre_unit = PreviousUnits[shadow_here]; if (IsUnit(shadow_cur_unit) || IsUnit(shadow_pre_unit)) { if (Something(shadow_cur) && shadow_cur.change == Change.Stayed) { if (s > .5) { shadow_pre = shadow_cur; } shadow += ShadowSprite(player, shadow_pre, shadow_pre_unit, shadow_subcell_pos, ShadowTexture, selection_blend, selection_size, solid_blend_flag, solid_blend); } else { if (IsValid(shadow_cur.direction)) { var prior_dir = prior_direction(shadow_cur); shadow_cur.direction = prior_dir; vec2 offset = (1 - s) * direction_to_vec(prior_dir); shadow += ShadowSprite(player, shadow_cur, shadow_cur_unit, shadow_subcell_pos + offset, ShadowTexture, selection_blend, selection_size, solid_blend_flag, solid_blend); } if (IsValid(shadow_pre.direction) && shadow.a < .025f) { vec2 offset = -s *direction_to_vec(shadow_pre.direction); shadow += ShadowSprite(player, shadow_pre, shadow_pre_unit, shadow_subcell_pos + offset, ShadowTexture, selection_blend, selection_size, solid_blend_flag, solid_blend); } } } // Calculate unit pixel color output = color.TransparentBlack; vec2 subcell_pos = get_subcell_pos(vertex, CurrentData.Size); data cur = CurrentData[Here], pre = PreviousData[Here]; unit cur_unit = CurrentUnits[Here], pre_unit = PreviousUnits[Here]; if (!IsUnit(cur_unit) && !IsUnit(pre_unit)) { return(shadow); } if (Something(cur) && cur.change == Change.Stayed) { if (s > .5) { pre = cur; } float _s = (cur_unit.anim == _0 ? t : s); if (cur_unit.anim == Anim.DoRaise) { cur_unit.anim = Anim.Die; _s = 1f - _s; } float frame = _s * UnitSpriteSheet.AnimLength + Float(cur_unit.anim); output += Sprite(player, pre, pre_unit, subcell_pos, frame, UnitTexture, selection_blend, selection_size, solid_blend_flag, solid_blend); } else { float frame = s * UnitSpriteSheet.AnimLength + Float(Anim.Walk); if (IsValid(cur.direction)) { var prior_dir = prior_direction(cur); cur.direction = prior_dir; vec2 offset = (1 - s) * direction_to_vec(prior_dir); output += Sprite(player, cur, cur_unit, subcell_pos + offset, frame, UnitTexture, selection_blend, selection_size, solid_blend_flag, solid_blend); } if (IsValid(pre.direction) && output.a < .025f) { vec2 offset = -s *direction_to_vec(pre.direction); output += Sprite(player, pre, pre_unit, subcell_pos + offset, frame, UnitTexture, selection_blend, selection_size, solid_blend_flag, solid_blend); } } if (output.a < .025f) { output = shadow; } return(output); }
static void Main(string[] args) { Texture offscreenColorTexture = null; Texture offscreenDepthTexture = null; Filament.RenderTarget offscreenRenderTarget = null; View offscreenView = null; Scene offscreenScene = null; Camera offscreenCamera = null; int lightEntity = -1; Material meshMaterial = null; MaterialInstance meshMatInstance = null; Mesh monkeyMesh = null; int reflectedMonkey = -1; Matrix4x4 transform = Matrix4x4.Identity; int quadEntity = -1; Vector3 quadCenter = Vector3.Zero; Vector3 quadNormal = Vector3.Zero; VertexBuffer quadVb = null; IndexBuffer quadIb = null; Material quadMaterial = null; MaterialInstance quadMatInstance = null; ReflectionMode mode = ReflectionMode.Camera; var app = new Application( new WindowConfig() { Title = "rendertarget", }, new ApplicationConfig() ); app.Setup = (engine, view, scene) => { var tcm = engine.TransformManager; var rcm = engine.RenderableManager; var vp = view.Viewport; var resourceData = new SampleDataLoader(); var monkeyData = new MonkeyDataLoader(); // Instantiate offscreen render target. offscreenScene = engine.CreateScene(); offscreenView = engine.CreateView(); offscreenView.Scene = offscreenScene; offscreenView.PostProcessingEnabled = false; offscreenColorTexture = TextureBuilder.Create() .WithWidth(vp.Width) .WithHeight(vp.Height) .WithLevels(1) .WithUsage(TextureUsage.ColorAttachment | TextureUsage.Sampleable) .WithFormat(TextureFormat.Rgba8) .Build(engine); offscreenDepthTexture = TextureBuilder.Create() .WithWidth(vp.Width) .WithHeight(vp.Height) .WithLevels(1) .WithUsage(TextureUsage.DepthAttachment) .WithFormat(TextureFormat.Depth24) .Build(engine); offscreenRenderTarget = RenderTargetBuilder.Create() .WithTexture(AttachmentPoint.Color, offscreenColorTexture) .WithTexture(AttachmentPoint.Depth, offscreenDepthTexture) .Build(engine); offscreenView.RenderTarget = offscreenRenderTarget; offscreenView.Viewport = new Viewport(0, 0, vp.Width, vp.Height); offscreenCamera = engine.CreateCamera(EntityManager.Create()); offscreenView.Camera = offscreenCamera; app.AddOffscreenView(offscreenView); // Position and orient the mirror in an interesting way. var c = quadCenter = new Vector3(-2, 0, -5); var n = quadNormal = Vector3.Normalize(new Vector3(1, 0, 2)); var u = Vector3.Normalize(Vector3.Cross(quadNormal, new Vector3(0, 1, 0))); var v = Vector3.Cross(n, u); u = 1.5f * u; v = 1.5f * v; Vertex[] kQuadVertices = { new() { Position = c - u - v, Uv = new Vector2(1, 0) }, new() { Position = c + u - v, Uv = new Vector2(0, 0) }, new() { Position = c - u + v, Uv = new Vector2(1, 1) }, new() { Position = c + u + v, Uv = new Vector2(0, 1) }, }; var vbo = new byte[20 * 4]; MemoryStream vboStream = new MemoryStream(vbo); BinaryWriter vboWriter = new BinaryWriter(vboStream); vboWriter.Write(kQuadVertices[0].Position.X); vboWriter.Write(kQuadVertices[0].Position.Y); vboWriter.Write(kQuadVertices[0].Position.Z); vboWriter.Write(kQuadVertices[0].Uv.X); vboWriter.Write(kQuadVertices[0].Uv.Y); vboWriter.Write(kQuadVertices[1].Position.X); vboWriter.Write(kQuadVertices[1].Position.Y); vboWriter.Write(kQuadVertices[1].Position.Z); vboWriter.Write(kQuadVertices[1].Uv.X); vboWriter.Write(kQuadVertices[1].Uv.Y); vboWriter.Write(kQuadVertices[2].Position.X); vboWriter.Write(kQuadVertices[2].Position.Y); vboWriter.Write(kQuadVertices[2].Position.Z); vboWriter.Write(kQuadVertices[2].Uv.X); vboWriter.Write(kQuadVertices[2].Uv.Y); vboWriter.Write(kQuadVertices[3].Position.X); vboWriter.Write(kQuadVertices[3].Position.Y); vboWriter.Write(kQuadVertices[3].Position.Z); vboWriter.Write(kQuadVertices[3].Uv.X); vboWriter.Write(kQuadVertices[3].Uv.Y); // Create quad vertex buffer. quadVb = VertexBufferBuilder.Create() .WithVertexCount(4) .WithBufferCount(1) .WithAttribute(VertexAttribute.Position, 0, ElementType.Float3, 0, 20) .WithAttribute(VertexAttribute.Uv0, 0, ElementType.Float2, 12, 20) .Build(engine); quadVb.SetBufferAt(engine, 0, vbo); // Create quad index buffer. var kQuadIndices = new ushort[] { 0, 1, 2, 3, 2, 1 }; quadIb = IndexBufferBuilder.Create() .WithIndexCount(6) .WithBufferType(IndexType.UShort) .Build(engine); quadIb.SetBuffer(engine, kQuadIndices); // Create quad material and renderable. quadMaterial = MaterialBuilder.Create() .WithPackage(resourceData.LoadMirror()) .Build(engine); quadMatInstance = quadMaterial.CreateInstance(); var sampler = new TextureSampler(SamplerMinFilter.Linear, SamplerMagFilter.Linear); quadMatInstance.SetParameter("albedo", offscreenColorTexture, sampler); quadEntity = EntityManager.Create(); RenderableBuilder.Create() .WithBoundingBox( new Box( new Vector3(-1, -1, -1), new Vector3(1, 1, 1) ) ) .WithMaterial(0, quadMatInstance) .WithGeometry(0, PrimitiveType.Triangles, quadVb, quadIb, 0, 6) .WithCulling(false) .WithReceiveShadows(false) .WithCastShadows(false) .Build(engine, quadEntity); scene.AddEntity(quadEntity); // Instantiate mesh material. meshMaterial = MaterialBuilder.Create() .WithPackage(resourceData.LoadAiDefaultMat()) .Build(engine); var mi = meshMatInstance = meshMaterial.CreateInstance(); mi.SetParameter("baseColor", RgbType.Linear, new Color(0.8f, 1.0f, 1.0f)); mi.SetParameter("metallic", 0.0f); mi.SetParameter("roughness", 0.4f); mi.SetParameter("reflectance", 0.5f); // Add monkey into the scene. monkeyMesh = MeshReader.LoadFromBuffer(engine, monkeyData.LoadSuzanne(), mi); var ti = tcm.GetInstance(monkeyMesh.Renderable); transform = Matrix4x4.CreateTranslation(0, 0, -4) * tcm.GetWorldTransform(ti); rcm.SetCastShadows(rcm.GetInstance(monkeyMesh.Renderable), false); scene.AddEntity(monkeyMesh.Renderable); // Create a reflected monkey, which is used only for ReflectionMode::RENDERABLES. reflectedMonkey = EntityManager.Create(); RenderableBuilder.Create() .WithBoundingBox( new Box( new Vector3(-2, -2, -2), new Vector3(2, 2, 2) ) ) .WithMaterial(0, mi) .WithGeometry(0, PrimitiveType.Triangles, monkeyMesh.VertexBuffer, monkeyMesh.IndexBuffer) .WithReceiveShadows(true) .WithCastShadows(false) .Build(engine, reflectedMonkey); mode = SetReflectionMode(offscreenScene, offscreenView, reflectedMonkey, monkeyMesh, ReflectionMode.Camera); // Add light source to both scenes. // NOTE: this is slightly wrong when the reflection mode is RENDERABLES. lightEntity = EntityManager.Create(); LightBuilder.Create(LightType.Sun) .WithColor(Color.ToLinearAccurate(new sRGBColor(0.98f, 0.92f, 0.89f))) .WithIntensity(110000) .WithDirection(new Vector3(0.7f, -1, -0.8f)) .WithSunAngularRadius(1.9f) .WithCastShadows(false) .Build(engine, lightEntity); scene.AddEntity(lightEntity); offscreenScene.AddEntity(lightEntity); };
public static void InitNoise(Context context) { uint tex_width = 64; uint tex_height = 64; uint tex_depth = 64; var texBuf = new Buffer(context, new BufferDesc() { Width = tex_width, Depth = tex_depth, Height = tex_height, Format = Format.Float, Type = BufferType.Input }); var ts = texBuf.Map(); var rnd = new Random(); float[] b = new float[tex_depth * tex_height * tex_width]; Voronoi_repeat(16, (int)tex_width, (int)tex_height, (int)tex_depth, b); for (int i = 0; i < tex_depth * tex_height * tex_width; i++) { ts.Write(b[i]); //((float)rnd.NextDouble()); } texBuf.Unmap(); var noiseSampler = new TextureSampler(context, new TextureSamplerDesc() { Filter = new FilterMinMagMip() { Mag = FilterMode.Linear, Min = FilterMode.Linear, Mip = FilterMode.None }, Wrap = new WrapUVW() { WrapU = WrapMode.Repeat, WrapV = WrapMode.Repeat }, Index = TextureIndexMode.NormalizeCoords, Read = TextureReadMode.NormalizedFloat, MaxAnisotropy = 1.0f, MipLevels = 1 } ); noiseSampler.SetBuffer(texBuf, 0); context["noise_texture"].Set(noiseSampler); context["origin"].SetFloat3(new Vector3(0, 0, 1)); context["diameter"].Set(0.85f); context["turbulence"].Set(3.5f); /* int tex_width = 64; int tex_height = 64; int tex_depth = 64; Buffer noiseBuffer = m_context->createBuffer(RT_BUFFER_INPUT, RT_FORMAT_FLOAT, tex_width, tex_height, tex_depth); float *tex_data = (float *) noiseBuffer->map(); if (m_parameters.proc == PROCEDURE_VORONOI) { // Distances to Voronoi control points (repeated version, taking the 26 surrounding cubes into account!) Voronoi_repeat(16, tex_width, tex_height, tex_depth, tex_data); } else { // Random noise in range [0, 1] for (int i = tex_width * tex_height * tex_depth; i > 0; i--) { // One channel 3D noise in [0.0, 1.0] range. *tex_data++ = rand_range(0.0f, 1.0f); } } noiseBuffer->unmap(); // Noise texture sampler TextureSampler noiseSampler = m_context->createTextureSampler(); noiseSampler->setWrapMode(0, RT_WRAP_REPEAT); noiseSampler->setWrapMode(1, RT_WRAP_REPEAT); noiseSampler->setFilteringModes(RT_FILTER_LINEAR, RT_FILTER_LINEAR, RT_FILTER_NONE); noiseSampler->setIndexingMode(RT_TEXTURE_INDEX_NORMALIZED_COORDINATES); noiseSampler->setReadMode(RT_TEXTURE_READ_NORMALIZED_FLOAT); noiseSampler->setMaxAnisotropy(1.0f); noiseSampler->setMipLevelCount(1); noiseSampler->setArraySize(1); noiseSampler->setBuffer(0, 0, noiseBuffer); m_context["noise_texture"]->setTextureSampler(noiseSampler); // 1D color ramp buffer, 4 float channels, all entries in the range [0.0, 1.0]. Buffer colorRampBuffer = m_context->createBuffer(RT_BUFFER_INPUT, RT_FORMAT_FLOAT4, 1024); tex_data = (float *) colorRampBuffer->map(); create_color_ramp(m_parameters.ramp, 1024, tex_data); colorRampBuffer->unmap(); */ }
public TextureSampler CreateTextureSampler(string path, bool scale = false) { var newTex = Path.GetFileName(path) ?? path; if (samplers.ContainsKey(newTex)) return samplers[newTex]; else { if (!File.Exists(path)) { Console.WriteLine("ISSUES DUDE {0} not found", path); throw new ArgumentException("imagepath"); } Console.WriteLine("{0} Loading. {1} total samplers loaded ", Path.GetFileName(path), samplers.Count); using (var bitmap = new FreeImageBitmap(path)) { var bmp = bitmap.Width > MaxTextureWidth || bitmap.Height > MaxTextureHeight ? GetScaledBmp(bitmap) : bitmap; var desc = new BufferDesc() { Width = (uint) bmp.Width, Height = (uint) bmp.Height, Format = Format.Float4, Type = BufferType.Input }; var texData = EngineContext.Instance.ResourceManager.CreateBuffer(context, desc); BufferStream data = texData.Map(); for (int i = 0; i < bmp.Height; i++) { switch (bmp.ColorDepth) { case 8: Scanline<byte> s_8 = bmp.GetScanline<byte>(i); for (int j = 0; j < bmp.Width; j++) { var c = new Vector4(bmp.Palette[s_8[j]].rgbRed/255.0f, bmp.Palette[s_8[j]].rgbGreen/255.0f, bmp.Palette[s_8[j]].rgbBlue/255.0f, 1.0f); data.Write(c); } break; case 24: Scanline<RGBTRIPLE> s_t = bmp.GetScanline<RGBTRIPLE>(i); for (int j = 0; j < bmp.Width; j++) { var rgb = new RgbSpectrum(s_t[j].rgbtRed/255.0f, s_t[j].rgbtGreen/255.0f, s_t[j].rgbtBlue/255.0f); rgb.DeGamma(); var c = new Vector4(rgb.c1, rgb.c2, rgb.c3, 1.0f); data.Write(c); } break; case 32: Scanline<RGBQUAD> s_32 = bmp.GetScanline<RGBQUAD>(i); for (int j = 0; j < bmp.Width; j++) { var rgb = new RgbSpectrum(s_32[j].rgbRed / 255.0f, s_32[j].rgbGreen / 255.0f, s_32[j].rgbBlue / 255.0f); rgb.DeGamma(); var c = new Vector4(rgb.c1, rgb.c2, rgb.c3, 1.0f); data.Write(c); } break; } } texData.Unmap(); TextureSamplerDesc texDesc = TextureSamplerDesc.Default; texDesc.Read = TextureReadMode.ElementType; TextureSampler sampler = new TextureSampler(context, texDesc); sampler.SetBuffer(texData, 0); samplers.Add(newTex, sampler); Console.WriteLine("2D Sampler loaded {0} {1}x{2} pixels", path, bmp.Width, bmp.Height); return sampler; } } }
static void Main(string[] args) { Texture texture = null; Skybox skybox = null; VertexBuffer vertexBuffer = null; IndexBuffer indexBuffer = null; Material material = null; MaterialInstance materialInstance = null; Camera camera = null; int cameraEntity = -1; int renderable = -1; var app = new Application( new WindowConfig() { Title = "texturedquad" }, new ApplicationConfig() ); app.Setup = (engine, view, scene) => { var path = Path.Combine(app.RootAssetPath, "textures/Moss_01/Moss_01_Color.png"); if (!File.Exists(path)) { Console.WriteLine("The texture {0} does not exist", path); Environment.Exit(1); } using (var stream = File.OpenRead(path)) { var imageResult = ImageResult.FromStream(stream, ColorComponents.RedGreenBlueAlpha); Console.WriteLine("Loaded texture: {0}x{1}", imageResult.Width, imageResult.Height); var pixelBuffer = new PixelBufferDescriptor(imageResult.Data, PixelDataFormat.Rgba, PixelDataType.UByte); texture = TextureBuilder.Create() .WithWidth(imageResult.Width) .WithHeight(imageResult.Height) .WithLevels(1) .WithSampler(TextureSamplerType.Texture2d) .WithFormat(TextureFormat.Rgba8) .Build(engine); texture.SetImage(engine, 0, pixelBuffer); } // Set up view skybox = SkyboxBuilder.Create() .WithColor(new Color(0.1f, 0.125f, 0.25f, 1.0f)) .Build(engine); scene.Skybox = skybox; cameraEntity = EntityManager.Create(); camera = engine.CreateCamera(cameraEntity); view.PostProcessingEnabled = false; view.Camera = camera; // Create quad renderable var vbo = new VertexBufferObject(); vbo.Write(new Vector2(-1, -1)); vbo.Write(new Vector2(0, 0)); vbo.Write(new Vector2(1, -1)); vbo.Write(new Vector2(1, 0)); vbo.Write(new Vector2(-1, 1)); vbo.Write(new Vector2(0, 1)); vbo.Write(new Vector2(1, 1)); vbo.Write(new Vector2(1, 1)); vertexBuffer = VertexBufferBuilder.Create() .WithVertexCount(4) .WithBufferCount(1) .WithAttribute(VertexAttribute.Position, 0, ElementType.Float2, 0, 16) .WithAttribute(VertexAttribute.Uv0, 0, ElementType.Float2, 8, 16) .Build(engine); vertexBuffer.SetBufferAt(engine, 0, vbo); var sampleData = new SampleDataLoader(); indexBuffer = IndexBufferBuilder.Create() .WithIndexCount(6) .WithBufferType(IndexType.UShort) .Build(engine); indexBuffer.SetBuffer(engine, QUAD_INDICES); material = MaterialBuilder.Create() .WithPackage(sampleData.LoadBakedTexture()) .Build(engine); var sampler = new TextureSampler(SamplerMinFilter.Linear, SamplerMagFilter.Linear); materialInstance = material.CreateInstance(); materialInstance.SetParameter("albedo", texture, sampler); renderable = EntityManager.Create(); RenderableBuilder.Create() .WithBoundingBox( new Box( new Vector3(-1, -1, -1), new Vector3(1, 1, 1) ) ) .WithMaterial(0, materialInstance) .WithGeometry(0, PrimitiveType.Triangles, vertexBuffer, indexBuffer, 0, 6) .WithCulling(false) .WithReceiveShadows(false) .WithCastShadows(false) .Build(engine, renderable); scene.AddEntity(renderable); }; app.Cleanup = (engine, view, scene) => { engine.Destroy(skybox); engine.Destroy(renderable); engine.Destroy(materialInstance); engine.Destroy(material); engine.Destroy(texture); engine.Destroy(vertexBuffer); engine.Destroy(indexBuffer); engine.DestroyCameraComponent(cameraEntity); EntityManager.Destroy(cameraEntity); }; app.Animate = (engine, view, now) => { var zoom = 2.0f + 2.0f * MathF.Sin(now); var width = view.Viewport.Width; var height = view.Viewport.Height; var aspect = (float)width / (float)height; camera.SetProjection(Projection.Ortho, -aspect * zoom, aspect * zoom, -zoom, zoom, -1, 1 ); }; app.Run(); }
public void Run(VertexIn[] vertexBuffer, int[] indexBuffer, CBuffer constantBuffer, Bitmap outputBuffer, float[,] depthBuffer) { TextureSampler sampler = new TextureSampler() { _pipeline = this }; //initialize variables if (verts == null || verts.Length == vertexBuffer.Length) { verts = new VertexData[vertexBuffer.Length]; } if (depthBuffer != null) { if (depthLock == null || depthLock.GetLength(0) != outputBuffer.Width || depthLock.GetLength(1) != outputBuffer.Height) { depthLock = new object[depthBuffer.GetLength(0), depthBuffer.GetLength(0)]; } for (int x = 0; x < outputBuffer.Width; x++) { for (int y = 0; y < outputBuffer.Height; y++) { depthLock[x, y] = new object(); } } } //Create tasks and process vertices; Parallel.For(0, vertexBuffer.Length, (i) => { verts[i] = VertexShader.VertexMain(vertexBuffer[i], in constantBuffer); verts[i].Position.Y = -verts[i].Position.Y; }); int size = outputBuffer.Width * outputBuffer.Height; BitmapData dat = outputBuffer.LockBits(new Rectangle(0, 0, 800, 600), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); byte[] colDat = new byte[size * 4]; Marshal.Copy(dat.Scan0, colDat, 0, colDat.Length); int width = outputBuffer.Width; int height = outputBuffer.Height; //Create tasks and process data to output pixels Parallel.For(0, indexBuffer.Length / 3, (i) => { int i1 = i * 3; //Assemble geometry and rasterize triangles List <FragmentData> frags = SoftwareRasterizer.Rasterize(verts[indexBuffer[i1]], verts[indexBuffer[i1 + 1]], verts[indexBuffer[i1 + 2]], height, width); Parallel.For(0, frags.Count, (j) => { //get fragment FragmentData frag = frags[j]; //get pixel color Vector4 pixel = FragmentShader.FragmentMain(frag, in sampler, in constantBuffer); //store coord into ints for speed int x = (int)frag.Position.X, y = (int)frag.Position.Y; //don't do depth test if no buffer is given if (depthBuffer == null) { lock (depthLock[x, y]) { int index = (y * width) + x; index *= 4; colDat[index] = (byte)(pixel.Z * 255); colDat[index + 1] = (byte)(pixel.Y * 255); colDat[index + 2] = (byte)(pixel.X * 255); colDat[index + 3] = (byte)(pixel.W * 255); } } else { //check depth buffer and set output if necessary //lock for thread safety lock (depthLock[x, y]) { //check if our pixel is nearer than nearest pixel previously drawn float depth = depthBuffer[x, y]; if (frag.Position.Z <= depth) { //if our pixel is closest, set depthbuffer to our depth depthBuffer[x, y] = frag.Position.Z; //set outputBuffer color int index = (y * width) + x; index *= 4; colDat[index] = (byte)(pixel.Z * 255); colDat[index + 1] = (byte)(pixel.Y * 255); colDat[index + 2] = (byte)(pixel.X * 255); colDat[index + 3] = (byte)(pixel.W * 255); } } } }); }); Marshal.Copy(colDat, 0, dat.Scan0, colDat.Length); outputBuffer.UnlockBits(dat); }
static void Main(string[] args) { Material material = null; MaterialInstance materialInstance = null; Texture normal = null; Texture albedo = null; Texture ao = null; Texture metallic = null; Texture roughness = null; Mesh mesh = null; Matrix4x4 transform; var app = new Application( new WindowConfig() { Title = "suzanne", }, new ApplicationConfig() { IblDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), IBL_FOLDER) } ); app.Setup = (engine, view, scene) => { var tcm = engine.TransformManager; var rcm = engine.RenderableManager; var monkeyData = new MonkeyDataLoader(); // Create textures. The KTX bundles are freed by KtxUtility. var albedoBundle = new KtxBundle(monkeyData.LoadAlbedoS3tc()); var aoBundle = new KtxBundle(monkeyData.LoadAo()); var metallicBundle = new KtxBundle(monkeyData.LoadMetallic()); var roughnessBundle = new KtxBundle(monkeyData.LoadRougness()); albedo = KtxUtility.CreateTexture(engine, albedoBundle, true); ao = KtxUtility.CreateTexture(engine, aoBundle, false); metallic = KtxUtility.CreateTexture(engine, metallicBundle, false); roughness = KtxUtility.CreateTexture(engine, roughnessBundle, false); normal = LoadNormalMap(engine, monkeyData.LoadNormal()); var resourceData = new SampleDataLoader(); var sampler = new TextureSampler(SamplerMinFilter.LinearMipmapLinear, SamplerMagFilter.Linear); // Instantiate material. material = MaterialBuilder.Create() .WithPackage(resourceData.LoadTexturedLit()) .Build(engine); materialInstance = material.CreateInstance(); materialInstance.SetParameter("albedo", albedo, sampler); materialInstance.SetParameter("ao", ao, sampler); materialInstance.SetParameter("metallic", metallic, sampler); materialInstance.SetParameter("normal", normal, sampler); materialInstance.SetParameter("roughness", roughness, sampler); var indirectLight = app.Ibl.IndirectLight; indirectLight.Intensity = 100000; indirectLight.Rotation = Matrix4x4.CreateFromAxisAngle(Vector3.UnitY, 0.5f); // Add geometry into the scene. mesh = MeshReader.LoadFromBuffer(engine, monkeyData.LoadSuzanne(), materialInstance); var ti = tcm.GetInstance(mesh.Renderable); transform = tcm.GetWorldTransform(ti) * Matrix4x4.CreateTranslation(0, 0, -4); rcm.SetCastShadows(rcm.GetInstance(mesh.Renderable), false); scene.AddEntity(mesh.Renderable); tcm.SetTransform(ti, transform); }; app.Cleanup = (engine, view, scene) => { engine.Destroy(materialInstance); engine.Destroy(mesh.Renderable); engine.Destroy(material); engine.Destroy(albedo); engine.Destroy(normal); engine.Destroy(roughness); engine.Destroy(metallic); engine.Destroy(ao); }; app.Run(); }
public City(CityEdge[] boundaryLoop) : base(boundaryLoop, null, true, 1) { entrence = Vector2.zero; terrainGenerator = new TerrainGenerator(120f, 30f); cityParent = new GameObject("CityParent", typeof(Transform)).transform; }
private void BuildMaterials(SceneMaterial[] sceneMaterials, SceneResourceReference[] sceneResources) { foreach (var sceneMaterial in sceneMaterials) { var material = new Material(Session.OptixContext); if (this.Materials == null) { this.Materials = new Dictionary<string, Material>(StringComparer.InvariantCultureIgnoreCase); } this.Materials.Add(sceneMaterial.Name, material); sceneMaterial.ResolveReferences(); if (OnMaterialScriptsResolve != null) { var args = new MaterialResolveArgs { MaterialName = sceneMaterial.Name, IsVolume = MaterialManager.IsVolume(sceneMaterial.Name) }; var scripts = OnMaterialScriptsResolve(args).ToArray(); for (int n = 0; n < RayTypeCount; n++) { material.Programs[n] = new SurfaceProgram(Session.OptixContext, n == 0 ? RayHitType.Closest : RayHitType.Any, scripts[n].PtxPath, scripts[n].Method); //material["diffuse_color"].SetFloat3((Vector3)sceneMaterial["diffuse_color"]); //material["glossy_color"].SetFloat3((Vector3)sceneMaterial["gloss_color"]); //material["specular_color"].SetFloat3((Vector3)sceneMaterial["specular_color"]); //material["index_of_refraction"].Set(1.5f); //material["phong_exp"].Set((float)sceneMaterial["exponent"]); //(Vector3)sceneMaterial["emission_color"] string diffuse_map = sceneMaterial.Get<string>("!diffuse_map", null); string alpha_map = sceneMaterial.Get<string>("!alpha_map", null); string bump_map = sceneMaterial.Get<string>("!bump_map", null); var samplers = LoadTextures(diffuse_map, bump_map, alpha_map, material); var materialDescription = new MaterialDescription() { diffuse = (Vector3)sceneMaterial["diffuse_color"], gloss = (Vector3)sceneMaterial["gloss_color"], specular = (Vector3)sceneMaterial["specular_color"], index_of_refraction = sceneMaterial.Get("index_of_refraction", 1.5f), roughness = sceneMaterial.Get("roughness", 1.0f), reflectivity = sceneMaterial.Get("reflectivity", 0.75f), exponent = (float)sceneMaterial["exponent"], emission = (Vector3)sceneMaterial["emission_color"] }; if (samplers[0] > 0) { materialDescription.diffuse_tex = samplers[0]; materialDescription.use_diffuse = 1; } if (samplers[1] > 0) { materialDescription.bump_tex = samplers[1]; materialDescription.use_bump = 1; } if (samplers[2] > 0) { materialDescription.alpha_tex = samplers[2]; materialDescription.use_alpha = 1; } if (this.MaterialDescriptions == null) { this.MaterialDescriptions = new List<MaterialDescription>(); } this.MaterialDescriptions.Add(materialDescription); material["material_description_id"].Set(this.MaterialDescriptions.IndexOf(materialDescription)); sceneMaterial["MaterialDescriptionIndex"] = this.MaterialDescriptions.IndexOf(materialDescription); if (args.IsVolume) { material["use_density_map"].Set(1); if (densityMap == null) { uint w = 126, h = 126, d = 126; byte[] voxelData = new byte[w * h * d]; //Random rnd = new Random(); //for (int i = 0; i < w; i++) // for (int j = 0; j < h; j++) // for (int k = 0; k < d; k++) // { // voxelData[i + w * (j + k * d)] = (byte)(rnd.Next(255 - i)); // } var voxData = VolumeDataManager.OpenSlab(@"C:\Users\aircraft\Downloads\MagicaVoxel-0.97-win-mac\export\export\maze.slab.vox"); //VolumeDataManager.OpenXRaw(@"C:\Users\aircraft\Downloads\MagicaVoxel-0.97-win-mac\export\export\monu1.xraw"); w = (uint)voxData.Width; h = (uint)voxData.Height; d = (uint)voxData.Depth; voxelData = voxData.Data; var voxDataBuffer = new Buffer(ComponentPipeline.Instance.Session.OptixContext, new BufferDesc() { Width = w, Depth = d, Height = h, Format = Format.Byte, Type = BufferType.Input }); voxDataBuffer.SetData(voxelData); densityMap = new TextureSampler(ComponentPipeline.Instance.Session.OptixContext, TextureSamplerDesc.Default); densityMap.SetBuffer(voxDataBuffer, 0U); } material["density_map"].Set(densityMap.GetId()); } } } else { throw new ApplicationException("Material resolve event is not initialized"); } //Evaluate programs count - engine dependent //Set programs - dependent on prev. step //END TODO sceneMaterial.InitializeOptixEntity(material, sceneMaterial.Name + " : " + ((BrdfTypes)sceneMaterial["brdf_id"])); } }