Inheritance: MonoBehaviour
示例#1
0
        private void NrmGenerator_Load(object sender, EventArgs e)
        {
            Mesh quadMesh = MeshFactory.CreateQuad();

            quadGeom = new Geometry(quadMesh);
            quadGeom.SetShader(ShaderManager.GetShader(typeof(NormalMapShader)));
            MtlViewerGame mtlPreview = new MtlViewerGame();

            mtlPreview.Rotate         = false;
            mtlPreview.Camera.Enabled = false;
            mtlPreview.Camera.Width   = 256;
            mtlPreview.Camera.Height  = 256;

            //  mtlPreview.Camera = new ApexEngine.Rendering.Cameras.OrthoCamera(-2, 2, -2, 2, -2, 2);
            mtlPreview.Camera.Translation = new ApexEngine.Math.Vector3f(0, 0, -3);
            mtlPreview.RootNode.AddChild(quadGeom);
            ApexEngineControl mtlViewer = new ApexEngineControl(mtlPreview);

            mtlViewer.Framerate = 50;
            mtlViewer.Dock      = DockStyle.Fill;
            pnlObj.Controls.Add(mtlViewer);

            quadGeom.Material.SetValue("delta_value", 5.0f);
            //mtlPreview.RenderManager.PostProcessor.PostFilters.Add(new BlurPostFilter(true));
            //mtlPreview.RenderManager.PostProcessor.PostFilters.Add(new BlurPostFilter(false));
        }
        public void TestPointLight()
        {
            var game = EngineFactory.CreateEngine();

            game.Initialize();

            var e = new Engine.WorldRendering.Entity()
            {
                Mesh = MeshFactory.Load("Core\\TileSet\\ts001sg001")
            };

            var light = new PointLight
            {
                Position = new Vector3(-1, 0, 0)
            };
            var time = 2f;


            game.AddSimulator(new BasicSimulator(delegate
            {
                time           += TW.Graphics.Elapsed;
                light.Position  = new Vector3(-1, (float)Math.Sin(time), (float)Math.Cos(time));
                light.Size      = 10;
                light.Intensity = 2;
            }));


            game.AddSimulator(new WorldRenderingSimulator());



            game.Run();
        }
示例#3
0
        public override void Init()
        {
            // ShadowMappingComponent smc;
            // RenderManager.AddComponent(smc = new ShadowMappingComponent(cam, Environment));
            // smc.RenderMode = ShadowMappingComponent.ShadowRenderMode.Forward;



            Geometry floor = new Geometry(MeshFactory.CreateCube(new Math.Vector3f(-5f, -0.5f, -5f), new Math.Vector3f(5, 0.5f, 5f)));

            rootNode.AddChild(floor);
            PhysicsWorld.AddObject(floor, 0.0f);



            Node test = (Node)AssetManager.LoadModel(AssetManager.GetAppPath() + "\\models\\sphere16.obj");

            test.SetLocalTranslation(new Math.Vector3f(0, 25, 0));
            rootNode.AddChild(test);

            PhysicsWorld.AddObject(test, 5.0f);


            Sound     cat = (Sound)AssetManager.Load(AssetManager.GetAppPath() + "\\sounds\\cat.wav");
            AudioNode an  = new AudioNode(cat);

            test.AddChild(an);

            InputManager.AddKeyboardEvent(new Input.KeyboardEvent(Input.InputManager.KeyboardKey.Space, () => { an.Play(); }));
        }
        public void Initialize(TWEngine game)
        {
            game.AddSimulator(new PhysXSimulator());
            game.AddSimulator(new WorldRenderingSimulator());
            game.AddSimulator(new PhysXDebugRendererSimulator());


            var e = new Engine.WorldRendering.Entity
            {
                Mesh        = MeshFactory.Load("Core\\TileSet\\ts001sg001"),
                Visible     = true,
                Solid       = true,
                WorldMatrix = Matrix.Translation(0, 5, 0)
            };

            e = new Engine.WorldRendering.Entity
            {
                Mesh        = MeshFactory.Load("Core\\TileSet\\ts001sg001"),
                Visible     = true,
                Solid       = false,
                WorldMatrix = Matrix.Translation(0, 10, 0)
            };

            e = new Engine.WorldRendering.Entity
            {
                Mesh        = MeshFactory.Load("Core\\Barrel01"),
                Visible     = true,
                Solid       = true,
                Static      = false,
                WorldMatrix = Matrix.Translation(0, 20, 0)
            };
        }
示例#5
0
        protected override void InitNode()
        {
            if (Settings == null)
            {
                return;
            }

            SunGlareMaterial = MaterialHelper.CreateTemp(SunGlareShader, "Sunglare", (int)RenderQueue);

            SunGlareMesh        = MeshFactory.MakePlane(8, MeshFactory.PLANE.XY, false, false, false);
            SunGlareMesh.bounds = new Bounds(Vector4.zero, new Vector3(9e37f, 9e37f, 9e37f));

            for (var i = 0; i < Settings.Ghost1SettingsList.Count; i++)
            {
                Ghost1Settings.SetRow(i, Settings.Ghost1SettingsList[i]);
            }

            for (var i = 0; i < Settings.Ghost2SettingsList.Count; i++)
            {
                Ghost2Settings.SetRow(i, Settings.Ghost2SettingsList[i]);
            }

            for (var i = 0; i < Settings.Ghost3SettingsList.Count; i++)
            {
                Ghost3Settings.SetRow(i, Settings.Ghost3SettingsList[i]);
            }

            InitUniforms(SunGlareMaterial);
        }
