コード例 #1
0
        private void ConstructLevel(int id)
        {
            if (_rCube != null)
            {
                return;
            }

            _lvlTmp = LevelTemplates.LvlTmp;

            // load meshes
            GlobalFieldMesh = MeshReader.LoadMesh("Assets/Tile.obj.model");
            GlobalCubeMesh  = MeshReader.LoadMesh("Assets/Cube.obj.model");

            // load textures
            var imgData = RContext.LoadImage("Assets/tex_stone.jpg");

            TextureField = RContext.CreateTexture(imgData);

            imgData     = RContext.LoadImage("Assets/tex_cube.jpg");
            TextureCube = RContext.CreateTexture(imgData);

            // camera
            _camPosition    = -3000; // colh
            _objOrientation = float4x4.CreateRotationX(MathHelper.Pi / 2);

            // create cube and set vars
            _rCube = new RollingCube(this);

            _startXy  = new int[2];
            _curLvlId = id;

            // load level
            LoadLevel(id);
        }
コード例 #2
0
ファイル: Main.cs プロジェクト: reliefpfeiler42/Fusee
        public override void Init()
        {
            _angleHorz = 0.2f;
            _angleVert = 0.2f;

            // is called on startup
            RC.ClearColor = new float4(1, 1, 1, 1);

            // initialize the variables
            _meshTea      = MeshReader.LoadMesh(@"Assets/Teapot.obj.model");
            _meshCube     = MeshReader.LoadMesh(@"Assets/Cube.obj.model");
            _meshSphere   = MeshReader.LoadMesh(@"Assets/Sphere.obj.model");
            _meshCylinder = MeshReader.LoadMesh(@"Assets/Cylinder.obj.model");
            _meshPlatonic = MeshReader.LoadMesh(@"Assets/Platonic.obj.model");
            //RC.CreateShader(Vs, Ps);
            _spColor      = RC.CreateShader(Vs, Ps); //MoreShaders.GetShader("simple", RC);
            _spTexture    = RC.CreateShader(Vt, Pt); //MoreShaders.GetShader("texture", RC);
            _spCustom     = RC.CreateShader(VLin, PLin);
            _colorParam   = _spColor.GetShaderParam("vColor");
            _colorCustom  = _spCustom.GetShaderParam("vColor");
            _textureParam = _spTexture.GetShaderParam("vTexture");

            // load texture
            var imgData = RC.LoadImage("Assets/world_map.jpg");

            _iTex = RC.CreateTexture(imgData);


            _physic = new Physics();

            _gui = new GUI(RC);
            _gui.SetUp(_physic.GetNumRB(), _physic.GetShapes());
        }
コード例 #3
0
        // is called on startup
        public override void Init()
        {
            RC.ClearColor = new float4(1f, 1f, 1f, 1);

            // initialize the variables
            _meshTea = MeshReader.LoadMesh(@"Assets/Teapot.obj.model");

            _shaderEffect.AttachToContext(RC);

            /*
             * RC.SetRenderState(RenderState.ZEnable, (uint) 1);
             * RC.SetRenderState(RenderState.AlphaBlendEnable, (uint) 1);
             * RC.SetRenderState(RenderState.BlendFactor, (uint)new ColorUint(0.25f, 0.25f, 0.25f, 0.25f));
             * RC.SetRenderState(RenderState.BlendOperation, (uint)(BlendOperation.Add));
             * RC.SetRenderState(RenderState.SourceBlend, (uint)(Blend.BlendFactor));
             * RC.SetRenderState(RenderState.DestinationBlend, (uint)(Blend.InverseBlendFactor));
             */

            RC.SetRenderState(new RenderStateSet
            {
                AlphaBlendEnable = true,
                BlendFactor      = new float4(0.5f, 0.5f, 0.5f, 0.5f),
                BlendOperation   = BlendOperation.Add,
                SourceBlend      = Blend.BlendFactor,
                DestinationBlend = Blend.InverseBlendFactor
            });
            RC.SetRenderState(RenderState.AlphaBlendEnable, (uint)0);
        }
コード例 #4
0
        public override object Execute(List <string> args)
        {
            if (args.Count != 2)
            {
                return(false);
            }

            var fileType = args[0];
            var fileName = args[1];

            if (fileType != "obj")
            {
                throw new NotSupportedException(fileType);
            }

            if (Definition.Geometry.Resource == null)
            {
                Console.WriteLine("ERROR: Render geometry does not have a resource associated with it.");
                return(true);
            }

            //
            // Deserialize the resource definition
            //

            var definition = Cache.ResourceCache.GetRenderGeometryApiResourceDefinition(Definition.Geometry.Resource);

            Definition.Geometry.SetResourceBuffers(definition);

            using (var resourceStream = new MemoryStream())
            {
                //
                // Extract the resource data
                //
                var file = new FileInfo(fileName);

                if (!file.Directory.Exists)
                {
                    file.Directory.Create();
                }

                using (var objFile = new StreamWriter(file.Create()))
                {
                    var objExtractor = new ObjExtractor(objFile);

                    foreach (var mesh in Definition.Geometry.Meshes)
                    {
                        var vertexCompressor = new VertexCompressor(Definition.Geometry.Compression[0]);
                        var meshReader       = new MeshReader(Cache.Version, mesh);
                        objExtractor.ExtractMesh(meshReader, vertexCompressor);
                    }

                    objExtractor.Finish();
                }
            }

            Console.WriteLine("Done!");

            return(true);
        }
コード例 #5
0
ファイル: World.cs プロジェクト: JynxSp0ck/MadJam
        public World(GameObject obj)
        {
            this.obj = obj;
            chunkobj = Find.name(obj, "Chunks");
            chunks   = new RenderChunk[Settings.map_size, Settings.map_size, Settings.map_size];
            for (int i = 0; i < Settings.map_size; i++)
            {
                for (int j = 0; j < Settings.map_size; j++)
                {
                    for (int k = 0; k < Settings.map_size; k++)
                    {
                        chunks[i, j, k] = null;
                    }
                }
            }
            loadTextures();
            generator = new MeshGenerator();
            Mesh m = new MeshReader(Resources.Load <TextAsset>("Models/cube").text.Split('\n')).getMesh();

            Vector3[] v = m.vertices;
            for (int i = 0; i < v.Length; i++)
            {
                MeshGenerator.cube.vertices.Add(new Vec3(v[i].x, v[i].y, v[i].z));
            }
            Vector2[] c = m.uv;
            for (int i = 0; i < v.Length; i++)
            {
                MeshGenerator.cube.coords.Add(new Vec2(c[i].x, c[i].y));
            }
            MeshGenerator.cube.triangles.AddRange(m.triangles);
        }
コード例 #6
0
        public override void Init()
        {
            _world = new World(RC);

            // load mesh as geometry
            var geo1 = MeshReader.LoadGeometry("Assets/Cube.obj.model");

            // create and set shader
            var sp = RC.CreateShader(VsSimpleTexture, PsSimpleTexture);

            RC.SetShader(sp);

            var material = new ShaderMaterial(sp);

            // load a texture and write a text on it
            var imgData = RC.LoadImage("Assets/cube_tex.jpg");

            imgData = RC.TextOnImage(imgData, "Verdana", 80f, "FUSEE rocks!", "Black", 0, 30);

            var iTex = RC.CreateTexture(imgData);

            Texture1Param = sp.GetShaderParam("texture1");
            RC.SetShaderParamTexture(Texture1Param, iTex);

            // add object with material
            _world.AddObject(geo1, material, 0, 0, 500);

            RC.ClearColor = new float4(0.1f, 0.1f, 0.1f, 1);
        }
