Inheritance: MonoBehaviour
    public TriangleMeshActor(Game game, Vector3 position, float scale,
        Texture2D heightMap,
        float[,] heightData)
        : base(game)
    {
        this.position = position;
        this.scale = new Vector3(1,1,1);

        _body = new Body();

        _body.MoveTo(position, Matrix.Identity);

        Array2D field = new Array2D(heightData.GetUpperBound(0), heightData.GetUpperBound(1));

        int upperZ = heightData.GetUpperBound(1);
        for (int x = 0; x < heightData.GetUpperBound(0); x++)
        {
            for (int z = 0; z < upperZ; z++)
            {
                field.SetAt(x, z, heightData[x, upperZ - 1 - z]);
            }
        }

        _skin = new CollisionSkin(null);

        float X = heightMap.Width / 2 * scale;
        float Z = heightMap.Height / 2 * scale;
        _skin.AddPrimitive(new Heightmap(field, X, -Z, scale, scale), new MaterialProperties(0.7f, 0.7f, 0.6f));

        _skin.ExternalData = this;

        PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(_skin);
    }
示例#2
0
        /// <summary>
        /// Updates the current gesture.
        /// </summary>
        /// <param name="body">The body.</param>
        /// <returns>A GesturePartResult based on whether the gesture part has been completed.</returns>
        public GesturePartResult Update(Body body)
        {
            // Right and Left Hand in front of Shoulders
            if (body.Joints[JointType.HandLeft].Position.Z < body.Joints[JointType.ElbowLeft].Position.Z && body.Joints[JointType.HandRight].Position.Z < body.Joints[JointType.ElbowRight].Position.Z)
            {
                // Hands between shoulder and hip
                if (body.Joints[JointType.HandRight].Position.Y < body.Joints[JointType.SpineShoulder].Position.Y && body.Joints[JointType.HandRight].Position.Y > body.Joints[JointType.SpineBase].Position.Y &&
                    body.Joints[JointType.HandLeft].Position.Y < body.Joints[JointType.SpineShoulder].Position.Y && body.Joints[JointType.HandLeft].Position.Y > body.Joints[JointType.SpineBase].Position.Y)
                {
                    // Hands between shoulders
                    if (body.Joints[JointType.HandRight].Position.X < body.Joints[JointType.ShoulderRight].Position.X && body.Joints[JointType.HandRight].Position.X > body.Joints[JointType.ShoulderLeft].Position.X &&
                        body.Joints[JointType.HandLeft].Position.X > body.Joints[JointType.ShoulderLeft].Position.X && body.Joints[JointType.HandLeft].Position.X < body.Joints[JointType.ShoulderRight].Position.X)
                    {
                        // Hands very close
                        if (body.Joints[JointType.HandRight].Position.X - body.Joints[JointType.HandLeft].Position.X < 0)
                        {
                            return GesturePartResult.Succeeded;
                        }

                        return GesturePartResult.Undetermined;
                    }

                    return GesturePartResult.Failed;
                }

                return GesturePartResult.Failed;
            }

            return GesturePartResult.Failed;
        }
 /// <summary>
 /// Updates all gestures.
 /// </summary>
 /// <param name="data">The skeleton data.</param>
 public void UpdateAllGestures(Body data)
 {
     foreach (Gesture gesture in this.gestures)
     {
         gesture.UpdateGesture(data);
     }
 }
示例#4
0
 /// <summary>
 /// Constructor for AngleJoint
 /// </summary>
 /// <param name="bodyA">The first body</param>
 /// <param name="bodyB">The second body</param>
 public AngleJoint(Body bodyA, Body bodyB)
     : base(bodyA, bodyB)
 {
     JointType = JointType.Angle;
     BiasFactor = .2f;
     MaxImpulse = float.MaxValue;
 }
示例#5
0
 public Tower(int pozList, int x, int y, Body body, int firer, int firem, int fired, string firet, string targt, int rech, int tbi, int tti, int rr, string re, string he)
 {
     Group = -1;
     Slots = 0;
     TurretAngle = 0;
     X = x;
     Y = y;
     PozList = pozList;
     TextureBaseIndex = tbi;
     TextureTurretIndex = tti;
     HitPoints = body.HitPoints;
     Energy = body.Energy;
     Angle = body.Angle;
     Radius = body.Radius;
     Shield = body.Shield;
     Mass = body.Mass;
     RodRadius = rr;
     RodEffect = re;
     HitEffect = he;
     TargetType = targt;
     TargetMineralInd = -1;
     FireType = firet;
     FireDemage = fired;
     Recharge = rech;
     Recharged = 0;
     FireMass = firem;
     FireRang = firer;
     Powered = false;
 }
示例#6
0
        protected override void Open()
        {
            dispose += DemoHelper.BasicDemoSetup(DemoInfo);


            Scene.Engine.AddLogic(new GravityPointField(new Vector2D(500, 500), 1000, new Lifespan()));


            Light light = new Light();
            light.Position.X = 000;
            light.Position.Y = 000;
            light.Position.Z = 0100;

            Body lightBody = new Body(new PhysicsState(), ShapeFactory.CreateCircle(15, 20), 40, new Coefficients(0, 1), new Lifespan());
            BodyGraphic lightGraphic = new BodyGraphic(lightBody);

            lightGraphic.DrawProperties.Add(new Color3Property(1, 1, 1));

            Scene.AddGraphic(lightGraphic);

            lightBody.PositionChanged += delegate(object sender, EventArgs e)
            {
                light.Position = lightBody.State.Position.Linear.ToVector3D(100);
            };

            IShape shape = ShapeFactory.CreateSprite(
                Cache<SurfacePolygons>.GetItem("Monkey.png"),
                Cache<Surface>.GetItem("MonkeyNormal.bmp"),
                false, true,
                3, 8, 16,
                light);
            DemoHelper.AddGrid(DemoInfo, shape, 40, new BoundingRectangle(40, 40, 900, 900), 100, 100);

        }
示例#7
0
 public OscMessage BuildJointMessage(Body body, KeyValuePair<JointType, Joint> joint)
 {
     var address = String.Format("/bodies/{0}/joints/{1}", body.TrackingId, joint.Key);
     var position = joint.Value.Position;
     //System.Diagnostics.Debug.WriteLine(address);
     return new OscMessage(address, position.X, position.Y, position.Z, joint.Value.TrackingState.ToString());
 }
示例#8
0
 public FrictionJoint(Body bodyA, Body bodyB, Vector2 localAnchorA, Vector2 localAnchorB)
     : base(bodyA, bodyB)
 {
     JointType = JointType.Friction;
     LocalAnchorA = localAnchorA;
     LocalAnchorB = localAnchorB;
 }
 public FixedAngleSpring(Body body, float springConstant, float dampingConstant)
 {
     _body = body;
     SpringConstant = springConstant;
     DampingConstant = dampingConstant;
     _targetAngle = body.TotalRotation;
 }
示例#10
0
 public KillEntityTask(Body entity, KillType type)
 {
     Mode = type;
     Name = "Kill Entity: " + entity.Name + " " + entity.GlobalID;
     EntityToKill = entity;
     Priority = PriorityType.Urgent;
 }
示例#11
0
        public void Format(Body body, Pickles.Parser.Table table)
        {
            WordTable wordTable = new WordTable();
            wordTable.Append(GenerateTableProperties());
            var headerRow = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            foreach (var cell in table.HeaderRow)
            {
                var wordCell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                wordCell.Append(new Paragraph(new Run(new Text(cell))));
                headerRow.Append(wordCell);
            }
            wordTable.Append(headerRow);

            foreach (var row in table.DataRows)
            {
                var wordRow = new DocumentFormat.OpenXml.Wordprocessing.TableRow();

                foreach (var cell in row)
                {
                    var wordCell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                    wordCell.Append(new Paragraph(new Run(new Text(cell))));
                    wordRow.Append(wordCell);
                }

                wordTable.Append(wordRow);
            }

            body.Append(wordTable);
        }
示例#12
0
        /// <summary>
        /// Updates the current gesture.
        /// </summary>
        /// <param name="body">The body.</param>
        /// <returns>A GesturePartResult based on whether the gesture part has been completed.</returns>
        public GesturePartResult Update(Body body)
        {
            // Right and Left Hand in front of Shoulders
            if (body.Joints[JointType.HandLeft].Position.Z < body.Joints[JointType.ElbowLeft].Position.Z && body.Joints[JointType.HandRight].Position.Z < body.Joints[JointType.ElbowRight].Position.Z)
            {
                //Debug.WriteLine("Zoom 0 - Right hand in front of right shoudler - PASS");

                // Hands between shoulder and hip
                if (body.Joints[JointType.HandRight].Position.Y < body.Joints[JointType.SpineShoulder].Position.Y && body.Joints[JointType.HandRight].Position.Y > body.Joints[JointType.SpineBase].Position.Y &&
                    body.Joints[JointType.HandLeft].Position.Y < body.Joints[JointType.SpineShoulder].Position.Y && body.Joints[JointType.HandLeft].Position.Y > body.Joints[JointType.SpineBase].Position.Y)
                {
                    // Hands between shoulders
                    if (body.Joints[JointType.HandRight].Position.X < body.Joints[JointType.ShoulderRight].Position.X && body.Joints[JointType.HandRight].Position.X > body.Joints[JointType.ShoulderLeft].Position.X &&
                        body.Joints[JointType.HandLeft].Position.X > body.Joints[JointType.ShoulderLeft].Position.X && body.Joints[JointType.HandLeft].Position.X < body.Joints[JointType.ShoulderRight].Position.X)
                    {
                        return GesturePartResult.Succeeded;
                    }

                    return GesturePartResult.Undetermined;
                }

                return GesturePartResult.Failed;
            }

            return GesturePartResult.Failed;
        }
        public void Format(Body body, ScenarioOutline scenarioOutline)
        {
            if (this.configuration.HasTestResults)
            {
                TestResult testResult = this.testResults.GetScenarioOutlineResult(scenarioOutline);
                if (testResult == TestResult.Passed)
                {
                    body.GenerateParagraph("Passed", "Passed");
                }
                else if (testResult == TestResult.Failed)
                {
                    body.GenerateParagraph("Failed", "Failed");
                }
            }

            body.GenerateParagraph(scenarioOutline.Name, "Heading2");
            if (!string.IsNullOrEmpty(scenarioOutline.Description))
            {
                body.GenerateParagraph(scenarioOutline.Description, "Normal");
            }

            foreach (Step step in scenarioOutline.Steps)
            {
                this.wordStepFormatter.Format(body, step);
            }

            foreach (var example in scenarioOutline.Examples)
            {
                body.GenerateParagraph("Examples: " + example.Description, "Heading3");
                this.wordTableFormatter.Format(body, example.TableArgument);
            }
        }
示例#14
0
        // Cache here per time step to reduce cache misses.
        //  Vec2 m_localCenterA, m_localCenterB;
        // float m_invMassA, m_invIA;
        // float m_invMassB, m_invIB;
        protected Joint(IWorldPool worldPool, JointDef def)
        {
            Debug.Assert(def.bodyA != def.bodyB);

            pool = worldPool;
            m_type = def.type;
            m_prev = null;
            m_next = null;
            m_bodyA = def.bodyA;
            m_bodyB = def.bodyB;
            m_collideConnected = def.collideConnected;
            m_islandFlag = false;
            m_userData = def.userData;

            m_edgeA = new JointEdge();
            m_edgeA.joint = null;
            m_edgeA.other = null;
            m_edgeA.prev = null;
            m_edgeA.next = null;

            m_edgeB = new JointEdge();
            m_edgeB.joint = null;
            m_edgeB.other = null;
            m_edgeB.prev = null;
            m_edgeB.next = null;

            // m_localCenterA = new Vec2();
            // m_localCenterB = new Vec2();
        }
 public void Format(Body body, string description)
 {
     foreach (var paragraph in description.Split(new string[] {"\n", "\r"}, StringSplitOptions.RemoveEmptyEntries))
     {
         body.GenerateParagraph(paragraph, "Normal");
     }
 }
示例#16
0
 private void OnLeaveWorld(World w, Body b)
 {
     Vector3 pos;
     Quaternion orient;
     b.getPositionOrientation(out pos, out orient);
     b.setPositionOrientation(new Vector3(), orient);
 }
示例#17
0
        /// <summary>
        /// Updates the current gesture.
        /// </summary>
        /// <param name="skeleton">The skeleton.</param>
        /// <returns>A GesturePartResult based on whether the gesture part has been completed.</returns>
        public GesturePartResult Update(Body skeleton)
        {
            JointType signalElbow;
            JointType signalShoulder;
            HandState handState;
            if (MouseMoveData.signalHand == JointType.HandRight)
            {
                signalElbow = JointType.ElbowRight;
                signalShoulder = JointType.ShoulderRight;
                handState = skeleton.HandRightState;
            }
            else
            {
                signalElbow = JointType.ElbowLeft;
                signalShoulder = JointType.ShoulderLeft;
                handState = skeleton.HandLeftState;
            }

            // Hand above elbow
            if (skeleton.Joints[MouseMoveData.signalHand].Position.Y > skeleton.Joints[signalElbow].Position.Y && handState == HandState.Lasso)
            {
                PokeGestureData.farDistance = Math.Sqrt(Math.Pow(skeleton.Joints[MouseMoveData.signalHand].Position.X - skeleton.Joints[signalShoulder].Position.X, 2) +
                                       Math.Pow(skeleton.Joints[MouseMoveData.signalHand].Position.Y - skeleton.Joints[signalShoulder].Position.Y, 2) +
                                       Math.Pow(skeleton.Joints[MouseMoveData.signalHand].Position.Z - skeleton.Joints[signalShoulder].Position.Z, 2));
                if (PokeGestureData.farDistance - PokeGestureData.startDistance > PokeGestureData.startDistance / 12)
                {
                    return GesturePartResult.Succeeded;
                }
            }

            // Hand dropped
            return GesturePartResult.Failed;
        }
示例#18
0
 protected override bool CanCollide(Body thisBody, Body otherBody, Ignorer other)
 {
     GroupIgnorer value = other as GroupIgnorer;
     return
         value == null ||
         CanCollideInternal(value);
 }
