System.Collections.Generic.List.Add(float)

Here are the examples of the csharp api System.Collections.Generic.List.Add(float) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

931 Examples 7

19 Source : DialogueManagerController.cs
with MIT License
from 0xbustos

public bool DisplayNextSentence()
        {
            foreach (LetterComponent letter in this.letters)
            {
                GameObject.Destroy( letter.gameObject );
            }

            this.currentSpeed = this.Model.WaitTime;
            this.currentEffect = null;
            this.effects.Clear();
            this.speeds.Clear();
            this.letters.Clear();
            this.currentX = 0;
            this.currentY = 0;

            if (sentences.Count == 0)
            {
                EndDialogue();
                return false;
            }

            this.Model.ImageText.sprite = sprites.Dequeue();
            this.sentence = sentences.Dequeue();
            this.audioQueue = voices.Dequeue();
            this.Model.WaitTime = 0f;
            string onlyWords = string.Empty;

            for (int i = 0; i < this.sentence.Length; i++)
            {
                if (this.sentence[i] == '[')
                {
                    i = this.changeSpeed( i );
                }
                else if (this.sentence[i] == '<')
                {
                    i = this.changeEffect( i );
                }
                else
                {
                    this.effects.Add( this.currentEffect );
                    if (this.sentence[i] != ' ')
                    {
                        this.speeds.Add( ( float )this.currentSpeed );
                    }
                    onlyWords += this.sentence[i];
                }
            }

            string[] words = onlyWords.Split( ' ' );
            int letterSpacing = ( int )( this.fontSize * 0.5 );
            int currentIndexEffects = 0;
            int currentIndexSpeeds = 0;
            foreach (string word in words)
            {
                GameObject wordObject = new GameObject( word, typeof( RectTransform ) );
                wordObject.transform.SetParent( this.Model.DialogueStartPoint );
                int wordSize = word.Length * letterSpacing;
                if (this.currentX + wordSize > this.boxSize)
                {
                    this.currentX = 0;
                    this.currentY -= ( int )( this.fontSize * 0.9 );
                }
                wordObject.GetComponent<RectTransform>().localPosition = new Vector3( currentX, currentY, 0 );

                for (int i = 0; i < word.Length; i++)
                {
                    GameObject letterObject = new GameObject( word[i].ToString() );
                    letterObject.transform.SetParent( wordObject.transform );
                    Text myText = letterObject.AddComponent<Text>();
                    myText.text = word[i].ToString();
                    myText.alignment = TextAnchor.LowerCenter;
                    myText.fontSize = this.fontSize;
                    myText.font = this.Model.Font;
                    myText.material = this.Model.Material;
                    myText.GetComponent<RectTransform>().localPosition = new Vector3( i * letterSpacing, 0, 0 );
                    myText.color = new Color( 0.0f, 0.0f, 0.0f, 0.0f );
                    RectTransform rt = letterObject.GetComponentInParent<RectTransform>();
                    rt.sizeDelta = new Vector2( this.fontSize, this.fontSize );
                    rt.pivot = new Vector2( 0, 1 );

                    LetterComponent letterComponent = letterObject.AddComponent<LetterComponent>();
                    
                    Letter newLetter = new Letter
                    {
                        Character = word[i],
                        Speed = this.speeds[currentIndexSpeeds],
                        isActive = false
                    };
                    if (this.effects[currentIndexEffects] != null)
                    {
                        newLetter.Effect = this.effects[currentIndexEffects].Build( letterObject );
                    }
                    letterComponent.Model = newLetter;
                    this.letters.Add( letterComponent );
                    currentIndexEffects++;
                    currentIndexSpeeds++;
                }
                currentX += wordSize + letterSpacing;
                currentIndexEffects++;
            }
            return true;
        }

19 Source : Formatter.Array1.List.cs
with MIT License
from 1996v

public List<Single> Deserialize(ref BssomReader reader, ref BssomDeserializeContext context)
        {
            if (reader.TryReadNullWithEnsureArray1BuildInType(BssomType.Float32Code))
            {
                return default;
            }

            context.Option.Security.DepthStep(ref context);
            reader.SkipVariableNumber();
            int len = reader.ReadVariableNumber();
            List<float> val = new List<Single>(len);
            for (int i = 0; i < len; i++)
            {
                val.Add(reader.ReadFloat32WithOutTypeHead());
            }
            context.Depth--;
            return val;
        }

19 Source : SlidingMaxTest.cs
with MIT License
from 39M

[Test]
    public void IsFunctional() {
      List<float> list = new List<float>();

      for (int i = 0; i < 1000; i++) {
        float newValue = Random.value;

        _slidingMax.AddValue(newValue);

        list.Add(newValue);
        while (list.Count > MAX_HISTORY) {
          list.RemoveAt(0);
        }

        float max = list[0];
        for (int j = 1; j < list.Count; j++) {
          max = Mathf.Max(max, list[j]);
        }

        replacedert.That(max, Is.EqualTo(_slidingMax.Max));
      }
    }

19 Source : Ball3DAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        state.Add(gameObject.transform.rotation.z);
        state.Add(gameObject.transform.rotation.x);
        state.Add((ball.transform.position.x - gameObject.transform.position.x));
        state.Add((ball.transform.position.y - gameObject.transform.position.y));
        state.Add((ball.transform.position.z - gameObject.transform.position.z));
        state.Add(ball.transform.GetComponent<Rigidbody>().velocity.x);
        state.Add(ball.transform.GetComponent<Rigidbody>().velocity.y);
        state.Add(ball.transform.GetComponent<Rigidbody>().velocity.z);
        return state;
    }

19 Source : PushAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
	{
		List<float> state = new List<float>();
        Vector3 velocity = GetComponent<Rigidbody>().velocity;
        Vector3 blockVelocity = block.GetComponent<Rigidbody>().velocity;
        state.Add((transform.position.x - area.transform.position.x));
        state.Add((transform.position.y - area.transform.position.y));
        state.Add((transform.position.z + 5 - area.transform.position.z));

        state.Add((goalHolder.transform.position.x - area.transform.position.x));
        state.Add((goalHolder.transform.position.y - area.transform.position.y));
        state.Add((goalHolder.transform.position.z + 5 - area.transform.position.z));

        state.Add((block.transform.position.x - area.transform.position.x));
        state.Add((block.transform.position.y - area.transform.position.y));
        state.Add((block.transform.position.z + 5 - area.transform.position.z));

		state.Add(velocity.x);
		state.Add(velocity.y);
		state.Add(velocity.z);

		state.Add(blockVelocity.x);
		state.Add(blockVelocity.y);
		state.Add(blockVelocity.z);

        state.Add(block.transform.localScale.x);
        state.Add(goalHolder.transform.localScale.x);

		return state;
	}

19 Source : WallAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
	{
		List<float> state = new List<float>();
        Vector3 velocity = GetComponent<Rigidbody>().velocity;
        state.Add((transform.position.x - area.transform.position.x));
        state.Add((transform.position.y - area.transform.position.y));
        state.Add((transform.position.z + 5 - area.transform.position.z));

        state.Add((goalHolder.transform.position.x - area.transform.position.x));
        state.Add((goalHolder.transform.position.y - area.transform.position.y));
        state.Add((goalHolder.transform.position.z + 5 - area.transform.position.z));

        state.Add((block.transform.position.x - area.transform.position.x));
        state.Add((block.transform.position.y - area.transform.position.y));
        state.Add((block.transform.position.z + 5 - area.transform.position.z));

		state.Add(wall.transform.localScale.y);

		state.Add(velocity.x);
		state.Add(velocity.y);
		state.Add(velocity.z);

        Vector3 blockVelocity = block.GetComponent<Rigidbody>().velocity;
		state.Add(blockVelocity.x);
		state.Add(blockVelocity.y);
		state.Add(blockVelocity.z);

		return state;
	}

19 Source : CrawlerAgentConfigurable.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        state.Add(body.transform.rotation.eulerAngles.x);
        state.Add(body.transform.rotation.eulerAngles.y);
        state.Add(body.transform.rotation.eulerAngles.z);

        state.Add(body.gameObject.GetComponent<Rigidbody>().velocity.x);
        state.Add(body.gameObject.GetComponent<Rigidbody>().velocity.y);
        state.Add(body.gameObject.GetComponent<Rigidbody>().velocity.z);

        state.Add((body.gameObject.GetComponent<Rigidbody>().velocity.x - past_velocity.x) / Time.fixedDeltaTime);
        state.Add((body.gameObject.GetComponent<Rigidbody>().velocity.y - past_velocity.y) / Time.fixedDeltaTime);
        state.Add((body.gameObject.GetComponent<Rigidbody>().velocity.z - past_velocity.z) / Time.fixedDeltaTime);
        past_velocity = body.gameObject.GetComponent<Rigidbody>().velocity;

        foreach (Transform t in limbs)
        {
            state.Add(t.localPosition.x);
            state.Add(t.localPosition.y);
            state.Add(t.localPosition.z);
            state.Add(t.localRotation.x);
            state.Add(t.localRotation.y);
            state.Add(t.localRotation.z);
            state.Add(t.localRotation.w);
            Rigidbody rb = t.gameObject.GetComponent < Rigidbody >();
            state.Add(rb.velocity.x);
            state.Add(rb.velocity.y);
            state.Add(rb.velocity.z);
            state.Add(rb.angularVelocity.x);
            state.Add(rb.angularVelocity.y);
            state.Add(rb.angularVelocity.z);
        }




        for (int index = 0; index < 4; index++)
        {
            if (leg_touching[index])
            {
                state.Add(1.0f);
            }
            else
            {
                state.Add(0.0f);
            }
            leg_touching[index] = false;
        }






        return state;
    }

