コード例 #1
0
        public Node Load(Node parentNode)
        {
            this.Node = parentNode.CreateChild(this.Name);

            this.LoadCubicElement(this.Node);

            var resourceCache = DIContainer.Get <Urho.Resources.ResourceCache>();

            var fileExtension = this.Source.FileExtension();
            var hash          = this.Source.ToMD5() + fileExtension;
            var model         = resourceCache.GetModel(hash);

            _StaticModel       = this.Node.CreateComponent <StaticModel>();
            _StaticModel.Model = model;

            _StaticModel.CastShadows = this.CastShadows;

            this.LoadMaterials(_StaticModel, resourceCache);
            this.ApplyPhysics(this.Node);

            return(this.Node);
        }
コード例 #2
0
        public void SerializeEmptyModelTest()
        {
            var model        = new StaticModel();
            var serializer   = new Serializer(model);
            var memoryStream = new MemoryStream();
            var streamWriter = new StreamWriter(memoryStream);

            serializer.Serialize(streamWriter);
            streamWriter.Flush();
            memoryStream.Seek(0, SeekOrigin.Begin);

            const string expected =
                "{\"class_name\":\"sequential\",\"config\":{\"name\":\"sequential_1\",\"layers\":[]},\"keras_version\":\"2.2.5\",\"backend\":\"tensorflow\"}";
            string actual;

            using (var reader = new StreamReader(memoryStream))
            {
                actual = reader.ReadLine();
            }

            Assert.True(expected.Equals(actual, StringComparison.CurrentCultureIgnoreCase));
        }
コード例 #3
0
ファイル: PhysicsSample.cs プロジェクト: vaclavpetr/Blog
        public override void OnSurfaceAddedOrUpdated(string surfaceId, DateTimeOffset lastUpdateTimeUtc,
                                                     SpatialVertex[] vertexData, short[] indexData,
                                                     Vector3 boundsCenter, Quaternion boundsRotation)
        {
            var         isNew       = false;
            StaticModel staticModel = null;
            var         node        = _environmentNode.GetChild(surfaceId, false);

            if (node != null)
            {
                isNew       = false;
                staticModel = node.GetComponent <StaticModel>();
            }
            else
            {
                isNew       = true;
                node        = _environmentNode.CreateChild(surfaceId);
                staticModel = node.CreateComponent <StaticModel>();
            }

            node.Position = boundsCenter;
            node.Rotation = boundsRotation;
            var model = CreateModelFromVertexData(vertexData, indexData);

            staticModel.Model = model;

            if (isNew)
            {
                staticModel.SetMaterial(_spatialMaterial);
            }

            var rigidBody = node.CreateComponent <RigidBody>();

            rigidBody.RollingFriction = 0.5f;
            rigidBody.Friction        = 0.5f;
            var collisionShape = node.CreateComponent <CollisionShape>();

            collisionShape.SetTriangleMesh(model, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
        }
コード例 #4
0
        /// <summary>
        /// Spawns an Instance of an defined StaticModel
        /// </summary>
        /// <param name="model"></param>
        /// <param name="fOffset"></param>
        /// <param name="vPosition"></param>
        /// <param name="fAngle"></param>
        /// <returns></returns>
        internal void SpawnInstance(StaticModel model, GroupCenter groupCenter, Vector3 position, Vector3 rotation)
        {
            StaticInstance instance = new StaticInstance();

            instance.model = model;
            //instance.mesh = UnityEngine.Object.Instantiate(model.prefab);
            instance.CelestialBody = FlightGlobals.currentMainBody;

            instance.groupCenter = groupCenter;
            instance.Group       = groupCenter.Group;

            instance.transform.position = position;
            instance.transform.parent   = groupCenter.gameObject.transform;

            instance.RelativePosition = instance.transform.localPosition;
            instance.Orientation      = rotation;

            if (!Directory.Exists(KSPUtil.ApplicationRootPath + "GameData/" + KerbalKonstructs.newInstancePath))
            {
                Directory.CreateDirectory(KSPUtil.ApplicationRootPath + "GameData/" + KerbalKonstructs.newInstancePath);
            }
            instance.configPath = KerbalKonstructs.newInstancePath + "/" + model.name + "-instances.cfg";
            instance.configUrl  = null;

            enableColliders  = false;
            enableColliders2 = false;

            instance.Orientate();
            instance.Activate();

            KerbalKonstructs.SelectInstance(instance, true);

            GrassColor2 grassMod = instance.gameObject.GetComponent <GrassColor2>();

            if (grassMod != null)
            {
                grassMod.UpdateCallBack(StaticsEditorGUI.defaultGrassPreset);
            }
        }
コード例 #5
0
        //###################################################################################################################
        public override void OnSurfaceAddedOrUpdated(SpatialMeshInfo surface, Model generatedModel)
        {
            // create a node for spatial mapping if not exist
            Node node = this.Scene.GetChild(surface.SurfaceId, false);

            if (node == null)
            {
                node = this.Scene.CreateChild(surface.SurfaceId);
            }

            // add the spatial map to the node
            StaticModel staticModel = node.CreateComponent <StaticModel>();

            staticModel.Model = generatedModel;

            // set position and orientation of the map according to the world scene
            node.Position = surface.BoundsCenter;
            node.Rotation = surface.BoundsRotation;

            // stop spatial mapping to avoid slowness
            StopSpatialMapping();
        }
コード例 #6
0
        /// <summary>
        /// Creates a StaticModel from a GeometricPrimitive and specified dimensions.
        /// </summary>
        /// <param name="primitiveType">Type of primitive to create</param>
        /// <param name="height">Height of primitive, used by cubes and cylinders.</param>
        /// <param name="width">Width of primitive, used by cubes.</param>
        /// <param name="depth">Depth of primitive, used by cubes.</param>
        /// <param name="diameter">Diameter of primitive, used by cylinders, spheres, toruses, and teapots.</param>
        private void LoadModelFromPrimitive(GeometricPrimitiveType primitiveType, float height, float width, float depth, float diameter)
        {
            GeometricPrimitive primitive;

            switch (primitiveType)
            {
            case GeometricPrimitiveType.Box:
                primitive = new CubePrimitive(this.parentEntity.Game.GraphicsDevice, height, width, depth);
                break;

            case GeometricPrimitiveType.Sphere:
                primitive = new SpherePrimitive(this.parentEntity.Game.GraphicsDevice, diameter, 16);
                break;

            case GeometricPrimitiveType.Cylinder:
                primitive = new CylinderPrimitive(this.parentEntity.Game.GraphicsDevice, height, diameter, 16);
                break;

            case GeometricPrimitiveType.Cone:
                primitive = new ConePrimitive(this.parentEntity.Game.GraphicsDevice, height, diameter, 16);
                break;

            case GeometricPrimitiveType.Torus:
                primitive = new TorusPrimitive(this.parentEntity.Game.GraphicsDevice, diameter, 0.3333f, 16);
                break;

            case GeometricPrimitiveType.Teapot:
                primitive = new TeapotPrimitive(this.parentEntity.Game.GraphicsDevice, diameter, 8);
                break;

            default:
                throw new Exception("LoadPrimitive does not handle this type of GeometricPrimitive. Was a new primitive type made and not handled here?");
            }

            if (null != primitive)
            {
                model = new StaticModel(primitive, this.parentEntity.Game.GraphicsDevice);
            }
        }
コード例 #7
0
ファイル: PlayerScript.cs プロジェクト: Erdroy/FlaxSamples
        void Update()
        {
            Screen.CursorVisible = false;
            Screen.CursorLock    = CursorLockMode.Locked;

            // Mouse
            Vector2 mouseDelta = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));

            pitch = Mathf.Clamp(pitch + mouseDelta.Y, -88, 88);
            yaw  += mouseDelta.X;

            // Jump
            if (CanJump && Input.GetAction("Jump"))
            {
                _jump = true;
            }

            // Shoot
            if (CanShoot && Input.GetAction("Fire"))
            {
                var ball         = RigidBody.New();
                var ballCollider = SphereCollider.New();
                var ballModel    = StaticModel.New();
                ballModel.Model          = SphereModel;
                ballModel.Parent         = ball;
                ballModel.StaticFlags    = StaticFlags.None;
                ballCollider.Parent      = ball;
                ballCollider.StaticFlags = StaticFlags.None;
                ball.UseCCD      = true;
                ball.StaticFlags = StaticFlags.None;
                ball.Transform   = new Transform(
                    CameraTarget.Position + Horizontal(CameraTarget.Direction) * 70.0f,
                    Quaternion.Identity,
                    new Vector3(0.1f));
                SceneManager.SpawnActor(ball);
                ball.LinearVelocity = CameraTarget.Direction * 600.0f;
                Destroy(ball, 5.0f);
            }
        }
