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);
        }
Exemple #2
0
        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;
                }
            }
        }
        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));
        }
Exemple #4
0
        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();

             */
        }
        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"]));
            }
        }