static void DoOrientationHandlesGUI(ShapeComponent shapeComponent, bool updatePrefs)
        {
            if (GUIUtility.hotControl != 0 && !s_OrientationControlIDs.Contains(GUIUtility.hotControl))
            {
                return;
            }

            foreach (var f in Faces)
            {
                if (f.IsVisible && EditorShapeUtility.PointerIsInFace(f))
                {
                    if (DoOrientationHandle(f, shapeComponent))
                    {
                        UndoUtility.RecordComponents <Transform, ProBuilderMesh, ShapeComponent>(shapeComponent.GetComponents(typeof(Component)), "Rotate Shape");
                        shapeComponent.RotateInsideBounds(s_ShapeRotation);

                        ProBuilderEditor.Refresh();

                        if (updatePrefs)
                        {
                            DrawShapeTool.SaveShapeParams(shapeComponent);
                        }
                    }
                }
            }
        }
    private void UpdateServer(float deltaTime)
    {
        ComponentsManager.Instance.ForEach <InputMessage>((entityId, input) => {
            if (!ComponentsManager.Instance.TryGetComponent(new EntityComponent(entityId), out InputMessageIdTracker msgTracker))
            {
                msgTracker = new InputMessageIdTracker(input.messageID);
            }
            int numberOfInputsToSimulate = input.messageID - msgTracker.currentMessageId + 1;

            if (!ECSManager.Instance.Config.enableInputPrediction)
            {
                numberOfInputsToSimulate = 1;
            }

            for (int i = numberOfInputsToSimulate; i > 0; i--)
            {
                KeyCode keyCode            = (KeyCode)input.keycode[input.keycode.Count - i];
                ShapeComponent playerShape = ComponentsManager.Instance.GetComponent <ShapeComponent>(entityId);
                playerShape = updatePosition(keyCode, playerShape, deltaTime);

                if (!provoqueCollision(entityId, playerShape))
                {
                    ComponentsManager.Instance.SetComponent <ShapeComponent>(entityId, playerShape);
                }
            }
            ComponentsManager.Instance.SetComponent <InputMessageIdTracker>(entityId, new InputMessageIdTracker(input.messageID + 1));
        });
    }
Example #3
0
    /**
     * <summary>
     * On collides with any 2D game object
     * </summary>
     *
     * <returns>
     * void
     * </returns>
     */
    protected virtual void OnCollisionEnter2D(Collision2D collision)
    {
        ShapeComponent shapeComponent = collision.transform.GetComponent <ShapeComponent>();

        if (shapeComponent == null)
        {
            return;
        }

        // Is colliding with triangle
        if (shapeComponent is TriangleComponent)
        {
            this.spriteRenderer.color = Color.red;
        }

        // Is colliding with circle
        else if (shapeComponent is CircleComponent)
        {
            this.spriteRenderer.color = Color.blue;
        }

        // Is colliding with square
        else if (shapeComponent is SquareComponent)
        {
            this.spriteRenderer.color = Color.green;
        }
    }
Example #4
0
    public LocalObject(LocalShape localShape, string _uniqueName = "", Inventory _inventory = null)
    {
        uniqueName = _uniqueName;
        shape = new ShapeComponent(localShape, this);

        if (localShape.type == LocalType.Get("Destructible") || localShape.type == LocalType.Get("Container"))
        {
            hp = new HPComponent(this);
        }
        else if (localShape.type == LocalType.Get("Creature"))
        {
            hp = new HPComponent(this);
            movement = new Movement(this);
            defence = new Defence(this);
            attack = new Attack(this);
            abilities = new Abilities(this);
            fatigue = new Fatigue(this);
            eating = new Eating(this);
        }

        if (_inventory != null)
        {
            inventory = new Inventory(6, 1, "", false, null, this);
            _inventory.CopyTo(inventory);
        }
    }
Example #5
0
        /// <summary>
        /// Creates a mesh shape for serialising <paramref name="shapeComponent"/> and its associated mesh data.
        /// </summary>
        /// <param name="shapeComponent">The component to create a shape for.</param>
        /// <returns>A shape instance suitable for configuring to generate serialisation messages.</returns>
        protected override Shapes.Shape CreateSerialisationShape(ShapeComponent shapeComponent)
        {
            MeshDataComponent meshData = shapeComponent.GetComponent <MeshDataComponent>();

            if (meshData != null)
            {
                ObjectAttributes attr = new ObjectAttributes();
                EncodeAttributes(ref attr, shapeComponent.gameObject, shapeComponent);

                Shapes.MeshShape mesh = new Shapes.MeshShape(meshData.DrawType,
                                                             Maths.Vector3Ext.FromUnity(meshData.Vertices),
                                                             meshData.Indices,
                                                             shapeComponent.ObjectID,
                                                             shapeComponent.Category,
                                                             Maths.Vector3.Zero,
                                                             Maths.Quaternion.Identity,
                                                             Maths.Vector3.One);
                mesh.SetAttributes(attr);
                mesh.CalculateNormals = meshData.CalculateNormals;
                if (!meshData.CalculateNormals && meshData.Normals != null && meshData.Normals.Length > 0)
                {
                    mesh.Normals = Maths.Vector3Ext.FromUnity(meshData.Normals);
                }

                return(mesh);
            }
            return(null);
        }