コード例 #8
0
ファイル: ModelTests.cs プロジェクト: galiosmax/NND
        public void RemoveNodeTest()
        {
            var model = new StaticModel();

            Assert.NotNull(model.GetLayerNodes());
            Assert.That(model.GetLayerNodes()?.Length == 0);

            var layerType = new LayerType("Dropout", "Core",
                                          new[]
            {
                new Parameter("rate", "Float", "1.0", Array.Empty <string>())
            }
                                          );

            model.AddNode(layerType);

            Assert.That(model.GetLayerNodes()?.Length == 1);

            model.RemoveNode(0);

            Assert.That(model.GetLayerNodes()?.Length == 0);
        }
コード例 #9
0
ファイル: Renderer.cs プロジェクト: ruo2012/SevenEngine
        /// <summary>Renders a single static model using "GL.DrawArrays()".</summary>
        /// <param name="staticModel">The mesh to be rendered.</param>
        public static void DrawStaticModel(StaticModel staticModel)
        {
            /*Matrix4 perspective = Matrix4.CreatePerspectiveFieldOfView(
             * (float)_currentCamera.FieldOfView,
             * (float)_screenWidth / (float)_screenHeight,
             * (float)_currentCamera.NearClipPlane,
             * (float)_currentCamera.FarClipPlane);
             * perspective.Transpose();
             * Matrix4 camera = _currentCamera.GetMatrix();
             * camera = perspective;*/

            // Apply the 3D projection matrix transformations
            SetProjectionMatrix();

            if (staticModel.ShaderOverride != null)
            {
                GL.UseProgram(staticModel.ShaderOverride.GpuHandle);
            }
            else
            {
                GL.UseProgram(DefaultShaderProgram.GpuHandle);
            }

            //GL.UseProgram(ShaderManager.LightShader.GpuHandle);

            // Apply the model view matrix transformations
            GL.MatrixMode(MatrixMode.Modelview);
            // Apply the camera transformation
            Matrix4 cameraTransform = _currentCamera.GetMatrix();

            GL.LoadMatrix(ref cameraTransform);
            // Apply the world transformation
            GL.Translate(staticModel.Position.X, staticModel.Position.Y, staticModel.Position.Z);
            GL.Rotate(staticModel.Orientation.W * 180f / 3.14f, staticModel.Orientation.X, staticModel.Orientation.Y, staticModel.Orientation.Z);
            GL.Scale(staticModel.Scale.X, staticModel.Scale.Y, staticModel.Scale.Z);

            // Call the drawing functions for each mesh within the model
            staticModel.Meshes.Foreach((Foreach <StaticMesh>)DrawStaticModelPart);
        }