19 Source : GridAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        int closestGoalDistance = 2 * (int)academy.resetParameters["gridSize"];
        GameObject currentClosestGoal = academy.actorObjs[0];
        int closestPitDistance = 2 * (int)academy.resetParameters["gridSize"];
        GameObject currentClosestPit = academy.actorObjs[0];
        GameObject agent = academy.actorObjs[0];
        List<float> state = new List<float>();
        foreach (GameObject actor in academy.actorObjs)
        {
            if (actor.tag == "agent")
            {
                agent = actor;
                state.Add(actor.transform.position.x / (gridSize + 1));
                state.Add(actor.transform.position.z / (gridSize + 1));
                continue;
            }
        }
        foreach (GameObject actor in academy.actorObjs)
        {
            if (actor.tag == "goal")
            {
                int distance = (int)Mathf.Abs(agent.transform.position.x - actor.transform.position.x) + (int)Mathf.Abs(agent.transform.position.z - actor.transform.position.z);
                if (closestGoalDistance > distance)
                {
                    closestGoalDistance = distance;
                    currentClosestGoal = actor;
                }
            }
            if (actor.tag == "pit")
            {
                int distance = (int)Mathf.Abs(agent.transform.position.x - actor.transform.position.x) + (int)Mathf.Abs(agent.transform.position.z - actor.transform.position.z);
                if (closestPitDistance > distance)
                {
                    closestPitDistance = distance;
                    currentClosestPit = actor;
                }
            }
        }

        state.Add(currentClosestGoal.transform.position.x / (gridSize + 1));
        state.Add(currentClosestGoal.transform.position.z / (gridSize + 1));
        state.Add(currentClosestPit.transform.position.x / (gridSize + 1));
        state.Add(currentClosestPit.transform.position.z / (gridSize + 1));

        return state;
    }

19 Source : CrossingAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();

        state.Add(transform.position.x);
        state.Add(transform.position.z);

        foreach(GameObject other in others)
        {
            state.Add(other.transform.position.x);
            state.Add(other.transform.position.z);
        }

        state.Add(myGoal.transform.position.x);
        state.Add(myGoal.transform.position.z);

        return state;
    }

19 Source : PedestriansAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();

        state.Add(transform.position.x);
        state.Add(transform.position.y);
        state.Add(transform.position.z);

        foreach (GameObject obstacle in obstacles)
        {
            state.Add(obstacle.transform.position.x);
            state.Add(obstacle.transform.position.y);
            state.Add(obstacle.transform.position.z);
        }

        state.Add(goal.transform.position.x);
        state.Add(goal.transform.position.y);
        state.Add(goal.transform.position.z);
        
        return state;
    }

19 Source : PPOLAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        state.Add(currentX);
        state.Add(currentZ);
        state.Add(targetX);
        state.Add(targetZ);
        return state;
    }

19 Source : ReacherAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
	{
		List<float> state = new List<float>();
        state.Add(pendulumA.transform.rotation.x);
        state.Add(pendulumA.transform.rotation.y);
        state.Add(pendulumA.transform.rotation.z);
        state.Add(pendulumA.transform.rotation.w);
        state.Add(rbA.angularVelocity.x);
        state.Add(rbA.angularVelocity.y);
        state.Add(rbA.angularVelocity.z);
        state.Add(rbA.velocity.x);
        state.Add(rbA.velocity.y);
        state.Add(rbA.velocity.z);

        state.Add(pendulumB.transform.rotation.x);
        state.Add(pendulumB.transform.rotation.y);
        state.Add(pendulumB.transform.rotation.z);
        state.Add(pendulumB.transform.rotation.w);
        state.Add(rbB.angularVelocity.x);
        state.Add(rbB.angularVelocity.y);
        state.Add(rbB.angularVelocity.z);
        state.Add(rbB.velocity.x);
        state.Add(rbB.velocity.y);
        state.Add(rbB.velocity.z);

        state.Add(goal.transform.position.x - transform.position.x);
        state.Add(goal.transform.position.y - transform.position.y);
        state.Add(goal.transform.position.z - transform.position.z);

        state.Add(hand.transform.position.x - transform.position.x);
        state.Add(hand.transform.position.y - transform.position.y);
        state.Add(hand.transform.position.z - transform.position.z);


		return state;
	}

19 Source : TennisAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        state.Add(invertMult * gameObject.transform.position.x);
        state.Add(gameObject.transform.position.y);
        state.Add(invertMult * gameObject.GetComponent<Rigidbody>().velocity.x);
        state.Add(gameObject.GetComponent<Rigidbody>().velocity.y);

        state.Add(invertMult * ball.transform.position.x);
        state.Add(ball.transform.position.y);
        state.Add(invertMult * ball.GetComponent<Rigidbody>().velocity.x);
        state.Add(ball.GetComponent<Rigidbody>().velocity.y);
        return state;
    }

19 Source : AreaAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        Vector3 velocity = GetComponent<Rigidbody>().velocity;

		state.Add((transform.position.x - area.transform.position.x));
		state.Add((transform.position.y - area.transform.position.y));
		state.Add((transform.position.z + 5 - area.transform.position.z));
		state.Add(velocity.x);
		state.Add(velocity.y);
		state.Add(velocity.z);
		return state;
	}

19 Source : ObstacleAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        state.Add(currentX);
        state.Add(currentZ);
        state.Add(obstacleX);
        state.Add(obstacleZ);
        state.Add(goalX);
        state.Add(goalZ);
        return state;
    }

19 Source : BasicAgent.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
	{
		List<float> state = new List<float>();
		state.Add(position);
		return state;
	}

19 Source : CrawlerAgentConfigurable.cs
with Apache License 2.0
from A7ocin

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        state.Add(body.transform.rotation.eulerAngles.x);
        state.Add(body.transform.rotation.eulerAngles.y);
        state.Add(body.transform.rotation.eulerAngles.z);

        state.Add(body.gameObject.GetComponent<Rigidbody>().velocity.x);
        state.Add(body.gameObject.GetComponent<Rigidbody>().velocity.y);
        state.Add(body.gameObject.GetComponent<Rigidbody>().velocity.z);

        state.Add((body.gameObject.GetComponent<Rigidbody>().velocity.x - past_velocity.x) / Time.fixedDeltaTime);
        state.Add((body.gameObject.GetComponent<Rigidbody>().velocity.y - past_velocity.y) / Time.fixedDeltaTime);
        state.Add((body.gameObject.GetComponent<Rigidbody>().velocity.z - past_velocity.z) / Time.fixedDeltaTime);
        past_velocity = body.gameObject.GetComponent<Rigidbody>().velocity;

        foreach (Transform t in limbs)
        {
            state.Add(t.localPosition.x);
            state.Add(t.localPosition.y);
            state.Add(t.localPosition.z);
            state.Add(t.localRotation.x);
            state.Add(t.localRotation.y);
            state.Add(t.localRotation.z);
            state.Add(t.localRotation.w);
            Rigidbody rb = t.gameObject.GetComponent < Rigidbody >();
            state.Add(rb.velocity.x);
            state.Add(rb.velocity.y);
            state.Add(rb.velocity.z);
            state.Add(rb.angularVelocity.x);
            state.Add(rb.angularVelocity.y);
            state.Add(rb.angularVelocity.z);
        }




        for (int index = 0; index < 4; index++)
        {
            if (leg_touching[index])
            {
                state.Add(1.0f);
            }
            else
            {
                state.Add(0.0f);
            }
            leg_touching[index] = false;
        }






        return state;
    }

19 Source : ExternalCommunicator.cs
with Apache License 2.0
from A7ocin

public void giveBrainInfo(Brain brain)
    {
        string brainName = brain.gameObject.name;
        current_agents[brainName] = new List<int>(brain.agents.Keys);
        List<float> concatenatedStates = new List<float>();
        List<float> concatenatedRewards = new List<float>();
        List<float> concatenatedMemories = new List<float>();
        List<bool> concatenatedDones = new List<bool>();
        List<float> concatenatedActions = new List<float>();
        Dictionary<int, List<Camera>> collectedObservations = brain.CollectObservations();
        Dictionary<int, List<float>> collectedStates = brain.CollectStates();
        Dictionary<int, float> collectedRewards = brain.CollectRewards();
        Dictionary<int, float[]> collectedMemories = brain.CollectMemories();
        Dictionary<int, bool> collectedDones = brain.CollectDones();
        Dictionary<int, float[]> collectedActions = brain.CollectActions();

        foreach (int id in current_agents[brainName])
        {
            concatenatedStates = concatenatedStates.Concat(collectedStates[id]).ToList();
            concatenatedRewards.Add(collectedRewards[id]);
            concatenatedMemories = concatenatedMemories.Concat(collectedMemories[id].ToList()).ToList();
            concatenatedDones.Add(collectedDones[id]);
            concatenatedActions = concatenatedActions.Concat(collectedActions[id].ToList()).ToList();
        }
        StepMessage message = new StepMessage()
        {
            brain_name = brainName,
            agents = current_agents[brainName],
            states = concatenatedStates,
            rewards = concatenatedRewards,
            actions = concatenatedActions,
            memories = concatenatedMemories,
            dones = concatenatedDones
        };
        string envMessage = JsonConvert.SerializeObject(message, Formatting.Indented);
        sender.Send(AppendLength(Encoding.ASCII.GetBytes(envMessage)));
        Receive();
        int i = 0;
        foreach (resolution res in brain.brainParameters.cameraResolutions)
        {
            foreach (int id in current_agents[brainName])
            {
                sender.Send(AppendLength(TexToByteArray(brain.ObservationToTex(collectedObservations[id][i], res.width, res.height))));
                Receive();
            }
            i++;
        }

        hreplacedentState[brainName] = true;

        if (hreplacedentState.Values.All(x => x))
        {
            // if all the brains listed have sent their state
            sender.Send(Encoding.ASCII.GetBytes((academy.done ? "True" : "False")));
            List<string> brainNames = hreplacedentState.Keys.ToList();
            foreach (string k in brainNames)
            {
                hreplacedentState[k] = false;
            }
        }

    }

19 Source : SmoothMouseLook.cs
with Apache License 2.0
from A7ocin