示例#19
0
        public Cursor(EntityState es, Town t, XmlParser xp)
            : base(es, "Cursor")
        {
            _town = t;

            //Current data path is GameState->Town->Cursor
            var path = es.Name + "->" + _town.Name + "->" + Name;

            Body = new Body(this, "Body");
            AddComponent(Body);

            Physics = new Physics(this, "Physics");
            AddComponent(Physics);

            ImageRender = new ImageRender(this, "ImageRender");
            AddComponent(ImageRender);

            _aimleftkey = new DoubleInput(this, "AimLeftKey", Keys.A, Buttons.DPadLeft, PlayerIndex.One);
            AddComponent(_aimleftkey);

            _aimrightkey = new DoubleInput(this, "AimRightKeys", Keys.D, Buttons.DPadRight, PlayerIndex.One);
            AddComponent(_aimrightkey);

            _quickaimkey = new DoubleInput(this, "QuickAimKey", Keys.LeftShift, Buttons.RightShoulder, PlayerIndex.One);
            AddComponent(_quickaimkey);

            ParseXml(xp, path);

            ImageRender.Origin = new Vector2(ImageRender.Texture.Width / 2f, ImageRender.Texture.Height / 2f);
            Body.Position = _town.Body.Position +
                            (_town.TileRender.Origin - Vector2.UnitY * 40 - ImageRender.Origin) *
                            ImageRender.Scale;
        }
        public static string SerializeHomePageData(Body skeleton, Dictionary<JointType, Point> jointPoints, Boolean alarmOn, double avgFrames, int currFrames, List<String> excRemaining)
        {
            JSONSkeleton jsonSkeleton = new JSONSkeleton
            {
                ID = skeleton.TrackingId.ToString(),
                Joints = new List<JSONJoint>()
            };

            foreach (JointType jointType in jointPoints.Keys)
            {
                jsonSkeleton.Joints.Add(new JSONJoint
                {
                    Name = jointType.ToString().ToLower(),
                    X = jointPoints[jointType].X,
                    Y = jointPoints[jointType].Y
                });
            }

            JSONHomePageData jsonHomePageData = new JSONHomePageData
            {
                Skeleton = jsonSkeleton,
                AlarmOn = alarmOn,
                AvgFrames = avgFrames,
                CurrFrames = currFrames,
                ExcRemaining = excRemaining
            };

            JSONHomePage jsonHomePage = new JSONHomePage{
                Page = "home",
                Operation = "default",
                Data = jsonHomePageData
            };

            return Serialize(jsonHomePage);
        }
示例#21
0
 void SetupPhysics()
 {
     if(body == null) {
         body = GetComponent<FSBodyComponent>().PhysicsBody;
         body.CreateFixture(CreateDiamond(Height, Width, Density));
     }
 }
示例#22
0
 public void Format(Body body, string description)
 {
     foreach (var paragraph in SplitDescription(description))
     {
         body.GenerateParagraph(paragraph, "Normal");
     }
 }
示例#23
0
        /// <summary>
        /// Updates the current gesture.
        /// </summary>
        /// <param name="body">The body.</param>
        /// <returns>A GesturePartResult based on whether the gesture part has been completed.</returns>
        public GesturePartResult Update(Body body)
        {
            // //left hand in front of left Shoulder
            if (body.Joints[JointType.HandLeft].Position.Z < body.Joints[JointType.ElbowLeft].Position.Z && body.Joints[JointType.HandRight].Position.Y < body.Joints[JointType.SpineBase].Position.Y)
            {
                // Debug.WriteLine("GesturePart 1 - left hand in front of left Shoulder - PASS");
                // /left hand below shoulder height but above hip height
                if (body.Joints[JointType.HandLeft].Position.Y < body.Joints[JointType.Head].Position.Y && body.Joints[JointType.HandLeft].Position.Y > body.Joints[JointType.SpineBase].Position.Y)
                {
                    // Debug.WriteLine("GesturePart 1 - left hand below shoulder height but above hip height - PASS");
                    // //left hand left of left Shoulder
                    if (body.Joints[JointType.HandLeft].Position.X < body.Joints[JointType.ShoulderRight].Position.X && body.Joints[JointType.HandLeft].Position.X > body.Joints[JointType.ShoulderLeft].Position.X)
                    {
                        // Debug.WriteLine("GesturePart 1 - left hand left of left Shoulder - PASS");
                        return GesturePartResult.Succeeded;
                    }

                    // Debug.WriteLine("GesturePart 1 - left hand left of left Shoulder - UNDETERMINED");
                    return GesturePartResult.Undetermined;
                }

                // Debug.WriteLine("GesturePart 1 - left hand below shoulder height but above hip height - FAIL");
                return GesturePartResult.Failed;
            }

            // Debug.WriteLine("GesturePart 1 - left hand in front of left Shoulder - FAIL");
            return GesturePartResult.Failed;
        }
示例#24
0
 private void SetBody(Body body)
 {
     this.body = body;
     this.body.Tag = this;
     this.body.PositionChanged += OnPositionChanged;
     this.body.ShapeChanged += OnShapeChanged;
 }
示例#25
0
        private void CreateWalls()
        {
            var wallCoff = new Coefficients(0.8f, 0.95f);
            var wallLife = new Lifespan();

            var flrState = new PhysicsState(new ALVector2D((float)0.0, ((float)ActualWidth) * ((float)0.5), (float)ActualHeight + 100.0));
            var flrShape = new PolygonShape(VertexHelper.CreateRectangle(ActualWidth, 200), 2);
            var bdyFloor = new Body(flrState, flrShape, float.PositiveInfinity, wallCoff, wallLife);

            var ceiState = new PhysicsState(new ALVector2D((float)0.0, ((float)ActualWidth) * ((float)0.5), -100.0));
            var ceiShape = new PolygonShape(VertexHelper.CreateRectangle(ActualWidth, 200), 2);
            var bdyCeiling = new Body(ceiState, ceiShape, float.PositiveInfinity, wallCoff, wallLife);

            var lwlState = new PhysicsState(new ALVector2D((float)0.0, -100.0, ((float)ActualHeight) * ((float)0.5)));
            var lwlShape = new PolygonShape(VertexHelper.CreateRectangle(200, ActualHeight), 2);
            var bdyLeftWall = new Body(lwlState, lwlShape, float.PositiveInfinity, wallCoff, wallLife);

            var rwlState = new PhysicsState(new ALVector2D((float)0.0, (float)ActualWidth + 100.0, ((float)ActualHeight) * ((float)0.5)));
            var rwlShape = new PolygonShape(VertexHelper.CreateRectangle(200, ActualHeight), 2);
            var bdyRightWall = new Body(rwlState, rwlShape, float.PositiveInfinity, wallCoff, wallLife);

            engine.AddBody(bdyFloor);
            engine.AddBody(bdyCeiling);
            engine.AddBody(bdyLeftWall);
            engine.AddBody(bdyRightWall);
        }
示例#26
0
        public void Format(Body body, Scenario scenario)
        {
            if (this.configuration.HasTestResults)
            {
                TestResult testResult = this.nunitResults.GetScenarioResult(scenario);
                if (testResult.WasExecuted && testResult.WasSuccessful)
                {
                    body.GenerateParagraph("Passed", "Passed");
                }
                else if (testResult.WasExecuted && !testResult.WasSuccessful)
                {
                    body.GenerateParagraph("Failed", "Failed");
                }
            }

            body.GenerateParagraph(scenario.Name, "Heading2");
            if (!string.IsNullOrEmpty(scenario.Description))
            {
                body.GenerateParagraph(scenario.Description, "Normal");
            }

            foreach (Step step in scenario.Steps)
            {
                this.wordStepFormatter.Format(body, step);
            }
        }
示例#27
0
 public BodyGraphic(Body body)
     : base(GetIDrawable(body), body.Matrices.ToWorld, body.Lifetime)
 {
     SetBody(body);
     this.IsLifetimeOwner = false;
     this.isBodyOwner = true;
 }
示例#28
0
        public static void DrawSkeleton(this Canvas canvas, Body body, CoordinateMapper mapper)
        {
            if (body == null) return;

            foreach (Joint joint in body.Joints.Values)
            {
                canvas.DrawPoint(joint, mapper);
            }

            canvas.DrawLine(body.Joints[JointType.Head], body.Joints[JointType.Neck], mapper);
            canvas.DrawLine(body.Joints[JointType.Neck], body.Joints[JointType.SpineShoulder], mapper);
            canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.ShoulderLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.ShoulderRight], mapper);
            canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.SpineMid], mapper);
            canvas.DrawLine(body.Joints[JointType.ShoulderLeft], body.Joints[JointType.ElbowLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.ShoulderRight], body.Joints[JointType.ElbowRight], mapper);
            canvas.DrawLine(body.Joints[JointType.ElbowLeft], body.Joints[JointType.WristLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.ElbowRight], body.Joints[JointType.WristRight], mapper);
            canvas.DrawLine(body.Joints[JointType.WristLeft], body.Joints[JointType.HandLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.WristRight], body.Joints[JointType.HandRight], mapper);
            canvas.DrawLine(body.Joints[JointType.HandLeft], body.Joints[JointType.HandTipLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.HandRight], body.Joints[JointType.HandTipRight], mapper);
            canvas.DrawLine(body.Joints[JointType.HandTipLeft], body.Joints[JointType.ThumbLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.HandTipRight], body.Joints[JointType.ThumbRight], mapper);
            canvas.DrawLine(body.Joints[JointType.SpineMid], body.Joints[JointType.SpineBase], mapper);
            canvas.DrawLine(body.Joints[JointType.SpineBase], body.Joints[JointType.HipLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.SpineBase], body.Joints[JointType.HipRight], mapper);
            canvas.DrawLine(body.Joints[JointType.HipLeft], body.Joints[JointType.KneeLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.HipRight], body.Joints[JointType.KneeRight], mapper);
            canvas.DrawLine(body.Joints[JointType.KneeLeft], body.Joints[JointType.AnkleLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.KneeRight], body.Joints[JointType.AnkleRight], mapper);
            canvas.DrawLine(body.Joints[JointType.AnkleLeft], body.Joints[JointType.FootLeft], mapper);
            canvas.DrawLine(body.Joints[JointType.AnkleRight], body.Joints[JointType.FootRight], mapper);
        }
 public void TrackBody(Body body)
 {
     //Vector3 position = BodySourceView.GetVector3FromJoint( body.Joints[jointToTrack]);
     //handStateVisual = body.HandRightState;
     //SetHandPosition(position);
     uıComponent.UpdateComponent(body);
 }
示例#30
0
 /// <summary>
 /// This overload will keep the explosion relative to the body.
 /// NOTE:  This class won't touch body.Visuals
 /// </summary>
 public ExplosionWithVisual(Body body, double waveSpeed, double forceAtCenter, double maxRadius, Viewport3D viewport, double visualStartRadius)
     : base(body, waveSpeed, forceAtCenter, maxRadius)
 {
     _viewport = viewport;
     _visualStartRadius = visualStartRadius;
     CreateVisual();
 }
示例#31
0
        internal override void InitVelocityConstraints(ref TimeStep step)
        {
            Body b1 = BodyA;
            Body b2 = BodyB;

            LocalCenterA = b1.LocalCenter;
            LocalCenterB = b2.LocalCenter;

            Transform xf1, xf2;

            b1.GetTransform(out xf1);
            b2.GetTransform(out xf2);

            // Compute the effective masses.
            Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - LocalCenterA);
            Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - LocalCenterB);
            Vector2 d  = b2.Sweep.C + r2 - b1.Sweep.C - r1;

            InvMassA = b1.InvMass;
            InvIA    = b1.InvI;
            InvMassB = b2.InvMass;
            InvIB    = b2.InvI;

            // Compute motor Jacobian and effective mass.
            {
                _axis = MathUtils.Multiply(ref xf1.R, _localXAxis1);
                _a1   = MathUtils.Cross(d + r1, _axis);
                _a2   = MathUtils.Cross(r2, _axis);

                _motorMass = InvMassA + InvMassB + InvIA * _a1 * _a1 + InvIB * _a2 * _a2;

                if (_motorMass > Settings.Epsilon)
                {
                    _motorMass = 1.0f / _motorMass;
                }
            }

            // Prismatic constraint.
            {
                _perp = MathUtils.Multiply(ref xf1.R, _localYAxis1);

                _s1 = MathUtils.Cross(d + r1, _perp);
                _s2 = MathUtils.Cross(r2, _perp);

                float m1 = InvMassA, m2 = InvMassB;
                float i1 = InvIA, i2 = InvIB;

                float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2;
                float k12 = i1 * _s1 + i2 * _s2;
                float k13 = i1 * _s1 * _a1 + i2 * _s2 * _a2;
                float k22 = i1 + i2;
                float k23 = i1 * _a1 + i2 * _a2;
                float k33 = m1 + m2 + i1 * _a1 * _a1 + i2 * _a2 * _a2;

                _K.Col1 = new Vector3(k11, k12, k13);
                _K.Col2 = new Vector3(k12, k22, k23);
                _K.Col3 = new Vector3(k13, k23, k33);
            }

            // Compute motor and limit terms.
            if (_enableLimit)
            {
                float jointTranslation = Vector2.Dot(_axis, d);
                if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop)
                {
                    _limitState = LimitState.Equal;
                }
                else if (jointTranslation <= _lowerTranslation)
                {
                    if (_limitState != LimitState.AtLower)
                    {
                        _limitState = LimitState.AtLower;
                        _impulse.Z  = 0.0f;
                    }
                }
                else if (jointTranslation >= _upperTranslation)
                {
                    if (_limitState != LimitState.AtUpper)
                    {
                        _limitState = LimitState.AtUpper;
                        _impulse.Z  = 0.0f;
                    }
                }
                else
                {
                    _limitState = LimitState.Inactive;
                    _impulse.Z  = 0.0f;
                }
            }
            else
            {
                _limitState = LimitState.Inactive;
            }

            if (_enableMotor == false)
            {
                _motorImpulse = 0.0f;
            }

            if (Settings.EnableWarmstarting)
            {
                // Account for variable time step.
                _impulse      *= step.dtRatio;
                _motorImpulse *= step.dtRatio;

                Vector2 P  = _impulse.X * _perp + (_motorImpulse + _impulse.Z) * _axis;
                float   L1 = _impulse.X * _s1 + _impulse.Y + (_motorImpulse + _impulse.Z) * _a1;
                float   L2 = _impulse.X * _s2 + _impulse.Y + (_motorImpulse + _impulse.Z) * _a2;

                b1.LinearVelocityInternal  -= InvMassA * P;
                b1.AngularVelocityInternal -= InvIA * L1;

                b2.LinearVelocityInternal  += InvMassB * P;
                b2.AngularVelocityInternal += InvIB * L2;
            }
            else
            {
                _impulse      = Vector3.Zero;
                _motorImpulse = 0.0f;
            }
        }
 private Body GetPayload() => payload ?? (payload = this.serializationManager.DeserializeFromByteArray <Body>(eventHubMessage.Payload));