コード例 #7
0
        static void Main(string[] args)
        {
            var bb       = MeshReader.ReadMesh("..//..//..//..//dragon.mesh");
            var vertices = MeshReader.ReadVertices("..//..//..//..//dragon.mesh");

            HierarchyWriter.Write(bb, vertices, "..//..//..//..//dragon.bmesh");
        }
コード例 #8
0
        // is called on startup
        public override void Init()
        {
            RC.ClearColor = new float4(1, 1, 1, 1);

            _cubeMesh   = MeshReader.LoadMesh(@"Assets/cube.obj.model");
            _spColor    = MoreShaders.GetDiffuseColorShader(RC);
            _colorParam = _spColor.GetShaderParam("color");
        }
コード例 #9
0
ファイル: UnitTest1.cs プロジェクト: zawecha1/moddingSuite
        public void TestMeshReader()
        {
            var file = Path.Combine(@"C:\Users\enohka\Desktop\teststuff", "mesh_all.spk");

            var mreader = new MeshReader();

            using (var fs = new FileStream(file, FileMode.Open))
                mreader.Read(fs);
        }
コード例 #10
0
        public override void Init()
        {
            Input.Instance.InitializeDevices();

            _meshTea = MeshReader.LoadMesh(@"Assets/Teapot.obj.model");

            _spColor    = Shaders.GetDiffuseColorShader(RC);
            _colorParam = _spColor.GetShaderParam("color");
        }
コード例 #11
0
        public override void Init()
        {
            RC.ClearColor = new float4(1, 1, 1, 1);

            _pc = new PickingContext(RC);

            _meshTea  = MeshReader.LoadMesh(@"Assets/Teapot.obj.model");
            _meshCube = MeshReader.LoadMesh(@"Assets/Cube.obj.model");

            _spColor    = Shaders.GetDiffuseColorShader(RC);
            _colorParam = _spColor.GetShaderParam("color");
        }
コード例 #12
0
        public GameEntity(String meshPath, RenderContext rc, float posX = 0, float posY = 0, float posZ = 0, float angX = 0, float angY = 0, float angZ = 0)
        {
            _mesh = MeshReader.LoadMesh(meshPath);
            _rc   = rc;

            Position = float4x4.CreateRotationX(angX) *
                       float4x4.CreateRotationY(angY) *
                       float4x4.CreateRotationZ(angZ) *
                       float4x4.CreateTranslation(posX, posY, posZ);

            SetShader(_color);
        }
コード例 #13
0
ファイル: Physics.cs プロジェクト: reliefpfeiler42/Fusee
        public void InitGearConstraint()
        {
            var mesh = MeshReader.LoadMesh(@"Assets/Cube.obj.model");
            var rbA  = _world.AddRigidBody(0, new float3(0, 150, 0), float3.Zero, MyBoxCollider);

            _numRB++;


            var rbB = _world.AddRigidBody(1, new float3(0, 300, 0), float3.Zero, MyBoxCollider);

            _numRB++;
        }
コード例 #14
0
        // is called on startup
        public override void Init()
        {
            RC.ClearColor = new float4(0.1f, 0.1f, 0.5f, 1);

            _meshCube = MeshReader.LoadMesh(@"Assets/Cube.obj.model");

            _spTexture = Shaders.GetTextureShader(RC);

            _textureParam = _spTexture.GetShaderParam("texture1");

            _videoStream = VideoManager.Instance.LoadVideoFromFile(@"Assets/pot.webm", true);
            //_videoStream = VideoManager.Instance.LoadVideoFromCamera(0, false);
        }
コード例 #15
0
        public GameEntity(String meshPath, RenderContext rc, float posX = 0, float posY = 0, float posZ = 0, float angX = 0, float angY = 0, float angZ = 0)
        {
            _mesh = MeshReader.LoadMesh(meshPath);
            _rc   = rc;

            Position = float4x4.CreateRotationX(angX) *
                       float4x4.CreateRotationY(angY) *
                       float4x4.CreateRotationZ(angZ) *
                       float4x4.CreateTranslation(posX, posY, posZ);

            _shaderProgram = MoreShaders.GetDiffuseColorShader(rc);
            _shaderParam   = _shaderProgram.GetShaderParam("color");
        }
コード例 #16
0
        private bool ExtractObj(string variantName, FileInfo modelFile, RenderModel renderModel, RenderGeometryApiResourceDefinition resourceDefinition, Stream resourceStream)
        {
            var meshes           = new Dictionary <string, Mesh>();
            var vertexCompressor = new VertexCompressor(renderModel.Geometry.Compression[0]);

            foreach (var region in renderModel.Regions)
            {
                var regionName = CacheContext.GetString(region.Name);

                foreach (var permutation in region.Permutations)
                {
                    var permutationName = CacheContext.GetString(permutation.Name);

                    if (variantName != "*" && variantName != permutationName)
                    {
                        continue;
                    }

                    for (var i = 0; i < permutation.MeshCount; i++)
                    {
                        var name = $"{regionName}_{permutationName}_{i}";
                        meshes[name] = renderModel.Geometry.Meshes[permutation.MeshIndex + i];
                    }
                }
            }

            if (meshes.Count == 0)
            {
                Console.WriteLine($"ERROR: No meshes found under variant '{variantName}'!");
                return(false);
            }

            Console.Write("Extracting {0} mesh(es)...", meshes.Count);

            using (var objFile = new StreamWriter(modelFile.Create()))
            {
                var objExtractor = new ObjExtractor(objFile);

                foreach (var entry in meshes)
                {
                    var meshReader = new MeshReader(CacheContext.Version, entry.Value, resourceDefinition);
                    objExtractor.ExtractMesh(meshReader, vertexCompressor, resourceStream, entry.Key);
                }

                objExtractor.Finish();
            }

            Console.WriteLine("done!");

            return(true);
        }
コード例 #17
0
 private void LoadMeshWithObjParser()
 {
     RC.Clear(ClearFlags.Color | ClearFlags.Depth);
     _isCurrentlyLoading = true;
     _currentMesh        = null;
     Debug.WriteLine("Started loading Mesh using MeshReader.");
     RC.Clear(ClearFlags.Color | ClearFlags.Depth);
     _watch.Start();
     _currentMesh = MeshReader.LoadMesh(@"Assets/Teapot.obj.model");
     _watch.Stop();
     Debug.WriteLine("Mesh loaded using MeshReader in " + _watch.ElapsedMilliseconds + "ms");
     _watch.Reset();
     _isCurrentlyLoading = false;
 }
