Example #1
0
        float mReflectCoeff;     //!< Fresnel reflection coefficient (for glass) 

        Bsdf(
        Ray aRay,
        ref Normal normal,
        Material Material,
        SceneGeometryInfo aScene)
        {
            Setup(aRay, ref normal, Material, aScene);
        }
Example #2
0
        public void WriteScene( Stream inputStream, SceneGeometryInfo sceneGeometry ) {
            using( var wr = new BinaryWriter(inputStream) ) {
                wr.Write(SceneGeometryFileSignature);
                wr.Write(sceneGeometry.GlobalIndexing);
                wr.Write(sceneGeometry.Vertices.Length);
                wr.Write(sceneGeometry.TexCoords.Length);
                wr.Write(sceneGeometry.Normals.Length);
                wr.Write(sceneGeometry.Geometry.Length);

                //--Vertices

                foreach( var vector in sceneGeometry.Vertices ) {
                    wr.Write(vector.x);
                    wr.Write(vector.y);
                    wr.Write(vector.z);
                }

                foreach( var vector in sceneGeometry.Normals ) {
                    wr.Write(vector.x);
                    wr.Write(vector.y);
                    wr.Write(vector.z);
                }

                foreach( var vector in sceneGeometry.TexCoords ) {
                    wr.Write(vector.x);
                    wr.Write(vector.y);
                    wr.Write(vector.z);
                }


                foreach( var geometryInfo in sceneGeometry.Geometry ) {
                    wr.Write(geometryInfo.Name);
                    wr.Write(geometryInfo.MaterialName);
                    wr.Write(geometryInfo.UseNormals);
                    wr.Write(geometryInfo.UseTextures);


                    var indexes = geometryInfo.IndexData.SelectMany(BitConverter.GetBytes).ToArray();
                    var texIndexes = geometryInfo.TextureIndexData.SelectMany(BitConverter.GetBytes).ToArray();
                    var normIndexes = geometryInfo.NormalIndexData.SelectMany(BitConverter.GetBytes).ToArray();

                    wr.Write(geometryInfo.IndexData.Count);
                    wr.Write(geometryInfo.TextureIndexData.Count);
                    wr.Write(geometryInfo.NormalIndexData.Count);

                    wr.Write(indexes);
                    wr.Write(texIndexes);
                    wr.Write(normIndexes);

                }
            }
        }
Example #3
0
        public TriangleLight(SceneGeometryInfo sc, ref Triangle tri, int triIndex = -1, RgbSpectrum gain = new RgbSpectrum())
            : this(sc)
        {
            Gain = gain;
            if (triIndex != -1)
                triangleIndex = triIndex;

            this.tri = tri;
            var computeNormal = true;
            //Configuration.Instance.Get("Integrator.ComputeNormals", false);
            var normalInverse = true;
            //Configuration.Instance.Get("Integrator.InverseLightNormals", false);

            var multiplicator = normalInverse ? -1f : 1f;
            this.TriangleNormal = multiplicator * (computeNormal ? tri.ComputeNormal(ref scene.Vertices) : tri.Owner.GetTriangleNormal(triIndex, 0));
            this.area = tri.AreaV(ref scene.Vertices);
        }
Example #4
0
        public RgbSpectrum SamplePhoton(SceneGeometryInfo scene, float u0, float u1, float u2, float u3, float u4, out float pdf, out RayInfo ray)
        {
            // Choose two points p1 and p2 on scene bounding sphere
            var worldCenter = scene.BoundingSphereCenter;
            var worldRadius = scene.BoundingSphereRadius * 1.01f;

            var p1 = worldCenter + worldRadius * MC.UniformSampleSphere(u0, u1);
            var p2 = worldCenter + worldRadius * MC.UniformSampleSphere(u2, u3);

            // Construct ray between p1 and p2
            ray = new RayInfo(p1, (p2 - p1).Normalize(), 1e-4f, 1e4f);

            // Compute InfiniteAreaLight ray weight
            Vector toCenter = (worldCenter - p1).Normalize();
            var rayDir = ray.Dir;
            float costheta = MathLab.AbsDot(ref toCenter, ref rayDir);
            pdf = costheta / (4f * MathLab.M_PI * MathLab.M_PI * worldRadius * worldRadius);

            return Le(ray.Dir);
        }
Example #5
0
 public SceneManager(TriangleMesh[] geometry, SceneGeometryInfo sceneGeometry, MaterialInfo[] mats)
 {
     this.sceneGeometry = sceneGeometry;
     this.geometry = geometry;
     this.materials = mats.ToDictionary(item => item.Name.ToLower());
     var acc =
         //new OctreeAcceleration();
         //new BVHAccellerationStructure();
         //new BoundingVolumeHierarchyAcceleration();
         //new BottomUpBvhAccelleration();
         //new LinearBvhAccelleration();
         //new TopDownBvhAccell();
         new BoundingVolumeHierarchyAccelerationStructure();
     //new BruteForceAccellerationStructure();
     //new BspAccellerationStructure();
     acc.Init(sceneGeometry, this, geometry);
     this.accel = acc;
     this.lights = new List<ILight>();
     this.defaultMaterial = new MaterialInfo() { Kd = new RgbSpectrum(0.6f) };
     Console.WriteLine("Using {0} ", accel.GetType().Name);
 }
Example #6
0
        void Setup(
            Ray aRay,
            ref Normal normal,
            Material Material,
            SceneGeometryInfo aScene)
        {
            mMaterialID = -1;
            mFrame.SetFromZ(ref normal);
            var invdir = -aRay.Direction;
            mLocalDirFix = mFrame.ToLocal(ref invdir);

            // reject rays that are too parallel with tangent plane
            if (Math.Abs(mLocalDirFix.z) < Consts.EPS_COSINE)
            {
                return;
            }

            GetComponentProbabilities(Material, mProbabilities);

            mIsDelta = (Math.Abs(mProbabilities.diffProb) < MathLab.Epsilon) && (Math.Abs(mProbabilities.phongProb) < MathLab.Epsilon);

            // now it becomes valid
            mMaterialID = 1;//Material.mIOR;
        }