コード例 #10
0
        private void DisplayInfoText(StaticModel hoverselected)
        {
            if (hoverselected != null)
            {
                var infotext = infowindow.GetChild("InfoText") as Text;
                infowindow.SetVisible(true);
                infowindow.Position = Input.MousePosition + new IntVector2(10, 10);
                string todisplay = hoverselected.Node.Name;

                var cusComponent = hoverselected.Node.GetComponent <CustomNodeComponent>();
                if (cusComponent == null)
                {
                    cusComponent = hoverselected.Node.CreateComponent <CustomNodeComponent>();
                }
                if (!string.IsNullOrEmpty(cusComponent.Vmap))
                {
                    if (cusComponent.Info == null || cusComponent.Info.Count == 0)
                    {
                        cusComponent.Info = new List <data>().JDeserializemyData(cusComponent.Vmap);
                    }
                }
                if (cusComponent.Info != null)
                {
                    foreach (var item in cusComponent.Info)
                    {
                        todisplay += $"\n{item.Key}: {item.value}";
                    }
                    infotext.SetText(todisplay);
                }
                else
                {
                    infotext.SetText(todisplay);
                }
            }
            else
            {
                infowindow.SetVisible(false);
            }
        }
コード例 #11
0
        protected override async void Start()
        {
            base.Start();

            cursorNode           = Scene.CreateChild();
            cursorNode.Position  = Vector3.UnitZ * 100;    //hide cursor at start - pos at (0,0,100)
            cursorModel          = cursorNode.CreateComponent <Urho.Shapes.Plane>();
            cursorModel.ViewMask = 0x80000000;             //hide from raycasts (Raycast() uses a differen viewmask so the cursor won't be visible for it)
            cursorNode.RunActions(new RepeatForever(new ScaleTo(0.3f, 0.15f), new ScaleTo(0.3f, 0.2f)));

            var cursorMaterial = new Material();

            cursorMaterial.SetTexture(TextureUnit.Diffuse, ResourceCache.GetTexture2D("Textures/Cursor.png"));
            cursorMaterial.SetTechnique(0, CoreAssets.Techniques.DiffAlpha);
            cursorModel.Material    = cursorMaterial;
            cursorModel.CastShadows = false;

            Input.TouchEnd     += args => OnGestureTapped(args.X, args.Y);
            UnhandledException += OnUnhandledException;

            ContinuesHitTestAtCenter = true;
        }
コード例 #12
0
        /// <inheritdoc />
        protected override void DrawSelectionDepth(GPUContext context, SceneRenderTask task, GPUTexture customDepth)
        {
            var foliage = GizmoMode.SelectedFoliage;

            if (!foliage)
            {
                return;
            }
            var instanceIndex = GizmoMode.SelectedInstanceIndex;

            if (instanceIndex < 0 || instanceIndex >= foliage.InstancesCount)
            {
                return;
            }

            // Draw single instance
            var instance = foliage.GetInstance(instanceIndex);
            var model    = foliage.GetFoliageType(instance.Type).Model;

            if (model)
            {
                Transform instanceWorld = foliage.Transform.LocalToWorld(instance.Transform);

                if (!_staticModel)
                {
                    _staticModel = new StaticModel
                    {
                        StaticFlags = StaticFlags.None
                    };
                }

                _staticModel.Model     = model;
                _staticModel.Transform = instanceWorld;
                _actors.Add(_staticModel);

                Renderer.DrawSceneDepth(context, task, customDepth, _actors);
            }
        }
コード例 #13
0
        protected override void Start()
        {
            base.Start();

            Scene.CreateComponent <DebugRenderer>();

            cursorNode          = Scene.CreateChild();
            cursorNode.Position = Vector3.UnitZ * 100;             //hide cursor at start - pos at (0,0,100)

            cursorModel          = cursorNode.CreateComponent <Urho.Shapes.Plane>();
            cursorModel.ViewMask = 0x80000000;             //hide from raycasts (Raycast() uses a differen viewmask so the cursor won't be visible for it)

            cursorNode.RunActions(new RepeatForever(new ScaleTo(0.3f, 0.15f), new ScaleTo(0.3f, 0.2f)));

            var cursorMaterial = new Material();

            cursorMaterial.SetTexture(TextureUnit.Diffuse, ResourceCache.GetTexture2D("Textures/Cursor.png"));
            cursorMaterial.SetTechnique(0, CoreAssets.Techniques.DiffAlpha);
            cursorModel.Material    = cursorMaterial;
            cursorModel.CastShadows = false;

            Input.TouchEnd     += args => OnGestureTapped(args.X, args.Y);
            UnhandledException += OnUnhandledException;

            ContinuesHitTestAtCenter = true;

            loadingLabel = new Text
            {
                Value = "Detecting planes...",
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment   = VerticalAlignment.Center,
                TextAlignment       = HorizontalAlignment.Center,
            };

            loadingLabel.SetColor(new Color(0.5f, 1f, 0f));
            loadingLabel.SetFont(font: CoreAssets.Fonts.AnonymousPro, size: 42);
            UI.Root.AddChild(loadingLabel);
        }