Example #6
0
        /// <summary>
        /// Handle update messages.
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="packet"></param>
        /// <param name="reader"></param>
        /// <returns></returns>
        protected virtual Error HandleMessage(UpdateMessage msg, PacketBuffer packet, BinaryReader reader)
        {
            TextEntry text = new TextEntry();

            text.ID          = msg.ObjectID;
            text.ObjectFlags = msg.Flags;
            text.Position    = new Vector3(msg.Attributes.X, msg.Attributes.Y, msg.Attributes.Z);
            text.Colour      = ShapeComponent.ConvertColour(msg.Attributes.Colour);
            text.Active      = true;

            // Read the text.
            int textLength = reader.ReadUInt16();

            if (textLength > 0)
            {
                byte[] textBytes = reader.ReadBytes(textLength);
                text.Text = System.Text.Encoding.Default.GetString(textBytes);
            }

            if (text.ID != 0)
            {
                PersistentText.UpdateEntry(text);
            }

            return(new Error());
        }
Example #7
0
        /// <summary>
        /// Handle create messages.
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="packet"></param>
        /// <param name="reader"></param>
        /// <returns></returns>
        protected virtual Error HandleMessage(CreateMessage msg, PacketBuffer packet, BinaryReader reader)
        {
            TextEntry text = new TextEntry();

            text.ID          = msg.ObjectID;
            text.ObjectFlags = msg.Flags;
            text.Category    = msg.Category;
            text.Position    = new Vector3(msg.Attributes.X, msg.Attributes.Y, msg.Attributes.Z);
            text.Colour      = ShapeComponent.ConvertColour(msg.Attributes.Colour);
            text.Active      = CategoryCheck(text.Category);

            // Read the text.
            int textLength = reader.ReadUInt16();

            if (textLength > 0)
            {
                byte[] textBytes = reader.ReadBytes(textLength);
                text.Text = System.Text.Encoding.UTF8.GetString(textBytes);
            }

            if (msg.ObjectID == 0)
            {
                TransientText.Add(text);
            }
            else
            {
                PersistentText.Add(text);
            }

            return(new Error());
        }
Example #8
0
        /// <summary>
        /// Overridden to handle component pieces.
        /// </summary>
        protected override void EncodeAttributes(ref ObjectAttributes attr, GameObject obj, ShapeComponent comp)
        {
            Transform transform = obj.transform;

            attr.X         = transform.localPosition.x;
            attr.Y         = transform.localPosition.y;
            attr.Z         = transform.localPosition.z;
            attr.RotationX = transform.localRotation.x;
            attr.RotationY = transform.localRotation.y;
            attr.RotationZ = transform.localRotation.z;
            attr.RotationW = transform.localRotation.w;
            Transform child;

            child = transform.GetChild(Tes.Tessellate.Capsule.CylinderIndex);
            if (child)
            {
                attr.ScaleX = attr.ScaleY = child.localScale.x;
                attr.ScaleZ = child.localScale.y;
            }
            if (comp != null)
            {
                attr.Colour = ShapeComponent.ConvertColour(comp.Colour);
            }
            else
            {
                attr.Colour = 0xffffffu;
            }
        }
Example #9
0
 public void AddShape(ShapeComponent newshape)
 {
     SetLeft(newshape, newshape.Location.X);
     SetTop(newshape, newshape.Location.Y);
     Shapes.Add(newshape);
     Children.Add(newshape);
 }
 internal static void ApplyPrefsSettings(ShapeComponent shapeComponent)
 {
     shapeComponent.pivotLocation      = (PivotLocation)s_LastPivotLocation.value;
     shapeComponent.pivotLocalPosition = s_LastPivotPosition.value;
     shapeComponent.size     = s_LastSize.value;
     shapeComponent.rotation = s_LastRotation.value;
 }
Example #11
0
        /// <summary>
        /// Encode transform attributes for text.
        /// </summary>
        /// <param name="attr"></param>
        /// <param name="obj"></param>
        /// <param name="comp"></param>
        protected override void EncodeAttributes(ref ObjectAttributes attr, GameObject obj, ShapeComponent comp)
        {
            Transform transform = obj.transform;
            // Convert position to Unity position.
            Vector3 pos = FrameTransform.UnityToRemote(obj.transform.position, ServerInfo.CoordinateFrame);

            attr.X         = pos.x;
            attr.Y         = pos.y;
            attr.Z         = pos.z;
            attr.RotationX = transform.localRotation.x;
            attr.RotationY = transform.localRotation.y;
            attr.RotationZ = transform.localRotation.z;
            attr.RotationW = transform.localRotation.w;
            attr.ScaleX    = 1.0f;
            attr.ScaleY    = 1.0f;
            attr.ScaleZ    = 12.0f;

            TextMesh text = obj.GetComponent <TextMesh>();

            if (text != null)
            {
                attr.ScaleZ = text.fontSize;
            }
            if (comp != null)
            {
                attr.Colour = ShapeComponent.ConvertColour(comp.Colour);
            }
            else
            {
                attr.Colour = 0xffffffu;
            }
        }
        internal static void DoEditingGUI(ShapeComponent shapeComponent, bool updatePrefs = false)
        {
            if (shapeComponent == null)
            {
                return;
            }

            var scale    = shapeComponent.transform.lossyScale;
            var position = shapeComponent.transform.position
                           + Vector3.Scale(shapeComponent.transform.TransformDirection(shapeComponent.shapeBox.center), scale);
            var matrix = Matrix4x4.TRS(position, shapeComponent.transform.rotation, Vector3.one);

            using (new Handles.DrawingScope(matrix))
            {
                EditorShapeUtility.UpdateFaces(shapeComponent.editionBounds, scale, Faces);

                for (int i = 0; i < 4; ++i)
                {
                    s_OrientationControlIDs[i] = GUIUtility.GetControlID(FocusType.Passive);
                }

                var absSize = Math.Abs(shapeComponent.editionBounds.size);
                if (absSize.x > Mathf.Epsilon && absSize.y > Mathf.Epsilon && absSize.z > Mathf.Epsilon)
                {
                    DoOrientationHandlesGUI(shapeComponent, updatePrefs);
                }

                DoSizeHandlesGUI(shapeComponent, updatePrefs);
            }
        }