Example #7
0
        public SceneGeometryInfo LoadData(string fileName) {
            sceneMats = new Dictionary<string, MaterialInfo>();
            textures = new Dictionary<string, ImageTextureInfo>();
            COLLADA model = COLLADA.Load(fileName);
            var result = new SceneGeometryInfo();
            var sceneVerts = new List<Point>();
            var meshes = new Dictionary<string, GeometryInfo>();
            var sceneNormals = new List<Vector>();
            var sceneTexData = new List<Vector>();
            var cams = new List<CameraInfo>();

            foreach (var item in model.Items) {
                if (item is library_materials) {
                    var materials = item as library_materials;

                    foreach (var material in materials.material) {

                    }

                }


                if (item is library_cameras) {
                    var cameras = item as library_cameras;
                    foreach (var camera in cameras.camera) {
                        if (camera.optics.technique.Length > 0) {
                            var t = camera.optics.technique[0];

                        }
                        var camItem = new CameraInfo() { CameraName = camera.id.Replace("-lib", string.Empty) };
                        cams.Add(camItem);
                    }
                }

                var geometries = item as library_geometries;
                if (geometries == null)
                    continue;

                // Iterate on geomerty in library_geometries 
                foreach (var geom in geometries.geometry) {
                    var meshInfo = geom.Item as mesh;
                    if (meshInfo == null)
                        continue;

                    var mesh = new GeometryInfo() { Name = geom.name.Replace("Mesh", string.Empty) };
                    meshes.Add(mesh.Name, mesh);


                    // Dump source[] for geom
                    foreach (var source in meshInfo.source) {
                        var float_array = source.Item as float_array;
                        if (float_array == null)
                            continue;

                        if (source.id.Contains("Position")) {
                            sceneVerts.AddRange(float_array.Values.ToPointList());
                            mesh.VertexData = new FloatStore(float_array.Values.ToFloatArray());
                        }
                        else if (source.id.Contains("Normal")) {
                            sceneNormals.AddRange(float_array.Values.ToVectorList());
                            mesh.NormalData = new FloatStore(float_array.Values.ToFloatArray());
                        }
                        else if (source.id.Contains("UV")) {
                            sceneTexData.AddRange(float_array.Values.ToVectorList());
                            mesh.TextureData = new FloatStore(float_array.Values.ToFloatArray());
                        }
                        else {
                            Console.WriteLine("Geometry {0} Unknown source {1} : ", geom.id, source.id);
                        }

                        Console.Write("Geometry {0} source {1} : ", geom.id, source.id);

                        /*
                        foreach (var mesh_source_value in float_array.Values)
                            Console.Write("{0} ", mesh_source_value);
                         */
                        Console.WriteLine();
                    }

                    // Dump Items[] for geom
                    foreach (var meshItem in meshInfo.Items) {

                        if (meshItem is vertices) {
                            var vertices = meshItem as vertices;
                            var inputs = vertices.input;
                            foreach (var input in inputs)
                                Console.WriteLine("\t Semantic {0} Source {1}", input.semantic, input.source);
                        }
                        else if (meshItem is triangles) {
                            var triangles = meshItem as triangles;
                            var inputs = triangles.input;
                            foreach (var input in inputs)
                                Console.WriteLine("\t Semantic {0} Source {1} Offset {2}", input.semantic, input.source,
                                                  input.offset);
                            Console.WriteLine("\t Indices {0}", triangles.p);
                        }
                        else if (meshItem is polygons) {
                            var polygons = meshItem as polygons;
                            var inputs = polygons.input;
                            foreach (var input in inputs)
                                Console.WriteLine("\t Semantic {0} Source {1} Offset {2}", input.semantic, input.source,
                                                  input.offset);

                            var indexes = polygons.Items.SelectMany(u => u.ToString().Split(' ')).Select(ix => int.Parse(ix, CultureInfo.InvariantCulture)).ToArray();
                            mesh.IndexData = new IntStore(indexes.Where((x, i) => i % 3 == 0));
                            mesh.NormalIndexData = new IntStore(indexes.Where((x, i) => (i + 1) % 3 == 0));
                            mesh.TextureIndexData = new IntStore(indexes.Where((x, i) => (i + 2) % 3 == 0));

                            Console.WriteLine("\t Indices {0}", indexes.ToArray());
                        }
                    }
                }
            }


            foreach (var node in model.Items.OfType<library_visual_scenes>().SelectMany(sceneNode => sceneNode.visual_scene.SelectMany(it => it.node))) {
                if (node.instance_camera != null && node.instance_camera.Length > 0) {
                    var cam = cams.FirstOrDefault(m => m.CameraName.Equals(node.id));
                    if (cam != null) {
                        cam.PosTransform = new Matrix4x4(((matrix)node.Items[0]).Values);
                        cam.Position = new Point(cam.PosTransform[3], cam.PosTransform[7], cam.PosTransform[11]);
                        cam.Up = new Vector(0, 0, -1f);
                        Console.WriteLine("Camera {0} initialized", cam.CameraName);
                    }
                    continue;
                }

                if (cams.Any(cam => node.id.Contains(cam.CameraName))) {
                    var cam = cams.FirstOrDefault(cm => node.id.Contains(cm.CameraName));
                    if (cam != null) {
                        cam.DirTransform = new Matrix4x4(((matrix)node.Items[0]).Values);
                        cam.Direction = new Vector(cam.DirTransform[3], cam.DirTransform[7], cam.DirTransform[11]);
                        Console.WriteLine("Camera {0} initialized", cam.CameraName);
                    }
                    continue;
                }

                if (node.instance_geometry != null && node.instance_geometry.Length > 0) {
                    var mesh = meshes[node.id];
                    if (mesh != null) {
                        var instanceMaterials = node.instance_geometry[0].bind_material;
                        if (instanceMaterials != null)
                            mesh.MaterialName = instanceMaterials.technique_common[0].symbol;
                        mesh.Transform = new Matrix4x4(((matrix)node.Items[0]).Values);
                        Console.WriteLine(mesh);
                    }
                }
            }



            result.Geometry = meshes.Values.ToArray();
            result.Vertices = sceneVerts.ToArray();
            result.Normals = sceneNormals.ToArray();
            result.TexCoords = sceneTexData.ToArray();
            result.Cameras = cams.ToArray();

            return result;
        }
Example #8
0
        public SceneGraphService()
        {
            sceneGraph = new SceneGraphInfo();
            frameParsers = new Dictionary<Type, Action<IFrameElement>>();
            cameras = new List<CameraInfo>();
            frameParsers.Add(typeof(FrameCamera), cameraItem =>
            {
                var item = (FrameCamera)cameraItem;
                cameras.Add(new CameraInfo(item));
                //var transform = Transform.LookAt(item.Position, item.Target, item.Up);
                //CameraNode cam = new CameraNode(transform, transform.GetInverse(), );
                /*Camera = new PinholeCamera(width, height){ Fov = 40f};
                Camera.LookAt(item.Position, item.Target, item.Up);*/
            });



            frameParsers.Add(typeof(FrameObjFileReference), item =>
            {
                var objFileRef = (FrameObjFileReference)item;
                var loader = BaseContainer.Get<IGeometryLoader>("LoadObj");
                    //new GlobalIndexObjLoader();
                scene = loader.Load(objFileRef.ObjFilePath, objFileRef.InvertNormals);
                var mload = BaseContainer.Get<IMaterialLoader>("LoadMtl");
                    //new MaterialLoader();
                mats = mload.LoadMaterials(objFileRef.MtlFilePath);

                foreach (var materialInfo in mats) {
                    if (materialInfo.Name.ToLower().Contains("glass") ||
                         materialInfo.Name.ToLower().Contains("wire_134006006")
                         ) {
                        materialInfo.Kt = materialInfo.DiffuseReflectance;
                        materialInfo.DiffuseReflectance = RgbSpectrum.ZeroSpectrum();

                        materialInfo.MediumInfo = MediumInfo.Glass;
                    }
                    if (materialInfo.Name.ToLower().Contains("metal")) {
                        materialInfo.SpecularReflectance = materialInfo.DiffuseReflectance;
                    }
                }
            });

/*
            frameParsers.Add(typeof(Frame3DsFileReference), item =>
            {
                var sceneFileRef = (Frame3DsFileReference)item;
                var loader = new SceneLoader();
                scene = loader.Load(sceneFileRef.FilePath);
                mats = loader.LoadMaterials(sceneFileRef.FilePath);

                foreach (var materialInfo in mats) {
                    if (materialInfo.Name.ToLower().Contains("glass") ||
                         materialInfo.Name.ToLower().Contains("wire_134006006")
                         ) {
                        materialInfo.Kt = materialInfo.Kd;
                        materialInfo.Kd = RgbSpectrum.ZeroSpectrum();

                        materialInfo.MediumInfo = Glass;
                    }
                    if (materialInfo.Name.ToLower().Contains("metal")) {
                        materialInfo.Kr = materialInfo.Kd;
                    }
                }
                if (scene.Cameras != null && scene.Cameras.Any()) {
                    Camera = new BasicPerspectiveCamera(scene.Cameras[0].Position, scene.Cameras[0].Direction, scene.Cameras[0].Up, width, height) { Fov = scene.Cameras[0].Fov };
                }
            });
*/

            

            frameParsers.Add(typeof(FrameLightsource), item =>
            {
                if (lights == null) {
                    lights = new List<LightsourceInfo>();
                }
                var lightsource = (FrameLightsource)item;
                lights.Add(new LightsourceInfo(lightsource));
            });



            frameParsers.Add(typeof(FrameVolumeArea) , item =>
            {
                if (volumeMats == null)
                {
                    volumeMats = new List<VolumeMaterialInfo>();
                }
                var vm = (FrameVolumeArea) item;
                volumeMats.Add(new VolumeMaterialInfo()
                {
                    Name = vm.MeshName,
                    Outscattering = vm.Emittance,
                    Inscattering = vm.Scattering,
                    Absorbtion = vm.Absorbance
                });
            });
        }