void Update ()
		{
			if (axes == RotationAxes.MouseXAndY)
			{			
				rotAverageY = 0f;
				rotAverageX = 0f;
				
				rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
				rotationX += Input.GetAxis("Mouse X") * sensitivityX;
				
				rotArrayY.Add(rotationY);
				rotArrayX.Add(rotationX);
				
				if (rotArrayY.Count >= frameCounter) {
					rotArrayY.RemoveAt(0);
				}
				if (rotArrayX.Count >= frameCounter) {
					rotArrayX.RemoveAt(0);
				}
				
				for(int j = 0; j < rotArrayY.Count; j++) {
					rotAverageY += rotArrayY[j];
				}
				for(int i = 0; i < rotArrayX.Count; i++) {
					rotAverageX += rotArrayX[i];
				}
				
				rotAverageY /= rotArrayY.Count;
				rotAverageX /= rotArrayX.Count;
				 
				rotAverageY = ClampAngle (rotAverageY, minimumY, maximumY);
				rotAverageX = ClampAngle (rotAverageX, minimumX, maximumX);
				
				Quaternion yQuaternion = Quaternion.AngleAxis (rotAverageY, Vector3.left);
				Quaternion xQuaternion = Quaternion.AngleAxis (rotAverageX, Vector3.up);
				
				// alter camera pitch
				transform.localRotation = originalRotation * yQuaternion;
				// alter parent facing
				transform.parent.localRotation = parentRotation * xQuaternion;
			}
			else if (axes == RotationAxes.MouseX)
			{			
				rotAverageX = 0f;
				
				rotationX += Input.GetAxis("Mouse X") * sensitivityX;
				
				rotArrayX.Add(rotationX);
				
				if (rotArrayX.Count >= frameCounter) {
					rotArrayX.RemoveAt(0);
				}
				for(int i = 0; i < rotArrayX.Count; i++) {
					rotAverageX += rotArrayX[i];
				}
				rotAverageX /= rotArrayX.Count;
				 
					rotAverageX = ClampAngle (rotAverageX, minimumX, maximumX);
				
				Quaternion xQuaternion = Quaternion.AngleAxis (rotAverageX, Vector3.up);
				transform.parent.localRotation = parentRotation * xQuaternion;		
			}
			else
			{			
				rotAverageY = 0f;
				
				rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
				
				rotArrayY.Add(rotationY);
				
				if (rotArrayY.Count >= frameCounter) {
					rotArrayY.RemoveAt(0);
				}
				for(int j = 0; j < rotArrayY.Count; j++) {
					rotAverageY += rotArrayY[j];
				}
				rotAverageY /= rotArrayY.Count;
				 
					rotAverageY = ClampAngle (rotAverageY, minimumY, maximumY);
				
				Quaternion yQuaternion = Quaternion.AngleAxis (rotAverageY, Vector3.left);
				transform.localRotation = originalRotation * yQuaternion;
			}
		}

19 Source : StripMeshLineRenderer.cs
with Apache License 2.0
from abist-co-ltd

protected override void UpdateLine()
        {
            if (stripMeshRenderer == null)
            {
                Debug.LogError("Strip mesh renderer has been destroyed - disabling");
                enabled = false;
            }

            if (!LineDataSource.enabled)
            {
                stripMeshRenderer.enabled = false;
                return;
            }

            stripMeshRenderer.enabled = true;
            positions.Clear();
            forwards.Clear();
            colors.Clear();
            widths.Clear();
            
            for (int i = 0; i <= LineStepCount; i++)
            {
                float normalizedDistance = GetNormalizedPointAlongLine(i);
                positions.Add(LineDataSource.GetPoint(normalizedDistance));
                colors.Add(GetColor(normalizedDistance));
                widths.Add(GetWidth(normalizedDistance));
                forwards.Add(LineDataSource.GetVelocity(normalizedDistance));
            }

            GenerateStripMesh(positions, colors, widths, uvOffset, forwards, stripMesh, LineDataSource.LineTransform.up);
        }

19 Source : OvrAvatarPacket.cs
with MIT License
from absurd-joy

public void AddFrame(OvrAvatarDriver.PoseFrame frame, float deltaSeconds)
    {
        frameTimes.Add(Duration + deltaSeconds);
        frames.Add(frame);
    }

19 Source : OvrAvatarPacket.cs
with MIT License
from absurd-joy

public static OvrAvatarPacket Read(Stream stream)
    {
        BinaryReader reader = new BinaryReader(stream);

        // Todo: bounds check frame count
        int frameCount = reader.ReadInt32();
        List<float> frameTimes = new List<float>(frameCount);
        for (int i = 0; i < frameCount; ++i)
        {
            frameTimes.Add(reader.ReadSingle());
        }
        List<OvrAvatarDriver.PoseFrame> frames = new List<OvrAvatarDriver.PoseFrame>(frameCount);
        for (int i = 0; i < frameCount; ++i)
        {
            frames.Add(reader.ReadPoseFrame());
        }

        // Todo: bounds check audio packet count
        int audioPacketCount = reader.ReadInt32();
        List<byte[]> audioPackets = new List<byte[]>(audioPacketCount);
        for (int i = 0; i < audioPacketCount; ++i)
        {
            int audioPacketSize = reader.ReadInt32();
            byte[] audioPacket = reader.ReadBytes(audioPacketSize);
            audioPackets.Add(audioPacket);
        }

        return new OvrAvatarPacket(frameTimes, frames, audioPackets);
    }

19 Source : P2PManager.cs
with MIT License
from absurd-joy

void ReadTimeSyncMessage(ulong remoteID, byte[] msg)
		{
			if (!m_remoteSentTimeCache.ContainsKey(remoteID))
			{
				SendTimeSyncMessage(remoteID);
				return;
			}

			int offset = 1;
			float remoteTime = UnpackFloat(msg, ref offset);
			float now = Time.realtimeSinceStartup;
			float latency = (now - m_remoteSentTimeCache[remoteID]) / 2;
			float remoteTimeOffset = now - (remoteTime + latency);

			m_remoteSyncTimeCache[remoteID].Add(remoteTimeOffset);

			if (m_remoteSyncTimeCache[remoteID].Count < TIME_SYNC_MESSAGE_COUNT)
			{
				SendTimeSyncMessage(remoteID);
			}
			else
			{
				if (PlatformManager.MyID < remoteID)
				{
					// this client started the sync, need to send one last message to
					// the remote so they can finish their sync calculation
					SendTimeSyncMessage(remoteID);
				}

				// sort the times and remember the median
				m_remoteSyncTimeCache[remoteID].Sort();
				float median = m_remoteSyncTimeCache[remoteID][TIME_SYNC_MESSAGE_COUNT/2];

				// calucate the mean and standard deviation
				double mean = 0;
				foreach (var time in m_remoteSyncTimeCache[remoteID])
				{
					mean += time;
				}
				mean /= TIME_SYNC_MESSAGE_COUNT;

				double std_dev = 0;
				foreach (var time in m_remoteSyncTimeCache[remoteID])
				{
					std_dev += (mean-time)*(mean-time);
				}
				std_dev = Math.Sqrt(std_dev)/TIME_SYNC_MESSAGE_COUNT;

				// time delta is the mean of the values less than 1 standard deviation from the median
				mean = 0;
				int meanCount = 0;
				foreach (var time in m_remoteSyncTimeCache[remoteID])
				{
					if (Math.Abs(time-median) < std_dev)
					{
						mean += time;
						meanCount++;
					}
				}
				mean /= meanCount;
				Debug.LogFormat("Time offset to {0} is {1}", remoteID, mean);

				m_remoteSyncTimeCache.Remove(remoteID);
				m_remoteSentTimeCache.Remove(remoteID);
				m_remotePlayers[remoteID].remoteTimeOffset = (float)mean;

				// now that times are synchronized, lets try to coordinate the
				// start time for the match
				OfferMatchStartTime();
			}
		}

19 Source : LandDefs.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void Unpack(BinaryReader reader)
        {
            NumBlockLength  = reader.ReadInt32();
            NumBlockWidth   = reader.ReadInt32();
            SquareLength    = reader.ReadSingle();
            LBlockLength    = reader.ReadInt32();
            VertexPerCell   = reader.ReadInt32();
            MaxObjHeight    = reader.ReadSingle();
            SkyHeight       = reader.ReadSingle();
            RoadWidth       = reader.ReadSingle();

            for (int i = 0; i < 256; i++)
                LandHeightTable.Add(reader.ReadSingle());
        }

19 Source : Monster_Magic.cs
with GNU Affero General Public License v3.0
from ACEmulator

private float GetProbabilityAny()
        {
            var probabilities = new List<float>();

            foreach (var spell in Biota.GetKnownSpellsProbabilities(BiotaDatabaseLock))
            {
                var probability = spell > 2.0f ? spell - 2.0f : spell / 100.0f;

                probabilities.Add(probability);
            }

            return Probability.GetProbabilityAny(probabilities);
        }

19 Source : Coroutines.cs
with MIT License
from adrenak

public CoroutineHandle Run(float delay, IEnumerator routine) {
            running.Add(routine);
            delays.Add(delay);
            return new CoroutineHandle(this, routine);
        }

19 Source : PickupItemSyncer.cs
with GNU General Public License v3.0
from aelariane

private void SendPickedUpItems(PhotonPlayer targtePlayer)
    {
        if (targtePlayer == null)
        {
            Debug.LogWarning("Cant send PickupItem spawn times to unknown targetPlayer.");
            return;
        }
        double time = PhotonNetwork.time;
        double num = time + 0.20000000298023224;
        PickupItem[] array = new PickupItem[PickupItem.DisabledPickupItems.Count];
        PickupItem.DisabledPickupItems.CopyTo(array);
        List<float> list = new List<float>(array.Length * 2);
        foreach (PickupItem pickupItem in array)
        {
            if (pickupItem.SecondsBeforeRespawn <= 0f)
            {
                list.Add((float)pickupItem.ViewID);
                list.Add(0f);
            }
            else
            {
                double num2 = pickupItem.TimeOfRespawn - PhotonNetwork.time;
                if (pickupItem.TimeOfRespawn > num)
                {
                    Debug.Log(string.Concat(new object[]
                    {
                        pickupItem.ViewID,
                        " respawn: ",
                        pickupItem.TimeOfRespawn,
                        " timeUntilRespawn: ",
                        num2,
                        " (now: ",
                        PhotonNetwork.time,
                        ")"
                    }));
                    list.Add((float)pickupItem.ViewID);
                    list.Add((float)num2);
                }
            }
        }
        Debug.Log(string.Concat(new object[]
        {
            "Sent count: ",
            list.Count,
            " now: ",
            time
        }));
        BasePV.RPC("PickupItemInit", targtePlayer, new object[]
        {
            PhotonNetwork.time,
            list.ToArray()
        });
    }