Example #13
0
        /// <summary>
        /// Handle additional <see cref="UpdateMessage"/> data.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="msg"></param>
        /// <param name="packet"></param>
        /// <param name="reader"></param>
        /// <returns></returns>
        protected override Error PostHandleMessage(GameObject obj, UpdateMessage msg, PacketBuffer packet, BinaryReader reader)
        {
            TextMesh       textMesh  = obj.GetComponent <TextMesh>();
            ShapeComponent shapeComp = obj.GetComponent <ShapeComponent>();

            if (textMesh != null && shapeComp != null)
            {
                textMesh.fontSize = (int)msg.Attributes.ScaleZ;
                textMesh.color    = shapeComp.Colour;
            }

            // Convert position to Unity position.
            obj.transform.localPosition = FrameTransform.RemoteToUnity(obj.transform.localPosition, ServerInfo.CoordinateFrame);

            if (shapeComp != null && (msg.Flags & (ushort)Text3DFlag.SceenFacing) != (shapeComp.ObjectFlags & (ushort)Text3DFlag.SceenFacing))
            {
                // Screen facing flag changed.
                if ((msg.Flags & (ushort)Text3DFlag.SceenFacing) != 0)
                {
                    // Need to use -forward for text.
                    ScreenFacing.AddToManager(obj, -Vector3.forward, Vector3.up);
                }
                else
                {
                    // Need to use -forward for text.
                    ScreenFacing.RemoveFromManager(obj);
                }
            }
            return(new Error());
        }
Example #14
0
        public void AddComponents()
        {
            TestManager.Helpers.OpenSceneFromFile(TestManager.Helpers.TestDataDir + @"\ComponentTest\ComponentTest.scene");

            // add script-component to static mesh
            ShapeComponent staticMeshScriptComp = CreateScriptComponent(TestManager.Helpers.TestDataDir + @"\ComponentTest\Scripting\StaticMeshScript.lua");
            ShapeBase      staticMesh           = EditorManager.Scene.FindShapeByName("StaticMesh");

            EditorManager.Actions.Add(new AddShapeComponentAction(staticMesh, staticMeshScriptComp));

            // add script-component to terrain
            ShapeComponent terrainScriptComp = CreateScriptComponent(TestManager.Helpers.TestDataDir + @"\ComponentTest\Scripting\TerrainScript.lua");
            ShapeBase      terrain           = EditorManager.Scene.FindShapeByName("Terrain0");

            EditorManager.Actions.Add(new AddShapeComponentAction(terrain, terrainScriptComp));

            // Start the simulation
            EditorManager.EditorMode = EditorManager.Mode.EM_ANIMATING;
            TestManager.Helpers.ProcessEvents();

            int iFrameCount = 1000;

            for (int i = 0; i < iFrameCount; i++)
            {
                EditorManager.EngineManager.WriteText2D(300.0f, 10.0f, "Added script-component to staticMesh and terrain", VisionColors.White);
                EditorManager.ActiveView.UpdateView(true);
            }

            // Stop the simulation
            EditorManager.EditorMode = EditorManager.Mode.EM_NONE;

            EditorManager.Scene.Save();
            TestManager.Helpers.CloseTestProject();
        }
Example #15
0
        /// <summary>
        /// Handle additional <see cref="CreateMessage"/> data.
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="msg"></param>
        /// <param name="packet"></param>
        /// <param name="reader"></param>
        /// <returns></returns>
        protected override Error PostHandleMessage(GameObject obj, CreateMessage msg, PacketBuffer packet, BinaryReader reader)
        {
            // Convert position to Unity position.
            obj.transform.localPosition = FrameTransform.RemoteToUnity(obj.transform.localPosition, ServerInfo.CoordinateFrame);

            // Read the text in the buffer.
            int textLength = reader.ReadUInt16();

            if (textLength > 0)
            {
                TextMesh textMesh = obj.GetComponent <TextMesh>();
                if (textMesh == null)
                {
                    textMesh = obj.AddComponent <TextMesh>();
                }

                byte[] textBytes = reader.ReadBytes(textLength);
                textMesh.text = System.Text.Encoding.UTF8.GetString(textBytes);
                ShapeComponent shapeComp = obj.GetComponent <ShapeComponent>();
                if (shapeComp != null)
                {
                    textMesh.fontSize = (int)msg.Attributes.ScaleZ;
                    textMesh.color    = shapeComp.Colour;
                }
            }

            if ((msg.Flags & (ushort)Text3DFlag.SceenFacing) != 0)
            {
                // Need to use -forward for text.
                ScreenFacing.AddToManager(obj, -Vector3.forward, Vector3.up);
            }

            return(base.PostHandleMessage(obj, msg, packet, reader));
        }