Example #9
0
        private SceneGraphInfo CreateSceneGraph( SceneGeometryInfo geoInfo,
                                                Transform worldTransform, 
                                                SceneGraphChangesType changes = SceneGraphChangesType.FullGraph ) {
            var scene = new SceneGraphInfo() { RootNode = new SceneGraphRootNode() };

            var cams = (cameras.Select(
                cameraInfo =>
                new {
                    cameraInfo,
                    camTransform = Transform.LookAt((Point)cameraInfo.Position, (Point)cameraInfo.Direction, cameraInfo.Up)
                })
                                   .Select(
                                       @t =>
                                       new CameraNode(@t.camTransform, @t.camTransform.GetInverse(), @t.cameraInfo) {
                                           Name = @t.cameraInfo.CameraName
                                       })).Cast<SceneGraphElement>().ToList();

            var scg = new SceneGeometryDataNode(worldTransform, worldTransform.GetInverse(), geoInfo);
            scene.RootNode.Children.Add(scg);

            var geoGroup = new GeometryGroupNode(worldTransform, worldTransform.GetInverse(), scg.Id) {FindRoot = scene.RootNode};
            scene.RootNode.Children.Add(geoGroup);

            var elements = geoInfo.Geometry.Select(
                geometryInfo => new { geometryInfo, geoTransform = new Transform()} )
                                      .Select(
                                          @t =>
                                          new GeometryElementNode(@t.geoTransform, @t.geoTransform.GetInverse(),
                                              @t.geometryInfo)).ToArray();

            geoGroup.Children.AddRange(elements);

            geoGroup.Children.AddRange(elements.Select(geoData => new GeometryInstanceNode(geoData.ObjectToWorld, geoData.WorldToObject, geoData.Id){ FindRoot = scg }));
            scene.RootNode.Children.AddRange(cams);
            scene.RootNode.Children.AddRange(mats.Select(item => new SceneMaterialDataNode(item)));
            scene.RootNode.Children.AddRange(this.lights.Select(item=>new LightsourceNode(null, null, item)));
            if (volumeMats != null && volumeMats.Any())
                scene.RootNode.Children.AddRange(volumeMats.Select(item=>new VolumeNode<VolumeMaterialInfo>(null, null, item)));
            scene.RootNode.WorldToObject = worldTransform;

            return scene;
        }
Example #10
0
        public SceneGeometryInfo ReadScene( Stream inputStream ) {
            var sceneGeometry =  new SceneGeometryInfo();

            using( var reader = new BinaryReader(inputStream) ) {
                var sign = reader.ReadString();
                if( !sign.Equals(SceneGeometryFileSignature) ) {
                    throw new ApplicationException("Invalid data format. Signature not found");
                }
                sceneGeometry.GlobalIndexing = reader.ReadBoolean();
                sceneGeometry.Vertices = new Point[reader.ReadInt32()];
                sceneGeometry.TexCoords= new Vector[reader.ReadInt32()];
                sceneGeometry.Normals= new Vector[reader.ReadInt32()];
                sceneGeometry.Geometry= new GeometryInfo[reader.ReadInt32()];

                //--Vertices

                for( int index = 0; index<sceneGeometry.Vertices.Length; index++ ) {
                    sceneGeometry.Vertices[index].x = reader.ReadSingle();
                    sceneGeometry.Vertices[index].y = reader.ReadSingle();
                    sceneGeometry.Vertices[index].z = reader.ReadSingle();
                }

                for( int index = 0; index<sceneGeometry.Normals.Length; index++ ) {
                    sceneGeometry.Normals[index].x = reader.ReadSingle();
                    sceneGeometry.Normals[index].y = reader.ReadSingle();
                    sceneGeometry.Normals[index].z = reader.ReadSingle();
                }

                for( int index = 0; index<sceneGeometry.TexCoords.Length; index++ ) {
                    sceneGeometry.TexCoords[index].x = reader.ReadSingle();
                    sceneGeometry.TexCoords[index].y = reader.ReadSingle();
                    sceneGeometry.TexCoords[index].z = reader.ReadSingle();
                }

                foreach( var geometryInfo in sceneGeometry.Geometry ) {
                    geometryInfo.Name           = reader.ReadString();
                    geometryInfo.MaterialName   = reader.ReadString();
                    geometryInfo.UseNormals     = reader.ReadBoolean();
                    geometryInfo.UseTextures    = reader.ReadBoolean();

                    int indexCount = reader.ReadInt32();
                    int texIndexCount = reader.ReadInt32();
                    int normIndexCount = reader.ReadInt32();

                    var indexData = new List<int>(indexCount);
                    var texIndexData = new List<int>(indexCount);
                    var normIndexData = new List<int>(indexCount);



                    var r = reader.ReadBytes(indexCount*4);
                    for( int i=0; i<indexCount; i=+4 ) {
                        indexData.Add(BitConverter.ToInt32(r, i));
                    }

                    r = reader.ReadBytes(texIndexCount*4);
                    for( int i=0; i<texIndexCount; i=+4 ) {
                        texIndexData.Add(BitConverter.ToInt32(r, i));
                    }

                    r = reader.ReadBytes(normIndexCount*4);
                    for( int i=0; i<normIndexCount; i=+4 ) {
                        normIndexData.Add(BitConverter.ToInt32(r, i));
                    }

                    geometryInfo.IndexData = new IntStore(indexData);
                    geometryInfo.TextureIndexData = new IntStore(texIndexData);
                    geometryInfo.NormalIndexData= new IntStore(normIndexData);
                }
            }
            return sceneGeometry;
        }
        public void OpenSceneConfiguration(string configPath)
        {
            Scene = new RayEngineScene();
            this.Scene.DefaultLightGain = config.Get("LightGain", new RgbSpectrum(1.75f));
            this.Scene.MaxPathDepth = config.Get("MaxPathDepth", 10);
            this.Scene.RussianRuletteImportanceCap = config.Get("RRImportanceCap", 0.75f);
            this.Scene.MaxPaths = config.Get("PathBufferSize", 65536 >> 1);
            this.Scene.ShadowRayCount = config.Get("ShadowRayCount", 1);

            var loader = new SceneConfigurationLoader();
            loader.Load(configPath, Scene);
            this.width = ValueReader.Convert<int>(loader.Config.ReadFrame("width").ToString());
            this.height = ValueReader.Convert<int>(loader.Config.ReadFrame("height").ToString());
            this.AreaLightAsMeshLight = Scene.AreaLightAsMesh;

            this.Scene.MatLib = this.dependencyManager.GetMaterialPlugin(loader.MaterialInfos);
            if (loader.Materials.Any())
            {
                this.Scene.MatLib.Merge(loader.Materials.ToArray());
            }

            RenderThreadsCount = config.Get("RenderThreadsCount", 1);
            this.scene = loader.SceneGeo;

            var sceneBound = new AABB(scene.BoundingSphereCenter - scene.BoundingSphereRadius,
                                        scene.BoundingSphereCenter + scene.BoundingSphereRadius);
            sceneBound.Expand(1f);

            var volumeBound = sceneBound;
            this.FrameName = loader.Config.ReadFrame("name").ToString();

            Scene.VolumeIntegrator = new SingleScatteringIntegrator(volumeBound,
                                                                        volumeBound.Size.Length / 10f, //step
                                                                        0.05f, //Probability
                                                                        RgbSpectrum.UnitSpectrum() * 0.05f,  //Inscatering
                                                                        new RgbSpectrum(0.0005f)             //Emission

                                                                    );
            foreach (var triangleMeshInfo in Scene.sceneData.Meshes)
            {
                triangleMeshInfo.MaterialID = ((MaterialInfoContainer)Scene.MaterialProvider).GetMaterialID(triangleMeshInfo.MaterialName);
            }

            this.QualitySettings = loader.qualitySettings;
            this.OutputSettings = loader.outputSettings;
            this.Initialize();
        }