示例#6
0
文件: SoftDemo.cs 项目: diqost/bullet
        protected override void OnRender()
        {
            Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.LightGray, 1.0f, 0);
            Device.BeginScene();

            Device.SetTransform(TransformState.View, Freelook.View);

            foreach (CollisionObject colObj in PhysicsContext.World.CollisionObjectArray)
            {
                if (colObj.CollisionShape.ShapeType == BroadphaseNativeType.SoftBodyShape)
                {
                    if (IsDebugDrawEnabled)
                    {
                        continue;
                    }

                    Device.Material = softBodyMaterial;
                    Device.SetTransform(TransformState.World, Matrix.Identity);
                    MeshFactory.RenderSoftBody(colObj as SoftBody);
                }
                else
                {
                    RigidBody body = colObj as RigidBody;
                    Device.SetTransform(TransformState.World, body.MotionState.WorldTransform);
                    RenderWithMaterial(body);
                }
            }

            DebugDrawWorld();

            Fps.OnRender(FramesPerSecond);

            Device.EndScene();
            Device.Present();
        }
示例#7
0
    private void Awake()
    {
        Instance = this;

        Messenger.Setup(Debug);

        Planetoids = FindObjectsOfType <Planetoid>();
        Starfields = FindObjectsOfType <Starfield>();

        if (CameraHelper.Main() != null)
        {
            FrustumPlanes = GeometryUtility.CalculateFrustumPlanes(CameraHelper.Main());
        }

        if (PrototypeMesh == null)
        {
            PrototypeMesh = MeshFactory.SetupQuadMesh();
        }

        PreOutputDataBuffer    = new OutputStruct[QuadSettings.VerticesWithBorder];
        PreOutputSubDataBuffer = new OutputStruct[QuadSettings.VerticesWithBorderFull];
        OutputDataBuffer       = new OutputStruct[QuadSettings.Vertices];

        UpdateSettings();
    }
示例#8
0
        public void Start()
        {
            if (Sun == null)
            {
                if (GetComponent <AtmosphereSun>() != null)
                {
                    Sun = GetComponent <AtmosphereSun>();
                }
            }

            SunGlareMaterial = MaterialHelper.CreateTemp(SunGlareShader, "Sunglare", (int)RenderQueue);

            mesh        = MeshFactory.MakePlane(8, 8, MeshFactory.PLANE.XY, false, false, false);
            mesh.bounds = new Bounds(Vector4.zero, new Vector3(9e37f, 9e37f, 9e37f));

            for (int i = 0; i < Ghost1SettingsList.Count; i++)
            {
                Ghost1Settings.SetRow(i, Ghost1SettingsList[i]);
            }

            for (int i = 0; i < Ghost2SettingsList.Count; i++)
            {
                Ghost2Settings.SetRow(i, Ghost2SettingsList[i]);
            }

            for (int i = 0; i < Ghost3SettingsList.Count; i++)
            {
                Ghost3Settings.SetRow(i, Ghost3SettingsList[i]);
            }

            InitUniforms(SunGlareMaterial);
        }
示例#9
0
        private void Awake()
        {
            if (IsDeformed)
            {
                m_origin = Vector3.zero;
            }
            else
            {
                m_origin = new Vector3(0.0f, 0.0f, Radius);
            }

            Controller = GetComponentInChildren <Controller>();

            //if planet view is being use set the radius
            if (Controller.View is PlanetView)
            {
                (Controller.View as PlanetView).Radius = Radius;
            }

            //Get the nodes that are children of the manager
            OceanNode      = GetComponentInChildren <OceanNode>();
            SkyNode        = GetComponentInChildren <SkyNode>();
            SunNode        = GetComponentInChildren <SunNode>();
            m_terrainNodes = GetComponentsInChildren <TerrainNode>();

            m_samplers = new List <TileSampler>(GetComponentsInChildren <TileSampler>());
            m_samplers.Sort(new TileSamplerComparer());

            m_propertyBlock = new MaterialPropertyBlock();
            //make the mesh used to draw the terrain quads
            m_quadMesh        = MeshFactory.MakePlane(m_gridResolution, m_gridResolution);
            m_quadMesh.bounds = new Bounds(Vector3.zero, new Vector3(1e8f, 1e8f, 1e8f));
        }
示例#10
0
    public QuadtreeLODNode(float meshSize,
                           int meshVertexResolution,
                           Vector2 bottomLeftCoordinates,
                           Vector2 topLeftCoordinates,
                           Transform transform,
                           Material material)
    {
        gameObject_ = GameObject.Instantiate(new GameObject());
        gameObject_.AddComponent <MeshRenderer>();

        // Create the root mesh.
        mesh_ = MeshFactory.CreateMesh(meshSize, meshVertexResolution);
        gameObject_.AddComponent <MeshFilter> ().mesh = mesh_;
        meshVertexResolution_ = meshVertexResolution;

        // Make this mesh transform relative to parent.
        transform_        = gameObject_.transform;
        transform_.parent = transform;

        // Copy given material.
        material_ = new Material(Shader.Find("Standard"));
        gameObject_.GetComponent <Renderer>().material = material_;

        visible_ = true;

        children_ = new QuadtreeLODNode[] { null, null, null, null };

        bottomLeftCoordinates_ = bottomLeftCoordinates;
        topRightCoordinates_   = topLeftCoordinates;

        LoadMap();
        heightMapRequest = RequestHeightMap(bottomLeftCoordinates_, topRightCoordinates_, meshVertexResolution_);
    }