コード例 #18
0
        public override void Init()
        {
            RC.ClearColor = new float4(0.5f, 0.5f, 0.5f, 1);

            // load meshes
            Body   = MeshReader.LoadMesh(@"Assets/mageBodyOBJ.obj.model");
            GloveL = MeshReader.LoadMesh(@"Assets/mageGloveLOBJ.obj.model");
            GloveR = MeshReader.LoadMesh(@"Assets/mageGloveROBJ.obj.model");

            // set up shader, lights and textures
            var spBody = RC.CreateShader(VsBump, PsBump);

            RC.SetShader(spBody);

            RC.SetLightActive(0, 1);
            RC.SetLightPosition(0, new float3(5.0f, 0.0f, 2.0f));
            RC.SetLightAmbient(0, new float4(0.2f, 0.2f, 0.2f, 1.0f));
            RC.SetLightSpecular(0, new float4(0.1f, 0.1f, 0.1f, 1.0f));
            RC.SetLightDiffuse(0, new float4(0.8f, 0.8f, 0.8f, 1.0f));
            RC.SetLightDirection(0, new float3(-1.0f, 0.0f, 0.0f));

            RC.SetLightActive(1, 1);
            RC.SetLightPosition(1, new float3(-5.0f, 0.0f, 2.0f));
            RC.SetLightAmbient(1, new float4(0.5f, 0.5f, 0.5f, 1.0f));
            RC.SetLightSpecular(1, new float4(0.1f, 0.1f, 0.1f, 1.0f));
            RC.SetLightDiffuse(1, new float4(1.0f, 1.0f, 1.0f, 1.0f));
            RC.SetLightDirection(1, new float3(1.0f, 0.0f, 0.0f));

            _texture1ParamBody = spBody.GetShaderParam("texture1");
            _texture2ParamBody = spBody.GetShaderParam("normalTex");
            _specularLevelBody = spBody.GetShaderParam("specularLevel");

            var imgDataGlove  = RC.LoadImage("Assets/HandAOMap.jpg");
            var imgData2Glove = RC.LoadImage("Assets/HandschuhNormalMap.jpg");

            _iTexGlove  = RC.CreateTexture(imgDataGlove);
            _iTex2Glove = RC.CreateTexture(imgData2Glove);

            var imgData  = RC.LoadImage("Assets/TextureAtlas.jpg");
            var imgData2 = RC.LoadImage("Assets/TextureAtlasNormal.jpg");

            _iTex  = RC.CreateTexture(imgData);
            _iTex2 = RC.CreateTexture(imgData2);

            // misc settings
            _angleHorz = 0;
            _angleVert = 0;

            _rotationSpeed = 1.5f;
        }
コード例 #19
0
        private void EditMeshExecute(object obj)
        {
            var vm = CollectionViewSource.GetDefaultView(OpenFiles).CurrentItem as EdataFileViewModel;

            if (vm == null)
            {
                return;
            }

            var mesh = vm.FilesCollectionView.CurrentItem as EdataContentFile;

            if (mesh == null)
            {
                return;
            }

            var dispatcher = Dispatcher.CurrentDispatcher;

            Action <ViewModelBase, ViewModelBase> open = DialogProvider.ProvideView;
            Action <string> report = msg => StatusText = msg;

            var s = new Task(() =>
            {
                try
                {
                    dispatcher.Invoke(() => IsUIBusy = true);
                    dispatcher.Invoke(report, "Reading Mesh package...");

                    var reader   = new MeshReader();
                    var meshfile = reader.Read(vm.EdataManager.GetRawData(mesh));

                    var detailsVm = new MeshEditorViewModel(meshfile);

                    dispatcher.Invoke(open, detailsVm, this);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Unhandeled exception in Thread occoured: {0}", ex.ToString());
                }
                finally
                {
                    dispatcher.Invoke(() => IsUIBusy = false);
                    dispatcher.Invoke(report, "Ready");
                }
            });

            s.Start();
        }
コード例 #20
0
ファイル: Physics.cs プロジェクト: reliefpfeiler42/Fusee
        public void InitColliders()
        {
            MyBoxCollider      = _world.AddBoxShape(2);
            MySphereCollider   = _world.AddSphereShape(2);
            MyCylinderCollider = _world.AddCylinderShape(new float3(2, 4, 2));

            BoxMesh      = MeshReader.LoadMesh(@"Assets/Cube.obj.model");
            TeaPotMesh   = MeshReader.LoadMesh(@"Assets/Teapot.obj.model");
            PlatonicMesh = MeshReader.LoadMesh(@"Assets/Platonic.obj.model");
            float3[] verts = PlatonicMesh.Vertices;

            MyConvHull = _world.AddConvexHullShape(verts, true);

            float3[] vertsTeaPot = TeaPotMesh.Vertices;
            TeaPotHull = _world.AddConvexHullShape(vertsTeaPot, true);
            TeaPotHull.LocalScaling = new float3(0.05f, 0.05f, 0.05f);
        }
コード例 #21
0
ファイル: ObjExtractor.cs プロジェクト: TheGuardians/TagTool
        /// <summary>
        /// Writes mesh data to the .obj.
        /// </summary>
        /// <param name="reader">The mesh reader to use.</param>
        /// <param name="compressor">The vertex compressor to use.</param>
        /// <param name="resourceStream">A stream open on the resource data.</param>
        public void ExtractMesh(MeshReader reader, VertexCompressor compressor, Stream resourceStream)
        {
            // Read the vertex buffer and decompress each vertex
            var vertices = ReadVertices(reader, resourceStream);
            DecompressVertices(vertices, compressor);

            // Write out the vertices
            WriteVertices(vertices);

            // Read and write out the triangles for each part
            foreach (var part in reader.Mesh.Parts)
            {
                var indexes = ReadIndexes(reader, part, resourceStream);
                WriteTriangles(indexes);
            }
            _baseIndex += (uint)vertices.Count;
        }
コード例 #22
0
ファイル: Physics.cs プロジェクト: reliefpfeiler42/Fusee
        public void InitSliderConstraint()
        {
            var mesh = MeshReader.LoadMesh(@"Assets/Cube.obj.model");
            var rbA  = _world.AddRigidBody(1, new float3(400, 500, 0), float3.Zero, MyBoxCollider);

            _numRB++;
            rbA.LinearFactor  = new float3(0, 0, 0);
            rbA.AngularFactor = new float3(0, 0, 0);

            var rbB = _world.AddRigidBody(1, new float3(200, 500, 0), float3.Zero, MyBoxCollider);

            _numRB++;
            var frameInA = float4x4.Identity;

            frameInA.Row3 = new float4(0, 1, 0, 1);
            var frameInB = float4x4.Identity;

            frameInA.Row3 = new float4(0, 0, 0, 1);
            var sc = _world.AddSliderConstraint(rbA, rbB, frameInA, frameInB, true);
        }
コード例 #23
0
ファイル: FuseeApp.cs プロジェクト: reliefpfeiler42/Fusee
        // is called on startup
        public override void Init()
        {
            _theColor     = new float4(0.5f, 0.8f, 0, 1);
            RC.ClearColor = new float4(1, 1, 1, 1);

            // initialize the variables
            _meshTea  = MeshReader.LoadMesh(@"Assets/Teapot.obj.model");
            _meshFace = MeshReader.LoadMesh(@"Assets/Face.obj.model");

            _spColor   = MoreShaders.GetShader("simple", RC);
            _spTexture = MoreShaders.GetShader("texture", RC);

            _colorParam   = _spColor.GetShaderParam("vColor");
            _textureParam = _spTexture.GetShaderParam("texture1");

            // load texture
            var imgData = RC.LoadImage("Assets/world_map.jpg");

            _iTex = RC.CreateTexture(imgData);
        }