Example #12
0
        public RgbSpectrum SamplePhoton(SceneGeometryInfo scene, float u0, float u1, float u2, float u3, float u4, out float pdf, out RayInfo ray)
        {

            Vector dir = MC.UniformSampleSphere(u0, u1);

            ray = new RayInfo(Position+dir*Radius, dir, 1e-4f, 1e4f);

            pdf = MathLab.INV4PI;

            return (Power * Radius * MathLab.M_PI * 4f);
        }
Example #13
0
        public void Populate(int width, int height, SceneGraphInfo scg)
        {
            var svc = new SceneGraphService();
            svc.Populate(new GlobalIndexObjLoader(), new MaterialLoader());
            var cameras = new List<LtCamera>();
            var geometry = new List<LtGeoObject>();
            var lights = new List<LtLightsource>();
            var volumes = new List<LtVolume>();
            var solidMats = new List<SolidMaterial>();
            var matInfos = new List<MaterialInfo>();
            var lightInfos = new List<LightsourceInfo>();

            svc.SceneGraph.Visit((s) =>
            {
                if (s is GeometryGroupNode)
                {
                    sceneGeoInfo = (SceneGeometryInfo)scg.ResolveDataNode<SceneGeometryDataNode>(s as GeometryGroupNode).GetDataItem();
                }
                else if (s is LightsourceNode)
                {
                    var li = (LightsourceInfo)s.GetDataItem();
                    lightInfos.Add(li);
                }
                else if (s is CameraNode)
                {
                    var ci = (CameraInfo)s.GetDataItem();
                    cameras.Add(new LtCamera(new BasicPerspectiveCamera(ci.Position, ci.Direction, ci.Up, width, height, ci.Fov), ci));
                }
                else if (s is SceneMaterialDataNode)
                {
                    var mi = (MaterialInfo)s.GetDataItem();
                    matInfos.Add(mi);
                    Trace.TraceInformation("Loading textures for "+mi.Name);
                    Tracer.TraceLine("Loading textures for " + mi.Name);
                    foreach (var textureInfo in new[] { mi.Diffuse, mi.Alpha, mi.BumpMap, mi.NormalMap, mi.Specular })
                    {
                        TextureManager.Instance.LoadTexture(textureInfo);
                    }
                }
            });

            bool hasAreaLights = lightInfos.Any(item => item.Type == LightSourceTypes.Area);
            var solids = new Dictionary<string, SolidMaterial>();
            //Materials building 
            foreach (var materialInfo in matInfos)
            {
                var bsdf = SolidMaterialFactory.Instance.CreateMaterial(materialInfo);
                bsdf.Alpha = TextureManager.Instance.GetByInfo(materialInfo.Alpha);
                bsdf.Diffuse = TextureManager.Instance.GetByInfo(materialInfo.Diffuse);
                bsdf.Specular = TextureManager.Instance.GetByInfo(materialInfo.Specular);
                bsdf.Bump = TextureManager.Instance.GetByInfo(materialInfo.BumpMap);
                bsdf.Normal = TextureManager.Instance.GetByInfo(materialInfo.NormalMap);
                solidMats.Add(bsdf);
                bsdf.scene = scene;
                solids.Add(materialInfo.Name.ToLowerInvariant(), bsdf);
            }
            //Geometry
            foreach (var triangleMeshInfo in sceneData.Meshes)
            {
                if (VolumeSampler.IsVolume(triangleMeshInfo))
                {
                    var volumeObject = new LtVolume(new MeshShape(triangleMeshInfo), new VolumeProfile());
                    volumes.Add(volumeObject);
                }
                else
                {
                    var geoObject = new LtGeoObject(triangleMeshInfo,
                        solids[triangleMeshInfo.MaterialName.ToLowerInvariant()]);
                    geometry.Add(geoObject);
                }
                /*
                if (hasAreaLights)
                {
                    if (LightSampler.IsLight(triangleMeshInfo.MeshName))
                    {
                        
                    }
                }
                 */
            }

            //Lights

            foreach (var lightsourceInfo in lightInfos)
            {
                switch (lightsourceInfo.Type)
                {
                    case LightSourceTypes.Point:
                        lights.Add(new LtLightsource(new PointLightsource(), new EmissionProfile()));
                        break;
                }
            }

        }