示例#11
0
    private void InitOceanScreenGridMeshes()
    {
        OceanGridResolution = Mathf.Max(1, OceanGridResolution);

        // The number of squares in the grid on the x and y axis
        var NX         = Screen.width / OceanGridResolution;
        var NY         = Screen.height / OceanGridResolution;
        var gridsCount = 1;

        const int MAX_VERTS = 65000;

        // The number of meshes need to make a grid of this resolution
        if (NX * NY > MAX_VERTS)
        {
            gridsCount += (NX * NY) / MAX_VERTS;
        }

        OceanScreenMeshGrids = new Mesh[gridsCount];

        // Make the meshes. The end product will be a grid of verts that cover the screen on the x and y axis with the z depth at 0.
        // This grid is then projected as the ocean by the shader
        for (var i = 0; i < gridsCount; i++)
        {
            NY = Screen.height / gridsCount / OceanGridResolution;

            OceanScreenMeshGrids[i]        = MeshFactory.MakeOceanPlane(NX, NY, (float)i / (float)gridsCount, 1.0f / (float)gridsCount);
            OceanScreenMeshGrids[i].bounds = new Bounds(Vector3.zero, new Vector3(1e8f, 1e8f, 1e8f));
        }
    }
示例#12
0
        public static ActorSpawn?SpawnPointFromStartingLocation(H2vMap map,
                                                                ScenarioTag.AiSquadDefinition.StartingLocation loc)
        {
            var entity = new ActorSpawn();

            entity.FriendlyName = loc.Description;

            var charIndex = loc.CharacterIndex;

            if (charIndex == ushort.MaxValue)
            {
                charIndex = map.Scenario.AiSquadDefinitions[loc.SquadIndex].CharacterIndex;
            }

            TagRef <HaloModelTag> model = default;
            string modelDesc            = entity.FriendlyName;

            if (charIndex != ushort.MaxValue)
            {
                var character = map.GetTag(map.Scenario.CharacterDefinitions[charIndex].CharacterReference);
                if (map.TryGetTag <BaseTag>(character.Unit, out var unit) == false)
                {
                    return(null);
                }

                modelDesc = $"[{unit.Id}] {unit.Name}";

                if (unit is BipedTag biped)
                {
                    model = biped.Model;
                }
                else if (unit is VehicleTag vehicle)
                {
                    model = vehicle.Hlmt;
                }
            }
            else
            {
                // Use some default model?
                return(null);
            }

            var comp = new RenderModelComponent(entity, new Model <BitmapTag>
            {
                Note        = modelDesc,
                Flags       = ModelFlags.Diffuse | ModelFlags.CastsShadows | ModelFlags.ReceivesShadows,
                Meshes      = MeshFactory.GetRenderModel(map, model),
                RenderLayer = RenderLayers.Scripting
            });

            var orientation = Quaternion.CreateFromAxisAngle(EngineGlobals.Up, loc.Rotation);
            var xform       = new TransformComponent(entity, loc.Position, orientation);

            var originalTag = new OriginalTagComponent(entity, loc);

            entity.SetComponents(new Component[] { xform, comp, originalTag });

            return(entity);
        }
 /// <summary>
 /// Loads a mesh in the TWDir.GameData folder. The path is supposed to be without extension
 /// </summary>
 /// <param name="relativeCorePath"></param>
 /// <returns></returns>
 public IMesh LoadMesh(string relativeCorePath)
 {
     if (Path.GetExtension(relativeCorePath) == null)
     {
         throw new ArgumentException("relativeCorePath");
     }
     return(MeshFactory.Load(relativeCorePath));
 }
示例#14
0
        public static Machine FromTag(H2vMap map, ScenarioTag scenario, ScenarioTag.MachineryInstance instance)
        {
            var scenery = new Machine();

            scenery.FriendlyName = "Machine_" + instance.MachineryDefinitionIndex;

            if (instance.MachineryDefinitionIndex == ushort.MaxValue)
            {
                Console.WriteLine($"MACH index out of range");
                return(scenery);
            }

            var id  = scenario.MachineryDefinitions[instance.MachineryDefinitionIndex].Machinery;
            var tag = map.GetTag(id);

            scenery.FriendlyName = tag.Name;

            var orientation = QuaternionExtensions.FromH2vOrientation(instance.Orientation);
            var xform       = new TransformComponent(scenery, instance.Position, orientation);

            var components = new List <Component>();

            if (tag.Model != uint.MaxValue)
            {
                components.Add(new RenderModelComponent(scenery, new Model <BitmapTag>
                {
                    Note   = $"[{tag.Id}] {tag.Name}",
                    Meshes = MeshFactory.GetRenderModel(map, tag.Model),
                    Flags  = ModelFlags.Diffuse | ModelFlags.CastsShadows | ModelFlags.ReceivesShadows
                }));

                components.Add(new RenderModelComponent(scenery, new Model <BitmapTag>
                {
                    Note        = $"[{tag.Id}] {tag.Name} bones",
                    Meshes      = MeshFactory.GetBonesModel(map, tag.Model),
                    Flags       = ModelFlags.Wireframe,
                    RenderLayer = RenderLayers.Debug
                }));

                var body = PhysicsComponentFactory.CreateKinematicRigidBody(scenery, xform, map, tag.Model);
                if (body != null)
                {
                    components.Add(body);

                    components.Add(new RenderModelComponent(scenery, new Model <BitmapTag>
                    {
                        Meshes      = MeshFactory.GetRenderModel(body.Collider, new Vector4(1f, 0f, 1f, 1f)),
                        Flags       = ModelFlags.Wireframe | ModelFlags.IsStatic,
                        RenderLayer = RenderLayers.Collision
                    }));
                }
            }

            scenery.SetComponents(xform, components.ToArray());

            return(scenery);
        }