Example #16
0
        /// <summary>
        /// Set the visuals of <pararef name="partObject"/> to use <paramref name="meshDetails"/>.
        /// </summary>
        /// <param name="partObject">The part object</param>
        /// <param name="meshDetails">The mesh details.</param>
        /// <remarks>
        /// Adds multiple children to <paramref name="partObject"/> when <paramref name="meshDetails"/>
        /// contains multiple mesh objects.
        /// </remarks>
        protected virtual void SetMesh(ShapeComponent partObject, MeshCache.MeshDetails meshDetails)
        {
            // Clear all children as a hard reset.
            foreach (Transform child in partObject.GetComponentsInChildren <Transform>())
            {
                if (child.gameObject != partObject.gameObject)
                {
                    child.parent = null;
                    GameObject.Destroy(child.gameObject);
                }
            }

            // Add children for each mesh sub-sub-part.
            int subPartNumber = 0;

            foreach (Mesh mesh in meshDetails.FinalMeshes)
            {
                GameObject partMesh = new GameObject();
                partMesh.name = string.Format("sub-part{0}", subPartNumber);
                partMesh.transform.localPosition = meshDetails.LocalPosition;
                partMesh.transform.localRotation = meshDetails.LocalRotation;
                partMesh.transform.localScale    = meshDetails.LocalScale;

                MeshFilter filter = partMesh.AddComponent <MeshFilter>();
                filter.sharedMesh = mesh;

                MeshRenderer renderer = partMesh.AddComponent <MeshRenderer>();
                renderer.material       = meshDetails.Material;
                renderer.material.color = partObject.Colour;
                partMesh.transform.SetParent(partObject.transform, false);

                ++subPartNumber;
            }
        }
Example #17
0
        /// <summary>
        /// Called for each mesh part in the create messages.
        /// </summary>
        /// <param name="parent">The parent object for the part object.</param>
        /// <param name="reader">Message data reader.</param>
        /// <param name="partNumber">The part number/index.</param>
        /// <returns>An error code on failure.</returns>
        protected virtual Error AddMeshPart(GameObject parent, BinaryReader reader, int partNumber)
        {
            uint             meshId     = reader.ReadUInt32();
            ObjectAttributes attributes = new ObjectAttributes();

            if (!attributes.Read(reader))
            {
                return(new Error(ErrorCode.MalformedMessage, (int)ObjectMessageID.Create));
            }

            // Add the part and a child for the part's mesh.
            // This supports the mesh having its own transform or pivot offset.
            GameObject     part  = new GameObject();
            ShapeComponent shape = part.AddComponent <ShapeComponent>();

            part.name = string.Format("part{0}", partNumber);

            shape.ObjectID    = meshId; // Use for mesh ID.
            shape.Category    = 0;
            shape.ObjectFlags = 0;
            shape.Colour      = ShapeComponent.ConvertColour(attributes.Colour);

            DecodeTransform(attributes, part.transform);
            part.transform.SetParent(parent.transform, false);

            return(new Error());
        }
Example #18
0
        /// <summary>
        /// Creates a mesh set shape for serialising the mesh and its resource references.
        /// </summary>
        /// <param name="shapeComponent">The component to create a shape for.</param>
        /// <returns>A shape instance suitable for configuring to generate serialisation messages.</returns>
        protected override Shapes.Shape CreateSerialisationShape(ShapeComponent shapeComponent)
        {
            // Start by building the resource list.
            int partCount          = shapeComponent.transform.childCount;
            ObjectAttributes attrs = new ObjectAttributes();

            Shapes.MeshSet meshSet = new Shapes.MeshSet(shapeComponent.ObjectID, shapeComponent.Category);
            EncodeAttributes(ref attrs, shapeComponent.gameObject, shapeComponent);
            meshSet.SetAttributes(attrs);
            for (int i = 0; i < partCount; ++i)
            {
                // Write the mesh ID
                ShapeComponent partSrc = shapeComponent.transform.GetChild(i).GetComponent <ShapeComponent>();
                if (partSrc != null)
                {
                    MeshResourcePlaceholder part = new MeshResourcePlaceholder(partSrc.ObjectID);
                    // Encode attributes into target format.
                    EncodeAttributes(ref attrs, partSrc.gameObject, partSrc);
                    // And convert to matrix.
                    meshSet.AddPart(part, attrs.GetTransform());
                }
                else
                {
                    Log.Error("Failed to extract child {0} for mesh set {1}.", i, shapeComponent.name);
                    return(null);
                }
            }
            return(meshSet);
        }
        internal static void SaveShapeParams(ShapeComponent shapeComponent)
        {
            s_LastPivotLocation.value = (int)shapeComponent.pivotLocation;
            s_LastPivotPosition.value = shapeComponent.pivotLocalPosition;
            s_LastSize.value          = shapeComponent.size;
            s_LastRotation.value      = shapeComponent.rotation;

            EditorShapeUtility.SaveParams(shapeComponent.shape);
        }
Example #20
0
        private void Execute(ShapeComponent shapeComponent)
        {
            //InternalCanvas canvas = InternalCanvas.getInstance();
            //Point oldLocation = canvas.GetPositionOfShapeInCanvas(shapeComponent);
            Point oldLocation = shapeComponent.Location;
            Point newlocation = new Point(oldLocation.X + DifferenceInPosition.X, oldLocation.Y + DifferenceInPosition.Y);

            //canvas.SetNewShape(shapeComponent, newlocation.X, newlocation.Y);
            shapeComponent.Location = newlocation;
        }