コード例 #14
0
            public Preview(SkinnedModelWindow window)
                : base(true)
            {
                _window       = window;
                PlayAnimation = true;

                // Show floor widget
                _showFloorButton = ViewWidgetShowMenu.AddButton("Floor", button =>
                {
                    _floorModel.IsActive  = !_floorModel.IsActive;
                    _showFloorButton.Icon = _floorModel.IsActive ? Style.Current.CheckBoxTick : SpriteHandle.Invalid;
                });
                _showFloorButton.IndexInParent = 1;

                // Show current LOD widget
                _showCurrentLODButton = ViewWidgetShowMenu.AddButton("Current LOD", button =>
                {
                    _showCurrentLOD            = !_showCurrentLOD;
                    _showCurrentLODButton.Icon = _showCurrentLOD ? Style.Current.CheckBoxTick : SpriteHandle.Invalid;
                });
                _showCurrentLODButton.IndexInParent = 2;

                // Floor model
                _floorModel = new StaticModel
                {
                    Position = new Vector3(0, -25, 0),
                    Scale    = new Vector3(5, 0.5f, 5),
                    Model    = FlaxEngine.Content.LoadAsync <Model>(StringUtils.CombinePaths(Globals.EngineContentFolder, "Editor/Primitives/Cube.flax")),
                    IsActive = false
                };
                Task.AddCustomActor(_floorModel);

                // Enable shadows
                PreviewLight.ShadowsMode     = ShadowsCastingMode.All;
                PreviewLight.CascadeCount    = 3;
                PreviewLight.ShadowsDistance = 2000.0f;
                Task.ViewFlags |= ViewFlags.Shadows;
            }
コード例 #15
0
            public Preview(SkinnedModelWindow window)
                : base(true)
            {
                _window = window;

                // Show floor widget
                _showFloorButton = ViewWidgetButtonMenu.AddButton("Show floor", OnShowFloorModelClicked);
                _showFloorButton.IndexInParent = 1;

                // Floor model
                _floorModel          = StaticModel.New();
                _floorModel.Position = new Vector3(0, -25, 0);
                _floorModel.Scale    = new Vector3(5, 0.5f, 5);
                _floorModel.Model    = FlaxEngine.Content.LoadAsync <Model>(StringUtils.CombinePaths(Globals.EditorFolder, "Primitives/Cube.flax"));
                _floorModel.IsActive = false;
                Task.CustomActors.Add(_floorModel);

                // Enable shadows
                PreviewLight.ShadowsMode     = ShadowsCastingMode.All;
                PreviewLight.CascadeCount    = 2;
                PreviewLight.ShadowsDistance = 1000.0f;
                Task.Flags |= ViewFlags.Shadows;
            }
コード例 #16
0
        internal static void PimpLv2Runway(GameObject modelPrefab, bool state = false)
        {
            StaticModel modelLights = StaticDatabase.GetModelByName("SQUAD_Runway_Lights");
            //Log.Normal("Prefab name: " + modelPrefab.name);
            int count = 0;

            foreach (Transform target in modelPrefab.transform.FindAllRecursive("fxTarget"))
            {
                GameObject light = GameObject.Instantiate(modelLights.prefab);
                light.SetActive(state);
                //Log.Normal("found target: " + target.parent.name);
                light.transform.parent      = target.parent.FindRecursiveContains("runway");
                light.transform.localScale *= 0.6f;

                light.transform.rotation = modelPrefab.transform.rotation;

                light.transform.localPosition = new Vector3(6.5f, 0.85f, -1050f + count * 330);

                light.name = light.transform.parent.name + "_lights";

                count++;
            }
        }
コード例 #17
0
            public AnimationGraphPreview(AnimationGraphWindow window)
                : base(true)
            {
                _window = window;

                // Show floor widget
                _showFloorButton               = ViewWidgetShowMenu.AddButton("Floor", OnShowFloorModelClicked);
                _showFloorButton.Icon          = Style.Current.CheckBoxTick;
                _showFloorButton.IndexInParent = 1;

                // Floor model
                _floorModel          = new StaticModel();
                _floorModel.Position = new Vector3(0, -25, 0);
                _floorModel.Scale    = new Vector3(5, 0.5f, 5);
                _floorModel.Model    = FlaxEngine.Content.LoadAsync <Model>(StringUtils.CombinePaths(Globals.EngineContentFolder, "Editor/Primitives/Cube.flax"));
                Task.AddCustomActor(_floorModel);

                // Enable shadows
                PreviewLight.ShadowsMode     = ShadowsCastingMode.All;
                PreviewLight.CascadeCount    = 2;
                PreviewLight.ShadowsDistance = 1000.0f;
                Task.ViewFlags |= ViewFlags.Shadows;
            }
コード例 #18
0
ファイル: ModelTests.cs プロジェクト: galiosmax/NND
        public void AddNodeWithIndexTest()
        {
            var model = new StaticModel();

            Assert.NotNull(model.GetLayerNodes());
            Assert.That(model.GetLayerNodes()?.Length == 0);

            var layerType = new LayerType("Dropout", "Core",
                                          new[]
            {
                new Parameter("rate", "Float", "1.0", Array.Empty <string>())
            }
                                          );

            model.AddNode(layerType);
            var firstNode = model.GetLayerNodes()?.First();

            Assert.AreEqual(firstNode, model.GetLayerNodes()?[0]);

            model.AddNode(layerType, 0);

            Assert.AreEqual(firstNode, model.GetLayerNodes()?[1]);
        }