示例#33
0
        //goes through all the AItargets, evaluates how preferable it is to attack the target,
        //whether the Character can see/hear the target and chooses the most preferable target within
        //sight/hearing range
        public void UpdateTargets(Character character)
        {
            var prevAiTarget = selectedAiTarget;

            selectedAiTarget     = null;
            selectedTargetMemory = null;
            targetValue          = 0.0f;

            UpdateTargetMemories();

            foreach (AITarget target in AITarget.List)
            {
                if (Level.Loaded != null && target.WorldPosition.Y > Level.Loaded.Size.Y)
                {
                    continue;
                }

                float valueModifier = 0.0f;
                float dist          = 0.0f;


                Character targetCharacter = target.Entity as Character;

                //ignore the aitarget if it is the Character itself
                if (targetCharacter == character)
                {
                    continue;
                }

                if (targetCharacter != null)
                {
                    if (targetCharacter.IsDead)
                    {
                        if (eatDeadPriority == 0.0f)
                        {
                            continue;
                        }
                        valueModifier = eatDeadPriority;
                    }
                    else if (targetCharacter.SpeciesName == "human")
                    {
                        if (attackHumans == 0.0f)
                        {
                            continue;
                        }
                        valueModifier = attackHumans;
                    }
                    else
                    {
                        EnemyAIController enemy = targetCharacter.AIController as EnemyAIController;
                        if (enemy != null)
                        {
                            if (enemy.combatStrength > combatStrength)
                            {
                                valueModifier = attackStronger;
                            }
                            else if (enemy.combatStrength < combatStrength)
                            {
                                valueModifier = attackWeaker;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                }
                else if (target.Entity != null && attackRooms != 0.0f)
                {
                    IDamageable targetDamageable = target.Entity as IDamageable;
                    if (targetDamageable != null && targetDamageable.Health <= 0.0f)
                    {
                        continue;
                    }

                    //skip the target if it's a room and the character is already inside a sub
                    if (character.AnimController.CurrentHull != null && target.Entity is Hull)
                    {
                        continue;
                    }

                    valueModifier = attackRooms;
                }

                if (valueModifier == 0.0f)
                {
                    continue;
                }

                dist = Vector2.Distance(character.WorldPosition, target.WorldPosition);

                //if the target has been within range earlier, the character will notice it more easily
                //(i.e. remember where the target was)
                if (targetMemories.ContainsKey(target))
                {
                    dist *= 0.5f;
                }

                //ignore target if it's too far to see or hear
                if (dist > target.SightRange * sight && dist > target.SoundRange * hearing)
                {
                    continue;
                }

                AITargetMemory targetMemory = FindTargetMemory(target);
                valueModifier = valueModifier * targetMemory.Priority / dist;

                if (Math.Abs(valueModifier) > Math.Abs(targetValue))
                {
                    Vector2 rayStart = character.AnimController.Limbs[0].SimPosition;
                    Vector2 rayEnd   = target.SimPosition;

                    if (target.Entity.Submarine != null && character.Submarine == null)
                    {
                        rayStart -= ConvertUnits.ToSimUnits(target.Entity.Submarine.Position);
                    }

                    Body      closestBody      = Submarine.CheckVisibility(rayStart, rayEnd);
                    Structure closestStructure = (closestBody == null) ? null : closestBody.UserData as Structure;

                    if (selectedAiTarget == null || Math.Abs(valueModifier) > Math.Abs(targetValue))
                    {
                        selectedAiTarget     = target;
                        selectedTargetMemory = targetMemory;

                        targetValue = valueModifier;
                    }
                }
            }

            if (selectedAiTarget != prevAiTarget)
            {
                wallAttackPos = Vector2.Zero;
            }
        }
示例#34
0
        private void GetTargetEntity()
        {
            targetEntity = null;

            if (Character.AnimController.CurrentHull != null)
            {
                wallAttackPos = Vector2.Zero;
                return;
            }

            //check if there's a wall between the target and the Character
            Vector2 rayStart = Character.SimPosition;
            Vector2 rayEnd   = selectedAiTarget.SimPosition;

            if (selectedAiTarget.Entity.Submarine != null && Character.Submarine == null)
            {
                rayStart -= ConvertUnits.ToSimUnits(selectedAiTarget.Entity.Submarine.Position);
            }

            Body closestBody = Submarine.CheckVisibility(rayStart, rayEnd);

            if (Submarine.LastPickedFraction == 1.0f || closestBody == null)
            {
                wallAttackPos = Vector2.Zero;
                return;
            }

            Structure wall = closestBody.UserData as Structure;

            if (wall == null)
            {
                wallAttackPos = Submarine.LastPickedPosition;
                if (selectedAiTarget.Entity.Submarine != null && Character.Submarine == null)
                {
                    wallAttackPos -= ConvertUnits.ToSimUnits(selectedAiTarget.Entity.Submarine.Position);
                }
            }
            else
            {
                int sectionIndex = wall.FindSectionIndex(ConvertUnits.ToDisplayUnits(Submarine.LastPickedPosition));

                float sectionDamage = wall.SectionDamage(sectionIndex);
                for (int i = sectionIndex - 2; i <= sectionIndex + 2; i++)
                {
                    if (wall.SectionBodyDisabled(i))
                    {
                        sectionIndex = i;
                        break;
                    }
                    if (wall.SectionDamage(i) > sectionDamage)
                    {
                        sectionIndex = i;
                    }
                }
                wallAttackPos = wall.SectionPosition(sectionIndex);
                //if (wall.Submarine != null) wallAttackPos += wall.Submarine.Position;
                wallAttackPos = ConvertUnits.ToSimUnits(wallAttackPos);
            }

            targetEntity = closestBody.UserData as IDamageable;
        }
示例#35
0
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            var isChanged = false;

            try
            {
                if (_keywordId == 0)
                {
                    var conflictKeywords = string.Empty;
                    if (KeywordManager.IsKeywordInsertConflict(PublishmentSystemId, PageUtils.FilterSql(TbKeywords.Text), out conflictKeywords))
                    {
                        FailMessage($"触发关键词“{conflictKeywords}”已存在,请设置其他关键词");
                    }
                    else
                    {
                        var keywordInfo = new KeywordInfo();


                        keywordInfo.KeywordId           = 0;
                        keywordInfo.PublishmentSystemId = PublishmentSystemId;
                        keywordInfo.Keywords            = PageUtils.FilterSql(TbKeywords.Text);
                        keywordInfo.IsDisabled          = !CbIsEnabled.Checked;
                        keywordInfo.KeywordType         = EKeywordType.Text;
                        keywordInfo.MatchType           = EMatchTypeUtils.GetEnumType(DdlMatchType.SelectedValue);
                        keywordInfo.Reply   = TbReply.Text;
                        keywordInfo.AddDate = DateTime.Now;
                        keywordInfo.Taxis   = 0;

                        DataProviderWx.KeywordDao.Insert(keywordInfo);

                        Body.AddSiteLog(PublishmentSystemId, "添加文本回复关键词", $"关键词:{TbKeywords.Text}");

                        isChanged = true;
                    }
                }
                else
                {
                    var conflictKeywords = string.Empty;
                    if (KeywordManager.IsKeywordUpdateConflict(PublishmentSystemId, _keywordId, TbKeywords.Text, out conflictKeywords))
                    {
                        FailMessage($"触发关键词“{conflictKeywords}”已存在,请设置其他关键词");
                    }
                    else
                    {
                        var keywordInfo = DataProviderWx.KeywordDao.GetKeywordInfo(_keywordId);
                        keywordInfo.Keywords   = TbKeywords.Text;
                        keywordInfo.IsDisabled = !CbIsEnabled.Checked;
                        keywordInfo.MatchType  = EMatchTypeUtils.GetEnumType(DdlMatchType.SelectedValue);
                        keywordInfo.Reply      = TbReply.Text;

                        DataProviderWx.KeywordDao.Update(keywordInfo);

                        Body.AddSiteLog(PublishmentSystemId, "编辑文本回复关键词", $"关键词:{TbKeywords.Text}");

                        isChanged = true;
                    }
                }
            }
            catch (Exception ex)
            {
                FailMessage(ex, "失败:" + ex.Message);
            }

            if (isChanged)
            {
                PageUtils.CloseModalPage(Page);
            }
        }
示例#36
0
        internal override bool SolvePositionConstraints()
        {
            Body b1 = BodyA;
            Body b2 = BodyB;

            Vector2 c1 = b1.Sweep.C;
            float   a1 = b1.Sweep.A;

            Vector2 c2 = b2.Sweep.C;
            float   a2 = b2.Sweep.A;

            // Solve linear limit constraint.
            float linearError = 0.0f;
            bool  active      = false;
            float C2          = 0.0f;

            Mat22 R1 = new Mat22(a1);
            Mat22 R2 = new Mat22(a2);

            Vector2 r1 = MathUtils.Multiply(ref R1, LocalAnchorA - LocalCenterA);
            Vector2 r2 = MathUtils.Multiply(ref R2, LocalAnchorB - LocalCenterB);
            Vector2 d  = c2 + r2 - c1 - r1;

            if (_enableLimit)
            {
                _axis = MathUtils.Multiply(ref R1, _localXAxis1);

                _a1 = MathUtils.Cross(d + r1, _axis);
                _a2 = MathUtils.Cross(r2, _axis);

                float translation = Vector2.Dot(_axis, d);
                if (Math.Abs(_upperTranslation - _lowerTranslation) < 2.0f * Settings.LinearSlop)
                {
                    // Prevent large angular corrections
                    C2          = MathUtils.Clamp(translation, -Settings.MaxLinearCorrection, Settings.MaxLinearCorrection);
                    linearError = Math.Abs(translation);
                    active      = true;
                }
                else if (translation <= _lowerTranslation)
                {
                    // Prevent large linear corrections and allow some slop.
                    C2 = MathUtils.Clamp(translation - _lowerTranslation + Settings.LinearSlop,
                                         -Settings.MaxLinearCorrection, 0.0f);
                    linearError = _lowerTranslation - translation;
                    active      = true;
                }
                else if (translation >= _upperTranslation)
                {
                    // Prevent large linear corrections and allow some slop.
                    C2 = MathUtils.Clamp(translation - _upperTranslation - Settings.LinearSlop, 0.0f,
                                         Settings.MaxLinearCorrection);
                    linearError = translation - _upperTranslation;
                    active      = true;
                }
            }

            _perp = MathUtils.Multiply(ref R1, _localYAxis1);

            _s1 = MathUtils.Cross(d + r1, _perp);
            _s2 = MathUtils.Cross(r2, _perp);

            Vector3 impulse;
            Vector2 C1 = new Vector2(Vector2.Dot(_perp, d), a2 - a1 - _refAngle);

            linearError = Math.Max(linearError, Math.Abs(C1.X));
            float angularError = Math.Abs(C1.Y);

            if (active)
            {
                float m1 = InvMassA, m2 = InvMassB;
                float i1 = InvIA, i2 = InvIB;

                float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2;
                float k12 = i1 * _s1 + i2 * _s2;
                float k13 = i1 * _s1 * _a1 + i2 * _s2 * _a2;
                float k22 = i1 + i2;
                float k23 = i1 * _a1 + i2 * _a2;
                float k33 = m1 + m2 + i1 * _a1 * _a1 + i2 * _a2 * _a2;

                _K.Col1 = new Vector3(k11, k12, k13);
                _K.Col2 = new Vector3(k12, k22, k23);
                _K.Col3 = new Vector3(k13, k23, k33);

                Vector3 C = new Vector3(-C1.X, -C1.Y, -C2);
                impulse = _K.Solve33(C); // negated above
            }
            else
            {
                float m1 = InvMassA, m2 = InvMassB;
                float i1 = InvIA, i2 = InvIB;

                float k11 = m1 + m2 + i1 * _s1 * _s1 + i2 * _s2 * _s2;
                float k12 = i1 * _s1 + i2 * _s2;
                float k22 = i1 + i2;

                _K.Col1 = new Vector3(k11, k12, 0.0f);
                _K.Col2 = new Vector3(k12, k22, 0.0f);

                Vector2 impulse1 = _K.Solve22(-C1);
                impulse.X = impulse1.X;
                impulse.Y = impulse1.Y;
                impulse.Z = 0.0f;
            }

            Vector2 P  = impulse.X * _perp + impulse.Z * _axis;
            float   L1 = impulse.X * _s1 + impulse.Y + impulse.Z * _a1;
            float   L2 = impulse.X * _s2 + impulse.Y + impulse.Z * _a2;

            c1 -= InvMassA * P;
            a1 -= InvIA * L1;
            c2 += InvMassB * P;
            a2 += InvIB * L2;

            // TODO_ERIN remove need for this.
            b1.Sweep.C = c1;
            b1.Sweep.A = a1;
            b2.Sweep.C = c2;
            b2.Sweep.A = a2;
            b1.SynchronizeTransform();
            b2.SynchronizeTransform();

            return(linearError <= Settings.LinearSlop && angularError <= Settings.AngularSlop);
        }
示例#37
0
        internal override void SolveVelocityConstraints(ref TimeStep step)
        {
            Body b1 = BodyA;
            Body b2 = BodyB;

            Vector2 v1 = b1.LinearVelocityInternal;
            float   w1 = b1.AngularVelocityInternal;
            Vector2 v2 = b2.LinearVelocityInternal;
            float   w2 = b2.AngularVelocityInternal;

            // Solve linear motor constraint.
            if (_enableMotor && _limitState != LimitState.Equal)
            {
                float Cdot       = Vector2.Dot(_axis, v2 - v1) + _a2 * w2 - _a1 * w1;
                float impulse    = _motorMass * (_motorSpeed - Cdot);
                float oldImpulse = _motorImpulse;
                float maxImpulse = step.dt * _maxMotorForce;
                _motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse);
                impulse       = _motorImpulse - oldImpulse;

                Vector2 P  = impulse * _axis;
                float   L1 = impulse * _a1;
                float   L2 = impulse * _a2;

                v1 -= InvMassA * P;
                w1 -= InvIA * L1;

                v2 += InvMassB * P;
                w2 += InvIB * L2;
            }

            Vector2 Cdot1 = new Vector2(Vector2.Dot(_perp, v2 - v1) + _s2 * w2 - _s1 * w1, w2 - w1);

            if (_enableLimit && _limitState != LimitState.Inactive)
            {
                // Solve prismatic and limit constraint in block form.
                float   Cdot2 = Vector2.Dot(_axis, v2 - v1) + _a2 * w2 - _a1 * w1;
                Vector3 Cdot  = new Vector3(Cdot1.X, Cdot1.Y, Cdot2);

                Vector3 f1 = _impulse;
                Vector3 df = _K.Solve33(-Cdot);
                _impulse += df;

                if (_limitState == LimitState.AtLower)
                {
                    _impulse.Z = Math.Max(_impulse.Z, 0.0f);
                }
                else if (_limitState == LimitState.AtUpper)
                {
                    _impulse.Z = Math.Min(_impulse.Z, 0.0f);
                }

                // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2)
                Vector2 b   = -Cdot1 - (_impulse.Z - f1.Z) * new Vector2(_K.Col3.X, _K.Col3.Y);
                Vector2 f2r = _K.Solve22(b) + new Vector2(f1.X, f1.Y);
                _impulse.X = f2r.X;
                _impulse.Y = f2r.Y;

                df = _impulse - f1;

                Vector2 P  = df.X * _perp + df.Z * _axis;
                float   L1 = df.X * _s1 + df.Y + df.Z * _a1;
                float   L2 = df.X * _s2 + df.Y + df.Z * _a2;

                v1 -= InvMassA * P;
                w1 -= InvIA * L1;

                v2 += InvMassB * P;
                w2 += InvIB * L2;
            }
            else
            {
                // Limit is inactive, just solve the prismatic constraint in block form.
                Vector2 df = _K.Solve22(-Cdot1);
                _impulse.X += df.X;
                _impulse.Y += df.Y;

                Vector2 P  = df.X * _perp;
                float   L1 = df.X * _s1 + df.Y;
                float   L2 = df.X * _s2 + df.Y;

                v1 -= InvMassA * P;
                w1 -= InvIA * L1;

                v2 += InvMassB * P;
                w2 += InvIB * L2;
            }

            b1.LinearVelocityInternal  = v1;
            b1.AngularVelocityInternal = w1;
            b2.LinearVelocityInternal  = v2;
            b2.AngularVelocityInternal = w2;
        }
示例#38
0
        void rptContents_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var ltlItemTitle       = e.Item.FindControl("ltlItemTitle") as Literal;
                var ltlColumnItemRows  = e.Item.FindControl("ltlColumnItemRows") as Literal;
                var ltlItemStatus      = e.Item.FindControl("ltlItemStatus") as Literal;
                var ltlItemEditUrl     = e.Item.FindControl("ltlItemEditUrl") as Literal;
                var ltlCommandItemRows = e.Item.FindControl("ltlCommandItemRows") as Literal;
                var ltlCategory        = e.Item.FindControl("ltlCategory") as Literal;

                var contentInfo = new ContentInfo(e.Item.DataItem);

                ltlItemTitle.Text = WebUtils.GetContentTitle(PublishmentSystemInfo, contentInfo, PageUrl);

                var showPopWinString = ModalCheckState.GetOpenWindowString(PublishmentSystemId, contentInfo, $@"/siteserver/cms/pagecontent.aspx?PublishmentSystemID={PublishmentSystemId}&NodeID={nodeInfo.NodeId}&DateFrom=&SearchType=&Keyword=&page=1&ChildNodeId={ChannelCategory.SelectedValue}");
                ltlCategory.Text = NodeManager.GetNodeNameNavigation(1, contentInfo.NodeId);

                ltlItemStatus.Text =
                    $@"<a href=""javascript:;"" title=""设置内容状态"" onclick=""{showPopWinString}"">{LevelManager.GetCheckState(
                        PublishmentSystemInfo, contentInfo.IsChecked, contentInfo.CheckedLevel)}</a>";

                //if (HasChannelPermissions(contentInfo.NodeId, AppManager.Cms.Permission.Channel.ContentEdit) || Body.AdministratorName == contentInfo.AddUserName)
                //{
                //    ltlItemEditUrl.Text =
                //        $"<a href=\"{WebUtils.GetContentAddEditUrl(PublishmentSystemId, nodeInfo, contentInfo.Id, PageUrl)}\">编辑</a>";
                //}
                if (HasChannelPermissions(contentInfo.NodeId, AppManager.Cms.Permission.Channel.ContentEdit) || Body.AdministratorName == contentInfo.AddUserName)
                {
                    ltlItemEditUrl.Text =
                        $"<a href=\"{WebUtils.GetContentAddEditUrlMulti(contentInfo.PublishmentSystemId, DataProvider.NodeDao.GetNodeInfo(contentInfo.NodeId), contentInfo.Id, GetPageUrlForContent(contentInfo,Body.GetQueryInt("NodeId")), Body.GetQueryInt("NodeId"))}\">编辑</a>";
                }
                ltlColumnItemRows.Text = TextUtility.GetColumnItemRowsHtml(styleInfoList, attributesOfDisplay, valueHashtable, tableStyle, PublishmentSystemInfo, contentInfo);

                ltlCommandItemRows.Text = TextUtility.GetCommandItemRowsHtml(tableStyle, PublishmentSystemInfo, nodeInfo, contentInfo, PageUrl, Body.AdministratorName);
            }
        }