19 Source : RoadGenerator.cs
with Apache License 2.0
from Aggrathon

public void AddNode(Vector3 node, float strength)
		{
			if(roadNodes == null)
			{
				roadNodes = new List<Vector3>();
				roadNodes.Add(node);
				strengths = new List<float>();
				strengths.Add(strength);
			}
			else
			{
				for (int i = 0; i < roadNodes.Count; i++)
				{
					if(roadNodes[i] == node)
					{
						if (strengths[i] < strength)
							strengths[i] = strength;
						return;
					}
				}
				roadNodes.Add(node);
				strengths.Add(strength);
			}
		}

19 Source : NNet.cs
with MIT License
from AJTech2002

public void Initialise (int hiddenLayerCount, int hiddenNeuronCount)
    {

        inputLayer.Clear();
        hiddenLayers.Clear();
        outputLayer.Clear();
        weights.Clear();
        biases.Clear();

        for (int i = 0; i < hiddenLayerCount + 1; i++)
        {

            Matrix<float> f = Matrix<float>.Build.Dense(1, hiddenNeuronCount);

            hiddenLayers.Add(f);

            biases.Add(Random.Range(-1f, 1f));

            //WEIGHTS
            if (i == 0)
            {
                Matrix<float> inputToH1 = Matrix<float>.Build.Dense(3, hiddenNeuronCount);
                weights.Add(inputToH1);
            }

            Matrix<float> HiddenToHidden = Matrix<float>.Build.Dense(hiddenNeuronCount, hiddenNeuronCount);
            weights.Add(HiddenToHidden);

        }

        Matrix<float> OutputWeight = Matrix<float>.Build.Dense(hiddenNeuronCount, 2);
        weights.Add(OutputWeight);
        biases.Add(Random.Range(-1f, 1f));

        RandomiseWeights();

    }

19 Source : DebugViewXNA.cs
with MIT License
from Alan-FGR

private void DrawPerformanceGraph()
        {
            _graphValues.Add(World.UpdateTime / TimeSpan.TicksPerMillisecond);

            if (_graphValues.Count > ValuesToGraph + 1)
                _graphValues.RemoveAt(0);

            float x = PerformancePanelBounds.X;
            float deltaX = PerformancePanelBounds.Width / (float)ValuesToGraph;
            float yScale = PerformancePanelBounds.Bottom - (float)PerformancePanelBounds.Top;

            // we must have at least 2 values to start rendering
            if (_graphValues.Count > 2)
            {
                _max = _graphValues.Max();
                _avg = _graphValues.Average();
                _min = _graphValues.Min();

                if (AdaptiveLimits)
                {
                    MaximumValue = _max;
                    MinimumValue = 0;
                }

                // start at last value (newest value added)
                // continue until no values are left
                for (int i = _graphValues.Count - 1; i > 0; i--)
                {
                    float y1 = PerformancePanelBounds.Bottom - ((_graphValues[i] / (MaximumValue - MinimumValue)) * yScale);
                    float y2 = PerformancePanelBounds.Bottom - ((_graphValues[i - 1] / (MaximumValue - MinimumValue)) * yScale);

                    Vector2 x1 = new Vector2(MathHelper.Clamp(x, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y1, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));
                    Vector2 x2 = new Vector2(MathHelper.Clamp(x + deltaX, PerformancePanelBounds.Left, PerformancePanelBounds.Right), MathHelper.Clamp(y2, PerformancePanelBounds.Top, PerformancePanelBounds.Bottom));

                    DrawSegment(x1, x2, Color.LightGreen);

                    x += deltaX;
                }
            }

            DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Top, string.Format("Max: {0} ms", _max));
            DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Center.Y - 7, string.Format("Avg: {0} ms", _avg));
            DrawString(PerformancePanelBounds.Right + 10, PerformancePanelBounds.Bottom - 15, string.Format("Min: {0} ms", _min));

            //Draw background.
            _background[0] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y);
            _background[1] = new Vector2(PerformancePanelBounds.X, PerformancePanelBounds.Y + PerformancePanelBounds.Height);
            _background[2] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y + PerformancePanelBounds.Height);
            _background[3] = new Vector2(PerformancePanelBounds.X + PerformancePanelBounds.Width, PerformancePanelBounds.Y);

            DrawSolidPolygon(_background, 4, Color.DarkGray, true);
        }

19 Source : YuPengClipper.cs
with MIT License
from Alan-FGR

private static void CalculateSimplicalChain(Vertices poly, out List<float> coeff,
                                                out List<Edge> simplicies)
    {
      simplicies = new List<Edge>();
      coeff = new List<float>();
      for (int i = 0; i < poly.Count; ++i)
      {
        simplicies.Add(new Edge(poly[i], poly[poly.NextIndex(i)]));
        coeff.Add(CalculateSimplexCoefficient(Vector2.Zero, poly[i], poly[poly.NextIndex(i)]));
      }
    }

19 Source : Program.cs
with MIT License
from Alan-FGR

static void Measure<T>(string text, bool warmup, Func<T> func)
    {
        if (warmup)
        {
            Console.WriteLine($"Warming up... ");
            func.Invoke();
            return;
        }

        Console.Write($"Measuring... ");

        sw_.Restart();
        T r = func.Invoke();
        float elapsedMicroseconds = sw_.ElapsedMicroseconds();

        if (!results_.ContainsKey(text))
            results_[text] = new List<float>();
        results_[text].Add(elapsedMicroseconds);

        Console.WriteLine($"it took {elapsedMicroseconds.ToString("f0").PadLeft(5)} µs to {text}. Result: {r}");
    }

19 Source : TextureConverter.cs
with MIT License
from Alan-FGR

private List<float> SearchCrossingEdges(Vertices polygon, int y)
        {
            // sick-o-note:
            // Used to search the x coordinates of edges in the polygon for a specific y coordinate.
            // (Usualy comming from the texture data, that's why it's an int and not a float.)

            List<float> edges = new List<float>();

            // current edge
            Vector2 slope;
            Vector2 vertex1;    // i
            Vector2 vertex2;    // i - 1

            // next edge
            Vector2 nextSlope;
            Vector2 nextVertex; // i + 1

            bool addFind;

            if (polygon.Count > 2)
            {
                // There is a gap between the last and the first vertex in the vertex list.
                // We will bridge that by setting the last vertex (vertex2) to the last 
                // vertex in the list.
                vertex2 = polygon[polygon.Count - 1];

                // We are moving along the polygon edges.
                for (int i = 0; i < polygon.Count; i++)
                {
                    vertex1 = polygon[i];

                    // Approx. check if the edge crosses our y coord.
                    if ((vertex1.Y >= y && vertex2.Y <= y) ||
                        (vertex1.Y <= y && vertex2.Y >= y))
                    {
                        // Ignore edges that are parallel to y.
                        if (vertex1.Y != vertex2.Y)
                        {
                            addFind = true;
                            slope = vertex2 - vertex1;

                            // Special threatment for edges that end at the y coord.
                            if (vertex1.Y == y)
                            {
                                // Create preview of the next edge.
                                nextVertex = polygon[(i + 1) % polygon.Count];
                                nextSlope = vertex1 - nextVertex;

                                // Ignore peaks. 
                                // If thwo edges are aligned like this: /\ and the y coordinate lies on the top,
                                // then we get the same x coord twice and we don't need that.
                                if (slope.Y > 0)
                                    addFind = (nextSlope.Y <= 0);
                                else
                                    addFind = (nextSlope.Y >= 0);
                            }

                            if (addFind)
                                edges.Add((y - vertex1.Y) / slope.Y * slope.X + vertex1.X); // Calculate and add the x coord.
                        }
                    }

                    // vertex1 becomes vertex2 :).
                    vertex2 = vertex1;
                }
            }

            edges.Sort();
            return edges;
        }

19 Source : SlugAgent.cs
with MIT License
from AleCamara

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        state.Add(bodyA.position.x - bodyC.position.x);
        state.Add(bodyB.position.x - bodyC.position.x);
        float velocity = (bodyC.position.x - _previousPositionC) / Time.fixedDeltaTime;
        state.Add(velocity);
        float acceleration = (velocity - _previousVelocityC) / Time.fixedDeltaTime;
        state.Add(acceleration);

        _previousPositionC = bodyC.position.x;
        _previousVelocityC = velocity;

        return state;
    }

19 Source : SlugAgent.cs
with MIT License
from AleCamara

public override List<float> CollectState()
    {
        List<float> state = new List<float>();
        state.Add(bodyA.position.x - bodyC.position.x);
        state.Add(bodyB.position.x - bodyC.position.x);
        float velocity = (bodyC.position.x - _previousPositionC) / Time.fixedDeltaTime;
        state.Add(velocity);
        float acceleration = (velocity - _previousVelocityC) / Time.fixedDeltaTime;
        state.Add(acceleration);

        _previousPositionC = bodyC.position.x;
        _previousVelocityC = velocity;

        return state;
    }

19 Source : Earcut.cs
with MIT License
from alen-smajic

public static Data Flatten(List<List<Vector3>> data)
		{
			var dataCount = data.Count;
			var totalVertCount = 0;
			for (int i = 0; i < dataCount; i++)
			{
				totalVertCount += data[i].Count;
			}

			var result = new Data() { Dim = 2 };
			result.Vertices = new List<float>(totalVertCount * 2);
			var holeIndex = 0;

			for (var i = 0; i < dataCount; i++)
			{
				var subCount = data[i].Count;
				for (var j = 0; j < subCount; j++)
				{
					result.Vertices.Add(data[i][j][0]);
					result.Vertices.Add(data[i][j][2]);
				}
				if (i > 0)
				{
					holeIndex += data[i - 1].Count;
					result.Holes.Add(holeIndex);
				}
			}
			return result;
		}