Example #21
0
        public void TestVolumeStaticMesh()
        {
            TestManager.Helpers.OpenSceneFromFile(Path.Combine(TestManager.Helpers.TestDataDir, @"CustomVolumeShapeTests\empty.scene"));

            CustomVolumeShape volume = new CustomVolumeShape();
            Layer             layer  = EditorManager.Scene.ActiveLayer;

            EditorManager.Actions.Add(AddShapeAction.CreateAddShapeAction(volume, null, layer, false));
            volume.Preview          = true;
            volume.CustomStaticMesh = true;
            volume.StaticMeshPath   = "Meshes\\kugel.vmesh";
            volume.Scaling          = new Vector3F(20.0f, 20.0f, 20.0f);

            DynLightShape light = new DynLightShape("test light");

            light.LightType = LightSourceType_e.Point;
            light.Position  = EditorManager.Scene.CurrentShapeSpawnPosition;
            EditorManager.Actions.Add(AddShapeAction.CreateAddShapeAction(light, null, layer, false));

            ShapeComponent component = CreateLightClippingComponent(volume);

            EditorManager.Actions.Add(new AddShapeComponentAction(light, component));

            for (int i = 0; i < 60; i++)
            {
                EditorManager.ActiveView.UpdateView(true);
            }

            bool success = EditorManager.Scene.SaveAs("volume.scene");

            Assert.IsTrue(success);
            EditorManager.Scene.Close();
            TestManager.Helpers.OpenSceneFromFile(Path.Combine(TestManager.Helpers.TestDataDir, @"CustomVolumeShapeTests\volume.scene"));

            for (int i = 0; i < 60; i++)
            {
                EditorManager.EngineManager.WriteText2D(10.0f, 10.0f, "This is the saved version", VisionColors.White);
                EditorManager.ActiveView.UpdateView(true);
            }

            EditorManager.Scene.ExportScene(null, null);
            EditorManager.Scene.Close();
            EditorManager.Scene = null;
            TestManager.Helpers.LoadExportedScene("volume.vscene");
            for (int i = 0; i < 60; i++)
            {
                EditorManager.EngineManager.WriteText2D(10.0f, 10.0f, "This is the exported version", VisionColors.White);
                EditorManager.ActiveView.UpdateView(true);
            }

            EditorManager.EditorMode = EditorManager.Mode.EM_NONE;
            TestManager.Helpers.CloseExportedScene();
            TestManager.Helpers.CloseActiveProject();
        }
    public static void SpawnEntity(uint entityId, Vector2 speed, Config.ShapeConfig entityConfig)
    {
        ECSManager.Instance.CreateShape(entityId, entityConfig);
        ShapeComponent shapeData = new ShapeComponent();

        shapeData.pos   = entityConfig.initialPos;
        shapeData.speed = speed;
        shapeData.shape = entityConfig.shape;
        shapeData.size  = entityConfig.size;
        ComponentsManager.Instance.SetComponent <ShapeComponent>(entityId, shapeData);
        ComponentsManager.Instance.SetComponent <EntityComponent>(entityId, new EntityComponent(entityId));
    }
    public void UpdateSystem()
    {
        if (ECSManager.Instance.NetworkManager.isClient && ECSManager.Instance.Config.enableInputPrediction)
        {
            int framesToPredict = ((World.Instance.latency / 20)) * 2;

            if (framesToPredict == 0 || World.Instance.inputHistory.Count < framesToPredict)
            {
                return;
            }

            uint    playerId         = (uint)CustomNetworkManager.Singleton.LocalClientId;
            Vector2 historicPosition = World.Instance.positionHistory[playerId][World.Instance.positionHistory[playerId].Count - framesToPredict];

            if (ComponentsManager.Instance.TryGetComponent(new EntityComponent(playerId), out ReplicationMessage replication))
            {
                if (Mathf.Abs(replication.pos.magnitude - historicPosition.magnitude) > 0.10)
                {
                    List <uint> ids = new List <uint>();
                    ComponentsManager.Instance.ForEach((EntityComponent entity, ReplicationMessage msg) =>
                    {
                        ShapeComponent shape = ComponentsManager.Instance.GetComponent <ShapeComponent>(entity);
                        shape.pos            = msg.pos;
                        ComponentsManager.Instance.SetComponent <ShapeComponent>(entity, shape);
                        ids.Add(entity.id);
                    });

                    InputManagerSystem             inputManagerSystem = new InputManagerSystem();
                    CircleCollisionDetectionSystem circleCollision    = new CircleCollisionDetectionSystem();
                    WallCollisionDetectionSystem   wallCollision      = new WallCollisionDetectionSystem();
                    BounceBackSystem     bounceBack     = new BounceBackSystem();
                    PositionUpdateSystem positionUpdate = new PositionUpdateSystem();

                    for (int i = World.Instance.inputHistory.Count - framesToPredict; i < World.Instance.inputHistory.Count; i++)
                    {
                        ComponentsManager.Instance.ClearComponents <CollisionEventComponent>();
                        circleCollision.UpdateSystem();
                        wallCollision.UpdateSystem();
                        bounceBack.UpdateSystem();
                        positionUpdate.UpdateSystemExtrapolation(ids);
                        inputManagerSystem.UpdateSystemPrediction(World.Instance.inputHistory[i], playerId);

                        //update historic for everyone
                        ComponentsManager.Instance.ForEach((EntityComponent entity, ReplicationMessage msg) =>
                        {
                            World.Instance.positionHistory[entity][i] = ComponentsManager.Instance.GetComponent <ShapeComponent>(entity).pos;
                        });
                    }
                }
                ComponentsManager.Instance.RemoveComponent <ReplicationMessage>(new EntityComponent(playerId));
            }
        }
    }
        public static void ApplyProperties(ShapeComponent shape, Vector3 newCenterPosition, Vector3 newSize)
        {
            var bounds = new Bounds();

            bounds.center = newCenterPosition;
            bounds.size   = newSize;

            UndoUtility.RecordComponents <Transform, ProBuilderMesh, ShapeComponent>(shape.GetComponents(typeof(Component)), "Resize Shape");
            shape.UpdateBounds(bounds);

            ProBuilderEditor.Refresh(false);
        }