コード例 #24
0
        public GameEntity(String meshPath, RenderContext rc, float posX = 0, float posY = 0, float posZ = 0, float angX = 0, float angY = 0, float angZ = 0)
        {
            if (meshPath.Contains("protobuf"))
            {
                _ser = new MySerializer();
                using (var file = File.OpenRead(meshPath))
                {
                    _mesh = _ser.Deserialize(file, null, typeof(Mesh)) as Mesh;
                }
            }
            else
            {
                _mesh = MeshReader.LoadMesh(meshPath);
            }

            _rc = rc;

            Position = float4x4.CreateRotationX(angX) *
                       float4x4.CreateRotationY(angY) *
                       float4x4.CreateRotationZ(angZ) *
                       float4x4.CreateTranslation(posX, posY, posZ);

            SetShader(_color);
        }
コード例 #25
0
        public override bool Execute(List<string> args)
        {
            if (args.Count != 3)
                return false;

            var variantName = args[0];
            var fileType = args[1];
            var fileName = args[2];

            if (fileType != "obj" && fileType != "amf")
                return false;

            // Find the variant to extract
            if (Definition.RenderModel == null)
            {
                Console.WriteLine("The model does not have a render model associated with it.");
                return true;
            }

            var variant = Definition.Variants.FirstOrDefault(v => (Info.StringIDs.GetString(v.Name) ?? v.Name.ToString()) == variantName);
            if (variant == null && Definition.Variants.Count > 0)
            {
                Console.WriteLine("Unable to find variant \"{0}\"", variantName);
                Console.WriteLine("Use \"listvariants\" to list available variants.");
                return true;
            }

            if (fileType == "amf")
                return ExtractAMF(variant, fileName);

            // Load resource caches
            Console.WriteLine("Loading resource caches...");
            var resourceManager = new ResourceDataManager();
            try
            {
                resourceManager.LoadCachesFromDirectory(Info.CacheFile.DirectoryName);
            }
            catch
            {
                Console.WriteLine("Unable to load the resource .dat files.");
                Console.WriteLine("Make sure that they all exist and are valid.");
                return true;
            }

            // Deserialize the render model tag
            Console.WriteLine("Reading model data...");
            RenderModel renderModel;
            using (var cacheStream = Info.CacheFile.OpenRead())
            {
                var renderModelContext = new TagSerializationContext(cacheStream, Info.Cache, Info.StringIDs, Definition.RenderModel);
                renderModel = Info.Deserializer.Deserialize<RenderModel>(renderModelContext);
            }

            if (renderModel.Geometry.Resource == null)
            {
                Console.WriteLine("Render model does not have a resource associated with it");
                return true;
            }

            // Deserialize the resource definition
            var resourceContext = new ResourceSerializationContext(renderModel.Geometry.Resource);
            var definition = Info.Deserializer.Deserialize<RenderGeometryResourceDefinition>(resourceContext);

            using (var resourceStream = new MemoryStream())
            {
                // Extract the resource data
                resourceManager.Extract(renderModel.Geometry.Resource, resourceStream);

                Directory.CreateDirectory(Path.GetDirectoryName(fileName));

                using (var objFile = new StreamWriter(File.Open(fileName, FileMode.Create, FileAccess.Write)))
                {
                    var objExtractor = new ObjExtractor(objFile);
                    var vertexCompressor = new VertexCompressor(renderModel.Geometry.Compression[0]); // Create a (de)compressor from the first compression block

                    if (variant != null)
                    {
                        // Extract each region in the variant
                        foreach (var region in variant.Regions)
                        {
                            // Get the corresonding region in the render model tag
                            if (region.RenderModelRegionIndex >= renderModel.Regions.Count)
                                continue;

                            var renderModelRegion = renderModel.Regions[region.RenderModelRegionIndex];

                            // Get the corresponding permutation in the render model tag
                            // (Just extract the first permutation for now)
                            if (region.Permutations.Count == 0)
                                continue;

                            var permutation = region.Permutations[0];

                            if (permutation.RenderModelPermutationIndex < 0 ||
                                permutation.RenderModelPermutationIndex >= renderModelRegion.Permutations.Count)
                                continue;

                            var renderModelPermutation = renderModelRegion.Permutations[permutation.RenderModelPermutationIndex];

                            // Extract each mesh in the permutation
                            var meshIndex = renderModelPermutation.MeshIndex;
                            var meshCount = renderModelPermutation.MeshCount;
                            var regionName = Info.StringIDs.GetString(region.Name) ?? region.Name.ToString();
                            var permutationName = Info.StringIDs.GetString(permutation.Name) ?? permutation.Name.ToString();

                            Console.WriteLine("Extracting {0} mesh(es) for {1}:{2}...", meshCount, regionName, permutationName);

                            for (var i = 0; i < meshCount; i++)
                            {
                                // Create a MeshReader for the mesh and pass it to the obj extractor
                                var meshReader = new MeshReader(Info.Version, renderModel.Geometry.Meshes[meshIndex + i], definition);
                                objExtractor.ExtractMesh(meshReader, vertexCompressor, resourceStream);
                            }
                        }
                    }
                    else
                    {
                        // No variant - just extract every mesh
                        Console.WriteLine("Extracting {0} mesh(es)...", renderModel.Geometry.Meshes.Count);

                        foreach (var mesh in renderModel.Geometry.Meshes)
                        {
                            // Create a MeshReader for the mesh and pass it to the obj extractor
                            var meshReader = new MeshReader(Info.Version, mesh, definition);
                            objExtractor.ExtractMesh(meshReader, vertexCompressor, resourceStream);
                        }
                    }

                    objExtractor.Finish();
                }
            }
            Console.WriteLine("Done!");
            return true;
        }