コード例 #19
0
        private async Task Create3DObject()
        {
            // Scene
            var scene = new Scene();

            scene.CreateComponent <Octree>();

            // Node (Rotation and Position)
            Node node = scene.CreateChild();

            node.Position = new Vector3(0, 0, 5);
            node.Rotation = new Quaternion(10, 60, 10);
            node.SetScale(1f);

            // Pyramid Model
            StaticModel modelObject = node.CreateComponent <StaticModel>();

            modelObject.Model = ResourceCache.GetModel("Models/Pyramid.mdl");

            // Light
            Node light = scene.CreateChild(name: "light");

            light.SetDirection(new Vector3(0.4f, -0.5f, 0.3f));
            light.CreateComponent <Light>();

            // Camera
            Node   cameraNode = scene.CreateChild(name: "camera");
            Camera camera     = cameraNode.CreateComponent <Camera>();

            // Viewport
            Renderer.SetViewport(0, new Viewport(scene, camera, null));

            // Action
            await node.RunActionsAsync(
                new RepeatForever(new RotateBy(duration: 1,
                                               deltaAngleX: 0, deltaAngleY: 90, deltaAngleZ: 0)));
        }
コード例 #20
0
        /// <summary>
        /// Creates a 3D plane
        /// </summary>
        /// <param name="width"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static StaticModel CreatePlane(int width, int length)
        {
            MeshVertex[] data = new MeshVertex[4];

            data[0].Position = new Vector3(0, 0, 0);
            data[0].Normal   = Vector3.UnitY;
            data[0].UV       = new Vector2(0, 0);
            data[0].Color    = new Vector4(1, 0, 0, 1);

            data[1].Position = new Vector3(width, 0, 0);
            data[1].Normal   = Vector3.UnitY;
            data[1].UV       = new Vector2(1, 0);
            data[1].Color    = new Vector4(1, 0, 0, 1);

            data[2].Position = new Vector3(width, 0, length);
            data[2].Normal   = Vector3.UnitY;
            data[2].UV       = new Vector2(1, 1);
            data[2].Color    = new Vector4(1, 0, 0, 1);

            data[3].Position = new Vector3(0, 0, length);
            data[3].Normal   = Vector3.UnitY;
            data[3].UV       = new Vector2(0, 1);
            data[3].Color    = new Vector4(1, 0, 0, 1);

            ushort[] indices = new ushort[6] {
                0, 1, 2, 2, 3, 0
            };

            Mesh m = new Mesh(data, indices);

            StaticModel model = new StaticModel();

            model.Meshes    = new Mesh[1];
            model.Meshes[0] = m;

            return(model);
        }
コード例 #21
0
        public void BoxStack(int totalRows, Vector3 offset)
        {
            int currentColumnMax = totalRows;

            float        boxScale = 9.0f;
            StaticModel  mesh     = this.game.ModelLoader.LoadStaticModel("Models/WoodCrate/Crate1");
            BoxShapeDesc boxShape = PhysicsComponent.CreateBoxShapeFromMesh(mesh, boxScale);

            for (int rows = 0; rows < totalRows; ++rows, --currentColumnMax)
            {
                for (int columns = 0; columns < currentColumnMax; ++columns)
                {
                    Vector3 boxPos = offset + new Vector3(columns * boxShape.Extents.X,
                                                          rows * boxShape.Extents.Y + (boxShape.Extents.Y * 0.5f),
                                                          0.0f);

                    boxPos.X -= currentColumnMax * boxShape.Extents.X * 0.5f;

                    int boxTemplate = 2;
                    if (rows == (totalRows - 1))
                    {
                        // Use a smoking box if we're on the top row
                        boxTemplate = 3;
                    }

                    var boxEntity = new BaseEntity(this.game, boxPos, Matrix.Identity, 9.0f);
                    this.game.SceneManager.AddEntityByTemplateID(boxEntity, boxTemplate);

                    if (boxTemplate == 3)
                    {
                        ParticleEmitterComponent emitter = boxEntity.GetComponentByType(ComponentType.ParticleEmitterComponent) as ParticleEmitterComponent;
                        // These give offsets for the emitter and how many particles per second to emit.
                        emitter.InitializeEmitterSettings(Vector3.Zero, 7, Vector3.Zero);
                    }
                }
            }
        }