示例#15
0
    private void Start()
    {
        mesh = MeshFactory.SetupRingSegmentMesh(4, 8, 8.0f, 16.0f, 1.0f);

        if (IsSubdivided)
        {
            MeshHelper.SubdivisionHelper.Subdivide4(mesh);
        }
    }
示例#16
0
    private void Start()
    {
        meshRenderer = GetComponent <MeshRenderer>();

        var meshFilter = GetComponent <MeshFilter>();

        meshFilter.mesh = MeshFactory.CreateSquare2D();

        audioManager = FindObjectOfType <AudioManager>();
    }
示例#17
0
        public void Init()
        {
            fbo.Init();
            Mesh mesh = MeshFactory.CreateQuad();

            mesh.Material.SetValue(Material.MATERIAL_DEPTHMASK, false);
            mesh.Material.SetValue(Material.MATERIAL_DEPTHTEST, false);
            quadGeom = new Geometry(mesh);
            postFilters.Add(new Filters.DefaultPostFilter());
        }
示例#18
0
        private static Model3DGroup Leg(Material legMaterial, Material footMaterial)
        {
            // Create parts
            MeshGeometry3D footMesh = MeshFactory.Sphere(4, 6, 1.1);
            // MeshGeometry3D legMesh = MeshFactory.Spiral( 3, 8, 1.1, 2.2 );
            MeshGeometry3D  legMesh   = MeshFactory.Sphere(8, 6, 1.1);
            GeometryModel3D footModel = new GeometryModel3D(footMesh, footMaterial);

            // Use the same material for front and back
            footModel.BackMaterial = footMaterial;
            GeometryModel3D topModel = new GeometryModel3D(legMesh, legMaterial);

            // Use the same material for front and back
            topModel.BackMaterial = legMaterial;
            GeometryModel3D bottomModel = new GeometryModel3D(legMesh, legMaterial);

            // Use the same material for front and back
            bottomModel.BackMaterial = legMaterial;

            // Create transforms for parts
            Transform3DGroup legPieceTransform = new Transform3DGroup();

            legPieceTransform.Children.Add(new TranslateTransform3D(new Vector3D(0, -1, 0)));
            legPieceTransform.Children.Add(new ScaleTransform3D(new Vector3D(.1, .3, .1), new Point3D()));
            Transform3DGroup footPieceTransform = new Transform3DGroup();

            footPieceTransform.Children.Add(new TranslateTransform3D(new Vector3D(0, -1, 0.5)));
            footPieceTransform.Children.Add(new ScaleTransform3D(new Vector3D(.2, .1, .3), new Point3D()));

            // Create groups
            Model3DGroup legJoint   = new Model3DGroup();
            Model3DGroup knee       = new Model3DGroup();
            Model3DGroup kneeJoint  = new Model3DGroup();
            Model3DGroup ankle      = new Model3DGroup();
            Model3DGroup ankleJoint = new Model3DGroup();

            // mix and match transforms to pieces ...
            footModel.Transform  = footPieceTransform;
            ankleJoint.Transform = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), -20));
            ankleJoint.Children.Add(footModel);
            ankle.Transform = new TranslateTransform3D(new Vector3D(0, -.6, 0));
            ankle.Children.Add(ankleJoint);
            bottomModel.Transform = legPieceTransform;
            kneeJoint.Transform   = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), 40));
            kneeJoint.Children.Add(ankle); // always add groups first
            kneeJoint.Children.Add(bottomModel);
            knee.Transform = new TranslateTransform3D(new Vector3D(0, -.6, 0));
            knee.Children.Add(kneeJoint);
            topModel.Transform = legPieceTransform;
            legJoint.Transform = new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), -20));
            legJoint.Children.Add(knee); // always add groups first
            legJoint.Children.Add(topModel);

            return(legJoint);
        }
示例#19
0
        /// <summary>
        /// This summary has not been prepared yet. NOSUMMARY - pantal07
        /// </summary>
        public static Model3D MakeModel(string model, Material material, Material backMaterial)
        {
            string exceptions = string.Empty;

            try
            {
                MeshGeometry3D  mesh   = MeshFactory.MakeMesh(model);
                Material        front  = (material == null) ? MaterialFactory.Default : material;
                Material        back   = backMaterial;
                GeometryModel3D model2 = new GeometryModel3D(mesh, front);
                model2.BackMaterial = back;
                return(model2);
            }
            catch (ArgumentException ex)
            {
                /* It wasn't a mesh */
                exceptions += ex.Message + ", ";
            }
#if SSL
            try
            {
                ScreenSpaceLines3D lines = ScreenSpaceLinesFactory.MakeLines(model);
                return(lines);
            }
            catch (ArgumentException)
            {
                /* It wasn't ScreenSpaceLines */
                exceptions += ex.Message + ", ";
            }
#endif
            try
            {
                Light light = LightFactory.MakeLight(model);
                return(light);
            }
            catch (ArgumentException ex)
            {
                /* It wasn't a Light */
                exceptions += ex.Message + ", ";
            }

            try
            {
                Model3DGroup group = SceneFactory.MakeScene(model);
                return(group);
            }
            catch (ArgumentException ex)
            {
                /* It wasn't a Scene */
                exceptions += ex.Message;
            }

            throw new ArgumentException("Cannot create (" + model + ").  Exceptions thrown: " + exceptions);
        }