Example #14
0
 public void Init(SceneGeometryInfo scene, IMaterialProvider materialProvider, TriangleMesh[] geometry)
 {
     this.sceneGeometry = scene;
     this.geometry = geometry;
 }
        public void OpenFrame(Library.Entity.Frames.FrameDescription frame)
        {
            this.CurrentFrame = new FrameConfiguration();

            this.config.Merge(frame);
            this.OutputSettings = new OutputSettingsInfo(frame);
            this.QualitySettings = new QualitySettingsInfo(frame);

            this.FrameName = frame.FrameName;

            if (!string.IsNullOrWhiteSpace(frame.WorkingDir))
                Directory.SetCurrentDirectory(frame.WorkingDir);
            /*
            foreach (var frameElement in frame.Elements.Where(frameElement => frameParsers.ContainsKey(frameElement.GetType()))) {
                frameParsers[frameElement.GetType()](frameElement);
            }*/

            if (Scene == null)
            {
                SceneGraphService svc = new SceneGraphService();
                svc.Populate(
                    //new ObjLoader(),
                    new GlobalIndexObjLoader(),
                    new MaterialLoader());

                //svc.OpenFrame(frame);
                _builder = new SceneBuilder() { SGService = svc };
                _builder.Setup();
                this.SceneGraph = _builder.SGService.SceneGraph;
                this.Scene = _builder.OpenFrame(frame, this.AreaLightAsMeshLight);

                this.Scene.DefaultLightGain = config.Get("LightGain", new RgbSpectrum(1.0f));
                this.Scene.MaxPathDepth = config.Get("MaxPathDepth", 10);
                this.Scene.RussianRuletteImportanceCap = config.Get("RRImportanceCap", 0.75f);
                this.Scene.MaxPaths = config.Get("PathBufferSize", 65536);
                this.Scene.ShadowRayCount = config.Get("ShadowRayCount", 1);
                this.Scene.TextureSamplingQuality = this.QualitySettings.TextureSamplingQuality;
                this.Scene.LightSamplingStrategy = this.QualitySettings.LightSamplingStrategy;
                RgbSpectrum.Gamma = true;
                /*
                if (GlobalConfiguration.Instance.SpectralRendering)
                {
                    this.Scene.SpectralMats = new BxDFLibrary(new LambertianBrdf(new[] { 0.5f, 0.5f, 0.5f }));
                    this.Scene.SpectralMats.Populate(_builder.MaterialInfos.ToArray());
                }
                else*/

                {
                    this.Scene.MatLib = this.dependencyManager.GetMaterialPlugin(_builder.MaterialInfos.ToArray());
                    if (_builder.FrameMaterialBuilder != null)
                    {
                        this.Scene.MatLib.Add(_builder.FrameMaterialBuilder.Materials);
                        _builder.FrameMaterialBuilder.CreateRayEngineMaterials(this.Scene);
                    }
                    //if (EnableMaterialOverrides) FrameMaterialBuilder.ApplyMaterialOverrides((this.Scene.MatLib as OptimizedBsdfLibrary).Materials, Scene);
                }


                RenderThreadsCount = config.Get("RenderThreadsCount", 1);
                this.scene = _builder.SceneGeo;

                var sceneBound = new AABB(scene.BoundingSphereCenter - scene.BoundingSphereRadius,
                                          scene.BoundingSphereCenter + scene.BoundingSphereRadius);
                sceneBound.Expand(1f);

                //var viewBound = new AABB(Scene.Camera.Target - 5f, Scene.Camera.Target + 5f);
                var c = new Point(Scene.Camera.Target);
                var bb = new AABB(c - 1f, c + 1f);
                var volumeBound = sceneBound;

                Scene.VolumeIntegrator = new SingleScatteringIntegrator(volumeBound,
                                                                         volumeBound.Size.Length / 10f, //step
                                                                         0.05f, //Probability
                                                                         RgbSpectrum.UnitSpectrum() * 0.05f,  //Inscatering
                                                                         new RgbSpectrum(0.000f)             //Emission

                                                                       );
                new RayEngineMaterialBuilder().BuildMaterials(this.Scene);
            }
            this.CurrentFrame.Width = frame.Get<int>("ImageWidth");
            this.CurrentFrame.Height = frame.Get<int>("ImageHeight");
            this.CurrentFrame.ImageSavePath = this.SavePath;
            this.CurrentFrame.LowLatency = lowLatency;
            this.CurrentFrame.MaxSamplesPerPixel = this.QualitySettings.SamplesPerPixel;

            this.Initialize();
            this.Scene.BuildPrimitives();
        }
Example #16
0
        public RgbSpectrum SamplePhoton(SceneGeometryInfo scene, float u0, float u1, float u2, float u3, float u4, out float pdf,
                                        out RayInfo ray)
        {
            float b0, b1, b2;
            Point orig;
            var tri = SampleTriangle(u4);

            tri.Sample(ref mesh.scene.Vertices, u0, u1, out orig, out b0, out b1, out b2);
            var TriangleNormal = NormalModifier * tri.ComputeNormal(ref mesh.scene.Vertices);
            var area = tri.AreaV(ref mesh.scene.Vertices);
            // Ray direction
            var sampleN = TriangleNormal;
            Vector dir = MC.UniformSampleSphere(u2, u3);
            float RdotN = Normal.Dot(ref dir, ref sampleN);
            if (RdotN < 0f)
            {
                dir *= -1f;
                RdotN = -RdotN;
            }

            ray = new RayInfo(orig, dir);

            pdf = (MathLab.INVTWOPI / area) * (1f / mesh.TrianglesCount);

            return (gain * RdotN);
        }
Example #17
0
 public TriangleLight(SceneGeometryInfo sc)
 {
     this.scene = sc;
 }
Example #18
0
        public SceneGeometryInfo Load(string fileName, bool invertNormals = false, params string[] additionalFiles)
        {
            this.Load3ds(fileName);

            var vertices = new List<Point>();
            int offset = 0;

            foreach (var model in this.models)
            {
                model.VertexOffset = offset;
                vertices.AddRange(model.vertices.Select(item => (Point)item));
                offset += model.vertices.Length;
            }

            var geo = models.Select(modelEntity => new GeometryInfo()
            {
                VertexData = new FloatStore(modelEntity.vertices.ToFloatList()),
                IndexData = new IntStore(modelEntity.indices.SelectMany(item => new[] {
                    (int)item.vertex1 + modelEntity.VertexOffset, 
                    (int)item.vertex2 + modelEntity.VertexOffset,
                    (int)item.vertex3 + modelEntity.VertexOffset
                })),
                NormalIndexData = new IntStore(),
                TextureIndexData = new IntStore(),
                MaterialName = modelEntity.material.MaterialName ?? "default",
                Name = modelEntity.ObjectName,
                NormalData = new FloatStore(modelEntity.normals.ToFloatList()),
                TextureData = new FloatStore(modelEntity.texcoords.ToFloatList()),
                GlobalIndexOffset = modelEntity.VertexOffset
            }).ToList();

            var geometry = new SceneGeometryInfo()
            {
                Vertices = vertices.ToArray(),
                TexCoords = this.models.SelectMany(item => item.texcoords ?? new UV[0]).ToVectorList().ToArray(),
                Normals = this.models.SelectMany(item => item.normals ?? new Vector[0]).ToArray(),
                Geometry = geo.ToArray(),
                Cameras = cameras.Select(item => new CameraInfo() { Position = (Point) item.Position, Direction = item.Direction, Up = new Vector(0, -1f, 0f), Fov = item.Lens }).ToArray(),
                GlobalIndexing = false
            };


            return geometry;
        }