Example #25
0
        void CheckScriptComponent(string shapeName, string scriptFileName)
        {
            ShapeBase shape = EditorManager.Scene.FindShapeByName(shapeName);

            Assert.IsTrue(shape.ComponentCount > 0);
            ShapeComponent shapeScriptComp = shape.Components.get_Item(0);

            Assert.IsNotNull(shapeScriptComp);
            DynamicProperty shapeProperty = shapeScriptComp.GetPropertyByName("ScriptFile");

            Assert.AreEqual(shapeProperty.Value, scriptFileName);
        }
Example #26
0
        /// <summary>
        /// Creates a text shape for serialisation.
        /// </summary>
        /// <param name="shapeComponent">The component to create a shape for.</param>
        /// <returns>A shape instance suitable for configuring to generate serialisation messages.</returns>
        protected override Shapes.Shape CreateSerialisationShape(ShapeComponent shapeComponent)
        {
            TextMesh text = shapeComponent.GetComponent <TextMesh>();

            if (text != null)
            {
                Shapes.Shape shape = new Shapes.Text3D(text.text);
                ConfigureShape(shape, shapeComponent);
                return(shape);
            }
            return(null);
        }
Example #27
0
        /// <summary>
        /// Overridden to read information about mesh parts.
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="packet"></param>
        /// <param name="reader"></param>
        /// <returns></returns>
        protected override Error HandleMessage(CreateMessage msg, PacketBuffer packet, BinaryReader reader)
        {
            GameObject obj = null;

            if (msg.ObjectID == 0)
            {
                // Cannot support transient objects: we need to get point data through additional
                // messages which requires a valid object id.
                return(new Error(ErrorCode.InvalidObjectID, 0));
            }
            else
            {
                obj = CreateObject(msg.ObjectID);
                if (!obj)
                {
                    // Object already exists.
                    return(new Error(ErrorCode.DuplicateShape, msg.ObjectID));
                }
            }

            ShapeComponent shapeComp = obj.GetComponent <ShapeComponent>();

            if (shapeComp)
            {
                shapeComp.Category    = msg.Category;
                shapeComp.ObjectFlags = msg.Flags;
                shapeComp.Colour      = ShapeComponent.ConvertColour(msg.Attributes.Colour);
            }

            obj.transform.SetParent(Root.transform, false);
            DecodeTransform(msg.Attributes, obj.transform);

            // Read additional attributes.
            PointsComponent pointsComp = obj.AddComponent <PointsComponent>();

            // Read the mesh ID to render points from.
            pointsComp.MeshID = reader.ReadUInt32();
            // Read the number of indices (zero implies show entire mesh).
            pointsComp.IndexCount = reader.ReadUInt32();
            pointsComp.PointSize  = reader.ReadByte();

            if (pointsComp.IndexCount == 0)
            {
                // Not expecting any index data messages.
                // Register the mesh now.
                RegisterForMesh(pointsComp);
            }

            return(new Error());
        }
Example #28
0
        /// <summary>
        /// Select the material for <paramref name="shape"/> based on <paramref name="meshData"/>
        /// configuration.
        /// </summary>
        /// <remarks>
        /// Wire frame selection may only be made for triangle draw types. In this case the
        /// <see cref="ShapeComponent"/> is checked for it's <code>Wireframe</code> flag.
        /// </remarks>
        /// <param name="shape">The shape object to select a material for.</param>
        /// <param name="meshData">Details of the mesh shape we are selecting a material for.</param>
        /// <returns>The appropriate material for rendering <paramref name="meshData"/>.</returns>
        Material SelectMaterial(ShapeComponent shape, MeshDataComponent meshData)
        {
            Material mat;

            switch (meshData.DrawType)
            {
            case MeshDrawType.Points:
                mat = Materials[MaterialLibrary.PointsUnlit];
                break;

            case MeshDrawType.Voxels:
                mat = Materials[MaterialLibrary.Voxels];
                break;

            default:
            case MeshDrawType.Lines:
                mat = Materials[MaterialLibrary.VertexColourUnlit];
                break;

            case MeshDrawType.Triangles:
                // Check wire frame.
                if (shape != null && shape.Wireframe)
                {
                    mat = Materials[MaterialLibrary.WireframeTriangles];
                }
                else if (shape != null && shape.TwoSided)
                {
                    if (meshData.CalculateNormals)
                    {
                        mat = Materials[MaterialLibrary.VertexColourLitTwoSided];
                    }
                    else
                    {
                        mat = Materials[MaterialLibrary.VertexColourUnlitTwoSided];
                    }
                }
                else if (meshData.CalculateNormals)
                {
                    mat = Materials[MaterialLibrary.VertexColourLit];
                }
                else
                {
                    mat = Materials[MaterialLibrary.VertexColourUnlit];
                }
                break;
            }

            return(mat);
        }
    public void SpawnPlayerEntity(uint playerId, ShapeComponent shapeData)
    {
        var entityConfig = new Config.ShapeConfig();

        entityConfig.shape      = Config.Shape.Circle;
        entityConfig.size       = shapeData.size;
        entityConfig.initialPos = shapeData.pos;
        SpawnEntity(playerId, new Vector2(), entityConfig);
        PlayerComponent playerComponent = new PlayerComponent()
        {
            playerId = playerId
        };

        ComponentsManager.Instance.SetComponent <PlayerComponent>(playerId, playerComponent);
    }