示例#20
0
        private Mesh CreateStarfieldMesh(float starDistance)
        {
            const int numberOfStars = 9110;

            var binaryDataFile = Resources.Load("Binary/Stars", typeof(TextAsset)) as TextAsset;

            if (binaryDataFile == null)
            {
                Debug.Log("Starfield: Binary data file reading error!");
                return(null);
            }

            var starsCIs = new List <CombineInstance>();

            using (var reader = new BinaryReader(new MemoryStream(binaryDataFile.bytes)))
            {
                for (int i = 0; i < numberOfStars - 1; i++)
                {
                    var star     = new StarfieldStar();
                    var starSize = StarsDistance / 100 * StarsScale;

                    // NOTE : Swap Z and Y...
                    star.Position = new Vector3(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle());
                    star.Color    = new Vector4(reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), 0);

                    star.Position = Vector3.Scale(star.Position, new Vector3(-1.0f, 1.0f, -1.0f));
                    star.Color.w  = new Vector3(star.Color.x, star.Color.y, star.Color.z).magnitude;

                    if (star.Color.w > 5.7f)
                    {
                        star.Color = Vector4.Normalize(star.Color) * 0.5f;
                    }

                    var ci = new CombineInstance
                    {
                        mesh      = MeshFactory.MakeBillboardQuad(starSize),
                        transform = MatrixHelper.BillboardMatrix(star.Position * starDistance)
                    };

                    ci.mesh.colors = new Color[] { star.Color, star.Color, star.Color, star.Color };

                    starsCIs.Add(ci);
                }
            }

            var mesh = new Mesh();

            mesh.name = string.Format("StarfieldMesh_({0})", Random.Range(float.MinValue, float.MaxValue));
            mesh.CombineMeshes(starsCIs.ToArray());
            mesh.bounds    = new Bounds(Vector3.zero, new Vector3(1e8f, 1e8f, 1e8f));
            mesh.hideFlags = HideFlags.DontSave;

            return(mesh);
        }
示例#21
0
        /// <summary>
        ///   Construye el mesh con los atributos que se le fueron agregando
        /// </summary>
        /// <param name="objMesh">ObjMesh</param>
        /// <returns>MeshBuilder</returns>
        public TgcMesh Build(ObjMesh objMesh)
        {
            TgcMesh unMesh = MeshFactory.createNewMesh(DxMesh, objMesh.Name, ChargueBufferStrategy.RenderType);

            SetBoundingBox(unMesh);
            unMesh.AutoTransform = AutoTransform;
            unMesh.Enabled       = Enable;
            unMesh.Materials     = MeshMaterials;
            unMesh.DiffuseMaps   = MeshTextures;
            return(unMesh);
        }
示例#22
0
 private static void PopulateVehicle(Vehicle item, H2vMap map, TransformComponent xform, VehicleTag vehi)
 {
     item.FriendlyName = vehi.Name;
     item.SetComponents(xform,
                        PhysicsComponentFactory.CreateDynamicRigidBody(item, xform, map, vehi.Hlmt),
                        new RenderModelComponent(item, new Model <BitmapTag>
     {
         Note   = $"[{vehi.Id}] {vehi.Name}",
         Flags  = ModelFlags.Diffuse | ModelFlags.CastsShadows | ModelFlags.ReceivesShadows,
         Meshes = MeshFactory.GetRenderModel(map, vehi.Hlmt)
     }));
 }
 void Update()
 {
     t += Time.deltaTime;
     if (t > 0.2f)
     {
         t = 0;
         if (MeshFactory.GetSectorMesh(radius, radian, edges, out Mesh sectorMesh))
         {
             sector.GetComponent <MeshFilter>().mesh = sectorMesh;
         }
     }
 }
示例#24
0
        public static Bloc FromTag(H2vMap map, ScenarioTag scenario, ScenarioTag.BlocInstance instance)
        {
            var scenery    = new Bloc();
            var components = new List <Component>();

            var bloc = scenario.BlocDefinitions[instance.BlocDefinitionIndex].Bloc;
            var tag  = map.GetTag(bloc);

            scenery.FriendlyName = tag.Name;

            components.Add(new RenderModelComponent(scenery, new Model <BitmapTag>
            {
                Note            = $"[{tag.Id}] {tag.Name}",
                Flags           = ModelFlags.Diffuse | ModelFlags.CastsShadows | ModelFlags.ReceivesShadows,
                Meshes          = MeshFactory.GetRenderModel(map, tag.PhysicalModel),
                ColorChangeData = PackColorChange(instance)
            }));

            var orientation = QuaternionExtensions.FromH2vOrientation(instance.Orientation);
            var xform       = new TransformComponent(scenery, instance.Position, orientation);

            var body = PhysicsComponentFactory.CreateDynamicRigidBody(scenery, xform, map, tag.PhysicalModel);

            if (body != null)
            {
                components.Add(body);
                components.Add(new RenderModelComponent(scenery, new Model <BitmapTag>
                {
                    Note        = $"bloc//{scenery.FriendlyName}-collision",
                    Meshes      = MeshFactory.GetRenderModel(body.Collider, new Vector4(0.19f, 0.47f, 0.15f, 1f)),
                    Flags       = ModelFlags.Wireframe | ModelFlags.IsStatic,
                    RenderLayer = RenderLayers.Collision
                }));
            }

            var comOffset = Vector3.Zero;

            if (map.TryGetTag(tag.PhysicalModel, out var hlmt) &&
                map.TryGetTag(hlmt.PhysicsModel, out var phmo) &&
                phmo.BodyParameters.Length > 0)
            {
                comOffset = phmo.BodyParameters[0].CenterOfMass;
            }

            components.Add(new BoundsComponent(scenery, comOffset - new Vector3(0.02f), comOffset + new Vector3(0.02f), new Vector4(1f, 1f, 0, 1f)));
            components.Add(new BoundsComponent(scenery, new Vector3(-0.02f), new Vector3(0.02f), new Vector4(0, 1f, 0, 1f)));

            components.Add(new OriginalTagComponent(scenery, instance));

            scenery.SetComponents(xform, components.ToArray());

            return(scenery);
        }
 public void Update()
 {
     if (active)
     {
         active = false;
         var stream = new QuadStream(origin, left, up, size, step, segments, startColor, endColor);
         var factory = new MeshFactory(stream);
         var filter = GetComponent<MeshFilter>();
         filter.mesh = new Mesh();
         factory.Bind(filter.mesh);
     }
 }