Example #19
0
        public SceneGeometryInfo Load(string filename, bool invertNormals = false, params string[] additionalFiles)
        {
            var FileName = filename;

            if (!File.Exists(filename))
            {
                throw new FileNotFoundException("OBJLoader Error: File not found", filename);
            }

            Positions = new List<Vector>();
            Normals = new List<Vector>();
            Texcoords = new List<Vector>();

            

            mMtrls = new Dictionary<string, ObjFileMaterial>();
            Groups = new List<ObjGroupInfo>();

            mCurrentGroup = null;
            mCurrentMtrlName = null;
            mCurrentMtrl = default(ObjFileMaterial);

            Console.Write("Loading: " + Path.GetFileName(FileName) + "... ");
            //float start = Time.GetTimeInSecs();

            mDirectory = Path.GetDirectoryName(FileName) + "\\";

            mCurrentGroup = new ObjGroupInfo("default");
            Groups.Add(mCurrentGroup);

            ParseFile(ParseObjToken, FileName);
            CreateNormals();
            SceneGeometryInfo result = new SceneGeometryInfo();
            result.Vertices = this.Positions.Select(i => (Point) i).ToArray();
            result.Normals = this.Normals.ToArray();
            result.TexCoords = this.Texcoords.ToArray();
            var geo = new List<GeometryInfo>();

            foreach (var objGroup in this.Groups)
            {
                if (!objGroup.VIndices.Any())
                {
                    Console.WriteLine("No inidexz-");
                    continue;
                    
                }

                if (string.IsNullOrWhiteSpace(objGroup.mtrl))
                {
                    Debugger.Break();
                }

                geo.Add(new GeometryInfo()
                {
                    IndexData = new IntStore(objGroup.VIndices.SelectMany(i=> new[] {i.v0, i.v1, i.v2})),
                    NormalIndexData = new IntStore(objGroup.NIndices.SelectMany(i=> new[] {i.v0, i.v1, i.v2})),
                    TextureIndexData = new IntStore(objGroup.TIndices.SelectMany(i => new[] { i.v0, i.v1, i.v2 })),
                    Name = objGroup.name,
                    MaterialName = objGroup.mtrl,
                });                
            }
            result.Geometry = geo.ToArray();

            return result;
        }
        public void OpenFrame(FrameDescription frame)
        {
            this.config.Merge(frame);
            this.OutputSettings = new OutputSettingsInfo(frame);
            this.QualitySettings = new QualitySettingsInfo(frame);

            this.FrameName = frame.FrameName;
            width = frame.Get<int>("ImageWidth");
            height = frame.Get<int>("ImageHeight");
            if (!string.IsNullOrWhiteSpace(frame.WorkingDir))
                Directory.SetCurrentDirectory(frame.WorkingDir);
   
            if (Scene == null) {
                var svc = new SceneGraphService();
                svc.Populate(new GlobalIndexObjLoader(), new MaterialLoader());

                var builder = new SceneBuilder() { SGService = svc };
                builder.Setup();
                this.Scene = builder.OpenFrame(frame, AreaLightAsMeshLight);
                this.Scene.DefaultLightGain = config.Get("LightGain", new RgbSpectrum(1.0f));
                this.Scene.MaxPathDepth = config.Get("MaxPathDepth", 15);
                this.Scene.RussianRuletteImportanceCap = config.Get("RRImportanceCap", 0.75f);
                this.Scene.MaxPaths = config.Get("PathBufferSize", 65536 >> 10);
                this.Scene.ShadowRayCount = config.Get("ShadowRayCount", 16);
                this.Scene.TextureSamplingQuality = this.QualitySettings.TextureSamplingQuality;
                this.Scene.AreaLightAsMesh = this.AreaLightAsMeshLight;
                this.Scene.MatLib = new OptimizedBsdfLibrary();

                this.Scene.MatLib.Populate(builder.MaterialInfos.ToArray());

                (this.Scene.MatLib as OptimizedBsdfLibrary) .Replace("Object_MaterialView_Test", this.ObjectMaterial);
                (this.Scene.MatLib as OptimizedBsdfLibrary).Replace("Plane_Material", this.PlaneMaterial);

                foreach (var brdf in ObjectMaterial.Where(brdf => brdf != null))
                {
                    builder.ProcessMaterial(0, brdf.MaterialData);
                }
                foreach (var brdf in PlaneMaterial.Where(brdf => brdf != null))
                {
                    builder.ProcessMaterial(1, brdf.MaterialData);
                }

                RenderThreadsCount = config.Get("RenderThreadsCount",1);
                this.scene = builder.SceneGeo;

                var sceneBound = new AABB(scene.BoundingSphereCenter - scene.BoundingSphereRadius,
                                          scene.BoundingSphereCenter + scene.BoundingSphereRadius);
                sceneBound.Expand(1f);

                //var viewBound = new AABB(Scene.Camera.Target - 5f, Scene.Camera.Target + 5f);
                Scene.VolumeIntegrator = new SingleScatteringIntegrator(sceneBound, sceneBound.Size.Length / 10f, 0.15f, RgbSpectrum.UnitSpectrum()*0.095f, new RgbSpectrum(0.0005f));
            }
         

            this.Initialize();

        }
Example #21
0
 public static RgbSpectrum UniformSampleLights(ref Vector wo, IAccellerationStructure intersector,
                                               SceneGeometryInfo scene, IList<ILight> lights, IntersectionInfo isect,
                                               SurfaceBsdf bsdf, FastRandom rnd)
 {
     var Ld = new RgbSpectrum();
     for (int index = 0; index < lights.Count; index++)
     {
         var lightsource = lights[index];
         Ld += EstimateDirect(ref wo, intersector, scene, lightsource, isect, bsdf, rnd);
     }
     return Ld;
 }
Example #22
0
        public void Init(GeometryInfo model, SceneGeometryInfo scene) {
            this.scene = scene;
            triangles = new List<Triangle>();
            normals = new Dictionary<int, Normal[]>(300);
            texCoords = new Dictionary<int, UV[]>();

            this.MaterialName = model.MaterialName;
            this.MeshName = model.Name;



            var delta = -1;
            var index = 0;
            bool hasNormals = false;
            Normal[] norms = null;
            int[] ni = null;

            bool hasTexCoords = false;
            UV[] texs = null;
            int[] ti = null;
            if (model.IndexData.Any()) {
                hasNormals = model.NormalIndexData.Any();
                hasTexCoords = model.TextureIndexData != null && model.TextureIndexData.Any();
                if (hasTexCoords) {
                    texs = scene.TexCoords.ToUVArray();
                    if (!texs.Any())
                        hasTexCoords = false;
                    ti = model.TextureIndexData.ToArray();
                }
                if (hasNormals) {
                    norms = scene.Normals.Select(item => new Normal(item)).ToArray();
                    ni = model.NormalIndexData.ToArray();
                }

                for (int i = 0; i < model.IndexData.Count; i += 3) {
                    index++;
                    var newTriangle = new Triangle(model.IndexData[i] - delta, model.IndexData[i + 1] - delta, model.IndexData[i + 2] - delta);
                    newTriangle.Index = triangles.Count;
                    newTriangle.Owner = this;
                    triangles.Add(newTriangle);
                    //meshIndexes.Add(extMesh);
                    if (hasTexCoords) {
                        var triIndex = index;
                        var t1 = texs[(ti[i] - 1)];
                        var t2 = texs[(ti[i + 1] - 1)];
                        var t3 = texs[(ti[i + 2] - 1)];
                        texCoords.Add(triIndex, new[] { t1, t2, t3 });
                    }
                    if (hasNormals) {
                        //Add vertice normal
                        var triIndex = index;
                        var norm1 = a*norms[(ni[i] - 1)];
                        var norm2 = a*norms[(ni[i + 1] - 1)];
                        var norm3 = a*norms[(ni[i + 2] - 1)];
                        normals.Add(triIndex, new[] { norm1, norm2, norm3 });
                    }
                    else {
                        var triIndex = index;
                        var norm1 = newTriangle.ComputeVerticeNormal(0, ref scene.Vertices);
                        var norm2 = newTriangle.ComputeVerticeNormal(1, ref scene.Vertices);
                        var norm3 = newTriangle.ComputeVerticeNormal(2, ref scene.Vertices);
                        normals.Add(triIndex, new[] { norm1, norm2, norm3 });
                    }
                }
                //extMesh.Indexes = model.IndexBuffer.Select(item => item - (extMesh.StartVertice - 1)).ToArray();
            }
            else {
                for (int i = 0; i < scene.Vertices.Length; i += 3) {
                    var tri = new Triangle(Array.IndexOf(scene.Vertices, scene.Vertices[i]),
                                           Array.IndexOf(scene.Vertices, scene.Vertices[i + 1]),
                                           Array.IndexOf(scene.Vertices, scene.Vertices[i + 2]));

                    triangles.Add(tri);
                    //meshIndexes.Add(extMesh);
                    index++;
                }
            }
        }