Example #30
0
        /// <summary>
        /// Overridden to handle component pieces.
        /// </summary>
        protected override void EncodeAttributes(ref ObjectAttributes attr, GameObject obj, ShapeComponent comp)
        {
            Transform transform = obj.transform;

            attr.Colour    = ShapeComponent.ConvertColour(comp.Colour);
            attr.X         = transform.localPosition.x;
            attr.Y         = transform.localPosition.y;
            attr.Z         = transform.localPosition.z;
            attr.RotationX = transform.localRotation.x;
            attr.RotationY = transform.localRotation.y;
            attr.RotationZ = transform.localRotation.z;
            attr.RotationW = transform.localRotation.w;
            attr.ScaleX    = transform.localScale.x;
            attr.ScaleY    = attr.ScaleZ = transform.localScale.z;
        }
Example #31
0
        ShapeComponent CreateScriptComponent(string scriptFileName)
        {
            ShapeComponentType t = (ShapeComponentType)EditorManager.EngineManager.ComponentClassManager.GetCollectionType("VScriptComponent");

            if (t == null)
            {
                return(null);
            }

            ShapeComponent comp = (ShapeComponent)t.CreateInstance(null);

            comp.SetPropertyValue("ScriptFile", scriptFileName);

            return(comp);
        }
 void MigrateCharacterControllerProperties(ShapeComponent physX, ShapeComponent havok)
 {
     havok.SetPropertyValue("Max_Slope", physX.GetPropertyValue("m_fSlopeLimit", false));
       float fRadius = (float)physX.GetPropertyValue("m_fRadius", false);
       float fHeight = (float)physX.GetPropertyValue("m_fHeight", false);
       if (fRadius > 0.0f && fHeight > 0.0f)
       {
     havok.SetPropertyValue("Capsule_Radius", fRadius);
     Vector3F top = new Vector3F(0.0f, 0.0f, fHeight + fRadius);
     havok.SetPropertyValue("Character_Top", top);
     Vector3F bottom = new Vector3F(0.0f, 0.0f, fRadius);
     havok.SetPropertyValue("Character_Bottom", bottom);
       }
       havok.SetPropertyValue("Debug", physX.GetPropertyValue("DebugRendering", false));
 }
        void MigratePhysXEntityProperties(DynamicPropertyCollection entityProps, ShapeComponent havok)
        {
            {
            // Havok: "Dynamic/Keyframed/Fixed/Sphere Inertia/Box Inertia/Thin Box Inertia/Character"
            // PhysX: "Dynamic/Static/Kinematic"
            string sValue = (string)entityProps.GetPropertyValue("m_ePhysicsType", false); // since it is an enum, we get it as a string
            if (sValue == "Static") sValue = "Fixed";
            else if (sValue == "Kinematic") sValue = "Keyframed";
            havok.SetPropertyValue("Havok_MotionType", sValue, false);
              }

              {
            // Havok: "Box/Sphere/Convex Hull/File/Capsule/Cylinder/Mesh"
            // PhysX: "Box/Sphere/File/Hull/Mesh"
            string sValue = (string)entityProps.GetPropertyValue("m_ePhysicsGeom", false); // since it is an enum, we get it as a string
            if (sValue == "Hull" || sValue == "File") sValue = "Convex Hull"; // since PhysXFile + Havok_FileResourceName does not match, convert "File" to "Convex Hull"
            havok.SetPropertyValue("Shape_Type", sValue, false);
              }

              // mass of zero is not legal for dynamic rigid bodies in Havok. Furthermore, very old versions of the entity class
              // did not have a mass property, so additionally check whether the property is there
              object fValue = entityProps.GetPropertyValue("m_fMass", false);
              if ((fValue is float) && ((float)fValue) > 0.0f)
            havok.SetPropertyValue("Havok_Mass", fValue);

              havok.SetPropertyValue("Shape_Radius", entityProps.GetPropertyValue("m_fRadius", false));
              havok.SetPropertyValue("Shape_BoxSize", entityProps.GetPropertyValue("m_bboxSize", false));
              havok.SetPropertyValue("Shape_PivotOffset", entityProps.GetPropertyValue("m_bLocalOffset", false));
              havok.SetPropertyValue("Debug_Render", entityProps.GetPropertyValue("DebugRendering", false));
        }
        /// <summary>
        /// Map properties from the START_VAR_TABLE(vPhysXRigidBody,... to the counterparts in START_VAR_TABLE(vHavokRigidBody...
        /// </summary>
        /// <param name="physX">Input physX rigid body property</param>
        /// <param name="havok">output havok component</param>
        void MigrateRigidBodyProperties(ShapeComponent physX, ShapeComponent havok)
        {
            {
            // Havok: "Dynamic/Keyframed/Fixed/Sphere Inertia/Box Inertia/Thin Box Inertia/Character"
            // PhysX: "Dynamic/Static/Kinematic"
            string sValue = (string)physX.GetPropertyValue("m_ePhysicsType", false); // since it is an enum, we get it as a string
            if (sValue == "Static") sValue = "Fixed";
            else if (sValue == "Kinematic") sValue = "Keyframed";
            havok.SetPropertyValue("Havok_MotionType", sValue, false);
              }

              {
            // Havok: "Box/Sphere/Convex Hull/File/Capsule/Cylinder/Mesh"
            // PhysX: "Box/Sphere/File/Hull/Mesh"
            string sValue = (string)physX.GetPropertyValue("m_ePhysicsGeom", false); // since it is an enum, we get it as a string
            if (sValue == "Hull" || sValue == "File") sValue = "Convex Hull"; // since "PhysXFile" + "Havok_FileResourceName" does not match, convert "File" to "Convex Hull"
            havok.SetPropertyValue("Shape_Type", sValue, false);
              }

              // mass of zero is not legal for dynamic rigid bodies in Havok
              float fMass = (float)physX.GetPropertyValue("m_fMass", false);
              if (fMass > 0.0f)
            havok.SetPropertyValue("Havok_Mass", fMass);

              havok.SetPropertyValue("Shape_Height", physX.GetPropertyValue("m_fHeight", false));
              havok.SetPropertyValue("Shape_Radius", physX.GetPropertyValue("m_fRadius", false));
              havok.SetPropertyValue("Shape_PivotOffset", physX.GetPropertyValue("m_vLocalOffset", false));
              havok.SetPropertyValue("Shape_BoxSize", physX.GetPropertyValue("m_bboxSize", false));
              havok.SetPropertyValue("Debug_Render", physX.GetPropertyValue("DebugRendering", false));
        }