示例#39
0
        /// <summary>
        /// Activate the explosion at the specified position.
        /// </summary>
        /// <param name="pos">The position where the explosion happens </param>
        /// <param name="radius">The explosion radius </param>
        /// <param name="maxForce">The explosion force at the explosion point (then is inversely proportional to the square of the distance)</param>
        /// <returns>A list of bodies and the amount of force that was applied to them.</returns>
        public Dictionary <Fixture, Vector2> Activate(Vector2 pos, float radius, float maxForce)
        {
            AABB aabb;

            aabb.LowerBound = pos + new Vector2(-radius, -radius);
            aabb.UpperBound = pos + new Vector2(radius, radius);
            Fixture[] shapes = new Fixture[MaxShapes];

            // More than 5 shapes in an explosion could be possible, but still strange.
            Fixture[] containedShapes = new Fixture[5];
            bool      exit            = false;

            int shapeCount          = 0;
            int containedShapeCount = 0;

            // Query the world for overlapping shapes.
            World.QueryAABB(
                fixture =>
            {
                if (fixture.TestPoint(ref pos))
                {
                    if (IgnoreWhenInsideShape)
                    {
                        exit = true;
                        return(false);
                    }

                    containedShapes[containedShapeCount++] = fixture;
                }
                else
                {
                    shapes[shapeCount++] = fixture;
                }

                // Continue the query.
                return(true);
            }, ref aabb);

            if (exit)
            {
                return(new Dictionary <Fixture, Vector2>());
            }

            Dictionary <Fixture, Vector2> exploded = new Dictionary <Fixture, Vector2>(shapeCount + containedShapeCount);

            // Per shape max/min angles for now.
            float[] vals     = new float[shapeCount * 2];
            int     valIndex = 0;

            for (int i = 0; i < shapeCount; ++i)
            {
                PolygonShape ps;
                CircleShape  cs = shapes[i].Shape as CircleShape;
                if (cs != null)
                {
                    // We create a "diamond" approximation of the circle
                    Vertices v   = new Vertices();
                    Vector2  vec = Vector2.Zero + new Vector2(cs.Radius, 0);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(0, cs.Radius);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(-cs.Radius, cs.Radius);
                    v.Add(vec);
                    vec = Vector2.Zero + new Vector2(0, -cs.Radius);
                    v.Add(vec);
                    ps = new PolygonShape(v, 0);
                }
                else
                {
                    ps = shapes[i].Shape as PolygonShape;
                }

                if ((shapes[i].Body.BodyType == BodyType.Dynamic) && ps != null)
                {
                    Vector2 toCentroid      = shapes[i].Body.GetWorldPoint(ps.MassData.Centroid) - pos;
                    float   angleToCentroid = (float)Math.Atan2(toCentroid.Y, toCentroid.X);
                    float   min             = float.MaxValue;
                    float   max             = float.MinValue;
                    float   minAbsolute     = 0.0f;
                    float   maxAbsolute     = 0.0f;

                    for (int j = 0; j < ps.Vertices.Count; ++j)
                    {
                        Vector2 toVertex = (shapes[i].Body.GetWorldPoint(ps.Vertices[j]) - pos);
                        float   newAngle = (float)Math.Atan2(toVertex.Y, toVertex.X);
                        float   diff     = (newAngle - angleToCentroid);

                        diff = (diff - MathHelper.Pi) % (2 * MathHelper.Pi);
                        // the minus pi is important. It means cutoff for going other direction is at 180 deg where it needs to be

                        if (diff < 0.0f)
                        {
                            diff += 2 * MathHelper.Pi; // correction for not handling negs
                        }
                        diff -= MathHelper.Pi;

                        if (Math.Abs(diff) > MathHelper.Pi)
                        {
                            continue; // Something's wrong, point not in shape but exists angle diff > 180
                        }
                        if (diff > max)
                        {
                            max         = diff;
                            maxAbsolute = newAngle;
                        }
                        if (diff < min)
                        {
                            min         = diff;
                            minAbsolute = newAngle;
                        }
                    }

                    vals[valIndex] = minAbsolute;
                    ++valIndex;
                    vals[valIndex] = maxAbsolute;
                    ++valIndex;
                }
            }

            Array.Sort(vals, 0, valIndex, _rdc);
            _data.Clear();
            bool rayMissed = true;

            for (int i = 0; i < valIndex; ++i)
            {
                Fixture fixture = null;
                float   midpt;

                int iplus = (i == valIndex - 1 ? 0 : i + 1);
                if (vals[i] == vals[iplus])
                {
                    continue;
                }

                if (i == valIndex - 1)
                {
                    // the single edgecase
                    midpt = (vals[0] + MathHelper.Pi * 2 + vals[i]);
                }
                else
                {
                    midpt = (vals[i + 1] + vals[i]);
                }

                midpt = midpt / 2;

                Vector2 p1 = pos;
                Vector2 p2 = radius * new Vector2((float)Math.Cos(midpt), (float)Math.Sin(midpt)) + pos;

                // RaycastOne
                bool hitClosest = false;
                World.RayCast((f, p, n, fr) =>
                {
                    Body body = f.Body;

                    if (!IsActiveOn(body))
                    {
                        return(0);
                    }

                    hitClosest = true;
                    fixture    = f;
                    return(fr);
                }, p1, p2);

                //draws radius points
                if ((hitClosest) && (fixture.Body.BodyType == BodyType.Dynamic))
                {
                    if ((_data.Any()) && (_data.Last().Body == fixture.Body) && (!rayMissed))
                    {
                        int       laPos = _data.Count - 1;
                        ShapeData la    = _data[laPos];
                        la.Max       = vals[iplus];
                        _data[laPos] = la;
                    }
                    else
                    {
                        // make new
                        ShapeData d;
                        d.Body = fixture.Body;
                        d.Min  = vals[i];
                        d.Max  = vals[iplus];
                        _data.Add(d);
                    }

                    if ((_data.Count > 1) &&
                        (i == valIndex - 1) &&
                        (_data.Last().Body == _data.First().Body) &&
                        (_data.Last().Max == _data.First().Min))
                    {
                        ShapeData fi = _data[0];
                        fi.Min = _data.Last().Min;
                        _data.RemoveAt(_data.Count - 1);
                        _data[0] = fi;
                        while (_data.First().Min >= _data.First().Max)
                        {
                            fi.Min  -= MathHelper.Pi * 2;
                            _data[0] = fi;
                        }
                    }

                    int       lastPos = _data.Count - 1;
                    ShapeData last    = _data[lastPos];
                    while ((_data.Count > 0) &&
                           (_data.Last().Min >= _data.Last().Max))    // just making sure min<max
                    {
                        last.Min       = _data.Last().Min - 2 * MathHelper.Pi;
                        _data[lastPos] = last;
                    }
                    rayMissed = false;
                }
                else
                {
                    rayMissed = true; // raycast did not find a shape
                }
            }

            for (int i = 0; i < _data.Count; ++i)
            {
                if (!IsActiveOn(_data[i].Body))
                {
                    continue;
                }

                float arclen = _data[i].Max - _data[i].Min;

                float first        = MathHelper.Min(MaxEdgeOffset, EdgeRatio * arclen);
                int   insertedRays = (int)Math.Ceiling(((arclen - 2.0f * first) - (MinRays - 1) * MaxAngle) / MaxAngle);

                if (insertedRays < 0)
                {
                    insertedRays = 0;
                }

                float offset = (arclen - first * 2.0f) / ((float)MinRays + insertedRays - 1);

                //Note: This loop can go into infinite as it operates on floats.
                //Added FloatEquals with a large epsilon.
                for (float j = _data[i].Min + first;
                     j < _data[i].Max || MathUtils.FloatEquals(j, _data[i].Max, 0.0001f);
                     j += offset)
                {
                    Vector2 p1        = pos;
                    Vector2 p2        = pos + radius * new Vector2((float)Math.Cos(j), (float)Math.Sin(j));
                    Vector2 hitpoint  = Vector2.Zero;
                    float   minlambda = float.MaxValue;

                    List <Fixture> fl = _data[i].Body.FixtureList;
                    for (int x = 0; x < fl.Count; x++)
                    {
                        Fixture      f = fl[x];
                        RayCastInput ri;
                        ri.Point1      = p1;
                        ri.Point2      = p2;
                        ri.MaxFraction = 50f;

                        RayCastOutput ro;
                        if (f.RayCast(out ro, ref ri, 0))
                        {
                            if (minlambda > ro.Fraction)
                            {
                                minlambda = ro.Fraction;
                                hitpoint  = ro.Fraction * p2 + (1 - ro.Fraction) * p1;
                            }
                        }

                        // the force that is to be applied for this particular ray.
                        // offset is angular coverage. lambda*length of segment is distance.
                        float impulse = (arclen / (MinRays + insertedRays)) * maxForce * 180.0f / MathHelper.Pi * (1.0f - Math.Min(1.0f, minlambda));

                        // We Apply the impulse!!!
                        Vector2 vectImp = Vector2.Dot(impulse * new Vector2((float)Math.Cos(j), (float)Math.Sin(j)), -ro.Normal) * new Vector2((float)Math.Cos(j), (float)Math.Sin(j));
                        _data[i].Body.ApplyLinearImpulse(ref vectImp, ref hitpoint);

                        // We gather the fixtures for returning them
                        if (exploded.ContainsKey(f))
                        {
                            exploded[f] += vectImp;
                        }
                        else
                        {
                            exploded.Add(f, vectImp);
                        }

                        if (minlambda > 1.0f)
                        {
                            hitpoint = p2;
                        }
                    }
                }
            }

            // We check contained shapes
            for (int i = 0; i < containedShapeCount; ++i)
            {
                Fixture fix = containedShapes[i];

                if (!IsActiveOn(fix.Body))
                {
                    continue;
                }

                float   impulse = MinRays * maxForce * 180.0f / MathHelper.Pi;
                Vector2 hitPoint;

                CircleShape circShape = fix.Shape as CircleShape;
                if (circShape != null)
                {
                    hitPoint = fix.Body.GetWorldPoint(circShape.Position);
                }
                else
                {
                    PolygonShape shape = fix.Shape as PolygonShape;
                    hitPoint = fix.Body.GetWorldPoint(shape.MassData.Centroid);
                }

                Vector2 vectImp = impulse * (hitPoint - pos);

                fix.Body.ApplyLinearImpulse(ref vectImp, ref hitPoint);

                if (!exploded.ContainsKey(fix))
                {
                    exploded.Add(fix, vectImp);
                }
            }

            return(exploded);
        }