コード例 #26
0
        public override bool Execute(List <string> args)
        {
            if (args.Count != 3)
            {
                return(false);
            }
            var variantName = args[0];
            var fileType    = args[1];
            var fileName    = args[2];

            if (fileType != "obj")
            {
                return(false);
            }

            // Find the variant to extract
            if (Definition.RenderModel == null)
            {
                Console.WriteLine("The model does not have a render model associated with it.");
                return(true);
            }
            var variant = Definition.Variants.FirstOrDefault(v => (Info.StringIds.GetString(v.Name) ?? v.Name.ToString()) == variantName);

            if (variant == null && Definition.Variants.Count > 0)
            {
                Console.WriteLine("Unable to find variant \"{0}\"", variantName);
                Console.WriteLine("Use \"listvariants\" to list available variants.");
                return(true);
            }

            // Load resource caches
            Console.WriteLine("Loading resource caches...");
            var resourceManager = new ResourceDataManager();

            try
            {
                resourceManager.LoadCachesFromDirectory(Info.CacheFile.DirectoryName);
            }
            catch
            {
                Console.WriteLine("Unable to load the resource .dat files.");
                Console.WriteLine("Make sure that they all exist and are valid.");
                return(true);
            }

            // Deserialize the render model tag
            Console.WriteLine("Reading model data...");
            RenderModel renderModel;

            using (var cacheStream = Info.CacheFile.OpenRead())
            {
                var renderModelContext = new TagSerializationContext(cacheStream, Info.Cache, Info.StringIds, Definition.RenderModel);
                renderModel = Info.Deserializer.Deserialize <RenderModel>(renderModelContext);
            }
            if (renderModel.Geometry.Resource == null)
            {
                Console.WriteLine("Render model does not have a resource associated with it");
                return(true);
            }

            // Deserialize the resource definition
            var resourceContext = new ResourceSerializationContext(renderModel.Geometry.Resource);
            var definition      = Info.Deserializer.Deserialize <RenderGeometryResourceDefinition>(resourceContext);

            using (var resourceStream = new MemoryStream())
            {
                // Extract the resource data
                resourceManager.Extract(renderModel.Geometry.Resource, resourceStream);
                using (var objFile = new StreamWriter(File.Open(fileName, FileMode.Create, FileAccess.Write)))
                {
                    var objExtractor     = new ObjExtractor(objFile);
                    var vertexCompressor = new VertexCompressor(renderModel.Geometry.Compression[0]); // Create a (de)compressor from the first compression block
                    if (variant != null)
                    {
                        // Extract each region in the variant
                        foreach (var region in variant.Regions)
                        {
                            // Get the corresonding region in the render model tag
                            if (region.RenderModelRegionIndex >= renderModel.Regions.Count)
                            {
                                continue;
                            }
                            var renderModelRegion = renderModel.Regions[region.RenderModelRegionIndex];

                            // Get the corresponding permutation in the render model tag
                            // (Just extract the first permutation for now)
                            if (region.Permutations.Count == 0)
                            {
                                continue;
                            }
                            var permutation = region.Permutations[0];
                            if (permutation.RenderModelPermutationIndex < 0 ||
                                permutation.RenderModelPermutationIndex >= renderModelRegion.Permutations.Count)
                            {
                                continue;
                            }
                            var renderModelPermutation = renderModelRegion.Permutations[permutation.RenderModelPermutationIndex];

                            // Extract each mesh in the permutation
                            var meshIndex       = renderModelPermutation.MeshIndex;
                            var meshCount       = renderModelPermutation.MeshCount;
                            var regionName      = Info.StringIds.GetString(region.Name) ?? region.Name.ToString();
                            var permutationName = Info.StringIds.GetString(permutation.Name) ?? permutation.Name.ToString();
                            Console.WriteLine("Extracting {0} mesh(es) for {1}:{2}...", meshCount, regionName, permutationName);
                            for (var i = 0; i < meshCount; i++)
                            {
                                // Create a MeshReader for the mesh and pass it to the obj extractor
                                var meshReader = new MeshReader(Info.Version, renderModel.Geometry.Meshes[meshIndex + i], definition);
                                objExtractor.ExtractMesh(meshReader, vertexCompressor, resourceStream);
                            }
                        }
                    }
                    else
                    {
                        // No variant - just extract every mesh
                        Console.WriteLine("Extracting {0} mesh(es)...", renderModel.Geometry.Meshes.Count);
                        foreach (var mesh in renderModel.Geometry.Meshes)
                        {
                            // Create a MeshReader for the mesh and pass it to the obj extractor
                            var meshReader = new MeshReader(Info.Version, mesh, definition);
                            objExtractor.ExtractMesh(meshReader, vertexCompressor, resourceStream);
                        }
                    }
                    objExtractor.Finish();
                }
            }
            Console.WriteLine("Done!");
            return(true);
        }
コード例 #27
0
        private void ExtractObj(FileInfo modelFile, RenderModel renderModel, Model.Variant modelVariant, RenderGeometryApiResourceDefinition resourceDefinition, Stream resourceStream)
        {
            using (var objFile = new StreamWriter(modelFile.Create()))
            {
                var objExtractor = new ObjExtractor(objFile);

                // Create a (de)compressor from the first compression block
                var vertexCompressor = new VertexCompressor(renderModel.Geometry.Compression[0]);

                if (modelVariant != null)
                {
                    // Extract each region in the variant
                    foreach (var region in modelVariant.Regions)
                    {
                        // Get the corresonding region in the render model tag
                        if (region.RenderModelRegionIndex >= renderModel.Regions.Count)
                        {
                            continue;
                        }

                        var renderModelRegion = renderModel.Regions[region.RenderModelRegionIndex];

                        // Get the corresponding permutation in the render model tag
                        // (Just extract the first permutation for now)
                        if (region.Permutations.Count == 0)
                        {
                            continue;
                        }

                        var permutation = region.Permutations[0];

                        if (permutation.RenderModelPermutationIndex < 0 ||
                            permutation.RenderModelPermutationIndex >= renderModelRegion.Permutations.Count)
                        {
                            continue;
                        }

                        var renderModelPermutation = renderModelRegion.Permutations[permutation.RenderModelPermutationIndex];

                        // Extract each mesh in the permutation
                        var meshIndex       = renderModelPermutation.MeshIndex;
                        var meshCount       = renderModelPermutation.MeshCount;
                        var regionName      = CacheContext.GetString(region.Name) ?? region.Name.ToString();
                        var permutationName = CacheContext.GetString(permutation.Name) ?? permutation.Name.ToString();

                        Console.WriteLine("Extracting {0} mesh(es) for {1}:{2}...", meshCount, regionName, permutationName);

                        for (var i = 0; i < meshCount; i++)
                        {
                            // Create a MeshReader for the mesh and pass it to the obj extractor
                            var meshReader = new MeshReader(CacheContext.Version, renderModel.Geometry.Meshes[meshIndex + i], resourceDefinition);
                            objExtractor.ExtractMesh(meshReader, vertexCompressor, resourceStream);
                        }
                    }
                }
                else
                {
                    // No variant - just extract every mesh
                    Console.WriteLine("Extracting {0} mesh(es)...", renderModel.Geometry.Meshes.Count);

                    foreach (var mesh in renderModel.Geometry.Meshes)
                    {
                        // Create a MeshReader for the mesh and pass it to the obj extractor
                        var meshReader = new MeshReader(CacheContext.Version, mesh, resourceDefinition);
                        objExtractor.ExtractMesh(meshReader, vertexCompressor, resourceStream);
                    }
                }

                objExtractor.Finish();
            }
        }
コード例 #28
0
        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);
            };
コード例 #29
0
ファイル: ObjExtractor.cs プロジェクト: TheGuardians/TagTool
        /// <summary>
        /// Reads the index buffer data and converts it into a triangle list if necessary.
        /// </summary>
        /// <param name="reader">The mesh reader to use.</param>
        /// <param name="part">The mesh part to read.</param>
        /// <param name="resourceStream">A stream open on the resource data.</param>
        /// <returns>The index buffer converted into a triangle list.</returns>
        private static uint[] ReadIndexes(MeshReader reader, Mesh.Part part, Stream resourceStream)
        {
            // Use index buffer 0
            var indexBuffer = reader.IndexBuffers[0];
            if (indexBuffer == null)
                throw new InvalidOperationException("Index buffer 0 is null");

            // Read the indexes
            var indexStream = reader.OpenIndexBufferStream(indexBuffer, resourceStream);
            indexStream.Position = part.FirstIndex;
            switch (indexBuffer.Type)
            {
                case PrimitiveType.TriangleList:
                    return indexStream.ReadIndexes(part.IndexCount);
                case PrimitiveType.TriangleStrip:
                    return indexStream.ReadTriangleStrip(part.IndexCount);
                default:
                    throw new InvalidOperationException("Unsupported index buffer type: " + indexBuffer.Type);
            }
        }