Example #35
0
        /// <summary>
        /// Called when this shape is added to the scene
        /// </summary>
        public override void OnAddedToScene()
        {
            base.OnAddedToScene ();
              AddHint(HintFlags_e.OnlyUniformScale);
              if (_pendingCoronaSetup != null && ((bool)_pendingCoronaSetup.GetPropertyValue("Enabled")))
              {
            this.AddComponentInternal(_pendingCoronaSetup);
            g_iCoronasConverted++;
            if (Modifiable)
              Modified = true;
              }
              _pendingCoronaSetup = null;

              if (_pendingLensFlareSetup != null && ((bool)_pendingLensFlareSetup.GetPropertyValue("Enabled")))
              {
            this.AddComponentInternal(_pendingLensFlareSetup);
            g_iCoronasConverted++;
            if (Modifiable)
              Modified = true;
              }
              _pendingLensFlareSetup = null;

              UpdateLightPreviewProperties();
        }
Example #36
0
 public override void OnRemoveComponent(ShapeComponent component)
 {
     base.OnRemoveComponent(component);
       UpdateLightPreviewProperties(); // in case the user adds a shadow component, we don't want it twice
 }
Example #37
0
        public override void OnRemoveComponent(ShapeComponent component)
        {
            base.OnRemoveComponent(component);
              UpdateLightPreviewProperties(); // in case the user adds a shadow component, we don't want it twice

              if (component.CollectionType.UniqueName == "VTimeOfDayComponent")
              {

            // Force propertygrid update if this shape is selected.
            if (EditorManager.SelectedShapes.Contains(this))
            {
              EditorManager.OnShapeSelectionChanged(new ShapeSelectionChangedArgs(EditorManager.SelectedShapes, EditorManager.SelectedShapes));

              // Light color is now editable!
              if (!EditorManager.ActiveView.HotSpots.Contains(_hotSpotColor))
            EditorManager.ActiveView.HotSpots.Add(_hotSpotColor);
            }
              }
        }
 void MigrateLineFollowerEntityProperties(DynamicPropertyCollection entityProps, ShapeComponent component)
 {
     component.SetPropertyValue("Model_AnimationName", entityProps.GetPropertyValue("AnimationName", false), false);
       component.SetPropertyValue("Path_Key", entityProps.GetPropertyValue("PathKey", false), false);
       component.SetPropertyValue("Path_NumberSteps", entityProps.GetPropertyValue("PathSteps", false), false);
       component.SetPropertyValue("Path_TriggerDistance", entityProps.GetPropertyValue("TriggerDistance", false), false);
       component.SetPropertyValue("Path_InitialOffset", entityProps.GetPropertyValue("InitialOffset", false), false);
       component.SetPropertyValue("Model_DeltaRotation", entityProps.GetPropertyValue("DeltaRotation", false), false);
       component.SetPropertyValue("Model_GroundOffset", entityProps.GetPropertyValue("ModelOffset", false), false);
       component.SetPropertyValue("Model_CapsuleHeight", entityProps.GetPropertyValue("CapsuleHeight", false), false);
       component.SetPropertyValue("Model_CapsuleRadius", entityProps.GetPropertyValue("CapsuleRadius", false), false);
       component.SetPropertyValue("Debug_DisplayBoxes", entityProps.GetPropertyValue("DisplayBoxes", false), false);
       component.SetPropertyValue("Debug_RenderMesh", entityProps.GetPropertyValue("DebugRendering", false), false);
 }
Example #39
0
 ShapeComponent GetCoronaComponentSafe()
 {
     if (_pendingCoronaSetup == null)
       {
     _pendingCoronaSetup = (ShapeComponent)EditorManager.EngineManager.ComponentClassManager.CreateCollection(this, "VCoronaComponent");
       }
       return _pendingCoronaSetup;
 }
Example #40
0
 ShapeComponent GetLensFlareComponentSafe()
 {
     if (_pendingLensFlareSetup == null)
       {
     _pendingLensFlareSetup = (ShapeComponent)EditorManager.EngineManager.ComponentClassManager.CreateCollection(this, "VLensFlareComponent");
       }
       return _pendingLensFlareSetup;
 }