19 Source : OctoMap.cs
with MIT License
from Alexander-Scott

private void GatherOctoMapNodes(List<Vector3> positions, List<float> sizes, float currentNodeSize,
            Vector3 currentNodeCentre,
            uint currentNodeId)
        {
            OctoMapNode currentNode = _nodes[currentNodeId];
            if (CheckNodeOccupied(currentNode))
            {
                positions.Add(currentNodeCentre);
                sizes.Add(currentNodeSize);
            }

            if (currentNode.ChildArrayId != null)
            {
                for (int i = 0; i < 8; i++)
                {
                    uint childId = _nodeChildren[currentNode.ChildArrayId.Value][i];
                    float newNodeSize = currentNodeSize / 2;
                    Vector3 newNodeCentre = GetBestFitChildNodeCentre(i, newNodeSize, currentNodeCentre);
                    GatherOctoMapNodes(positions, sizes, newNodeSize, newNodeCentre, childId);
                }
            }
        }

19 Source : VertexZoom.cs
with MIT License
from AlexLemminG

IEnumerator AnimateVertexColors()
        {

            // We force an update of the text object since it would only be updated at the end of the frame. Ie. before this code is executed on the first frame.
            // Alternatively, we could yield and wait until the end of the frame when the text object will be generated.
            m_TextComponent.ForceMeshUpdate();

            TMP_TextInfo textInfo = m_TextComponent.textInfo;

            Matrix4x4 matrix;
            TMP_MeshInfo[] cachedMeshInfoVertexData = textInfo.CopyMeshInfoVertexData();

            // Allocations for sorting of the modified scales
            List<float> modifiedCharScale = new List<float>();
            List<int> scaleSortingOrder = new List<int>();

            hasTextChanged = true;

            while (true)
            {
                // Allocate new vertices 
                if (hasTextChanged)
                {
                    // Get updated vertex data
                    cachedMeshInfoVertexData = textInfo.CopyMeshInfoVertexData();

                    hasTextChanged = false;
                }

                int characterCount = textInfo.characterCount;

                // If No Characters then just yield and wait for some text to be added
                if (characterCount == 0)
                {
                    yield return new WaitForSeconds(0.25f);
                    continue;
                }

                // Clear list of character scales
                modifiedCharScale.Clear();
                scaleSortingOrder.Clear();

                for (int i = 0; i < characterCount; i++)
                {
                    TMP_CharacterInfo charInfo = textInfo.characterInfo[i];

                    // Skip characters that are not visible and thus have no geometry to manipulate.
                    if (!charInfo.isVisible)
                        continue;

                    // Get the index of the material used by the current character.
                    int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;

                    // Get the index of the first vertex used by this text element.
                    int vertexIndex = textInfo.characterInfo[i].vertexIndex;

                    // Get the cached vertices of the mesh used by this text element (character or sprite).
                    Vector3[] sourceVertices = cachedMeshInfoVertexData[materialIndex].vertices;

                    // Determine the center point of each character at the baseline.
                    //Vector2 charMidBasline = new Vector2((sourceVertices[vertexIndex + 0].x + sourceVertices[vertexIndex + 2].x) / 2, charInfo.baseLine);
                    // Determine the center point of each character.
                    Vector2 charMidBasline = (sourceVertices[vertexIndex + 0] + sourceVertices[vertexIndex + 2]) / 2;

                    // Need to translate all 4 vertices of each quad to aligned with middle of character / baseline.
                    // This is needed so the matrix TRS is applied at the origin for each character.
                    Vector3 offset = charMidBasline;

                    Vector3[] destinationVertices = textInfo.meshInfo[materialIndex].vertices;

                    destinationVertices[vertexIndex + 0] = sourceVertices[vertexIndex + 0] - offset;
                    destinationVertices[vertexIndex + 1] = sourceVertices[vertexIndex + 1] - offset;
                    destinationVertices[vertexIndex + 2] = sourceVertices[vertexIndex + 2] - offset;
                    destinationVertices[vertexIndex + 3] = sourceVertices[vertexIndex + 3] - offset;

                    //Vector3 jitterOffset = new Vector3(Random.Range(-.25f, .25f), Random.Range(-.25f, .25f), 0);

                    // Determine the random scale change for each character.
                    float randomScale = Random.Range(1f, 1.5f);
                    
                    // Add modified scale and index
                    modifiedCharScale.Add(randomScale);
                    scaleSortingOrder.Add(modifiedCharScale.Count - 1);

                    // Setup the matrix for the scale change.
                    //matrix = Matrix4x4.TRS(jitterOffset, Quaternion.Euler(0, 0, Random.Range(-5f, 5f)), Vector3.one * randomScale);
                    matrix = Matrix4x4.TRS(new Vector3(0, 0, 0), Quaternion.idenreplacedy, Vector3.one * randomScale);

                    destinationVertices[vertexIndex + 0] = matrix.MultiplyPoint3x4(destinationVertices[vertexIndex + 0]);
                    destinationVertices[vertexIndex + 1] = matrix.MultiplyPoint3x4(destinationVertices[vertexIndex + 1]);
                    destinationVertices[vertexIndex + 2] = matrix.MultiplyPoint3x4(destinationVertices[vertexIndex + 2]);
                    destinationVertices[vertexIndex + 3] = matrix.MultiplyPoint3x4(destinationVertices[vertexIndex + 3]);

                    destinationVertices[vertexIndex + 0] += offset;
                    destinationVertices[vertexIndex + 1] += offset;
                    destinationVertices[vertexIndex + 2] += offset;
                    destinationVertices[vertexIndex + 3] += offset;

                    // Restore Source UVS which have been modified by the sorting
                    Vector2[] sourceUVs0 = cachedMeshInfoVertexData[materialIndex].uvs0;
                    Vector2[] destinationUVs0 = textInfo.meshInfo[materialIndex].uvs0;

                    destinationUVs0[vertexIndex + 0] = sourceUVs0[vertexIndex + 0];
                    destinationUVs0[vertexIndex + 1] = sourceUVs0[vertexIndex + 1];
                    destinationUVs0[vertexIndex + 2] = sourceUVs0[vertexIndex + 2];
                    destinationUVs0[vertexIndex + 3] = sourceUVs0[vertexIndex + 3];

                    // Restore Source Vertex Colors
                    Color32[] sourceColors32 = cachedMeshInfoVertexData[materialIndex].colors32;
                    Color32[] destinationColors32 = textInfo.meshInfo[materialIndex].colors32;

                    destinationColors32[vertexIndex + 0] = sourceColors32[vertexIndex + 0];
                    destinationColors32[vertexIndex + 1] = sourceColors32[vertexIndex + 1];
                    destinationColors32[vertexIndex + 2] = sourceColors32[vertexIndex + 2];
                    destinationColors32[vertexIndex + 3] = sourceColors32[vertexIndex + 3];
                }

                // Push changes into meshes
                for (int i = 0; i < textInfo.meshInfo.Length; i++)
                {
                    //// Sort Quads based modified scale
                    scaleSortingOrder.Sort((a, b) => modifiedCharScale[a].CompareTo(modifiedCharScale[b]));

                    textInfo.meshInfo[i].SortGeometry(scaleSortingOrder);

                    // Updated modified vertex attributes
                    textInfo.meshInfo[i].mesh.vertices = textInfo.meshInfo[i].vertices;
                    textInfo.meshInfo[i].mesh.uv = textInfo.meshInfo[i].uvs0;
                    textInfo.meshInfo[i].mesh.colors32 = textInfo.meshInfo[i].colors32;

                    m_TextComponent.UpdateGeometry(textInfo.meshInfo[i].mesh, i);
                }

                yield return new WaitForSeconds(0.1f);
            }
        }

19 Source : PointCurve.cs
with Apache License 2.0
from Algoryx

public bool Finalize()
    {
      m_time.Clear();

      var totalLength = TotalLength;
      if ( totalLength <= 0.0f )
        return false;

      m_time.Capacity = m_points.Count;
      var acreplacedulatedTime = 0.0f;
      m_time.Add( acreplacedulatedTime );
      for ( int i = 1; i < m_points.Count; ++i ) {
        acreplacedulatedTime += Vector3.Distance( m_points[ i - 1 ], m_points[ i ] ) / totalLength;
        m_time.Add( acreplacedulatedTime );
      }
      m_time[ m_points.Count - 1 ] = 1.0f;

      return true;
    }

19 Source : VisualizationHeatmapCSV.cs
with Apache License 2.0
from allenai

void Start() {
        string[] data = CSVFile.text.Split(new char[] { '\n' });
        float x, z, r;

        for (int i = 1; i < data.Length - 1; i++) {
            string[] row = data[i].Split(new char[] { ',' });

            float.TryParse(row[0], out x);
            xvalues.Add(x);

            float.TryParse(row[1], out z);
            zvalues.Add(z);

            float.TryParse(row[2], out r);
            rotationvalues.Add(r);
        }

        for (int i = 0; i < xvalues.Count; i++) {
            Vector3 pos = new Vector3(xvalues[i], 1, zvalues[i]);
            Vector3 rot = new Vector3(0, rotationvalues[i], 0);

            // just spawn the Heavy prefab for now since it is the most visible
            Instantiate(prefabHeavy, pos, Quaternion.Euler(rot));
        }
    }

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

void evaluate_naive_method(float[][] float_data) {
      var gi = create_generators(float_data);
      var batch_maes = new List<float>();
      var val_enumerator = gi.val_gen.GetEnumerator();

      for (int i = 0; i < gi.val_steps; i++) {
        if (val_enumerator.MoveNext() == false) { break; }
        var st = val_enumerator.Current;
        var num_samples_in_batch = st.num_strides * float_data[0].Length;
        var offset = (st.num_strides - 1) * float_data[0].Length + 1;
        var preds = Enumerable.Range(0, gi.batch_size).Select(x => st.samples[x * num_samples_in_batch + offset]);
        var mae = preds.Zip(st.targets, (l, n) => Math.Abs(l - n)).Average();
        batch_maes.Add(mae);
      }
      var mean_batch_maes = batch_maes.Average();
      Console.WriteLine(mean_batch_maes);
    }