示例#26
0
 public void Update()
 {
     if (active)
     {
         active = false;
         var stream  = new QuadStream(origin, left, up, size, step, segments, startColor, endColor);
         var factory = new MeshFactory(stream);
         var filter  = GetComponent <MeshFilter>();
         filter.mesh = new Mesh();
         factory.Bind(filter.mesh);
     }
 }
示例#27
0
    private void addFloor(GameObject boardHolder, OIGrid grid)
    {
        OIGrid     floorGrid   = grid.replace(TREE, FLOOR); //Metto floor sotto agli alberi
        GameObject floorPrefab = _behavior._floorMeshPrefab;
        GameObject created     = istantiate(floorPrefab, 0, 0, 0, boardHolder, "Floor");

        Mesh floorMesh = MeshFactory.createPlane(floorGrid, TILE_SIZE, FLOOR);

        created.GetComponent <MeshFilter>().mesh         = floorMesh;
        created.GetComponent <MeshCollider>().sharedMesh = floorMesh;
        created.transform.parent = boardHolder.transform;
    }
示例#28
0
        private void _renderSelectedElementBoundingBox()
        {
            var selectedElement = SceneEditorScene.SelectedElement;

            var transform    = selectedElement.WorldTransform.Transformation;
            var boundingBox  = ((SceneEditorScene)ParentScene).BoundingBoxes[selectedElement];
            var meshRenderer = _aabbGameElement.GetComponent <MeshRenderer>();

            meshRenderer.MeshFilter = MeshFactory.CreateCube(Vector3f.TransformPosition(boundingBox.Min, transform), Vector3f.TransformPosition(boundingBox.Max, transform));
            meshRenderer.MeshFilter.Mesh.VAO.DrawMode = BeginMode.Lines;

            meshRenderer.Render();
        }
示例#29
0
 public void Update()
 {
     if (active)
     {
         active = false;
         var geometry = new Tube(origin, left, up, size, color);
         var stream   = new Single(geometry);
         var factory  = new MeshFactory(stream);
         var filter   = GetComponent <MeshFilter>();
         filter.mesh = new Mesh();
         factory.Bind(filter.mesh);
     }
 }
 public void test_build_new_mesh()
 {
     var mesh = new Mesh();
     var quad = new Quad(new Vector3(0f, 0f, 0f),
                         new Vector3(0f, 1f, 0f),
                         new Vector3(1f, 0f, 0f),
                         new Vector2(10f, 10f),
                         new Color32(255, 255, 255, 255));
     MeshFactory instance = new MeshFactory(new Single(quad));
     instance.Bind(mesh);
     Assert(instance.vertexGen == 4);
     Assert(instance.triangleGen == 6);
 }
 public void Update()
 {
     if (active)
     {
         active = false;
         var geometry = new Quad(origin, left, up, size, color);
         var stream = new Single(geometry);
         var factory = new MeshFactory(stream);
         var filter = GetComponent<MeshFilter>();
         filter.mesh = new Mesh();
         factory.Bind(filter.mesh);
   }
 }
示例#32
0
        private static List <Entity> CreateFromItemCollection(H2vMap map, ItemCollectionTag itmc, ScenarioTag.ItemCollectionPlacement instance)
        {
            var entities = new List <Entity>();

            // I've only seen 1 item collections though
            foreach (var item in itmc.Items)
            {
                if (map.TryGetTag <BaseTag>(item.ItemTag, out var tag) == false)
                {
                    throw new Exception("No tag found for weap/equip");
                }

                TagRef <HaloModelTag> itemHlmt = default;

                if (tag is WeaponTag weap)
                {
                    itemHlmt = weap.Hlmt;
                }

                if (tag is EquipmentTag eqip)
                {
                    itemHlmt = eqip.Hlmt;
                }

                if (itemHlmt == default)
                {
                    continue;
                }

                var entity = new Item();
                entity.FriendlyName = tag.Name;

                var renderModel = new RenderModelComponent(entity, new Model <BitmapTag>
                {
                    Note = $"[{itmc.Id}] {itmc.Name}",
                    //Position = instance.Position,
                    //Orientation = baseRotation,
                    //Scale = new Vector3(1.3f),
                    Flags  = ModelFlags.Diffuse | ModelFlags.CastsShadows | ModelFlags.ReceivesShadows,
                    Meshes = MeshFactory.GetRenderModel(map, itemHlmt)
                });

                var xform = new TransformComponent(entity, instance.Position, QuaternionExtensions.FromH2vOrientation(instance.Orientation));
                var body  = PhysicsComponentFactory.CreateDynamicRigidBody(entity, xform, map, itemHlmt);

                entity.SetComponents(xform, renderModel, body);
                entities.Add(entity);
            }

            return(entities);
        }
    void OnEnable()
    {
        _factory        = target as MeshFactory;
        _visualizerList = serializedObject.FindProperty("Visualizers");
        mapId_Prop      = serializedObject.FindProperty("_mapId");
        script          = MonoScript.FromScriptableObject(_factory);

        if (string.IsNullOrEmpty(mapId_Prop.stringValue))
        {
            mapId_Prop.stringValue = _defaultMapId;
            serializedObject.ApplyModifiedProperties();
            Repaint();
        }
    }
 public void test_bind_existing_mesh()
 {
     var mesh = this.SpawnComponent<MeshFilter>();
     mesh.sharedMesh = new Mesh();
     var quad = new Quad(new Vector3(0f, 0f, 0f),
                         new Vector3(0f, 1f, 0f),
                         new Vector3(1f, 0f, 0f),
                         new Vector2(10f, 10f),
                         new Color32(255, 255, 255, 255));
     MeshFactory instance = new MeshFactory(new Single(quad));
     instance.Bind(mesh.sharedMesh);
     Assert(instance.vertexGen == 4);
     Assert(instance.triangleGen == 6);
     this.TearDown();
 }