示例#40
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            var permissions = PermissionsManager.GetPermissions(Body.AdministratorName);

            PageUtils.CheckRequestParameter("PublishmentSystemID", "NodeID");
            var nodeID      = Body.GetQueryInt("NodeID");
            var childNodeId = Body.GetQueryInt("ChildNodeId");

            relatedIdentities = RelatedIdentities.GetChannelRelatedIdentities(PublishmentSystemId, nodeID);
            nodeInfo          = NodeManager.GetNodeInfo(1, nodeID);
            tableName         = NodeManager.GetTableName(PublishmentSystemInfo, nodeInfo);
            tableStyle        = NodeManager.GetTableStyle(PublishmentSystemInfo, nodeInfo);
            styleInfoList     = TableStyleManager.GetTableStyleInfoList(tableStyle, tableName, relatedIdentities);
            var styleInfoList2 = TableStyleManager.GetTableStyleInfoList(tableStyle, "siteserver_Node", relatedIdentities);
            Dictionary <string, string> category = DataProvider.NodeDao.GetNodeIdListLevel(2, nodeID);
            int contentNum = 0;

            if (nodeInfo.Additional.IsPreviewContents)
            {
                new Action(() =>
                {
                    DataProvider.ContentDao.DeletePreviewContents(PublishmentSystemId, tableName, nodeInfo);
                }).BeginInvoke(null, null);
            }

            if (!HasChannelPermissions(nodeID, AppManager.Cms.Permission.Channel.ContentView, AppManager.Cms.Permission.Channel.ContentAdd, AppManager.Cms.Permission.Channel.ContentEdit, AppManager.Cms.Permission.Channel.ContentDelete, AppManager.Cms.Permission.Channel.ContentTranslate))
            {
                if (!Body.IsAdministratorLoggin)
                {
                    PageUtils.RedirectToLoginPage();
                    return;
                }
                PageUtils.RedirectToErrorPage("您无此栏目的操作权限!");
                return;
            }

            attributesOfDisplay = TranslateUtils.StringCollectionToStringCollection(NodeManager.GetContentAttributesOfDisplay(PublishmentSystemId, nodeID));

            //this.attributesOfDisplay = TranslateUtils.StringCollectionToStringCollection(this.nodeInfo.Additional.ContentAttributesOfDisplay);

            spContents.ControlToPaginate = rptContents;
            rptContents.ItemDataBound   += rptContents_ItemDataBound;
            spContents.ItemsPerPage      = 20;//PublishmentSystemInfo.Additional.PageSize;

            var administratorName = AdminUtility.IsViewContentOnlySelf(Body.AdministratorName, PublishmentSystemId, nodeID)
                    ? Body.AdministratorName
                    : string.Empty;

            if (Body.IsQueryExists("SearchType"))
            {
                string     nodeListString   = Body.GetQueryString("ChildNodeId");
                List <int> owningNodeIdList = new List <int>();
                if (!string.IsNullOrEmpty(nodeListString))
                {
                    string[] nodeArray = nodeListString.Split(new char[] { ',' });

                    foreach (string node in nodeArray)
                    {
                        if (!string.IsNullOrEmpty(node))
                        {
                            int nodeId = Convert.ToInt32(node);
                            owningNodeIdList.Add(nodeId);
                            contentNum = contentNum + DataProvider.NodeDao.GetNodeInfo(nodeId).ContentNum;
                        }
                    }
                    nodeListString = nodeListString.TrimEnd(',');
                }
                else
                {
                    nodeListString = Body.GetQueryString("NodeId");
                }

                spContents.SelectCommand = DataProvider.ContentDao.GetSelectCommendForLower(nodeListString, tableStyle, tableName, PublishmentSystemId, nodeID, permissions.IsSystemAdministrator, owningNodeIdList, Body.GetQueryString("SearchType"), Body.GetQueryString("Keyword"), Body.GetQueryString("DateFrom"), string.Empty, false, ETriState.All, false, false, false, administratorName);
            }
            else
            {
                var        test     = tableName;
                List <int> nodeList = new List <int>();
                nodeList.Add(nodeID);
                var firstChildList = DataProvider.NodeDao.GetNodeIdListByParentId(1, nodeID);
                if (firstChildList != null && firstChildList.Count > 0)
                {
                    nodeList.AddRange(firstChildList);
                    foreach (var firstchild in firstChildList)
                    {
                        var secondList = DataProvider.NodeDao.GetNodeIdListByParentId(1, firstchild);
                        if (secondList != null && secondList.Count > 0)
                        {
                            nodeList.AddRange(secondList);
                        }
                    }
                }
                var nodeCollectionIdStr = string.Empty;
                foreach (int nodeId in nodeList)
                {
                    nodeCollectionIdStr = nodeCollectionIdStr + nodeId + ',';
                    contentNum          = contentNum + DataProvider.NodeDao.GetNodeInfo(nodeId).ContentNum;
                }
                nodeCollectionIdStr      = nodeCollectionIdStr.TrimEnd(',');
                spContents.SelectCommand = BaiRongDataProvider.ContentDao.GetSelectCommendForLowerLevel(tableName, nodeCollectionIdStr, ETriState.All, administratorName, base.PublishmentSystemId);
            }

            spContents.SortField     = BaiRongDataProvider.ContentDao.GetSortFieldName();
            spContents.SortMode      = SortMode.DESC;
            spContents.OrderByString = ETaxisTypeUtils.GetOrderByString(tableStyle, ETaxisType.OrderByTaxisDesc);

            //分页的时候,不去查询总条数,直接使用栏目的属性:ContentNum
            spContents.IsQueryTotalCount = false;
            spContents.TotalCount        = contentNum;//nodeInfo.ContentNum;
            ltlContentButtons.Text       = WebUtils.GetContentCommandsStandard(Body.AdministratorName, PublishmentSystemInfo, nodeInfo, PageUrlReturn, GetRedirectUrl(base.PublishmentSystemId, nodeInfo.NodeId), false);
            if (!IsPostBack)
            {
                var nodeName = NodeManager.GetNodeNameNavigation(PublishmentSystemId, nodeID);
                //BreadCrumbWithItemTitle(AppManager.Cms.LeftMenu.IdContent, "内容管理", nodeName, string.Empty);

                if (styleInfoList != null)
                {
                    foreach (var styleInfo in styleInfoList)
                    {
                        if (styleInfo.IsVisible)
                        {
                            var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName);
                            SearchType.Items.Add(listitem);
                        }
                    }
                }
                string NodeIdAll = nodeID + ",";
                if (category != null)
                {
                    foreach (var chanelCategory in category)

                    {
                        NodeIdAll = NodeIdAll + chanelCategory.Value + ",";
                        var nodechildId = DataProvider.NodeDao.GetNodeInfoListByParentId(1, Convert.ToInt32(chanelCategory.Value));
                        if (nodechildId != null && nodechildId.Count > 0)
                        {
                            string chidNodeList = string.Empty;
                            foreach (var child in nodechildId)
                            {
                                NodeIdAll    = NodeIdAll + child.NodeId + ",";
                                chidNodeList = chidNodeList + child.NodeId + ",";
                            }
                            var listitem = new ListItem(chanelCategory.Key, chidNodeList);
                            ChannelCategory.Items.Add(listitem);
                        }
                        else
                        {
                            var listitem = new ListItem(chanelCategory.Key, chanelCategory.Value);
                            NodeIdAll = NodeIdAll + chanelCategory.Value + ",";
                            ChannelCategory.Items.Add(listitem);
                        }
                    }
                }
                var listitemAll = new ListItem("全部", NodeIdAll);
                ChannelCategory.Items.Add(listitemAll);
                ListItem listItemSelect = null;
                foreach (ListItem listItem in ChannelCategory.Items)
                {
                    if (listItem.Value.Equals(Body.GetQueryString("ChildNodeId")))
                    {
                        listItemSelect = listItem;
                    }
                }
                if (listItemSelect != null)
                {
                    listItemSelect.Selected = true;
                }
                else
                {
                    listitemAll.Selected = true;
                }
                //添加隐藏属性
                SearchType.Items.Add(new ListItem("内容ID", ContentAttribute.Id));
                SearchType.Items.Add(new ListItem("添加者", ContentAttribute.AddUserName));
                SearchType.Items.Add(new ListItem("最后修改者", ContentAttribute.LastEditUserName));
                SearchType.Items.Add(new ListItem("内容组", ContentAttribute.ContentGroupNameCollection));

                if (Body.IsQueryExists("SearchType"))
                {
                    DateFrom.Text = Body.GetQueryString("DateFrom");
                    ControlUtils.SelectListItems(SearchType, Body.GetQueryString("SearchType"));
                    Keyword.Text            = Body.GetQueryString("Keyword");
                    ltlContentButtons.Text += @"
<script>
$(document).ready(function() {
	$('#contentSearch').show();
});
</script>
";
                }

                ltlColumnHeadRows.Text  = ContentUtility.GetColumnHeadRowsHtml(styleInfoList, attributesOfDisplay, tableStyle, PublishmentSystemInfo);
                ltlCommandHeadRows.Text = ContentUtility.GetCommandHeadRowsHtml(Body.AdministratorName, tableStyle, PublishmentSystemInfo, nodeInfo);
                spContents.DataBind();
            }
        }
示例#41
0
        public override bool Validate()
        {
            if (!retval.Validate() || !base.Validate())
            {
                Console.Write(" in method " + Name + " ");
                return(false);
            }

            Parameters parms = Parameters;

            is_get = ((((parms.IsAccessor && retval.IsVoid) || (parms.Count == 0 && !retval.IsVoid)) || (parms.Count == 0 && !retval.IsVoid)) && HasGetterName);
            is_set = ((parms.IsAccessor || (parms.VisibleCount == 1 && retval.IsVoid)) && HasSetterName);

            call = "(" + (IsStatic ? "" : container_type.CallByName() + (parms.Count > 0 ? ", " : "")) + Body.GetCallString(is_set) + ")";

            return(true);
        }
示例#42
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            var permissions = PermissionsManager.GetPermissions(Body.AdministratorName);

            PageUtils.CheckRequestParameter("PublishmentSystemID");
            _nodeId = Body.GetQueryInt("NodeID");
            if (_nodeId == 0)
            {
                _nodeId = PublishmentSystemId;
            }
            var nodeInfo = NodeManager.GetNodeInfo(PublishmentSystemId, this._nodeId);

            _tableStyle = NodeManager.GetTableStyle(PublishmentSystemInfo, nodeInfo);
            var tableName = NodeManager.GetTableName(PublishmentSystemInfo, nodeInfo);

            _relatedIdentities  = RelatedIdentities.GetChannelRelatedIdentities(PublishmentSystemId, this._nodeId);
            _tableStyleInfoList = TableStyleManager.GetTableStyleInfoList(_tableStyle, tableName, _relatedIdentities);

            spContents.ControlToPaginate = rptContents;
            if (string.IsNullOrEmpty(Body.GetQueryString("NodeID")))
            {
                if (TranslateUtils.ToInt(PageNum.SelectedValue) == 0)
                {
                    spContents.ItemsPerPage = PublishmentSystemInfo.Additional.PageSize;
                }
                else
                {
                    spContents.ItemsPerPage = TranslateUtils.ToInt(PageNum.SelectedValue);
                }
                spContents.SelectCommand = DataProvider.ContentDao.GetSelectCommend(_tableStyle, tableName, PublishmentSystemId, _nodeId, permissions.IsSystemAdministrator, ProductPermissionsManager.Current.OwningNodeIdList, SearchType.SelectedValue, Keyword.Text, DateFrom.Text, DateTo.Text, true, ETriState.All, false, true);
            }
            else
            {
                if (Body.GetQueryInt("PageNum") == 0)
                {
                    spContents.ItemsPerPage = PublishmentSystemInfo.Additional.PageSize;
                }
                else
                {
                    spContents.ItemsPerPage = Body.GetQueryInt("PageNum");
                }
                spContents.SelectCommand = DataProvider.ContentDao.GetSelectCommend(_tableStyle, tableName, PublishmentSystemId, _nodeId, permissions.IsSystemAdministrator, ProductPermissionsManager.Current.OwningNodeIdList, Body.GetQueryString("SearchType"), Body.GetQueryString("Keyword"), Body.GetQueryString("DateFrom"), Body.GetQueryString("DateTo"), true, ETriState.All, false, true);
            }
            spContents.OrderByString   = ETaxisTypeUtils.GetOrderByString(_tableStyle, ETaxisType.OrderByIdDesc);
            rptContents.ItemDataBound += rptContents_ItemDataBound;

            if (!IsPostBack)
            {
                BreadCrumb(AppManager.Cms.LeftMenu.IdContent, "内容回收站", AppManager.Cms.Permission.WebSite.ContentTrash);

                if (Body.IsQueryExists("IsDeleteAll"))
                {
                    BaiRongDataProvider.ContentDao.DeleteContentsByTrash(PublishmentSystemId, tableName);
                    Body.AddSiteLog(PublishmentSystemId, "清空回收站");
                    SuccessMessage("成功清空回收站!");
                    AddWaitAndRedirectScript(PageUrl);
                    return;
                }
                else if (Body.IsQueryExists("IsRestore"))
                {
                    var idsDictionary = ContentUtility.GetIDsDictionary(Request.QueryString);
                    foreach (var nodeID in idsDictionary.Keys)
                    {
                        var contentIDArrayList = idsDictionary[nodeID];
                        DataProvider.ContentDao.TrashContents(PublishmentSystemId, NodeManager.GetTableName(PublishmentSystemInfo, nodeID), contentIDArrayList);
                    }
                    Body.AddSiteLog(PublishmentSystemId, "从回收站还原内容");
                    SuccessMessage("成功还原内容!");
                    AddWaitAndRedirectScript(PageUrl);
                    return;
                }
                else if (Body.IsQueryExists("IsRestoreAll"))
                {
                    DataProvider.ContentDao.RestoreContentsByTrash(PublishmentSystemId, tableName);
                    Body.AddSiteLog(PublishmentSystemId, "从回收站还原所有内容");
                    SuccessMessage("成功还原所有内容!");
                    AddWaitAndRedirectScript(PageUrl);
                    return;
                }
                NodeManager.AddListItems(NodeIDDropDownList.Items, PublishmentSystemInfo, true, false, Body.AdministratorName);

                if (_tableStyleInfoList != null)
                {
                    foreach (var styleInfo in _tableStyleInfoList)
                    {
                        if (styleInfo.IsVisible)
                        {
                            var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName);
                            SearchType.Items.Add(listitem);
                        }
                    }
                }
                //添加隐藏属性
                SearchType.Items.Add(new ListItem("内容ID", ContentAttribute.Id));
                SearchType.Items.Add(new ListItem("添加者", ContentAttribute.AddUserName));
                SearchType.Items.Add(new ListItem("最后修改者", ContentAttribute.LastEditUserName));

                if (Body.IsQueryExists("NodeID"))
                {
                    if (PublishmentSystemId != _nodeId)
                    {
                        ControlUtils.SelectListItems(NodeIDDropDownList, _nodeId.ToString());
                    }
                    ControlUtils.SelectListItems(PageNum, Body.GetQueryString("PageNum"));
                    ControlUtils.SelectListItems(SearchType, Body.GetQueryString("SearchType"));
                    Keyword.Text  = Body.GetQueryString("Keyword");
                    DateFrom.Text = Body.GetQueryString("DateFrom");
                    DateTo.Text   = Body.GetQueryString("DateTo");
                }

                spContents.DataBind();
            }

            if (!HasChannelPermissions(this._nodeId, AppManager.Cms.Permission.Channel.ContentDelete))
            {
                Delete.Visible    = false;
                DeleteAll.Visible = false;
            }
            else
            {
                Delete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(PublishmentSystemId, true, PageUrl));
                DeleteAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsDeleteAll", "True"), "确实要清空回收站吗?"));
            }
            Restore.Attributes.Add("onclick", PageUtils.GetRedirectStringWithCheckBoxValue(PageUtils.AddQueryString(PageUrl, "IsRestore", "True"), "IDsCollection", "IDsCollection", "请选择需要还原的内容!"));
            RestoreAll.Attributes.Add("onclick", PageUtils.GetRedirectStringWithConfirm(PageUtils.AddQueryString(PageUrl, "IsRestoreAll", "True"), "确实要还原所有内容吗?"));
        }