コード例 #22
0
        void InitWheel(string name, Vector3 offset, out Node wheelNode, out uint wheelNodeId)
        {
            var cache = GetSubsystem <ResourceCache>();

            // Note: do not parent the wheel to the hull scene node. Instead create it on the root level and let the physics
            // constraint keep it together
            wheelNode          = Scene.CreateChild(name);
            wheelNode.Position = Node.LocalToWorld(offset);
            wheelNode.Rotation = Node.Rotation * (offset.X >= 0.0 ? new Quaternion(0.0f, 0.0f, -90.0f) : new Quaternion(0.0f, 0.0f, 90.0f));
            wheelNode.Scale    = new Vector3(0.8f, 0.5f, 0.8f);
            // Remember the ID for serialization
            wheelNodeId = wheelNode.ID;

            StaticModel    wheelObject     = wheelNode.CreateComponent <StaticModel>();
            RigidBody      wheelBody       = wheelNode.CreateComponent <RigidBody>();
            CollisionShape wheelShape      = wheelNode.CreateComponent <CollisionShape>();
            Constraint     wheelConstraint = wheelNode.CreateComponent <Constraint>();

            wheelObject.Model = (cache.Get <Model>("Models/Cylinder.mdl"));
            wheelObject.SetMaterial(cache.Get <Material>("Materials/Stone.xml"));
            wheelObject.CastShadows = true;
            wheelShape.SetSphere(1.0f, Vector3.Zero, Quaternion.Identity);
            wheelBody.Friction             = (1.0f);
            wheelBody.Mass                 = 1.0f;
            wheelBody.LinearDamping        = 0.2f;  // Some air resistance
            wheelBody.AngularDamping       = 0.75f; // Could also use rolling friction
            wheelBody.CollisionLayer       = 1;
            wheelConstraint.ConstraintType = ConstraintType.CONSTRAINT_HINGE;
            wheelConstraint.OtherBody      = GetComponent <RigidBody>();                              // Connect to the hull body
            wheelConstraint.SetWorldPosition(wheelNode.Position);                                     // Set constraint's both ends at wheel's location
            wheelConstraint.SetAxis(Vector3.UnitY);                                                   // Wheel rotates around its local Y-axis
            wheelConstraint.SetOtherAxis(offset.X >= 0.0 ? Vector3.UnitX : new Vector3(-1f, 0f, 0f)); // Wheel's hull axis points either left or right
            wheelConstraint.LowLimit         = new Vector2(-180.0f, 0.0f);                            // Let the wheel rotate freely around the axis
            wheelConstraint.HighLimit        = new Vector2(180.0f, 0.0f);
            wheelConstraint.DisableCollision = true;                                                  // Let the wheel intersect the vehicle hull
        }
コード例 #23
0
ファイル: Progam.cs プロジェクト: yvesis/urho-samples
        public override void OnSurfaceAddedOrUpdated(SpatialMeshInfo surface, Model generatedModel)
        {
            bool        isNew       = false;
            StaticModel staticModel = null;
            Node        node        = environmentNode.GetChild(surface.SurfaceId, false);

            if (node != null)
            {
                isNew       = false;
                staticModel = node.GetComponent <StaticModel>();
            }
            else
            {
                isNew       = true;
                node        = environmentNode.CreateChild(surface.SurfaceId);
                staticModel = node.CreateComponent <StaticModel>();
            }

            node.Position     = surface.BoundsCenter;
            node.Rotation     = surface.BoundsRotation;
            staticModel.Model = generatedModel;

            if (isNew)
            {
                staticModel.SetMaterial(spatialMaterial);
                var rigidBody = node.CreateComponent <RigidBody>();
                rigidBody.RollingFriction = 0.5f;
                rigidBody.Friction        = 0.5f;
                var collisionShape = node.CreateComponent <CollisionShape>();
                collisionShape.SetTriangleMesh(generatedModel, 0, Vector3.One, Vector3.Zero, Quaternion.Identity);
            }
            else
            {
                //Update Collision shape
            }
        }
コード例 #24
0
        /// <summary>
        /// Spawns an Instance of an defined StaticModel
        /// </summary>
        /// <param name="model"></param>
        /// <param name="fOffset"></param>
        /// <param name="vPosition"></param>
        /// <param name="fAngle"></param>
        /// <returns></returns>
        public string SpawnInstance(StaticModel model, float fOffset, Vector3 vPosition)
        {
            StaticInstance instance = new StaticInstance();

            instance.isInSavegame = true;

            instance.heighReference = HeightReference.Terrain;

            instance.gameObject      = UnityEngine.Object.Instantiate(model.prefab);
            instance.RadiusOffset    = fOffset;
            instance.CelestialBody   = KerbalKonstructs.instance.getCurrentBody();
            instance.Group           = "Ungrouped";
            instance.RadialPosition  = vPosition;
            instance.RotationAngle   = 0;
            instance.Orientation     = Vector3.up;
            instance.VisibilityRange = (PhysicsGlobals.Instance.VesselRangesDefault.flying.unload + 3000);
            instance.RefLatitude     = KKMath.GetLatitudeInDeg(instance.RadialPosition);
            instance.RefLongitude    = KKMath.GetLongitudeInDeg(instance.RadialPosition);

            instance.model      = model;
            instance.configPath = null;
            instance.configUrl  = null;

            instance.SpawnObject(true);

            KerbalKonstructs.instance.selectedObject = instance;

            selectedObject = instance;
            startPosition  = selectedObject.gameObject.transform.position;

            instance.HighlightObject(XKCDColors.FreshGreen);

            this.Open();

            return(instance.UUID);
        }
コード例 #25
0
ファイル: API.cs プロジェクト: mstramb/Kerbal-Konstructs
        public static string PlaceStatic(string modelName, string bodyName, double lat, double lng, float alt, float rotation, bool isScanable = false)
        {
            StaticModel model = StaticDatabase.GetModelByName(modelName);

            if (model != null)
            {
                StaticInstance instance = new StaticInstance();
                instance.isInSavegame = true;

                instance.heighReference = HeightReference.Terrain;

                instance.gameObject      = UnityEngine.Object.Instantiate(model.prefab);
                instance.RadiusOffset    = alt;
                instance.CelestialBody   = ConfigUtil.GetCelestialBody(bodyName);
                instance.Group           = "Ungrouped";
                instance.RadialPosition  = KKMath.GetRadiadFromLatLng(instance.CelestialBody, lat, lng);
                instance.RotationAngle   = rotation;
                instance.Orientation     = Vector3.up;
                instance.VisibilityRange = (PhysicsGlobals.Instance.VesselRangesDefault.flying.unload + 3000);
                instance.RefLatitude     = lat;
                instance.RefLongitude    = lng;

                instance.model      = model;
                instance.configPath = null;
                instance.configUrl  = null;

                instance.isScanable = isScanable;

                instance.SpawnObject();

                return(instance.UUID);
            }

            Log.UserError("API:PlaceStatic: StaticModel not found in Database: " + modelName);
            return(null);
        }