示例#35
0
        public EarthlitNightScene(IEye eye)
        {
            this.eye = eye;
            device = eye.Device;
            swapChain = device.PrimarySwapChain;

            stars = new Stars(device, StarCount);

            var meshFactory = new MeshFactory(device, Handedness.Right, Winding.Clockwise);
            var earthMesh = meshFactory.CreateSphere(false, 1.0f, 36);
            earthVertexBuffer = earthMesh.Vertices.Buffer;
            earthIndexBuffer = earthMesh.Indices.Buffer;

            var formatInfo = eye.Adapters[0].GetSupportedFormats(FormatSupport.RenderTarget | FormatSupport.Texture2D | FormatSupport.TextureCube)
                .First(x => x.ColorBits == 24 && x.AlphaBits == 8 && x.ColorFormatType == FormatElementType.UNORM);
            starsProxyTexture = device.Create.Texture2D(new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Usage = Usage.Default,
                Width = SkyboxSize,
                Height = SkyboxSize,
                ArraySize = 1,
                MipLevels = 1,
                FormatID = formatInfo.ID
            });

            skyboxTexture = device.Create.Texture2D(new Texture2DDescription
            {
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                Usage = Usage.Default,
                Width = SkyboxSize,
                Height = SkyboxSize,
                ArraySize = 6,
                MipLevels = TextureHelper.MipLevels(SkyboxSize, SkyboxSize, 1),
                FormatID = formatInfo.ID,
                MiscFlags = MiscFlags.TextureCube | MiscFlags.GenerateMips
            });

            var textureLoader = new TextureLoader(device);

            earthTexture = textureLoader.Load("../Textures/BasicTest.png");
        }
示例#36
0
 public override void Initialize()
 {
     _meshFactory = new MeshFactory(Demo);
     MeshFactory = _meshFactory;
     info = new InfoText(glControl);
 }
示例#37
0
        public CubeScene(IEye eye, DisplayMode desctopDisplayMode)
            : base(eye, desctopDisplayMode)
        {
            var vertexShader = Device.Create.VertexShader(ShaderParser.Parse(VertexShaderText));
            var pixelShader = Device.Create.PixelShader(ShaderParser.Parse(PixelShaderText));
            shaderCombination = Device.Create.ShaderCombination(vertexShader, null, null, null, pixelShader);

            var meshFactory = new MeshFactory(Device, Handedness.Right, Winding.Clockwise);
            cubeMesh = meshFactory.CreateCube(2.0f);

            vertexLayout = Device.Create.VertexLayout(vertexShader, new[]
            {
                new VertexLayoutElement(ExplicitFormat.R32G32B32_FLOAT, 0, 0),
                new VertexLayoutElement(ExplicitFormat.R32G32B32_FLOAT, 0, 12),
                new VertexLayoutElement(ExplicitFormat.R32G32_FLOAT, 0, 24)
            });

            transformBuffer = Device.Create.Buffer(
                new BufferDescription { SizeInBytes = Transform.SizeInBytes, BindFlags = BindFlags.UniformBuffer, Usage = Usage.Dynamic });
            cameraVertexBuffer = Device.Create.Buffer(
                new BufferDescription { SizeInBytes = CameraVertex.SizeInBytes, BindFlags = BindFlags.UniformBuffer, Usage = Usage.Dynamic });
            cameraPixelBuffer = Device.Create.Buffer(
                new BufferDescription { SizeInBytes = CameraPixel.SizeInBytes, BindFlags = BindFlags.UniformBuffer, Usage = Usage.Dynamic });
            lightBuffer = Device.Create.Buffer(
                new BufferDescription { SizeInBytes = Light.SizeInBytes, BindFlags = BindFlags.UniformBuffer, Usage = Usage.Dynamic });

            var textureLoader = new TextureLoader(Device);

            var diffuseTexture = textureLoader.Load("../Textures/DiffuseTest.png");
            diffuseView = diffuseTexture.ViewAsShaderResource(diffuseTexture.FormatID, 0, diffuseTexture.MipLevels);

            var specularTexture = textureLoader.Load("../Textures/SpecularTest.png");
            specualrView = specularTexture.ViewAsShaderResource(specularTexture.FormatID, 0, specularTexture.MipLevels);

            samplerState = Device.Create.SamplerState(SamplerDescription.Default);
            depthStencilState = Device.Create.DepthStencilState(DepthStencilDescription.Enabled);
        }