コード例 #30
0
ファイル: ObjExtractor.cs プロジェクト: TheGuardians/TagTool
        /// <summary>
        /// Reads the vertex data for a mesh into a format-independent list.
        /// </summary>
        /// <param name="reader">The mesh reader to use.</param>
        /// <param name="resourceStream">A stream open on the resource data.</param>
        /// <returns>The list of vertices that were read.</returns>
        private static List<ObjVertex> ReadVertices(MeshReader reader, Stream resourceStream)
        {
            // Open a vertex reader on stream 0 (main vertex data)
            var mainBuffer = reader.VertexStreams[0];
            if (mainBuffer == null)
                throw new InvalidOperationException("Mesh does not have a vertex buffer bound to stream 0");
            var vertexReader = reader.OpenVertexStream(mainBuffer, resourceStream);

            switch (reader.Mesh.Type)
            {
                case VertexType.Rigid:
                    return ReadRigidVertices(vertexReader, mainBuffer.Count);
                case VertexType.Skinned:
                    return ReadSkinnedVertices(vertexReader, mainBuffer.Count);
                case VertexType.DualQuat:
                    return ReadDualQuatVertices(vertexReader, mainBuffer.Count);
                default:
                    throw new InvalidOperationException("Only Rigid, Skinned, and DualQuat meshes are supported");
            }
        }
コード例 #31
0
        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();
        }
コード例 #32
0
ファイル: QuadricErrorMetric.cs プロジェクト: gxmc/terremesh
        public void Load(System.IO.Stream stream)
        {
            var reader = new MeshReader(stream);

            //reader.ReadMesh(
        }
コード例 #33
0
        public override void Init()
        {
            _sceneManager = new SceneManager();
            _sceneManager.AttachToContext(RC);

            var spot = new SpotLight(new float3(0, 0, 0), new float3(0, 0, 0), new float4(0.7f, 0.7f, 0.7f, 1),
                                     new float4(0.3f, 0.3f, 0.3f, 1), new float4(0.1f, 0.1f, 0.1f, 1), (float)Math.PI / 8, 0);

            var sphereGeom   = MeshReader.LoadGeometry("Assets/Sphere.obj.model");
            var spaceboxGeom = MeshReader.LoadGeometry("Assets/Spacebox.obj.model");
            var lampGeom     = MeshReader.LoadGeometry("Assets/Lamp.obj.model");

            // main objects
            var worldOrigin = new SceneEntity("WorldOrigin", new MouseAction());

            var cameraholder = new SceneEntity("CameraOwner", new CamScript())
            {
                Transform =
                {
                    GlobalPosition = new float3(0, 0, 10)
                }
            };

            worldOrigin.AddChild(cameraholder);

            _sceneCamera = new Camera(cameraholder);
            _sceneCamera.Resize(Width, Height);

            var root = new SceneEntity("Root1", new MouseAction())
            {
                Transform =
                {
                    GlobalPosition = new float3(0, 0, 0),
                    GlobalScale    = new float3(1, 1, 1)
                }
            };

            var sphere = new SceneEntity("Sphere", new ActionCode(),
                                         new SpecularMaterial(RC, MoreShaders.GetSpecularShader(RC), "Assets/metall.jpg"),
                                         new Renderer(sphereGeom))
            {
                Transform =
                {
                    GlobalPosition = new float3(2,       0, 0),
                    GlobalScale    = new float3(0.5f, 0.5f, 0.5f)
                }
            };

            var cube = new SceneEntity("Sphere2", new ActionCode(),
                                       new BumpMaterial(RC, MoreShaders.GetBumpDiffuseShader(RC), "Assets/metall.jpg", "Assets/normal.jpg"),
                                       new Renderer(sphereGeom))
            {
                Transform =
                {
                    GlobalPosition = new float3(5, 0, 0)
                }
            };

            var light = new SceneEntity("Light", new ActionCode());

            var spaceBox = new SceneEntity("Spacebox",
                                           new DiffuseMaterial(RC, MoreShaders.GetDiffuseTextureShader(RC), "Assets/sky.jpg"),
                                           new Renderer(spaceboxGeom));

            spaceBox.Transform.GlobalScale      = new float3(0.5f, 0.5f, 0.5f);
            spaceBox.Transform.LocalEulerAngles = new float3(-90, 90, 0);

            _sceneManager.AddSceneEntity(worldOrigin);
            _sceneManager.AddSceneEntity(root);
            _sceneManager.AddSceneEntity(sphere);
            _sceneManager.AddSceneEntity(cube);
            _sceneManager.AddSceneEntity(light);
            _sceneManager.AddSceneEntity(spaceBox);

            // LightObject
            var lamp = new SceneEntity("DirLight", new RotateAction(new float3(0, 20, 0)),
                                       new DiffuseMaterial(RC, MoreShaders.GetDiffuseTextureShader(RC), "Assets/metall.jpg"),
                                       new Renderer(lampGeom))
            {
                Transform =
                {
                    GlobalPosition = new float3(0,       0, 0),
                    GlobalScale    = new float3(0.7f, 0.7f, 0.7f)
                }
            };

            light.AddChild(lamp);
            lamp.AddComponent(spot);

            _sceneManager.StartActionCode();

            RC.ClearColor = new float4(1, 0, 0, 1);
        }