コード例 #26
0
        public void SerializeNotEmptyModelTest()
        {
            var model = new StaticModel();

            model.AddNode(new LayerType("Input", "Core",
                                        new[]
            {
                new Parameter("shape", "Tuple", "1", Array.Empty <string>()),
                new Parameter("dtype", "String", "float32", new[] { "float32", "float64", "int32" })
            }
                                        ));
            model.AddNode(new LayerType("Reshape", "Core",
                                        new[]
            {
                new Parameter("target_shape", "Tuple", "1", Array.Empty <string>()),
            }
                                        ));
            var serializer   = new Serializer(model);
            var memoryStream = new MemoryStream();
            var streamWriter = new StreamWriter(memoryStream);

            serializer.Serialize(streamWriter);
            streamWriter.Flush();
            memoryStream.Seek(0, SeekOrigin.Begin);

            const string expected =
                "{\"class_name\":\"sequential\",\"config\":{\"name\":\"sequential_1\",\"layers\":[{\"class_name\":\"Reshape\",\"config\":{\"batch_input_shape\":[null,1],\"dtype\":\"float32\"}}]},\"keras_version\":\"2.2.5\",\"backend\":\"tensorflow\"}";
            string actual;

            using (var reader = new StreamReader(memoryStream))
            {
                actual = reader.ReadLine();
            }

            Assert.True(expected.Equals(actual, StringComparison.CurrentCultureIgnoreCase));
        }
コード例 #27
0
        public void updateSelection(StaticModel obj)
        {
            infAuthor          = obj.author;
            infMesh            = obj.mesh;
            infManufacturer    = obj.manufacturer;
            infCost            = obj.cost.ToString();
            infDescription     = obj.description;
            infTitle           = obj.title;
            infCategory        = obj.category;
            infLaunchTransform = obj.DefaultLaunchPadTransform;

            infLaunchLength = obj.DefaultLaunchSiteLength.ToString();
            infLaunchWidth  = obj.DefaultLaunchSiteWidth.ToString();
            infFacType      = obj.DefaultFacilityType;
            infFacMassCap   = obj.DefaultFacilityMassCapacity.ToString();
            infFacCraftCap  = obj.DefaultFacilityCraftCapacity.ToString();
            infStaffMax     = obj.DefaultStaffMax.ToString();
            //	infECMax = obj.getSetting("ECMax").ToString();
            //	infOreMax = obj.getSetting("OreMax").ToString();
            //	infPrOreMax = obj.getSetting("PrOreMax").ToString();
            infProdRateMax = obj.DefaultProductionRateMax.ToString();
            infScienceMax  = obj.DefaultScienceOMax.ToString();
            infFundsMax    = obj.DefaultFundsOMax.ToString();
        }
コード例 #28
0
        /// <inheritdoc />
        protected override void DrawSelectionDepth(GPUContext context, SceneRenderTask task, RenderTarget customDepth)
        {
            var foliage = GizmoMode.SelectedFoliage;

            if (!foliage)
            {
                return;
            }
            var instanceIndex = GizmoMode.SelectedInstanceIndex;

            if (instanceIndex < 0 || instanceIndex >= foliage.InstancesCount)
            {
                return;
            }

            // Draw single instance
            foliage.GetInstance(instanceIndex, out var instance);
            var model = foliage.GetFoliageTypeModel(instance.Type);

            if (model)
            {
                Transform instanceWorld = foliage.Transform.LocalToWorld(instance.Transform);

                if (!_staticModel)
                {
                    _staticModel             = StaticModel.New();
                    _staticModel.StaticFlags = StaticFlags.None;
                }

                _staticModel.Model     = model;
                _staticModel.Transform = instanceWorld;
                _actors.Add(_staticModel);

                context.DrawSceneDepth(task, customDepth, true, _actors, ActorsSources.CustomActors);
            }
        }
コード例 #29
0
        void CreateMovingBarrels(DynamicNavigationMesh navMesh)
        {
            Node        barrel = scene.CreateChild("Barrel");
            StaticModel model  = barrel.CreateComponent <StaticModel>();

            model.Model = ResourceCache.GetModel("Models/Cylinder.mdl");
            Material material = ResourceCache.GetMaterial("Materials/StoneTiled.xml");

            model.SetMaterial(material);
            material.SetTexture(TextureUnit.Diffuse, ResourceCache.GetTexture2D("Textures/TerrainDetail2.dds"));
            model.CastShadows = true;
            for (int i = 0; i < 20; ++i)
            {
                Node  clone = barrel.Clone(CreateMode.Replicated);
                float size  = 0.5f + NextRandom(1.0f);
                clone.Scale    = new Vector3(size / 1.5f, size * 2.0f, size / 1.5f);
                clone.Position = navMesh.FindNearestPoint(new Vector3(NextRandom(80.0f) - 40.0f, size * 0.5f, NextRandom(80.0f) - 40.0f), Vector3.One);
                CrowdAgent agent = clone.CreateComponent <CrowdAgent>();
                agent.Radius            = clone.Scale.X * 0.5f;
                agent.Height            = size;
                agent.NavigationQuality = NavigationQuality.Low;
            }
            barrel.Remove();
        }