Example #23
0
        public static RgbSpectrum EstimateDirect(ref Vector wo, IAccellerationStructure intersector, SceneGeometryInfo scene, ILight light, IntersectionInfo isect, SurfaceBsdf bsdf, FastRandom rnd)
        {
            RgbSpectrum Ld = new RgbSpectrum();
            Vector wi;
            float lightPdf, bsdfPdf;
            RayInfo shadowRay;
            RgbSpectrum Li = light.Sample(ref isect.GeometryInfo.HitPoint, ref isect.GeometryInfo.GeoNormal, rnd.NextFloat(), rnd.NextFloat(), rnd.NextFloat(),
                                          out shadowRay, out lightPdf);
            if (lightPdf > 0f && !Li.IsBlack())
            {
                wi = -shadowRay.Dir;
                RgbSpectrum f ;
                bsdf.f(ref wo, ref wi, ref isect.GeometryInfo.GeoNormal, ref Ld, out f);
                if (!f.IsBlack() && !intersector.Intersect(shadowRay))
                {
                    // Add light's contribution to reflected radiance
                    //Li *= visibility.Transmittance(scene, renderer, NULL, rng, arena);
                    if (light.IsDelta)
                        Ld += f * Li * (Vector.AbsDot(ref wi, ref isect.GeometryInfo.GeoNormal) / lightPdf);
                    else
                    {
                        bsdfPdf = bsdf.Pdf(ref wo, ref wi, BxDFTypes.BSDF_ALL_TYPES);
                        float weight = MC.PowerHeuristic(1, lightPdf, 1, bsdfPdf);
                        Ld += f * Li * (Vector.AbsDot(ref wi, ref isect.GeometryInfo.GeoNormal) * weight / lightPdf);
                    }
                }
            }
            if (!light.IsDelta)
            {
                //float bsdfPdf;
                bool spb;
                BsdfSampleData result;
                bsdf.Sample_f(ref wo, ref isect.GeometryInfo.GeoNormal, ref isect.GeometryInfo.ShadingNormal, ref Ld, rnd.NextFloat(),
                                              rnd.NextFloat(), rnd.NextFloat(), ref isect.TextureData, out result);
                bsdfPdf = result.Pdf;
                if (!result.F.IsBlack() && result.Pdf > 0f)
                {
                    if (lightPdf > 0f)
                    {
                        float weight = MC.PowerHeuristic(1, bsdfPdf, 1, lightPdf);
                        IntersectionInfo lightIsect;
                        RgbSpectrum li = new RgbSpectrum();
                        var ray = new RayInfo(isect.GeometryInfo.HitPoint, result.Wi, 1e-4f, 1e+4f);
                        if (intersector.Intersect(ray, out lightIsect))
                        {
                            if (light is TriangleLight && lightIsect.PrimitiveId.Equals(((TriangleLight)light).Owner.Id))
                                li = light.Le(-result.Wi);
                        }
                        else
                            li = light.Le(ray.Dir);
                        if (!li.IsBlack())
                        {
                            //Li *= scene->Transmittance(ray);
                            Ld += result.F * li * Vector.AbsDot(ref result.Wi, ref isect.GeometryInfo.GeoNormal) * weight / bsdfPdf;
                        }
                    }
                }
            }
            /*

            if (!light->IsDeltaLight()) {
		BxDFType flags = BxDFType(BSDF_ALL & ~BSDF_SPECULAR);
		Spectrum f = bsdf->Sample_f(wo, &wi,
			bs1, bs2, bcs, &bsdfPdf, flags);
		if (!f.Black() && bsdfPdf > 0.) {
			lightPdf = light->Pdf(p, n, wi);
			if (lightPdf > 0.) {
				// Add light contribution from BSDF sampling
				float weight = PowerHeuristic(1, bsdfPdf, 1, lightPdf);
				Intersection lightIsect;
				Spectrum Li(0.f);
				RayDifferential ray(p, wi);
				if (scene->Intersect(ray, &lightIsect)) {
					if (lightIsect.primitive->GetAreaLight() == light)
						Li = lightIsect.Le(-wi);
				}
				else
					Li = light->Le(ray);
				if (!Li.Black()) {
					Li *= scene->Transmittance(ray);
					Ld += f * Li * AbsDot(wi, n) * weight / bsdfPdf;
				}
			}
		}
	} 
             */
            return Ld;
        }
Example #24
0
        public SceneGeometryInfo Load(string fileName, bool invertNormals = false, params string[] additionalFiles)
        {
            var result = new SceneGeometryInfo();
            var objs = new List<GeometryInfo>();
            var curves = new List<CurveInfo>();
            string lastCommand = "f";

            FloatStore vb = null;
            FloatStore vt = null;
            FloatStore vn = null;

            IntStore ib = null;
            int giOffset = 0;

            IntStore tib = null;
            IntStore nib = null;
            int oCount = 0;
            var buffer = new Queue<string>();
            bool isCurve = false;
            string currentMaterial = null;
            ObjHandler.md *= invertNormals ? -1f : 1f;
            Console.WriteLine("Normals inverted : {0}", invertNormals);
            using( var reader = new StreamReader(fileName) ) {
                while( !reader.EndOfStream ) {
                    var s = reader.ReadLine();
                    if( String.IsNullOrEmpty(s) )
                        continue;
                    buffer.Enqueue(s);
                }
            }

            while( buffer.Count > 0 ) {
                string line = buffer.Dequeue();

                if( string.IsNullOrEmpty(line) )
                    continue;
                if (line.StartsWith("#"))
                {
                    isCurve = line.Contains("shape ");
                    continue;                    
                }

                //try
                //{
                var tag = line.Contains(" ") ? line.Substring(0, line.IndexOf(" ")).Trim() : line.Trim();
                switch( tag ) {
                    case "vt":
                        if( vt == null ) {
                            vt = objs[oCount - 1].TextureData;
                        }
                        objs[oCount - 1].UseTextures = true;
                        vt.AddRange(ObjHandler.Process_VT(line));
                        break;
                    case "vn":

                        if( vn == null ) {
                            vn = objs[oCount - 1].NormalData;
                        }
                        objs[oCount - 1].UseNormals = true;
                        vn.AddRange(ObjHandler.Process_VN(line));
                        break;
                    case "v":
                        if( lastCommand.Equals("f") ) {
                            if (isCurve)
                            {
                                if (curves.Count > 0)
                                {
                                    
                                }
                            }
                            if (objs.Count > 0)
                            {
                                giOffset += objs[oCount - 1].IndexData.Count;
                            }
                            var newObj = new GeometryInfo() { GlobalIndexOffset = giOffset, MaterialName = currentMaterial};
                            objs.Add(newObj);
                            //vb = newObj.VertexData;
                            vn = null;
                            ib = null;
                            tib = null;
                            nib = null;
                            oCount++;
                        }
                        if( vb == null ) {
                            vb = objs[oCount - 1].VertexData;
                        }
                        vb.AddRange(ObjHandler.Process_V(line));
                        break;

                    case "f":
                        if( ib == null ) {
                            ib = objs[oCount - 1].IndexData;
                        }
                        int[] tibs, nibs;
                        var ibValues = ObjHandler.Process_F(line, out nibs, out tibs);
                        bool TexInd = false;
                        bool NormInd = false;
                        ib.AddRange(ibValues);
                        if( objs[oCount - 1].UseTextures && objs[oCount - 1].UseNormals ) {
                            NormInd = true;
                            TexInd = true;
                        }
                        else if( objs[oCount - 1].UseTextures && !objs[oCount - 1].UseNormals ) {
                            TexInd = true;
                            tibs = nibs;
                        }
                        else
                            if( !objs[oCount - 1].UseTextures && objs[oCount - 1].UseNormals ) {
                                NormInd = true;
                            }
                        if( TexInd ) {
                            if( tib == null ) {
                                objs[oCount - 1].TextureIndexData = new IntStore();
                                tib = objs[oCount - 1].TextureIndexData;
                            }
                            if( tibs != null ) {
                                tib.AddRange(tibs);
                            }
                            else if( nibs != null) 
                            {
                                tib.AddRange(nibs);
                            }
                        }

                        if( NormInd ) {
                            if( nib == null ) {
                                objs[oCount - 1].NormalIndexData = new IntStore();
                                nib = objs[oCount - 1].NormalIndexData;
                            }
                            
                            if (nibs != null)
                                nib.AddRange(nibs);
                        }
                        break;

                    case "g":
                        if( lastCommand.Equals("f") ) {
                            var newObj = new GeometryInfo() {GlobalIndexOffset = giOffset, MaterialName = currentMaterial };
                            objs.Add(newObj);
                            //vb = null;
                            vn = null;
                            ib = null;
                            tib = null;
                            nib = null;
                            oCount++;
                        }
                        string name = string.Empty;
                        ObjHandler.Process_G(line, out name);
                        objs[oCount - 1].Name = name;
                        break;
                    case "usemtl":
                        string mtl = string.Empty;
                        ObjHandler.Process_Mtl(line, out mtl);
                        objs[oCount - 1].MaterialName = mtl.ToLowerInvariant();
                        currentMaterial = mtl.ToLowerInvariant();
                        break;
                    default:
                        continue;


                }
                lastCommand = tag;
                //}
                //catch (Exception ex)
                //{
                //    throw ex;
                //    //continue;

                //}
            }


            result.Vertices = vb.ToPointList().ToArray();
            AABB bounds = new AABB();
            AABB bounds1 = bounds;
            bounds = result.Vertices.Select(bounds1.Union).Aggregate<AABB>((c, i) => i.Union(c));
            result.BoundingSphereCenter = bounds.Center;
            result.BoundingSphereRadius = bounds1.Size.Length;
            if (vt != null && vt.Any())
                result.TexCoords = vt.TodVectorList().ToArray();
            result.Normals = new FloatStore( objs.SelectMany(item => item.NormalData) ).TodVectorList().ToArray();


            objs.ForEach(ob => {
                ob.IndexData.Iterator(Math.Abs);
                if( ob.TextureIndexData != null )
                    ob.TextureIndexData.Iterator(Math.Abs);
                if( ob.NormalIndexData != null )
                    ob.NormalIndexData.Iterator(Math.Abs);

                ob.Name = String.IsNullOrEmpty(ob.Name) ? Guid.NewGuid().ToString() : ob.Name;
            });

            result.Geometry = objs.ToArray();


            return result;
        }