コード例 #34
0
ファイル: Solar.cs プロジェクト: reliefpfeiler42/Fusee
        public override void Init()
        {
            SceneManager.RC = RC;
            SceneEntity _planet;
            // Lights
            DirectionalLight direct = new DirectionalLight(new float3(-500, 1000, 0), new float4(1, 1, 1, 1), new float3(0, 0, 0), 0);

            // Load Geometry

            Geometry planetgeometry = MeshReader.ReadWavefrontObj(new StreamReader(@"Assets/Sphere.obj.model"));
            Geometry spacebox       = MeshReader.ReadWavefrontObj(new StreamReader(@"Assets/spacebox.obj.model"));

            // Setup Empty Objects
            // Null Objects
            SceneEntity _emptyMoon;
            SceneEntity _emptyMercury;
            SceneEntity _emptyVenus;
            SceneEntity _emptyEarth;
            SceneEntity _emptyMars;
            SceneEntity _emptyJupiter;
            SceneEntity _emptySaturn;
            SceneEntity _emptyUranus;
            SceneEntity _emptyNeptun;

            _emptyMoon    = new SceneEntity("emptyPlanetHolder", new MoonAction(_speedearth * 5.0f));
            _emptyMercury = new SceneEntity("emptyPlanetHolder", new PlanetAction(_speedearth * 4.1477f));
            _emptyVenus   = new SceneEntity("emptyPlanetHolder", new PlanetAction(_speedearth * 1.6150f));
            _emptyEarth   = new SceneEntity("emptyPlanetHolder", new PlanetAction(_speedearth));
            _emptyMars    = new SceneEntity("emptyPlanetHolder", new PlanetAction(_speedearth * 0.5320f));
            _emptyJupiter = new SceneEntity("emptyPlanetHolder", new PlanetAction(_speedearth * 0.0833f));
            _emptySaturn  = new SceneEntity("emptyPlanetHolder", new PlanetAction(_speedearth * 0.03476f));
            _emptyUranus  = new SceneEntity("emptyPlanetHolder", new PlanetAction(_speedearth * 0.0119f));
            _emptyNeptun  = new SceneEntity("emptyPlanetHolder", new PlanetAction(_speedearth * 0.0062f));
            SceneManager.Manager.AddSceneEntity(_emptyMoon);
            SceneManager.Manager.AddSceneEntity(_emptyMercury);
            SceneManager.Manager.AddSceneEntity(_emptyVenus);
            SceneManager.Manager.AddSceneEntity(_emptyEarth);
            SceneManager.Manager.AddSceneEntity(_emptyMars);
            SceneManager.Manager.AddSceneEntity(_emptyJupiter);
            SceneManager.Manager.AddSceneEntity(_emptySaturn);
            SceneManager.Manager.AddSceneEntity(_emptyUranus);
            SceneManager.Manager.AddSceneEntity(_emptyNeptun);

            //Setup Camera
            // Scene Camera
            SceneEntity  cameraholder;
            CameraScript camscript;
            SceneEntity  WorldOrigin;

            WorldOrigin = new SceneEntity("WorldOrigin", new RotationScript());
            SceneManager.Manager.AddSceneEntity(WorldOrigin);
            cameraholder = new SceneEntity("CameraOwner", new CameraScript(), WorldOrigin);
            cameraholder.transform.GlobalPosition = new float3(0, 0, 10);
            scenecamera = new Camera(cameraholder);
            scenecamera.Resize(Width, Height);


            // Setup Space Box
            SceneEntity _spaceBox = new SceneEntity("Spacebox", new PlanetMaterial(MoreShaders.GetShader("simpel", RC), "Assets/spaceboxTexture.png"), new Renderer(spacebox));

            SceneManager.Manager.AddSceneEntity(_spaceBox);


            // Setup Earth
            _planet = new SceneEntity("Earth", new PlanetAction(new float3(0, 0.69635f * 365, 0)), _emptyEarth, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/earth.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(2.9f, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.1f, 0.1f, 0.1f);
            _planet.AddComponent(direct);

            //Setup Moon
            //_emptyMoon.transform.LocalPosition = _earth.transform.LocalPosition;
            //_emptyMoonAction = new MoonAction(_speedearth * 5.0f);
            //_emptyMoon.AddComponent(_emptyMoonAction);
            _planet = new SceneEntity("Moon", new PlanetAction(new float3(0, 2.7f, 0)), _emptyMoon, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/moon.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(0.5f, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.05f, 0.05f, 0.05f);


            //SceneManager.Manager.AddSceneEntity(_emptyMoon);
            //_emptyMoon.AddChild(_moon);
            //_emptyMoonAction.Init(_emptyMoon);

            /*
             * _moon = new SceneEntity { name = "Moon" };
             * _emptyMoonAction = new MoonAction(_earth, _speedearth * 5.0f);
             *
             *
             * _moonMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _moonImage = RC.LoadImage("Assets/moon.jpg");
             * _moonIShaderParam = _moonMaterial.sp.GetShaderParam("texture1");
             * _moonITexture = RC.CreateTexture(_moonImage);
             * _moonMaterial.Tex = _moonITexture;
             * _moonMaterial.Textureparam = _moonIShaderParam;
             * _moonRenderer = new Renderer(planetgeometry);
             * _moonRenderer.material = _moonMaterial;
             * _moon.AddComponent(_moonRenderer);
             * _emptyMoon.AddComponent(_emptyMoonAction);
             * _moon.transform.LocalPosition = new float3(0.5f, 0, 0);
             * _moon.transform.LocalScale = new float3(0.05f, 0.05f, 0.05f);
             * SceneManager.Manager.AddSceneEntity(_emptyMoon);
             * _emptyMoon.AddChild(_moon);
             * _emptyMoonAction.Init(_emptyMoon);
             */
            // Setup sun
            _planet = new SceneEntity("Sun", new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/sun.jpg"), new Renderer(planetgeometry));
            _planet.transform.LocalScale = new float3(2, 2, 2);
            SceneManager.Manager.AddSceneEntity(_planet);

            /*
             * _sun = new SceneEntity { name = "Sun" };
             * //_sunAction.Init(_sun);
             * _sunMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _sunImage = RC.LoadImage("Assets/sun.jpg");
             * _sunIShaderParam = _sunMaterial.sp.GetShaderParam("texture1");
             * _sunITexture = RC.CreateTexture(_sunImage);
             * _sunMaterial.Tex = _sunITexture;
             * _sunMaterial.Textureparam = _sunIShaderParam;
             * _sunRenderer = new Renderer(planetgeometry);
             * _sunRenderer.material = _sunMaterial;
             * _sun.AddComponent(_sunRenderer);
             * _sun.transform.LocalPosition = new float3(0,0,0);
             * _sun.transform.LocalScale = new float3(2,2,2);
             * //_earth.AddChild(_sun);
             * SceneManager.Manager.AddSceneEntity(_sun);
             */
            // Setup mercury
            _planet = new SceneEntity("Mercury", new PlanetAction(_speedearth * 6.2234f), _emptyMercury, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/merkur.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(2.35f, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.05f, 0.05f, 0.05f);

            /*
             * _mercury = new SceneEntity { name = "Mercury" };
             * _mercuryAction.Init(_mercury);
             * _mercuryMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _mercuryImage = RC.LoadImage("Assets/merkur.jpg");
             * _mercuryIShaderParam = _mercuryMaterial.sp.GetShaderParam("texture1");
             * _mercuryITexture = RC.CreateTexture(_mercuryImage);
             * _mercuryMaterial.Tex = _mercuryITexture;
             * _mercuryMaterial.Textureparam = _mercuryIShaderParam;
             * _mercuryRenderer = new Renderer(planetgeometry);
             * _mercuryRenderer.material = _mercuryMaterial;
             * _mercury.AddComponent(_mercuryRenderer);
             * _mercury.AddComponent(_mercuryAction);
             * _mercury.transform.LocalPosition = new float3(2.35f, 0, 0);
             * _mercury.transform.LocalScale = new float3(0.05f, 0.05f, 0.05f);
             * //SceneManager.Manager.AddSceneEntity(_mercury);
             * _emptyMercury.AddChild(_mercury);
             */
            // Setup venus
            _planet = new SceneEntity("Venus", new PlanetAction(_speedearth * 1.5021f), _emptyVenus, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/venus.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(2.6f, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.08f, 0.08f, 0.08f);

            /*
             * _venus = new SceneEntity { name = "Venus" };
             * _venusAction.Init(_venus);
             * _venusMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _venusImage = RC.LoadImage("Assets/venus.jpg");
             * _venusIShaderParam = _venusMaterial.sp.GetShaderParam("texture1");
             * _venusITexture = RC.CreateTexture(_venusImage);
             * _venusMaterial.Tex = _venusITexture;
             * _venusMaterial.Textureparam = _venusIShaderParam;
             * _venusRenderer = new Renderer(planetgeometry);
             * _venusRenderer.material = _venusMaterial;
             * _venus.AddComponent(_venusRenderer);
             * _venus.AddComponent(_venusAction);
             * _venus.transform.LocalPosition = new float3(2.6f, 0, 0);
             * _venus.transform.LocalScale = new float3(0.08f, 0.08f, 0.08f);
             * //SceneManager.Manager.AddSceneEntity(_venus);
             * _emptyVenus.AddChild(_venus);*/

            // Setup mars
            _planet = new SceneEntity("Mars", new PlanetAction(_speedearth * 374.125f), _emptyMars, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/mars.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(3.25f, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.07f, 0.07f, 0.07f);

            /*
             * _mars = new SceneEntity { name = "Mars" };
             * _marsAction.Init(_mars);
             * _marsMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _marsImage = RC.LoadImage("Assets/mars.jpg");
             * _marsIShaderParam = _marsMaterial.sp.GetShaderParam("texture1");
             * _marsITexture = RC.CreateTexture(_marsImage);
             * _marsMaterial.Tex = _marsITexture;
             * _marsMaterial.Textureparam = _marsIShaderParam;
             * _marsRenderer = new Renderer(planetgeometry);
             * _marsRenderer.material = _marsMaterial;
             * _mars.AddComponent(_marsRenderer);
             * _mars.AddComponent(_marsAction);
             * _mars.transform.LocalPosition = new float3(3.25f, 0, 0);
             * _mars.transform.LocalScale = new float3(0.07f, 0.07f, 0.07f);
             * //SceneManager.Manager.AddSceneEntity(_mars);
             * _emptyMars.AddChild(_mars);*/

            // Setup jupiter
            _planet = new SceneEntity("Jupiter", new PlanetAction(_speedearth * 882.62f), _emptyJupiter, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/jupiter.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(4, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.4f, 0.4f, 0.4f);

            /*
             * _jupiter = new SceneEntity { name = "Jupiter" };
             * _jupiterAction.Init(_jupiter);
             * _jupiterMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _jupiterImage = RC.LoadImage("Assets/jupiter.jpg");
             * _jupiterIShaderParam = _jupiterMaterial.sp.GetShaderParam("texture1");
             * _jupiterITexture = RC.CreateTexture(_jupiterImage);
             * _jupiterMaterial.Tex = _jupiterITexture;
             * _jupiterMaterial.Textureparam = _jupiterIShaderParam;
             * _jupiterRenderer = new Renderer(planetgeometry);
             * _jupiterRenderer.material = _jupiterMaterial;
             * _jupiter.AddComponent(_jupiterRenderer);
             * _jupiter.AddComponent(_jupiterAction);
             * _jupiter.transform.LocalPosition = new float3(4, 0, 0);
             * _jupiter.transform.LocalScale = new float3(0.4f, 0.4f, 0.4f);
             * //SceneManager.Manager.AddSceneEntity(_jupiter);
             * _emptyJupiter.AddChild(_jupiter);
             */
            // Setup saturn
            _planet = new SceneEntity("Saturn", new PlanetAction(_speedearth * 820.61f), _emptySaturn, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/saturn.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(5, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.3f, 0.3f, 0.3f);

            /*_saturn = new SceneEntity { name = "Saturn" };
             * _saturnAction.Init(_saturn);
             * _saturnMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _saturnImage = RC.LoadImage("Assets/saturn.jpg");
             * _saturnIShaderParam = _saturnMaterial.sp.GetShaderParam("texture1");
             * _saturnITexture = RC.CreateTexture(_saturnImage);
             * _saturnMaterial.Tex = _saturnITexture;
             * _saturnMaterial.Textureparam = _saturnIShaderParam;
             * _saturnRenderer = new Renderer(planetgeometry);
             * _saturnRenderer.material = _saturnMaterial;
             * _saturn.AddComponent(_saturnRenderer);
             * _saturn.AddComponent(_saturnAction);
             * _saturn.transform.LocalPosition = new float3(5, 0, 0);
             * _saturn.transform.LocalScale = new float3(0.3f, 0.3f, 0.3f);
             * //SceneManager.Manager.AddSceneEntity(_saturn);
             * _emptySaturn.AddChild(_saturn);*/

            // Setup uranus
            _planet = new SceneEntity("Uranus", new PlanetAction(_speedearth * 509.30f), _emptyUranus, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/uranus.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(6, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.12f, 0.12f, 0.12f);

            /*_uranus = new SceneEntity { name = "Uranus" };
             * _uranusAction.Init(_uranus);
             * _uranusMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _uranusImage = RC.LoadImage("Assets/uranus.jpg");
             * _uranusIShaderParam = _uranusMaterial.sp.GetShaderParam("texture1");
             * _uranusITexture = RC.CreateTexture(_uranusImage);
             * _uranusMaterial.Tex = _uranusITexture;
             * _uranusMaterial.Textureparam = _uranusIShaderParam;
             * _uranusRenderer = new Renderer(planetgeometry);
             * _uranusRenderer.material = _uranusMaterial;
             * _uranus.AddComponent(_uranusRenderer);
             * _uranus.AddComponent(_uranusAction);
             * _uranus.transform.LocalPosition = new float3(6, 0, 0);
             * _uranus.transform.LocalScale = new float3(0.12f, 0.12f, 0.12f);
             * //SceneManager.Manager.AddSceneEntity(_uranus);
             * _emptyUranus.AddChild(_uranus);*/

            // Setup neptun
            _planet = new SceneEntity("Neptun", new PlanetAction(_speedearth * 544.10f), _emptyNeptun, new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC), "Assets/neptune.jpg"), new Renderer(planetgeometry));
            _planet.transform.GlobalPosition = new float3(7, 0, 0);
            _planet.transform.GlobalScale    = new float3(0.14f, 0.14f, 0.14f);

            /*_neptun = new SceneEntity { name = "Neptun" };
             * _neptunAction.Init(_neptun);
             * _neptunMaterial = new PlanetMaterial(MoreShaders.GetShader("diffuse2", RC));
             * _neptunImage = RC.LoadImage("Assets/neptune.jpg");
             * _neptunIShaderParam = _neptunMaterial.sp.GetShaderParam("texture1");
             * _neptunITexture = RC.CreateTexture(_neptunImage);
             * _neptunMaterial.Tex = _neptunITexture;
             * _neptunMaterial.Textureparam = _neptunIShaderParam;
             * _neptunRenderer = new Renderer(planetgeometry);
             * _neptunRenderer.material = _neptunMaterial;
             * _neptun.AddComponent(_neptunRenderer);
             * _neptun.AddComponent(_neptunAction);
             * _neptun.transform.LocalPosition = new float3(7, 0, 0);
             * _neptun.transform.LocalScale = new float3(0.14f, 0.14f, 0.14f);
             * //SceneManager.Manager.AddSceneEntity(_neptun);
             * _emptyNeptun.AddChild(_neptun);*/
            SceneManager.Manager.StartActionCode();
            // Random Rotations
            _emptyEarth.transform.LocalEulerAngles   = new float3(0, 45, 0);
            _emptyMercury.transform.LocalEulerAngles = new float3(0, 55, 0);
            _emptyVenus.transform.LocalEulerAngles   = new float3(0, 335, 0);
            _emptyMars.transform.LocalEulerAngles    = new float3(0, 125, 0);
            _emptyJupiter.transform.LocalEulerAngles = new float3(0, 65, 0);
            _emptySaturn.transform.LocalEulerAngles  = new float3(0, 95, 0);
            _emptyUranus.transform.LocalEulerAngles  = new float3(0, 145, 0);
            _emptyNeptun.transform.LocalEulerAngles  = new float3(0, 245, 0);

            //camrotation.Init(WorldOrigin);
            RC.ClearColor = new float4(1, 0, 0, 1);
        }