コード例 #30
0
ファイル: GizmoHelper.cs プロジェクト: Spanyardie/Pulsar
        public static void SetAsSelected(Node node, Gizmo gizmo, PulsarScene scene)
        {
            StaticModel nodeModel = node.GetComponent <StaticModel>();

            if (nodeModel != null)
            {
                MaterialTemp tempMaterial = new MaterialTemp(nodeModel, scene.GetApplication());
                if (tempMaterial != null)
                {
                    tempMaterial.Name = "materialTemp";
                    tempMaterial.SetTransparentMaterial();

                    node.AddComponent(tempMaterial);
                    if (gizmo != null)
                    {
                        gizmo.Node.Position = node.Position;
                        Debug.Print("GizmoHelper.SetAsSelected - Calling gizmo.SetGizmoVisible with value true for gizmo '" + gizmo.Name);
                        gizmo.SetGizmoVisible(true);
                        Debug.Print("GizmoHelper.SetAsSelected - Setting gizmo.Node.Enabled to true for gizmo '" + gizmo.Name);
                        gizmo.Node.Enabled = true;
                    }
                }
            }
        }
コード例 #31
0
ファイル: Game1.cs プロジェクト: K42/Spong3D
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            sphere = new StaticModel(Content.Load<Model>(@"models/sphere"), 0, 0, 0);
            aX = new StaticModel(Content.Load<Model>(@"models/ring"), 0, 0, 0);
            aY = new StaticModel(Content.Load<Model>(@"models/ring"), 90, 0, 0);
            aZ = new StaticModel(Content.Load<Model>(@"models/ring"), 90, 90, 0);
            skydome = new StaticModel(Content.Load<Model>(@"models/skydome"), 2.0f, 1.0f, false);
            menudome = new StaticModel(Content.Load<Model>(@"models/skydome"), 2.0f, 1.0f, true);
            playDome = new BoundingSphere(Vector3.Zero, sphere.model.Meshes[0].BoundingSphere.Radius * 1.0f);
            intro_ball = Content.Load<Texture2D>(@"textures/intro_ball");
            logo = Content.Load<Texture2D>(@"textures/spong");
            arrow = Content.Load<Texture2D>(@"textures/arrow");
            bg1 = Content.Load<Texture2D>(@"textures/bg1");
            bg2 = Content.Load<Texture2D>(@"textures/bg2");
            dubstep_intro = Content.Load<Song>(@"music/intro");
            music1 = Content.Load<Song>(@"music/music1");
            music2 = Content.Load<Song>(@"music/music2");
            music3 = Content.Load<Song>(@"music/music3");
            powerUp = new PowerUp(this);
            menu = new MenuComponent(this, spriteBatch, Content.Load<SpriteFont>(@"fonts/menufont"), menuItems);
            duel_menu = new MenuComponent(this, spriteBatch, Content.Load<SpriteFont>(@"fonts/menufont"), duel_prop);

            topFont = Content.Load<SpriteFont>(@"fonts/topfont");
            alertFont = Content.Load<SpriteFont>(@"fonts/alertfont");

            Components.Add(powerUp);
            Components.Add(menu);
            Components.Add(duel_menu);
            powerUp.Enabled = false;
            menu.Enabled = false;
            duel_menu.Enabled = false;
            spaaace = TimeSpan.FromSeconds(0);

            menu_go = Content.Load<SoundEffect>(@"sounds/menu/menu_start");
            game_p_1 = Content.Load<SoundEffect>(@"sounds/game/game_p_1");
            game_p_2 = Content.Load<SoundEffect>(@"sounds/game/game_p_2");
            game_hit = Content.Load<SoundEffect>(@"sounds/game/game_hit");
            game_point = Content.Load<SoundEffect>(@"sounds/game/game_point");
            game_win = Content.Load<SoundEffect>(@"sounds/game/game_win");

            mainViewport = GraphicsDevice.Viewport;
            leftViewport = mainViewport;
            rightViewport = mainViewport;
            leftViewport.Width  /= 2;
            rightViewport.Width /= 2;
            rightViewport.X = leftViewport.Width;
            leftViewport.Height -= 100;
            rightViewport.Height -= 100;
            topBarViewport.Width = GraphicsDevice.Viewport.Width;
            topBarViewport.Height = 100;
            leftViewport.Y += 100;
            rightViewport.Y += 100;

            Random rnd = new Random();
            x = rnd.Next(100, mainViewport.Width - 300);
            y = rnd.Next(100, mainViewport.Height - 300);
            speed = new Vector2(rnd.Next(-10, 10), rnd.Next(-10, 10));

            playerView1 = new PlayerView(this, 1, leftViewport);
            playerView2 = new PlayerView(this, 2, rightViewport);
            menu_view = new PlayerView(this, 2, mainViewport);

            ball = new Ball(this);
            player1 = new Player(this, 1);
            player2 = new Player(this, 2);

            Components.Add(playerView1);
            Components.Add(playerView2);
            Components.Add(ball);
            Window.Title = "Spong 3D";
            setSpeed(1);
            MediaPlayer.Volume = 0.7f;
        }
コード例 #32
0
 internal bool HasCourse(CourseViewModel course, StaticModel.MarkingPeriod mp)
 {
     return _studentRow.HasCourse(course.CourseRow, mp);
 }