示例#43
0
        public void Generate(GenerationInfo gen_info, ClassBase implementor)
        {
            if (!Validate())
            {
                return;
            }

            Method comp = null;

            gen_info.CurrentMember = Name;

            /* we are generated by the get Method, if there is one */
            if (is_set || is_get)
            {
                if (Modifiers != "new " && container_type.GetPropertyRecursively(Name.Substring(3)) != null)
                {
                    return;
                }
                comp = GetComplement();
                if (comp != null && is_set)
                {
                    if (Parameters.AccessorReturnType == comp.ReturnType)
                    {
                        return;
                    }
                    else
                    {
                        is_set = false;
                        call   = "(Handle, " + Body.GetCallString(false) + ")";
                        comp   = null;
                    }
                }
                /* some setters take more than one arg */
                if (comp != null && !comp.is_set)
                {
                    comp = null;
                }
            }

            GenerateImport(gen_info.Writer);
            if (comp != null && retval.CSType == comp.Parameters.AccessorReturnType)
            {
                comp.GenerateImport(gen_info.Writer);
            }

            if (IsDeprecated)
            {
                gen_info.Writer.WriteLine("\t\t[Obsolete]");
            }
            gen_info.Writer.Write("\t\t");
            if (Protection != "")
            {
                gen_info.Writer.Write("{0} ", Protection);
            }
            GenerateDeclCommon(gen_info.Writer, implementor);

            if (is_get || is_set)
            {
                gen_info.Writer.Write("\t\t\t");
                gen_info.Writer.Write((is_get) ? "get" : "set");
                GenerateBody(gen_info, implementor, "\t");
            }
            else
            {
                GenerateBody(gen_info, implementor, "");
            }

            if (is_get || is_set)
            {
                if (comp != null && retval.CSType == comp.Parameters.AccessorReturnType)
                {
                    gen_info.Writer.WriteLine();
                    gen_info.Writer.Write("\t\t\tset");
                    comp.GenerateBody(gen_info, implementor, "\t");
                }
                gen_info.Writer.WriteLine();
                gen_info.Writer.WriteLine("\t\t}");
            }
            else
            {
                gen_info.Writer.WriteLine();
            }

            gen_info.Writer.WriteLine();

            Statistics.MethodCount++;
        }
        private CharacterCollisionTest()
        {
            //Ground body
            Body ground = BodyFactory.CreateEdge(World, new Vector2(-40.0f, 0.0f), new Vector2(40.0f, 0.0f));

            // Collinear edges
            EdgeShape shape = new EdgeShape(new Vector2(-8.0f, 1.0f), new Vector2(-6.0f, 1.0f));

            ground.CreateFixture(shape);
            shape = new EdgeShape(new Vector2(-6.0f, 1.0f), new Vector2(-4.0f, 1.0f));
            ground.CreateFixture(shape);
            shape = new EdgeShape(new Vector2(-4.0f, 1.0f), new Vector2(-2.0f, 1.0f));
            ground.CreateFixture(shape);

            // Square tiles
            PolygonShape tile = new PolygonShape(1);

            tile.SetAsBox(1.0f, 1.0f, new Vector2(4.0f, 3.0f), 0.0f);
            ground.CreateFixture(tile);
            tile.SetAsBox(1.0f, 1.0f, new Vector2(6.0f, 3.0f), 0.0f);
            ground.CreateFixture(tile);
            tile.SetAsBox(1.0f, 1.0f, new Vector2(8.0f, 3.0f), 0.0f);
            ground.CreateFixture(tile);

            // Square made from an edge chain.
            Vertices vertices = new Vertices(4);

            vertices.Add(new Vector2(-1.0f, 3.0f));
            vertices.Add(new Vector2(1.0f, 3.0f));
            vertices.Add(new Vector2(1.0f, 5.0f));
            vertices.Add(new Vector2(-1.0f, 5.0f));
            ChainShape chainShape = new ChainShape(vertices);

            ground.CreateFixture(chainShape);

            // Edge chain.
            vertices = new Vertices(10);
            vertices.Add(new Vector2(0.0f, 0.0f));
            vertices.Add(new Vector2(6.0f, 0.0f));
            vertices.Add(new Vector2(6.0f, 2.0f));
            vertices.Add(new Vector2(4.0f, 1.0f));
            vertices.Add(new Vector2(2.0f, 2.0f));
            vertices.Add(new Vector2(-2.0f, 2.0f));
            vertices.Add(new Vector2(-4.0f, 3.0f));
            vertices.Add(new Vector2(-6.0f, 2.0f));
            vertices.Add(new Vector2(-6.0f, 0.0f));

            BodyFactory.CreateChainShape(World, vertices, new Vector2(-10, 4));

            // Square character
            Body squareCharacter = BodyFactory.CreateRectangle(World, 1, 1, 20);

            squareCharacter.Position        = new Vector2(-3.0f, 5.0f);
            squareCharacter.BodyType        = BodyType.Dynamic;
            squareCharacter.FixedRotation   = true;
            squareCharacter.SleepingAllowed = false;

            squareCharacter.OnCollision  += CharacterOnCollision;
            squareCharacter.OnSeparation += CharacterOnSeparation;

            // Square character 2
            Body squareCharacter2 = BodyFactory.CreateRectangle(World, 0.5f, 0.5f, 20);

            squareCharacter2.Position        = new Vector2(-5.0f, 5.0f);
            squareCharacter2.BodyType        = BodyType.Dynamic;
            squareCharacter2.FixedRotation   = true;
            squareCharacter2.SleepingAllowed = false;

            // Hexagon character
            float       angle = 0.0f;
            const float delta = Settings.Pi / 3.0f;

            vertices = new Vertices(6);

            for (int i = 0; i < 6; ++i)
            {
                vertices.Add(new Vector2(0.5f * (float)Math.Cos(angle), 0.5f * (float)Math.Sin(angle)));
                angle += delta;
            }

            Body hexCharacter = BodyFactory.CreatePolygon(World, vertices, 20);

            hexCharacter.Position        = new Vector2(-5.0f, 8.0f);
            hexCharacter.BodyType        = BodyType.Dynamic;
            hexCharacter.FixedRotation   = true;
            hexCharacter.SleepingAllowed = false;

            // Circle character
            Body circleCharacter = BodyFactory.CreateCircle(World, 0.5f, 20);

            circleCharacter.Position        = new Vector2(3.0f, 5.0f);
            circleCharacter.BodyType        = BodyType.Dynamic;
            circleCharacter.FixedRotation   = true;
            circleCharacter.SleepingAllowed = false;
        }
示例#45
0
 public void MoveBeat()
 {
     Body.Beat(attack, "beatA", 0);
 }
示例#46
0
        public void GenerateBody(GenerationInfo gen_info, ClassBase implementor, string indent)
        {
            StreamWriter sw = gen_info.Writer;

            sw.WriteLine(" {");
            if (!IsStatic && implementor != null)
            {
                implementor.Prepare(sw, indent + "\t\t\t");
            }
            if (IsAccessor)
            {
                Body.InitAccessor(sw, Signature, indent);
            }
            Body.Initialize(gen_info, is_get, is_set, indent);

            if (HasWin32Utf8Variant)
            {
                if (!retval.IsVoid)
                {
                    sw.WriteLine(indent + "\t\t\t" + retval.MarshalType + " raw_ret;");
                }
                sw.WriteLine(indent + "\t\t\t" + "if (Environment.OSVersion.Platform == PlatformID.Win32NT ||");
                sw.WriteLine(indent + "\t\t\t" + "    Environment.OSVersion.Platform == PlatformID.Win32S ||");
                sw.WriteLine(indent + "\t\t\t" + "    Environment.OSVersion.Platform == PlatformID.Win32Windows ||");
                sw.WriteLine(indent + "\t\t\t" + "    Environment.OSVersion.Platform == PlatformID.WinCE)");
                if (retval.IsVoid)
                {
                    sw.WriteLine(indent + "\t\t\t\t" + CName + "_utf8" + call + ";");
                    sw.WriteLine(indent + "\t\t\t" + "else");
                    sw.WriteLine(indent + "\t\t\t\t" + CName + call + ";");
                }
                else
                {
                    sw.WriteLine(indent + "\t\t\t\traw_ret = " + CName + "_utf8" + call + ";");
                    sw.WriteLine(indent + "\t\t\t" + "else");
                    sw.WriteLine(indent + "\t\t\t\traw_ret = " + CName + call + ";");
                    sw.WriteLine(indent + "\t\t\t" + retval.CSType + " ret = " + retval.FromNative("raw_ret") + ";");
                }
            }
            else
            {
                sw.Write(indent + "\t\t\t");
                if (retval.IsVoid)
                {
                    sw.WriteLine(CName + call + ";");
                }
                else
                {
                    sw.WriteLine(retval.MarshalType + " raw_ret = " + CName + call + ";");
                    sw.WriteLine(indent + "\t\t\t" + retval.CSType + " ret = " + retval.FromNative("raw_ret") + ";");
                }
            }

            if (!IsStatic && implementor != null)
            {
                implementor.Finish(sw, indent + "\t\t\t");
            }
            Body.Finish(sw, indent);
            Body.HandleException(sw, indent);

            if (is_get && Parameters.Count > 0)
            {
                sw.WriteLine(indent + "\t\t\treturn " + Parameters.AccessorName + ";");
            }
            else if (!retval.IsVoid)
            {
                sw.WriteLine(indent + "\t\t\treturn ret;");
            }
            else if (IsAccessor)
            {
                Body.FinishAccessor(sw, Signature, indent);
            }

            sw.Write(indent + "\t\t}");
        }
示例#47
0
 public void FallBeat()
 {
     Body.Beat(attack, "beatA", 2000);
 }