示例#38
0
        public RenderToTextureScene(IEye eye, DisplayMode desctopDisplayMode)
            : base(eye, desctopDisplayMode)
        {
            var vertexShader = Device.Create.VertexShader(ShaderParser.Parse(VertexShaderText));
            var pixelShader = Device.Create.PixelShader(ShaderParser.Parse(PixelShaderText));
            shaderCombination = Device.Create.ShaderCombination(vertexShader, null, null, null, pixelShader);

            var meshFactory = new MeshFactory(Device, Handedness.Right, Winding.Clockwise);
            cubeMesh = meshFactory.CreateCube(2.0f);

            vertexLayout = Device.Create.VertexLayout(vertexShader, new[]
            {
                new VertexLayoutElement(ExplicitFormat.R32G32B32_FLOAT, 0, 0),
                new VertexLayoutElement(ExplicitFormat.R32G32B32_FLOAT, 0, 12),
                new VertexLayoutElement(ExplicitFormat.R32G32_FLOAT, 0, 24)
            });

            transformBuffer = Device.Create.Buffer(
                new BufferDescription { SizeInBytes = Transform.SizeInBytes, BindFlags = BindFlags.UniformBuffer, Usage = Usage.Dynamic });
            cameraVertexBuffer = Device.Create.Buffer(
                new BufferDescription { SizeInBytes = CameraVertex.SizeInBytes, BindFlags = BindFlags.UniformBuffer, Usage = Usage.Dynamic });
            lightBuffer = Device.Create.Buffer(
                new BufferDescription { SizeInBytes = Light.SizeInBytes, BindFlags = BindFlags.UniformBuffer, Usage = Usage.Dynamic });

            var renderTargetFormats = Eye.Adapters[0]
                .GetSupportedFormats(FormatSupport.Texture2D | FormatSupport.RenderTarget | FormatSupport.MipAutogen)
                .Where(fi => fi.ColorBits <= 24);
            if (!renderTargetFormats.Any()) throw new NotSupportedException("Render target textures are not supported.");
            var renderTargetFormatInfo = renderTargetFormats
                .OrderByDescending(fi => fi.ColorBits)
                .ThenBy(fi => fi.TotalBits)
                .First();

            var renderTargetTexture = Device.Create.Texture2D(new Texture2DDescription
            {
                Width = TargetSize,
                Height = TargetSize,
                MipLevels = TextureHelper.MipLevels(TargetSize, TargetSize, 1),
                ArraySize = 1,
                FormatID = renderTargetFormatInfo.ID,
                Sampling = Sampling.NoMultisampling,
                Usage = Usage.Default,
                BindFlags = BindFlags.RenderTarget | BindFlags.ShaderResource,
                MiscFlags = MiscFlags.GenerateMips,
                ExtraFlags = ExtraFlags.None
            });
            targetRtv = renderTargetTexture.ViewAsRenderTarget(renderTargetFormatInfo.ID, 0);
            targetSrv = renderTargetTexture.ViewAsShaderResource(renderTargetFormatInfo.ID, 0, renderTargetTexture.MipLevels);

            var dsFormats = Eye.Adapters[0].GetSupportedFormats(FormatSupport.Texture2D | FormatSupport.DepthStencil);
            var dsFormatInfo = dsFormats
                .OrderBy(fi => (fi.ColorBits == 24 && fi.AlphaBits == 8) ? 0 : 1)
                .ThenByDescending(fi => fi.ColorBits)
                .ThenBy(fi => fi.TotalBits)
                .First();

            var depthStencilTexture = Device.Create.Texture2D(new Texture2DDescription
            {
                Width = TargetSize,
                Height = TargetSize,
                MipLevels = 1,
                ArraySize = 1,
                FormatID = dsFormatInfo.ID,
                Sampling = Sampling.NoMultisampling,
                Usage = Usage.Default,
                BindFlags = BindFlags.DepthStencil,
                MiscFlags = MiscFlags.None,
                ExtraFlags = ExtraFlags.None
            });
            targetDsv = depthStencilTexture.ViewAsDepthStencil(dsFormatInfo.ID, DepthStencilViewFlags.None, 0);

            var textureLoader = new TextureLoader(Device);

            var diffuseTexture = textureLoader.Load("../Textures/DiffuseTest.png");
            diffuseView = diffuseTexture.ViewAsShaderResource(diffuseTexture.FormatID, 0, diffuseTexture.MipLevels);

            samplerState = Device.Create.SamplerState(SamplerDescription.Anisotropic);
            depthStencilState = Device.Create.DepthStencilState(DepthStencilDescription.Enabled);
        }
示例#39
0
 private void Recreate()
 {
     int numGrids = 3;
     int gridColumns = 16;
     int rowFactor = 1;
     List<Mesh> grids = new List<Mesh>();
     using (MeshFactory fact = new MeshFactory())
         grids.Add(fact.CreateDiamondGrid(gridColumns, gridColumns));
     for (int i = 0; i < numGrids-1; i++)
     {
         grids.Add(new ExpandableSquareGrid(gridColumns, gridColumns * rowFactor));
         gridColumns = (gridColumns + gridColumns * rowFactor) / 2;
         rowFactor = MathExtensions.Clamp(rowFactor / 2, 1, 10);
     }
     for (int i = 0; i < numGrids; i++)
     {
         grids.Add(new ExpandableSquareGrid(gridColumns, gridColumns));
     }
     SetScales(grids);
     MeshOptimiser.CombineIntoSingleMesh(this, grids);
     this.numGrids = grids.Count;
 }