19 Source : Program.cs
with MIT License
from anastasios-stamoulis

void load_text_labels(string path, List<string> texts, List<float> labels) {
      var label_types = new string[] { "neg", "pos" };
      foreach(var label_type in label_types) {
        var dir_name = System.IO.Path.Combine(path, label_type);
        foreach(var fname in System.IO.Directory.GetFiles(dir_name)) {
          if (fname.EndsWith(".txt")) {
            texts.Add(System.IO.File.ReadAllText(System.IO.Path.Combine(dir_name, fname), Encoding.UTF8));
            labels.Add((label_type == "neg") ? 0 : 1);
          }
        }
      }
    }

19 Source : HubListener.cs
with MIT License
from andruzzzhka

private static void HubLoop(object sender, HighResolutionTimerElapsedEventArgs e)
        {
            if(_ticksLength.Count > 30)
            {
                _ticksLength.RemoveAt(0);
            }
            _ticksLength.Add(DateTime.UtcNow.Subtract(_lastTick).Ticks/(float)TimeSpan.TicksPerMillisecond);
            _lastTick = DateTime.UtcNow;

            if (Settings.Instance.Server.ShowWindowreplacedle)
            {
                List<RoomInfo> roomsList = RoomsController.GetRoomInfosList();

                string replacedleBuffer = $"ServerHub v{replacedembly.GetEntryreplacedembly().GetName().Version}: {roomsList.Count} rooms, {hubClients.Count} clients in lobby, {roomsList.Select(x => x.players).Sum() + hubClients.Count} clients total {(Settings.Instance.Server.ShowTickrateInreplacedle ? $", {Tickrate.ToString("0.0")} tickrate" : "")}";

                if (_currentreplacedle != replacedleBuffer)
                {
                    _currentreplacedle = replacedleBuffer;
                    Console.replacedle = _currentreplacedle;
                }
            }

            List<Client> allClients = hubClients.Concat(RoomsController.GetRoomsList().SelectMany(x => x.roomClients)).Concat(RadioController.radioChannels.SelectMany(x => x.radioClients)).ToList();

            while (ListenerServer != null && ListenerServer.ReadMessage(out NetIncomingMessage msg))
            {
                try
                {
                    Program.networkBytesInNow += msg.LengthBytes;

                    switch (msg.MessageType)
                    {

                        case NetIncomingMessageType.ConnectionApproval:
                            {
                                byte[] versionBytes = msg.PeekBytes(4);
                                byte[] version = msg.ReadBytes(4);

                                if (version[0] == 0 && version[1] == 0)
                                {
                                    uint versionUint = BitConverter.ToUInt32(version, 0);
                                    uint serverVersionUint = ((uint)replacedembly.GetEntryreplacedembly().GetName().Version.Major).ConcatUInts((uint)replacedembly.GetEntryreplacedembly().GetName().Version.Minor).ConcatUInts((uint)replacedembly.GetEntryreplacedembly().GetName().Version.Build).ConcatUInts((uint)replacedembly.GetEntryreplacedembly().GetName().Version.Revision);
                                    msg.SenderConnection.Deny($"Version mismatch!\nServer:{serverVersionUint}\nClient:{versionUint}");
                                    Logger.Instance.Log($"Client version v{versionUint} tried to connect");
                                    break;
                                }

                                byte[] serverVersion = new byte[4] { (byte)replacedembly.GetEntryreplacedembly().GetName().Version.Major, (byte)replacedembly.GetEntryreplacedembly().GetName().Version.Minor, (byte)replacedembly.GetEntryreplacedembly().GetName().Version.Build, (byte)replacedembly.GetEntryreplacedembly().GetName().Version.Revision };

                                if (version[0] != serverVersion[0] || version[1] != serverVersion[1] || version[2] != serverVersion[2])
                                {
                                    msg.SenderConnection.Deny($"Version mismatch|{string.Join('.', serverVersion)}|{string.Join('.', version)}");
                                    Logger.Instance.Log($"Client version v{string.Join('.', version)} tried to connect");
                                    break;
                                }

                                PlayerInfo playerInfo = new PlayerInfo(msg);

                                if (Settings.Instance.Access.WhitelistEnabled)
                                {
                                    if (!IsWhitelisted(msg.SenderConnection.RemoteEndPoint, playerInfo))
                                    {
                                        msg.SenderConnection.Deny("You are not whitelisted on this ServerHub!");
                                        Logger.Instance.Warning($"Client {playerInfo.playerName}({playerInfo.playerId})@{msg.SenderConnection.RemoteEndPoint.Address} is not whitelisted!");
                                        break;
                                    }
                                }

                                if (IsBlacklisted(msg.SenderConnection.RemoteEndPoint, playerInfo))
                                {
                                    msg.SenderConnection.Deny("You are banned on this ServerHub!");
                                    Logger.Instance.Warning($"Client {playerInfo.playerName}({playerInfo.playerId})@{msg.SenderConnection.RemoteEndPoint.Address} is banned!");
                                    break;
                                }

                                NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                                outMsg.Write(serverVersion);
                                outMsg.Write(Settings.Instance.Server.ServerHubName);

                                msg.SenderConnection.Approve(outMsg);

                                Client client = new Client(msg.SenderConnection, playerInfo);
                                client.playerInfo.updateInfo.playerState = PlayerState.Lobby;

                                client.ClientDisconnected += ClientDisconnected;

                                hubClients.Add(client);
                                allClients.Add(client);
                                Logger.Instance.Log($"{playerInfo.playerName} connected!");
                            };
                            break;
                        case NetIncomingMessageType.Data:
                            {
                                Client client = allClients.FirstOrDefault(x => x.playerConnection.RemoteEndPoint.Equals(msg.SenderEndPoint));

                                switch ((CommandType)msg.ReadByte())
                                {
                                    case CommandType.Disconnect:
                                        {
                                            if (client != null)
                                            {
                                                allClients.Remove(client);
                                                ClientDisconnected(client);
                                            }
                                        }
                                        break;
                                    case CommandType.UpdatePlayerInfo:
                                        {
                                            if (client != null)
                                            {
                                                if (msg.PeekByte() == 1 || !client.lastUpdateIsFull)
                                                    client.UpdatePlayerInfo(msg);

                                                if (Settings.Instance.Misc.PlayerColors.ContainsKey(client.playerInfo.playerId))
                                                {
                                                    client.playerInfo.updateInfo.playerNameColor = Settings.Instance.Misc.PlayerColors[client.playerInfo.playerId];
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.UpdateVoIPData:
                                        {
                                            if (!Settings.Instance.Server.AllowVoiceChat)
                                                return;

                                            if (client != null)
                                            {
                                                UnityVOIP.VoipFragment data = new UnityVOIP.VoipFragment(msg);
                                                if (data.playerId == client.playerInfo.playerId)
                                                    client.playerVoIPQueue.Enqueue(data);
                                            }
                                        }
                                        break;
                                    case CommandType.JoinRoom:
                                        {
                                            if (client != null)
                                            {
                                                uint roomId = msg.ReadUInt32();

                                                BaseRoom room = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == roomId);

                                                if (room != null)
                                                {
                                                    if (room.roomSettings.UsePreplacedword)
                                                    {
                                                        if (RoomsController.ClientJoined(client, roomId, msg.ReadString()))
                                                        {
                                                            if (hubClients.Contains(client))
                                                                hubClients.Remove(client);
                                                            client.joinedRoomID = roomId;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (RoomsController.ClientJoined(client, roomId, ""))
                                                        {
                                                            if (hubClients.Contains(client))
                                                                hubClients.Remove(client);
                                                            client.joinedRoomID = roomId;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    RoomsController.ClientJoined(client, roomId, "");
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.LeaveRoom:
                                        {
                                            if (client != null)
                                            {
                                                RoomsController.ClientLeftRoom(client);
                                                client.joinedRoomID = 0;
                                                client.playerInfo.updateInfo.playerState = PlayerState.Lobby;
                                                if (!hubClients.Contains(client))
                                                    hubClients.Add(client);
                                            }
                                        }
                                        break;
                                    case CommandType.GetRooms:
                                        {
                                            NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                                            outMsg.Write((byte)CommandType.GetRooms);
                                            RoomsController.AddRoomListToMessage(outMsg);

                                            msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                            Program.networkBytesOutNow += outMsg.LengthBytes;
                                        }
                                        break;
                                    case CommandType.CreateRoom:
                                        {
                                            if (client != null)
                                            {
                                                uint roomId = RoomsController.CreateRoom(new RoomSettings(msg), client.playerInfo);

                                                NetOutgoingMessage outMsg = ListenerServer.CreateMessage(5);
                                                outMsg.Write((byte)CommandType.CreateRoom);
                                                outMsg.Write(roomId);

                                                msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                                Program.networkBytesOutNow += outMsg.LengthBytes;
                                            }
                                        }
                                        break;
                                    case CommandType.GetRoomInfo:
                                        {
                                            if (client != null)
                                            {
#if DEBUG
                                                Logger.Instance.Log("GetRoomInfo: Client room=" + client.joinedRoomID);
#endif
                                                if (client.joinedRoomID != 0)
                                                {
                                                    BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                    if (joinedRoom != null)
                                                    {
                                                        NetOutgoingMessage outMsg = ListenerServer.CreateMessage();

                                                        outMsg.Write((byte)CommandType.GetRoomInfo);

                                                        joinedRoom.GetRoomInfo().AddToMessage(outMsg);

                                                        msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                                        Program.networkBytesOutNow += outMsg.LengthBytes;
                                                    }
                                                }
                                            }

                                        }
                                        break;
                                    case CommandType.SetSelectedSong:
                                        {
                                            if (client != null && client.joinedRoomID != 0)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    if (msg.LengthBytes < 16)
                                                    {
                                                        joinedRoom.SetSelectedSong(client.playerInfo, null);
                                                    }
                                                    else
                                                    {
                                                        joinedRoom.SetSelectedSong(client.playerInfo, new SongInfo(msg));
                                                    }
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.RequestSong:
                                        {
                                            if (client != null && client.joinedRoomID != 0)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    if (msg.LengthBytes > 16)
                                                    {
                                                        joinedRoom.RequestSong(client.playerInfo, new SongInfo(msg));
                                                    }
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.RemoveRequestedSong:
                                        {
                                            if (client != null && client.joinedRoomID != 0)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    if (msg.LengthBytes > 16)
                                                    {
                                                        joinedRoom.RemoveRequestedSong(client.playerInfo, new SongInfo(msg));
                                                    }
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.SetLevelOptions:
                                        {
                                            if (client != null && client.joinedRoomID != 0)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    joinedRoom.SetLevelOptions(client.playerInfo, new LevelOptionsInfo(msg));
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.StartLevel:
                                        {
#if DEBUG
                                            Logger.Instance.Log("Received command StartLevel");
#endif

                                            if (client != null && client.joinedRoomID != 0)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    LevelOptionsInfo options = new LevelOptionsInfo(msg);
                                                    SongInfo song = new SongInfo(msg);
                                                    song.songDuration += 2.5f;
                                                    joinedRoom.StartLevel(client.playerInfo, options, song);
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.DestroyRoom:
                                        {
                                            if (client != null && client.joinedRoomID != 0)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    joinedRoom.DestroyRoom(client.playerInfo);
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.TransferHost:
                                        {
                                            if (client != null && client.joinedRoomID != 0)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    joinedRoom.TransferHost(client.playerInfo, new PlayerInfo(msg));
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.PlayerReady:
                                        {
                                            if (client != null && client.joinedRoomID != 0)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    joinedRoom.ReadyStateChanged(client.playerInfo, msg.ReadBoolean());
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.SendEventMessage:
                                        {
                                            if (client != null && client.joinedRoomID != 0 && Settings.Instance.Server.AllowEventMessages)
                                            {
                                                BaseRoom joinedRoom = RoomsController.GetRoomsList().FirstOrDefault(x => x.roomId == client.joinedRoomID);
                                                if (joinedRoom != null)
                                                {
                                                    string header = msg.ReadString();
                                                    string data = msg.ReadString();

                                                    joinedRoom.BroadcastEventMessage(header, data, new List<Client>() { client });
                                                    joinedRoom.BroadcastWebSocket(CommandType.SendEventMessage, new EventMessage(header, data));

                                                    EventMessageReceived?.Invoke(client, header, data);
#if DEBUG
                                                    Logger.Instance.Log($"Received event message! Header=\"{header}\", Data=\"{data}\"");
#endif
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.GetChannelInfo:
                                        {
                                            if (Settings.Instance.Radio.EnableRadio && RadioController.radioStarted)
                                            {
                                                int channelId = msg.ReadInt32();

                                                NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                                                outMsg.Write((byte)CommandType.GetChannelInfo);

                                                if (RadioController.radioChannels.Count > channelId)
                                                {
                                                    RadioController.radioChannels[channelId].channelInfo.AddToMessage(outMsg);
                                                }
                                                else
                                                {
                                                    new ChannelInfo() { channelId = -1, currentSong = new SongInfo() { levelId = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" } }.AddToMessage(outMsg);
                                                }

                                                msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                                Program.networkBytesOutNow += outMsg.LengthBytes;
                                            }
                                        }
                                        break;
                                    case CommandType.JoinChannel:
                                        {
                                            int channelId = msg.ReadInt32();

                                            NetOutgoingMessage outMsg = ListenerServer.CreateMessage();
                                            outMsg.Write((byte)CommandType.JoinChannel);

                                            if (RadioController.ClientJoinedChannel(client, channelId))
                                            {
                                                outMsg.Write((byte)0);
                                                hubClients.Remove(client);
                                            }
                                            else
                                            {
                                                outMsg.Write((byte)1);
                                            }

                                            msg.SenderConnection.SendMessage(outMsg, NetDeliveryMethod.ReliableOrdered, 0);
                                            Program.networkBytesOutNow += outMsg.LengthBytes;
                                        }
                                        break;
                                    case CommandType.GetSongDuration:
                                        {
                                            foreach (RadioChannel channel in RadioController.radioChannels)
                                            {
                                                if (channel.radioClients.Contains(client) && channel.requestingSongDuration)
                                                {
                                                    SongInfo info = new SongInfo(msg);
                                                    if (info.levelId == channel.channelInfo.currentSong.levelId)
                                                        channel.songDurationResponses.TryAdd(client, info.songDuration);
                                                }
                                            }
                                        }
                                        break;
                                    case CommandType.LeaveChannel:
                                        {
                                            if (RadioController.radioStarted && client != null)
                                                RadioController.ClientLeftChannel(client);
                                        }; break;
                                }
                            };
                            break;



                        case NetIncomingMessageType.WarningMessage:
                            Logger.Instance.Warning(msg.ReadString());
                            break;
                        case NetIncomingMessageType.ErrorMessage:
                            Logger.Instance.Error(msg.ReadString());
                            break;
                        case NetIncomingMessageType.StatusChanged:
                            {
                                NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();

                                Client client = allClients.FirstOrDefault(x => x.playerConnection.RemoteEndPoint.Equals(msg.SenderEndPoint));

                                if (client != null)
                                {
                                    if (status == NetConnectionStatus.Disconnected)
                                    {
                                        allClients.Remove(client);
                                        ClientDisconnected(client);
                                    }
                                }
                            }
                            break;
#if DEBUG
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.DebugMessage:
                            Logger.Instance.Log(msg.ReadString());
                            break;
                        default:
                            Logger.Instance.Log("Unhandled message type: " + msg.MessageType);
                            break;
#endif
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Log($"Exception on message received: {ex}");
                }
                ListenerServer.Recycle(msg);
            }


        }

19 Source : DanAgent.cs
with GNU General Public License v3.0
from Animal42069

internal void InitializeDan()
        {
            List<Transform> danTransforms = new List<Transform>();
            foreach (var boneName in BoneNames.DanBones)
            {
                Transform danBone = Tools.GetTransformOfChaControl(m_danCharacter, boneName);
                if (danBone != null)
                    danTransforms.Add(danBone);
            }

            Transform tamaTop = Tools.GetTransformOfChaControl(m_danCharacter, BoneNames.TamaTop);

            if (tamaTop == null || danTransforms.Count < 2)
                return;

            if (danTransforms.Count > 2)
                m_bpDanPointsFound = true;

            if (danTransforms.Count == 9)
                m_bpColliderBonesFound = true;

            Transform danEnd = Tools.GetTransformOfChaControl(m_danCharacter, BoneNames.BPDanEnd);
            Transform bellyEnd = Tools.GetTransformOfChaControl(m_danCharacter, BoneNames.BPBellyEnd);

            m_danPoints = new DanPoints(danTransforms, tamaTop, danEnd, bellyEnd);
            m_danPointsFound = true;
            m_baseDanLength = Vector3.Distance(danTransforms[0].position, danTransforms[1].position) * (danTransforms.Count - 1);
            lastDanDistance = m_baseDanLength;
            lastDanEndVector = Vector3.zero;

            if (m_bpColliderBonesFound)
            {
                m_danColliders = Tools.GetCollidersOfChaControl(m_danCharacter, BoneNames.BPDanBone);

                m_danColliderRadius = new List<float>();
                m_danColliderLength = new List<float>();

                foreach (var collider in m_danColliders)
                {
                    m_danColliderRadius.Add(collider.m_Radius);
                    m_danColliderLength.Add(collider.m_Height);
                }

                UpdateDanColliders(m_danOptions.danRadiusScale, m_danOptions.danLengthScale);
            }
            else
            {
                float baseSectionHalfLength = m_baseDanLength / (2 * (m_danPoints.danPoints.Count - 1));

                for (int danPoint = 1; danPoint < m_danPoints.danPoints.Count; danPoint++)
                {
                    m_danColliders.Add(Tools.InitializeCollider(m_danPoints.danPoints[danPoint - 1].transform, DefaultColliderRadius * m_danPoints.danPoints[danPoint].defaultLossyScale.x, ((baseSectionHalfLength + DefaultColliderLength) * 2),
                        new Vector3(0, DefaultColliderVertical, baseSectionHalfLength), DynamicBoneCollider.Direction.Z));
                }
            }
        }

19 Source : VerticalTextProjection.cs
with Apache License 2.0
from AnkiUniversal

public static List<TextBlock> FindAllTextBlock(GrayImage image, uint[] density, SplitMultiLines.Line line, int lineIndex)
        {
            if(lineIndex == 0)
            {
                AvgGapBlocks.Clear();
                AvgGapIntraChars.Clear();
            }

            startIndex = line.StartText;
            stopIndex = line.StartSpace;

            var blocks = InitTextBlocks(image, density, lineIndex);
            if (blocks.Count < 2)
                return blocks;

            GetAverageParams(blocks);

            PreProcessAllBlocksType(blocks, density, image);

            CalculateAverageGaps(blocks);
            MergeMarkBlocks(blocks);

            CalculateAverageGaps(blocks);
            MergeHalfCharBlocks(blocks);

            CalculateAverageGaps(blocks);

            GetTextBlockRatio(blocks);

            AvgGapBlocks.Add(avgGapBlock);
            AvgGapIntraChars.Add(avgGapIntraChar);

            return blocks;
        }

19 Source : EditSelectionMode.cs
with GNU General Public License v3.0
from anotak

public override void OnEngage()
		{
			base.OnEngage();
			
			bool autodrag = (pasting && mouseinside && BuilderPlug.Me.AutoDragOnPaste);
			
			// Add toolbar buttons
			General.Interface.AddButton(BuilderPlug.Me.MenusForm.FlipSelectionH);
			General.Interface.AddButton(BuilderPlug.Me.MenusForm.FlipSelectionV);
			
			// Add docker
			panel = new EditSelectionPanel(this);
			docker = new Docker("editselection", "Edit Selection", panel);
			General.Interface.AddDocker(docker);
			General.Interface.SelectDocker(docker);
			
			// We don't want to record this for undoing while we move the geometry around.
			// This will be set back to normal when we're done.
			General.Map.UndoRedo.IgnorePropChanges = true;
			
			// Convert geometry selection
			General.Map.Map.ClearAllMarks(false);
			General.Map.Map.MarkSelectedVertices(true, true);
			General.Map.Map.MarkSelectedThings(true, true);
			General.Map.Map.MarkSelectedLinedefs(true, true);
			General.Map.Map.MarkSelectedSectors(true, true);
			ICollection<Vertex> verts = General.Map.Map.GetVerticesFromLinesMarks(true);
			foreach(Vertex v in verts) v.Marked = true;
			ICollection<Sector> sects = General.Map.Map.GetSelectedSectors(true);
			foreach(Sector s in sects)
			{
				foreach(Sidedef sd in s.Sidedefs)
				{
					sd.Line.Marked = true;
					sd.Line.Start.Marked = true;
					sd.Line.End.Marked = true;
				}
			}
			selectedvertices = General.Map.Map.GetMarkedVertices(true);
			selectedthings = General.Map.Map.GetMarkedThings(true);
			unselectedvertices = General.Map.Map.GetMarkedVertices(false);
			
			// Make sure everything is selected so that it turns up red
			foreach(Vertex v in selectedvertices) v.Selected = true;
			ICollection<Linedef> markedlines = General.Map.Map.LinedefsFromMarkedVertices(false, true, false);
			foreach(Linedef l in markedlines) l.Selected = true;
			selectedlines = General.Map.Map.LinedefsFromMarkedVertices(false, true, false);
			unselectedlines = General.Map.Map.LinedefsFromMarkedVertices(true, false, false);
			
			// Array to keep original coordinates
			vertexpos = new List<Vector2D>(selectedvertices.Count);
			thingpos = new List<Vector2D>(selectedthings.Count);
			thingangle = new List<float>(selectedthings.Count);

			// A selection must be made!
			if((selectedvertices.Count > 0) || (selectedthings.Count > 0))
			{
				// Initialize offset and size
				offset.x = float.MaxValue;
				offset.y = float.MaxValue;
				Vector2D right;
				right.x = float.MinValue;
				right.y = float.MinValue;
				
				foreach(Vertex v in selectedvertices)
				{
					// Find left-top and right-bottom
					if(v.Position.x < offset.x) offset.x = v.Position.x;
					if(v.Position.y < offset.y) offset.y = v.Position.y;
					if(v.Position.x > right.x) right.x = v.Position.x;
					if(v.Position.y > right.y) right.y = v.Position.y;
					
					// Keep original coordinates
					vertexpos.Add(v.Position);
				}

				foreach(Thing t in selectedthings)
				{
					// Find left-top and right-bottom
					if((t.Position.x - t.Size) < offset.x) offset.x = t.Position.x - t.Size;
					if((t.Position.y - t.Size) < offset.y) offset.y = t.Position.y - t.Size;
					if((t.Position.x + t.Size) > right.x) right.x = t.Position.x + t.Size;
					if((t.Position.y + t.Size) > right.y) right.y = t.Position.y + t.Size;

					// Keep original coordinates
					thingpos.Add(t.Position);
					thingangle.Add(t.Angle);
				}
				
				// Calculate size
				size = right - offset;
				
				// If the width of a dimension is zero, add a little
				if(Math.Abs(size.x) < 1.0f)
				{
					size.x += ZERO_SIZE_ADDITION;
					offset.x -= ZERO_SIZE_ADDITION / 2;
				}
				
				if(Math.Abs(size.y) < 1.0f)
				{
					size.y += ZERO_SIZE_ADDITION;
					offset.y -= ZERO_SIZE_ADDITION / 2;
				}
				
				basesize = size;
				baseoffset = offset;
				
				// When pasting, we want to move the geometry so it is visible
				if(pasting)
				{
					// Mouse in screen?
					if(mouseinside)
					{
						offset = mousemappos - size / 2;
					}
					else
					{
						Vector2D viewmappos = new Vector2D(renderer.OffsetX, renderer.OffsetY);
						offset = viewmappos - size / 2;
					}

					UpdateGeometry();
					General.Map.Data.UpdateUsedTextures();

					if(!autodrag)
						General.Map.Map.Update();
				}
				
				// Set presentation
				if(selectedthings.Count > 0)
					renderer.SetPresentation(Presentation.Things);
				else
					renderer.SetPresentation(Presentation.Standard);
				
				// Update
				panel.ShowOriginalValues(baseoffset, basesize);
				UpdateRectangleComponents();
				UpdatePanel();
				Update();
				
				// When pasting and mouse is in screen, drag selection immediately
				if(autodrag) OnSelectBegin();
			}
			else
			{
				General.Interface.MessageBeep(MessageBeepType.Default);
				General.Interface.DisplayStatus(StatusType.Info, "A selection is required for this action.");
				
				// Cancel now
				General.Editing.CancelMode();
			}
		}

19 Source : Shake.cs
with MIT License
from ArchonInteractive

public override void Start(float amplitude, int frequency, float duration)
        {
            base.Start(amplitude, frequency, duration);

            _samples.Clear();

            var samples = duration*frequency;

            for (var i = 0; i < samples; i++)
                _samples.Add(Random.value * 2 - 1);
        }

19 Source : AssTagHandlerBase.cs
with MIT License
from arcusmaximus

protected static List<float> ParseFloatList(string arg)
        {
            List<string> items = ParseStringList(arg);
            if (items == null)
                return null;

            List<float> list = new List<float>();
            foreach (string item in items)
            {
                float.TryParse(item.Replace(" ", ""), NumberStyles.Float, CultureInfo.InvariantCulture, out float value);
                list.Add(value);
            }
            return list;
        }

19 Source : GridInformation.cs
with MIT License
from Aroueterra

void ISerializationCallbackReceiver.OnBeforeSerialize()
        {
            Grid grid = GetComponentInParent<Grid>();
            if (grid == null)
                return;

            m_PositionIntKeys.Clear();
            m_PositionIntValues.Clear();
            m_PositionStringKeys.Clear();
            m_PositionStringValues.Clear();
            m_PositionFloatKeys.Clear();
            m_PositionFloatValues.Clear();
            m_PositionDoubleKeys.Clear();
            m_PositionDoubleValues.Clear();
            m_PositionObjectKeys.Clear();
            m_PositionObjectValues.Clear();
            m_PositionColorKeys.Clear();
            m_PositionColorValues.Clear();

            foreach (var kvp in m_PositionProperties)
            {
                switch (kvp.Value.type)
                {
                    case GridInformationType.Integer:
                        m_PositionIntKeys.Add(kvp.Key);
                        m_PositionIntValues.Add((int)kvp.Value.data);
                        break;
                    case GridInformationType.String:
                        m_PositionStringKeys.Add(kvp.Key);
                        m_PositionStringValues.Add(kvp.Value.data as String);
                        break;
                    case GridInformationType.Float:
                        m_PositionFloatKeys.Add(kvp.Key);
                        m_PositionFloatValues.Add((float)kvp.Value.data);
                        break;
                    case GridInformationType.Double:
                        m_PositionDoubleKeys.Add(kvp.Key);
                        m_PositionDoubleValues.Add((double)kvp.Value.data);
                        break;
                    case GridInformationType.Color:
                        m_PositionColorKeys.Add(kvp.Key);
                        m_PositionColorValues.Add((Color)kvp.Value.data);
                        break;
                    default:
                        m_PositionObjectKeys.Add(kvp.Key);
                        m_PositionObjectValues.Add(kvp.Value.data as Object);
                        break;
                }
            }
        }

19 Source : Path.cs
with Apache License 2.0
from ascora

public float[] Approximate(float precision)
        {
            var pathIteratorFactory = new CachedPathIteratorFactory(new FullPathIterator(this));
            var pathIterator = pathIteratorFactory.Iterator();
            float[] points = new float[8];
            var segmentPoints = new List<Vector2>();
            var lengths = new List<float>();
            float errorSquared = precision * precision;
            while (!pathIterator.Done)
            {
                var type = pathIterator.CurrentSegment(points);
                switch (type)
                {
                    case PathIterator.ContourType.MoveTo:
                        AddMove(segmentPoints, lengths, points);
                        break;
                    case PathIterator.ContourType.Close:
                        AddLine(segmentPoints, lengths, points);
                        break;
                    case PathIterator.ContourType.Line:
                        AddLine(segmentPoints, lengths, points.Skip(2).ToArray());
                        break;
                    case PathIterator.ContourType.Arc:
                        AddBezier(points, QuadraticBezierCalculation, segmentPoints, lengths, errorSquared, false);
                        break;
                    case PathIterator.ContourType.Bezier:
                        AddBezier(points, CubicBezierCalculation, segmentPoints, lengths, errorSquared, true);
                        break;
                }
                pathIterator.Next();
            }

            if (!segmentPoints.Any())
            {
                int numVerbs = Contours.Count;
                if (numVerbs == 1)
                {
                    AddMove(segmentPoints, lengths, Contours[0].Points);
                }
                else
                {
                    // Invalid or empty path. Fall back to point(0,0)
                    AddMove(segmentPoints, lengths, new[] { 0.0f, 0.0f });
                }
            }

            float totalLength = lengths.Last();
            if (totalLength == 0)
            {
                // Lone Move instructions should still be able to animate at the same value.
                segmentPoints.Add(segmentPoints.Last());
                lengths.Add(1);
                totalLength = 1;
            }

            var numPoints = segmentPoints.Count;
            var approximationArraySize = numPoints * 3;

            var approximation = new float[approximationArraySize];

            int approximationIndex = 0;
            for (var i = 0; i < numPoints; i++)
            {
                var point = segmentPoints[i];
                approximation[approximationIndex++] = lengths[i] / totalLength;
                approximation[approximationIndex++] = point.X;
                approximation[approximationIndex++] = point.Y;
            }

            return approximation;
        }

See More Examples