示例#48
0
        public ApplyForce()
        {
            _world.Gravity = new Vector2(0.0f, 0.0f);

            const float k_restitution = 0.4f;

            Body ground;
            {
                BodyDef bd = new BodyDef();
                bd.position = new Vector2(0.0f, 20.0f);
                ground      = _world.CreateBody(bd);

                PolygonShape shape = new PolygonShape();

                FixtureDef sd = new FixtureDef();
                sd.shape       = shape;
                sd.density     = 0.0f;
                sd.restitution = k_restitution;

                // Left vertical
                shape.SetAsEdge(new Vector2(-20.0f, -20.0f), new Vector2(-20.0f, 20.0f));
                ground.CreateFixture(sd);

                // Right vertical
                shape.SetAsEdge(new Vector2(20.0f, -20.0f), new Vector2(20.0f, 20.0f));
                ground.CreateFixture(sd);

                // Top horizontal
                shape.SetAsEdge(new Vector2(-20.0f, 20.0f), new Vector2(20.0f, 20.0f));
                ground.CreateFixture(sd);

                // Bottom horizontal
                shape.SetAsEdge(new Vector2(-20.0f, -20.0f), new Vector2(20.0f, -20.0f));
                ground.CreateFixture(sd);
            }

            {
                Transform xf1 = new Transform();
                xf1.R.Set(0.3524f * (float)Settings.b2_pi);
                xf1.Position = MathUtils.Multiply(ref xf1.R, new Vector2(1.0f, 0.0f));

                Vector2[] vertices = new Vector2[3];
                vertices[0] = MathUtils.Multiply(ref xf1, new Vector2(-1.0f, 0.0f));
                vertices[1] = MathUtils.Multiply(ref xf1, new Vector2(1.0f, 0.0f));
                vertices[2] = MathUtils.Multiply(ref xf1, new Vector2(0.0f, 0.5f));

                PolygonShape poly1 = new PolygonShape();
                poly1.Set(vertices, 3);

                FixtureDef sd1 = new FixtureDef();
                sd1.shape   = poly1;
                sd1.density = 4.0f;

                Transform xf2 = new Transform();
                xf2.R.Set(-0.3524f * (float)Settings.b2_pi);
                xf2.Position = MathUtils.Multiply(ref xf2.R, new Vector2(-1.0f, 0.0f));

                vertices[0] = MathUtils.Multiply(ref xf2, new Vector2(-1.0f, 0.0f));
                vertices[1] = MathUtils.Multiply(ref xf2, new Vector2(1.0f, 0.0f));
                vertices[2] = MathUtils.Multiply(ref xf2, new Vector2(0.0f, 0.5f));

                PolygonShape poly2 = new PolygonShape();
                poly2.Set(vertices, 3);

                FixtureDef sd2 = new FixtureDef();
                sd2.shape   = poly2;
                sd2.density = 2.0f;

                BodyDef bd = new BodyDef();
                bd.type           = BodyType.Dynamic;
                bd.angularDamping = 5.0f;
                bd.linearDamping  = 0.1f;

                bd.position   = new Vector2(0.0f, 2.0f);
                bd.angle      = (float)Settings.b2_pi;
                bd.allowSleep = false;
                _body         = _world.CreateBody(bd);
                _body.CreateFixture(sd1);
                _body.CreateFixture(sd2);
            }

            {
                PolygonShape shape = new PolygonShape();
                shape.SetAsBox(0.5f, 0.5f);

                FixtureDef fd = new FixtureDef();
                fd.shape    = shape;
                fd.density  = 1.0f;
                fd.friction = 0.3f;

                for (int i = 0; i < 10; ++i)
                {
                    BodyDef bd = new BodyDef();
                    bd.type = BodyType.Dynamic;

                    bd.position = new Vector2(0.0f, 5.0f + 1.54f * i);
                    Body body = _world.CreateBody(bd);

                    body.CreateFixture(fd);

                    float gravity = 10.0f;
                    float I       = body.GetInertia();
                    float mass    = body.GetMass();

                    // For a circle: I = 0.5 * m * r * r ==> r = sqrt(2 * I / m)
                    float radius = (float)Math.Sqrt(2.0 * (double)(I / mass));

                    FrictionJointDef jd = new FrictionJointDef();
                    jd.localAnchorA     = Vector2.Zero;
                    jd.localAnchorB     = Vector2.Zero;
                    jd.bodyA            = ground;
                    jd.bodyB            = body;
                    jd.collideConnected = true;
                    jd.maxForce         = mass * gravity;
                    jd.maxTorque        = mass * radius * gravity;

                    _world.CreateJoint(jd);
                }
            }
        }
示例#49
0
 public override int GetHashCode() => 31 *Body.GetHashCode() + MediaType.GetHashCode();
示例#50
0
 public void Jump()
 {
     Body.Direction = 1;
     Body.JumpTo(Body.X, Body.Y - 240, "Jump", 0, 2, 3, new LivingCallBack(Beating));
 }
示例#51
0
        public async Task <IHttpActionResult> Register(UserRegistrationModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var modelErrors = new List <string>();
                    foreach (var modelState in ModelState.Values)
                    {
                        foreach (var modelError in modelState.Errors)
                        {
                            modelErrors.Add(modelError.ErrorMessage);
                        }
                    }
                    return(Content(HttpStatusCode.BadRequest, modelErrors[0].ToString()));
                }

                if (await _bucket.ExistsAsync(model.Email))
                {
                    return(Content(HttpStatusCode.Conflict, new Error($"Email '{model.Email}' already exists")));
                }
                if (await _bucket.ExistsAsync(model.EmiratId))
                {
                    return(Content(HttpStatusCode.Conflict, new Error($"EmiratId '{model.EmiratId}' already exists")));
                }
                if (await _bucket.ExistsAsync(model.Phone))
                {
                    return(Content(HttpStatusCode.Conflict, new Error($"Phone '{model.EmiratId}' already exists")));
                }
                Body body = new Body();
                body.UniFiedNumber  = model.Body.UniFiedNumber;
                body.PlaceOfBirthAr = model.Body.PlaceOfBirthAr;
                body.PlaceOfBirthEn = model.Body.PlaceOfBirthEn;
                body.DateOfBirth    = model.Body.DateOfBirth;

                if (model.Body.IdentityCard != null)
                {
                    IdentityCard identityCard = new IdentityCard();
                    identityCard.Number     = model.Body.IdentityCard.Number;
                    identityCard.IssueDate  = DateTime.Today;
                    identityCard.ExpiryDate = DateTime.Today;
                    body.IdentityCard       = identityCard;
                }

                if (model.Body.Nationality != null)
                {
                    Nationality nationality = new Nationality();
                    nationality.ArDesc = model.Body.Nationality.ArDesc;
                    nationality.EnDesc = model.Body.Nationality.EnDesc;
                    body.Nationality   = nationality;
                }

                if (model.Body.PersonName != null)
                {
                    PersonName personName = new PersonName();
                    personName.FullArabicName    = model.Body.PersonName.FirstNameArabic;
                    personName.FirstNameArabic   = model.Body.PersonName.FirstNameArabic;
                    personName.SecondNameArabic  = model.Body.PersonName.SecondNameArabic;
                    personName.ThirdNameArabic   = model.Body.PersonName.ThirdNameArabic;
                    personName.FourthNameArabic  = model.Body.PersonName.FourthNameArabic;
                    personName.FamilyNameArabic  = model.Body.PersonName.FamilyNameArabic;
                    personName.FullEnglishName   = model.Body.PersonName.FullEnglishName;
                    personName.FirstNameEnglish  = model.Body.PersonName.FirstNameEnglish;
                    personName.SecondNameEnglish = model.Body.PersonName.SecondNameEnglish;
                    personName.ThirdNameEnglish  = model.Body.PersonName.ThirdNameEnglish;
                    personName.FourthNameEnglish = model.Body.PersonName.FourthNameEnglish;
                    personName.FamilyNameEnglish = model.Body.PersonName.FamilyNameEnglish;
                    Tribe tribe = new Tribe();
                    tribe.ArDesc     = model.Body.PersonName.Tribe.ArDesc;
                    tribe.EnDesc     = model.Body.PersonName.Tribe.EnDesc;
                    personName.Tribe = tribe;
                    body.PersonName  = personName;
                }
                if (model.Body.Gender != null)
                {
                    Gender gender = new Gender();
                    gender.ArDesc = model.Body.Gender.ArDesc;
                    gender.EnDesc = model.Body.Gender.EnDesc;
                    body.Gender   = gender;
                }

                if (model.Body.CountryOfBirth != null)
                {
                    CountryOfBirth countryOfBirth = new CountryOfBirth();
                    countryOfBirth.ArDesc = model.Body.CountryOfBirth.ArDesc;
                    countryOfBirth.EnDesc = model.Body.CountryOfBirth.EnDesc;
                    body.CountryOfBirth   = countryOfBirth;
                }

                if (model.Body.EmirateOfBirth != null)
                {
                    EmirateOfBirth emirateOfBirth = new EmirateOfBirth();
                    emirateOfBirth.ArDesc = model.Body.EmirateOfBirth.ArDesc;
                    emirateOfBirth.EnDesc = model.Body.EmirateOfBirth.EnDesc;
                    body.EmirateOfBirth   = emirateOfBirth;
                }

                if (model.Body.EmirateOfBirth != null)
                {
                    CityOfBirth cityOfBirth = new CityOfBirth();
                    cityOfBirth.ArDesc = model.Body.CityOfBirth.ArDesc;
                    cityOfBirth.EnDesc = model.Body.CityOfBirth.EnDesc;
                    body.CityOfBirth   = cityOfBirth;
                }

                if (model.Body.MaritalStatus != null)
                {
                    MaritalStatus maritalStatus = new MaritalStatus();
                    maritalStatus.EnDesc = model.Body.MaritalStatus.EnDesc;
                    maritalStatus.ArDesc = model.Body.MaritalStatus.ArDesc;
                    body.MaritalStatus   = maritalStatus;
                }

                if (model.Body.Address != null)
                {
                    Address address = new Address();
                    address.AddressLine1 = model.Body.Address.AddressLine1;
                    address.AddressLine1 = model.Body.Address.AddressLine1;
                    address.City         = model.Body.Address.City;
                    address.State        = model.Body.Address.State;
                    address.Country      = model.Body.Address.Country;
                    body.Address         = address;
                }

                if (model.Body.Religion != null)
                {
                    Religion religion = new Religion();
                    religion.ArDesc = model.Body.Religion.ArDesc;
                    religion.EnDesc = model.Body.Religion.EnDesc;
                    body.Religion   = religion;
                }
                TrnHeader trnHeader = new TrnHeader();
                if (model.Body.Religion != null)
                {
                    trnHeader.ServiceProviderEntity = "APTC";
                }

                var eotp = GenerateOtp();
                var motp = GenerateOtp();
                sendEmail.SendOtpViaEmail(model.Email, model.Body.PersonName.FirstNameEnglish, eotp);
                //SendOtpViaMobile(model.Phone, motp);
                string password = Guid.NewGuid().ToString("d").Substring(1, 4);
                var    userDoc  = new Document <UserRegistrationModel>()
                {
                    Id      = "Customer_" + model.EmiratId,
                    Content = new UserRegistrationModel
                    {
                        IsVerifiedOtp = false,
                        EmailOtp      = eotp,
                        MobileOtp     = motp,
                        Language      = model.Language,
                        Email         = model.Email,
                        Password      = password,
                        Phone         = model.Phone,
                        OtherPhone    = model.OtherPhone,
                        EmiratId      = model.EmiratId,
                        PassPort      = model.PassPort,
                        Body          = body,
                        TrnHeader     = trnHeader
                    },
                };

                var result = await _bucket.InsertAsync(userDoc);

                if (!result.Success)
                {
                    return(Content(HttpStatusCode.InternalServerError, new Error(result.Message)));
                }
                else
                {
                    //sendEmail.SendUserIdAndPassword(model.Email, password);
                    var userDocLogin = new Document <Login>()
                    {
                        Id      = "Login_" + model.Email,
                        Content = new Login
                        {
                            Created_by   = model.Email,
                            Created_on   = DateTime.Now.ToString(),
                            UserId       = model.Email,
                            Password     = password,
                            Pre_language = model.Language,
                            Status       = "A",
                            Type         = "CAST",
                            Role         = "User",
                        },
                    };
                    IBucket _bucketLogin = ClusterHelper.GetBucket(ConfigurationManager.AppSettings.Get("CouchbaseLoginBucket"));
                    var     resultLogin  = await _bucketLogin.InsertAsync(userDocLogin);

                    return(Content(HttpStatusCode.Accepted, result.Document.Id));
                }
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.Forbidden, ex.StackTrace));
            }
        }
示例#52
0
 // Use this for specific initialization
 public void init(Body bodyToTrack, GameObject trackedBodyObj, BodySourceManager bodySourceManager)
 {
     trackedBody       = bodyToTrack;
     bodyManager       = bodySourceManager;
     trackedBodyObject = trackedBodyObj;
 }
示例#53
0
        private void CreateLeg(World world, float s, Vector2 wheelAnchor, int index)
        {
            Vector2 p1 = new Vector2(5.4f * s, 6.1f);
            Vector2 p2 = new Vector2(7.2f * s, 1.2f);
            Vector2 p3 = new Vector2(4.3f * s, 1.9f);
            Vector2 p4 = new Vector2(3.1f * s, -0.8f);
            Vector2 p5 = new Vector2(6.0f * s, -1.5f);
            Vector2 p6 = new Vector2(2.5f * s, -3.7f);

            PolygonShape poly1 = new PolygonShape(1f);
            PolygonShape poly2 = new PolygonShape(2f);

            Vertices vertices = new Vertices(3);

            if (s < 0f)
            {
                vertices.Add(p1);
                vertices.Add(p2);
                vertices.Add(p3);
                poly1.Set(vertices);

                vertices[0] = Vector2.Zero;
                vertices[1] = p5 - p4;
                vertices[2] = p6 - p4;
                poly2.Set(vertices);
            }
            else
            {
                vertices.Add(p1);
                vertices.Add(p3);
                vertices.Add(p2);
                poly1.Set(vertices);

                vertices[0] = Vector2.Zero;
                vertices[1] = p6 - p4;
                vertices[2] = p5 - p4;
                poly2.Set(vertices);
            }

            Body body1 = BodyFactory.CreateBody(world);

            body1.BodyType       = BodyType.Dynamic;
            body1.Position       = _position;
            body1.AngularDamping = 10f;
            if (s < 0f)
            {
                _leftLegs[index] = body1;
            }
            else
            {
                _rightLegs[index] = body1;
            }

            Body body2 = BodyFactory.CreateBody(world);

            body2.BodyType       = BodyType.Dynamic;
            body2.Position       = p4 + _position;
            body2.AngularDamping = 10f;
            if (s < 0f)
            {
                _leftShoulders[index] = body2;
            }
            else
            {
                _rightShoulders[index] = body2;
            }

            Fixture f1 = body1.CreateFixture(poly1);

            f1.CollisionGroup = -1;

            Fixture f2 = body2.CreateFixture(poly2);

            f2.CollisionGroup = -1;

            // Using a soft distanceraint can reduce some jitter.
            // It also makes the structure seem a bit more fluid by
            // acting like a suspension system.
            DistanceJoint djd = new DistanceJoint(body1, body2, body1.GetLocalPoint(p2 + _position),
                                                  body2.GetLocalPoint(p5 + _position));

            djd.DampingRatio = 0.5f;
            djd.Frequency    = 10f;

            world.AddJoint(djd);
            _walkerJoints.Add(djd);

            DistanceJoint djd2 = new DistanceJoint(body1, body2, body1.GetLocalPoint(p3 + _position),
                                                   body2.GetLocalPoint(p4 + _position));

            djd2.DampingRatio = 0.5f;
            djd2.Frequency    = 10f;

            world.AddJoint(djd2);
            _walkerJoints.Add(djd2);

            DistanceJoint djd3 = new DistanceJoint(body1, _wheel, body1.GetLocalPoint(p3 + _position),
                                                   _wheel.GetLocalPoint(wheelAnchor + _position));

            djd3.DampingRatio = 0.5f;
            djd3.Frequency    = 10f;

            world.AddJoint(djd3);
            _walkerJoints.Add(djd3);

            DistanceJoint djd4 = new DistanceJoint(body2, _wheel, body2.GetLocalPoint(p6 + _position),
                                                   _wheel.GetLocalPoint(wheelAnchor + _position));

            djd4.DampingRatio = 0.5f;
            djd4.Frequency    = 10f;

            world.AddJoint(djd4);
            _walkerJoints.Add(djd4);

            Vector2       anchor = p4 - new Vector2(0f, -0.8f);
            RevoluteJoint rjd    = new RevoluteJoint(body2, _chassis, body2.GetLocalPoint(_chassis.GetWorldPoint(anchor)),
                                                     anchor);

            world.AddJoint(rjd);
        }