Example #25
0
        public RgbSpectrum SamplePhoton(SceneGeometryInfo scene, float u0, float u1, float u2, float u3, float u4, out float pdf, out RayInfo ray)
        {
            float b0, b1, b2;
            Point orig;
            tri.Sample(ref scene.Vertices, u0, u1, out orig, out b0, out b1, out b2);

            // Ray direction
            var sampleN = this.TriangleNormal;
            Vector dir = MC.UniformSampleSphere(u2, u3);
            float RdotN = Normal.Dot(ref dir, ref sampleN);
            if (RdotN < 0f)
            {
                dir *= -1f;
                RdotN = -RdotN;
            }

            ray = new RayInfo(orig, dir);

            pdf = MathLab.INVTWOPI / area;

            return Gain * RdotN;
        }
Example #26
0
        public static RgbSpectrum UniformSampleLight(ref Vector wo, IAccellerationStructure intersector,
                                                     SceneGeometryInfo scene, IList<ILight> lights, IntersectionInfo isect,
                                                     SurfaceBsdf bsdf, FastRandom rnd)
        {
            int nLights = lights.Count;

            int lightNum = rnd.Next(0, nLights - 1);
            var light = lights[lightNum];
            return
                (float)nLights *
                EstimateDirect(ref wo, intersector, scene, light, isect, bsdf, rnd);
        }
Example #27
0
        public GLRenderer()
        {
            frameParsers = new Dictionary<Type, Action<IFrameElement>>();
            frameParsers.Add(typeof(FrameCamera), cameraItem =>
            {
                var item = (FrameCamera)cameraItem;
                /*Camera = new PinholeCamera(width, height){ Fov = 40f};
                Camera.LookAt(item.Position, item.Target, item.Up);*/
                Camera = new BasicPerspectiveCamera((Point) item.Position, item.Target, -item.Up, Width, Height) { Fov = 40 };
            });

            frameParsers.Add(typeof(FrameObjFileReference), item =>
            {
                var objFileRef = (FrameObjFileReference)item;
                var loader = new GlobalIndexObjLoader();
                scene = loader.Load(objFileRef.ObjFilePath);
                var mload = new MaterialLoader();
                mats = mload.LoadMaterials(objFileRef.MtlFilePath);

                foreach (var materialInfo in mats)
                {
                    if (materialInfo.Name.ToLower().Contains("glass") ||
                         materialInfo.Name.ToLower().Contains("wire_134006006")
                         )
                    {
                        materialInfo.Kt = materialInfo.DiffuseReflectance;
                        materialInfo.DiffuseReflectance = RgbSpectrum.ZeroSpectrum();

                        //materialInfo.MediumInfo = Glass;
                    }
                    if (materialInfo.Name.ToLower().Contains("metal"))
                    {
                        materialInfo.SpecularReflectance = materialInfo.DiffuseReflectance;
                    }
                }
            });


            frameParsers.Add(typeof(Frame3DsFileReference), item =>
            {
                var sceneFileRef = (Frame3DsFileReference)item;
                var loader = new SceneLoader();
                scene = loader.Load(sceneFileRef.FilePath);
                mats = loader.LoadMaterials(sceneFileRef.FilePath);

                foreach (var materialInfo in mats)
                {
                    if (materialInfo.Name.ToLower().Contains("glass") ||
                         materialInfo.Name.ToLower().Contains("wire_134006006")
                         )
                    {
                        materialInfo.Kt = materialInfo.DiffuseReflectance;
                        materialInfo.DiffuseReflectance = RgbSpectrum.ZeroSpectrum();

                        //materialInfo.MediumInfo = Glass;
                    }
                    if (materialInfo.Name.ToLower().Contains("metal"))
                    {
                        materialInfo.SpecularReflectance = materialInfo.DiffuseReflectance;
                    }
                }
                if (scene.Cameras != null && scene.Cameras.Any())
                {
                    Camera = new BasicPerspectiveCamera((Point) scene.Cameras[0].Position, scene.Cameras[0].Direction, scene.Cameras[0].Up, Width, Height) { Fov = scene.Cameras[0].Fov };
                }
            });


            frameParsers.Add(typeof(FrameLightsource), item =>
            {
                if (lights == null)
                {
                    lights = new List<ILight>();
                }
                var lightsource = (FrameLightsource)item;
                switch (lightsource.LightType)
                {
                    case LightSourceTypes.Point:
                        lights.Add(new PointLight(lightsource));
                        break;
                    case LightSourceTypes.EnvironmentMap:
                        lights.Add(envMap = new InfiniteLight(lightsource));
                        break;
                    case LightSourceTypes.Area:
                        //if (AreaLightAsMeshLight)
                        lights.Add(new MeshLight(lightsource));
                        break;
                }
            });
        }