示例#54
0
 public RequestData(Body body, ContentMediaType mediaType, ContentEncoding contentEncoding)
 {
     Body            = body;
     MediaType       = mediaType;
     ContentEncoding = contentEncoding;
 }
示例#55
0
        public static void DrawSkeleton(this Canvas canvas, Body body, CoordinateMapper mapper, Color color)
        {
            if (body == null)
            {
                return;
            }

            foreach (Joint joint in body.Joints.Values)
            {
                canvas.DrawPoint(joint, mapper, color);
            }

            if (body.Joints[JointType.Neck].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.Head], body.Joints[JointType.Neck], mapper, color);
            }
            if (body.Joints[JointType.SpineShoulder].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.Neck], body.Joints[JointType.SpineShoulder], mapper, color);
            }
            if (body.Joints[JointType.ShoulderLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.ShoulderLeft], mapper, color);
            }
            if (body.Joints[JointType.ShoulderRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.ShoulderRight], mapper, color);
            }
            if (body.Joints[JointType.SpineMid].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.SpineShoulder], body.Joints[JointType.SpineMid], mapper, color);
            }
            if (body.Joints[JointType.ElbowLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.ShoulderLeft], body.Joints[JointType.ElbowLeft], mapper, color);
            }
            if (body.Joints[JointType.ElbowRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.ShoulderRight], body.Joints[JointType.ElbowRight], mapper, color);
            }
            if (body.Joints[JointType.WristLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.ElbowLeft], body.Joints[JointType.WristLeft], mapper, color);
            }
            if (body.Joints[JointType.WristRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.ElbowRight], body.Joints[JointType.WristRight], mapper, color);
            }
            if (body.Joints[JointType.HandLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.WristLeft], body.Joints[JointType.HandLeft], mapper, color);
            }
            if (body.Joints[JointType.HandRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.WristRight], body.Joints[JointType.HandRight], mapper, color);
            }
            if (body.Joints[JointType.HandTipLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.HandLeft], body.Joints[JointType.HandTipLeft], mapper, color);
            }
            if (body.Joints[JointType.HandTipRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.HandRight], body.Joints[JointType.HandTipRight], mapper, color);
            }
            if (body.Joints[JointType.ThumbLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.WristLeft], body.Joints[JointType.ThumbLeft], mapper, color);
            }
            if (body.Joints[JointType.ThumbRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.WristRight], body.Joints[JointType.ThumbRight], mapper, color);
            }
            if (body.Joints[JointType.SpineBase].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.SpineMid], body.Joints[JointType.SpineBase], mapper, color);
            }
            if (body.Joints[JointType.HipLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.SpineBase], body.Joints[JointType.HipLeft], mapper, color);
            }
            if (body.Joints[JointType.HipRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.SpineBase], body.Joints[JointType.HipRight], mapper, color);
            }
            if (body.Joints[JointType.KneeLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.HipLeft], body.Joints[JointType.KneeLeft], mapper, color);
            }
            if (body.Joints[JointType.KneeRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.HipRight], body.Joints[JointType.KneeRight], mapper, color);
            }
            if (body.Joints[JointType.AnkleLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.KneeLeft], body.Joints[JointType.AnkleLeft], mapper, color);
            }
            if (body.Joints[JointType.AnkleRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.KneeRight], body.Joints[JointType.AnkleRight], mapper, color);
            }
            if (body.Joints[JointType.FootLeft].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.AnkleLeft], body.Joints[JointType.FootLeft], mapper, color);
            }
            if (body.Joints[JointType.FootRight].TrackingState != TrackingState.Inferred)
            {
                canvas.DrawLine(body.Joints[JointType.AnkleRight], body.Joints[JointType.FootRight], mapper, color);
            }
        }
示例#56
0
        public TheoJansenWalker(World world, PhysicsGameScreen screen, Vector2 position)
        {
            _position   = position;
            _motorSpeed = 2.0f;
            _motorOn    = true;
            _screen     = screen;

            _walkerJoints = new List <DistanceJoint>();

            _leftShoulders  = new Body[3];
            _rightShoulders = new Body[3];
            _leftLegs       = new Body[3];
            _rightLegs      = new Body[3];

            Vector2 pivot = new Vector2(0f, -0.8f);

            // Chassis
            {
                PolygonShape shape = new PolygonShape(1f);
                shape.SetAsBox(2.5f, 1.0f);

                _body =
                    new Sprite(_screen.ScreenManager.Assets.TextureFromShape(shape, MaterialType.Blank,
                                                                             Color.Beige, 1f));

                _chassis          = BodyFactory.CreateBody(world);
                _chassis.BodyType = BodyType.Dynamic;
                _chassis.Position = pivot + _position;

                Fixture fixture = _chassis.CreateFixture(shape);
                fixture.CollisionGroup = -1;
            }

            {
                CircleShape shape = new CircleShape(1.6f, 1f);
                _engine =
                    new Sprite(_screen.ScreenManager.Assets.TextureFromShape(shape, MaterialType.Waves,
                                                                             Color.Beige * 0.8f, 1f));

                _wheel          = BodyFactory.CreateBody(world);
                _wheel.BodyType = BodyType.Dynamic;
                _wheel.Position = pivot + _position;

                Fixture fixture = _wheel.CreateFixture(shape);
                fixture.CollisionGroup = -1;
            }

            {
                _motorJoint = new RevoluteJoint(_wheel, _chassis, _wheel.GetLocalPoint(_chassis.Position), Vector2.Zero);
                _motorJoint.CollideConnected = false;
                _motorJoint.MotorSpeed       = _motorSpeed;
                _motorJoint.MaxMotorTorque   = 400f;
                _motorJoint.MotorEnabled     = _motorOn;
                world.AddJoint(_motorJoint);
            }

            Vector2 wheelAnchor = pivot + new Vector2(0f, 0.8f);

            CreateLegTextures();

            CreateLeg(world, -1f, wheelAnchor, 0);
            CreateLeg(world, 1f, wheelAnchor, 0);

            _leftLeg.Origin       = AssetCreator.CalculateOrigin(_leftLegs[0]);
            _leftShoulder.Origin  = AssetCreator.CalculateOrigin(_leftShoulders[0]);
            _rightLeg.Origin      = AssetCreator.CalculateOrigin(_rightLegs[0]);
            _rightShoulder.Origin = AssetCreator.CalculateOrigin(_rightShoulders[0]);

            _wheel.SetTransform(_wheel.Position, 120f * Settings.Pi / 180f);
            CreateLeg(world, -1f, wheelAnchor, 1);
            CreateLeg(world, 1f, wheelAnchor, 1);

            _wheel.SetTransform(_wheel.Position, -120f * Settings.Pi / 180f);
            CreateLeg(world, -1f, wheelAnchor, 2);
            CreateLeg(world, 1f, wheelAnchor, 2);
        }
示例#57
0
 public SensorBody(Body body, KinectSensor kinectSensor)
 {
     this.HandTipRight = new SensorJoint(body.Joints[JointType.HandTipRight], kinectSensor);
     this.HandRight    = new SensorJoint(body.Joints[JointType.HandRight], kinectSensor);
     this.WristRight   = new SensorJoint(body.Joints[JointType.WristRight], kinectSensor);
 }
示例#58
0
        public static void AffectOutsideWorld(this Body body, FaceFrameResult face, CoordinateMapper mapper)
        {
            Joint handRight = body.Joints[JointType.HandRight];
            Joint handLeft  = body.Joints[JointType.HandLeft];

            bool isHandrightActive = handRight.Position.Y > handLeft.Position.Y;

            Joint     hand      = isHandrightActive ? handRight : handLeft;
            HandState handState = isHandrightActive ? body.HandRightState : body.HandLeftState;

            if (hand.TrackingState == TrackingState.NotTracked)
            {
                return;
            }

            // Forward position
            Point point = hand.Scale(mapper).NormalizeToScreenResolution(2.5f);

            System.Drawing.Point dp = new System.Drawing.Point((int)Math.Floor(point.X), (int)Math.Floor(point.Y));
            System.Windows.Forms.Cursor.Position = dp;

            // Special state
            if (body.HandRightState == HandState.Closed && body.HandLeftState == HandState.Closed)
            {
                float distance = handRight.Scale(mapper).Distance(handLeft.Scale(mapper));

                if (!isHandDistanceActive)
                {
                    lastHandDistance     = distance;
                    isHandDistanceActive = true;
                }

                VirtualMouse.WheelTo((int)(distance - lastHandDistance));

                lastHandDistance = distance;

                // OLD METHOD
                //Point distance = new Point();
                //distance.X = handRight.Scale(mapper).X - handLeft.Scale(mapper).X;
                //distance.Y = handRight.Scale(mapper).Y - handLeft.Scale(mapper).Y;

                //VirtualMouse.WheelTo((int) distance.Y);
            }
            else
            {
                // Disable hand distance
                if (isHandDistanceActive)
                {
                    isHandDistanceActive = false;
                }

                // Common state
                switch (handState)
                {
                case HandState.Open:
                    if (lastState == 1)
                    {
                        VirtualMouse.LeftUp();
                    }
                    if (lastState == 2)
                    {
                        VirtualMouse.RightUp();
                    }
                    lastState = 0;
                    break;

                case HandState.Closed:
                    // Send left down
                    VirtualMouse.LeftDown();
                    lastState = 1;
                    break;

                case HandState.Lasso:
                    // Send right click
                    if (lastState != 2)
                    {
                        VirtualMouse.RightClick();
                    }
                    lastState = 2;
                    break;

                case HandState.Unknown:
                    break;

                case HandState.NotTracked:
                    break;

                default:
                    break;
                }
            }
        }
示例#59
0
        /// <summary>
        /// Update the contact manifold and touching status.
        /// Note: do not assume the fixture AABBs are overlapping or are valid.
        /// </summary>
        /// <param name="contactManager">The contact manager.</param>
        internal void Update(ContactManager contactManager)
        {
            Manifold oldManifold = Manifold;

            // DISABLED for one-way platforms
            // Re-enable this contact.
            //Flags |= ContactFlags.Enabled;

            bool touching;
            bool wasTouching = (Flags & ContactFlags.Touching) == ContactFlags.Touching;

            bool sensor = FixtureA.IsSensor || FixtureB.IsSensor;

            Body bodyA = FixtureA.Body;
            Body bodyB = FixtureB.Body;

            // Is this contact a sensor?
            if (sensor)
            {
                Shape shapeA = FixtureA.Shape;
                Shape shapeB = FixtureB.Shape;
                touching = AABB.TestOverlap(shapeA, ChildIndexA, shapeB, ChildIndexB, ref bodyA.Xf, ref bodyB.Xf);

                // Sensors don't generate manifolds.
                Manifold.PointCount = 0;
            }
            else
            {
                Evaluate(ref Manifold, ref bodyA.Xf, ref bodyB.Xf);
                touching = Manifold.PointCount > 0;

                // Match old contact ids to new contact ids and copy the
                // stored impulses to warm start the solver.
                for (int i = 0; i < Manifold.PointCount; ++i)
                {
                    ManifoldPoint mp2 = Manifold.Points[i];
                    mp2.NormalImpulse  = 0.0f;
                    mp2.TangentImpulse = 0.0f;
                    ContactID id2   = mp2.Id;
                    bool      found = false;

                    for (int j = 0; j < oldManifold.PointCount; ++j)
                    {
                        ManifoldPoint mp1 = oldManifold.Points[j];

                        if (mp1.Id.Key == id2.Key)
                        {
                            mp2.NormalImpulse  = mp1.NormalImpulse;
                            mp2.TangentImpulse = mp1.TangentImpulse;
                            found = true;
                            break;
                        }
                    }
                    if (found == false)
                    {
                        mp2.NormalImpulse  = 0.0f;
                        mp2.TangentImpulse = 0.0f;
                    }

                    Manifold.Points[i] = mp2;
                }

                if (touching != wasTouching)
                {
                    bodyA.Awake = true;
                    bodyB.Awake = true;
                }
            }

            if (touching)
            {
                Flags |= ContactFlags.Touching;
            }
            else
            {
                Flags &= ~ContactFlags.Touching;
            }

            if (wasTouching == false && touching)
            {
                // CHANGE ORDER for one-way platforms
                //BeginContact can also return false and disable the contact
                if (contactManager.BeginContact != null)
                {
                    Enabled = contactManager.BeginContact(this);
                }

                //Report the collision to both participants:
                if (FixtureA.OnCollision != null)
                {
                    Enabled = FixtureA.OnCollision(FixtureA, FixtureB, this);
                }

                //Reverse the order of the reported fixtures. The first fixture is always the one that the
                //user subscribed to.
                if (FixtureB.OnCollision != null)
                {
                    Enabled = FixtureB.OnCollision(FixtureB, FixtureA, this);
                }

                ////BeginContact can also return false and disable the contact
                //if (contactManager.BeginContact != null)
                //    Enabled = contactManager.BeginContact(this);

                // DISABLED for one-way platforms
                //if the user disabled the contact (needed to exclude it in TOI solver), we also need to mark
                //it as not touching.
                //if (Enabled == false)
                //    Flags &= ~ContactFlags.Touching;
            }

            if (wasTouching && touching == false)
            {
                //Report the separation to both participants:
                if (FixtureA != null && FixtureA.OnSeparation != null)
                {
                    FixtureA.OnSeparation(FixtureA, FixtureB);
                }

                //Reverse the order of the reported fixtures. The first fixture is always the one that the
                //user subscribed to.
                if (FixtureB != null && FixtureB.OnSeparation != null)
                {
                    FixtureB.OnSeparation(FixtureB, FixtureA);
                }

                if (contactManager.EndContact != null)
                {
                    contactManager.EndContact(this);
                }
            }

            if (sensor)
            {
                return;
            }

            if (contactManager.PreSolve != null)
            {
                contactManager.PreSolve(this, ref oldManifold);
            }
        }
示例#60
0
        public override void OnInitialize(EntityManager manager)
        {
            PhysicsBody = BodyFactory.CreateBody(this.GDManager().PhysicsWorld, ConvertUnits2.ToSimUnits(Position), 0, BodyType.Static);

            PhysicsFixture = FixtureFactory.AttachCircle(ConvertUnits.ToSimUnits(_diameter / 2f), 1, PhysicsBody, this);
        }