UnityEngine.Vector3.Dot(UnityEngine.Vector3, UnityEngine.Vector3)

Here are the examples of the csharp api UnityEngine.Vector3.Dot(UnityEngine.Vector3, UnityEngine.Vector3) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

174 Examples 7

19 View Source File : StalkerAI.cs
License : MIT License
Project Creator : Donut-Studios

bool safeToGo()
	{
		// is the player looking at me?
		bool inView = Vector3.Dot(Vector3.forward, player_transform.InverseTransformPoint(my_transform.position)) > 0;
		// is the player too close to me?
		bool isClose = Vector3.Distance (player_transform.position, my_transform.position) < followDist;
		// are both conditions false? if so, it's safe to go.
		return !(inView || isClose);
	}

19 View Source File : MWater.cs
License : MIT License
Project Creator : Interactml

Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign)
        {
            Vector3 offsetPos = pos + normal * clipPlaneOffset;
            Matrix4x4 m = cam.worldToCameraMatrix;
            Vector3 cpos = m.MultiplyPoint(offsetPos);
            Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign;
            return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal));
        }

19 View Source File : LinearDrive.cs
License : MIT License
Project Creator : dag10

private float CalculateLinearMapping( Transform tr )
		{
			Vector3 direction = endPosition.position - startPosition.position;
			float length = direction.magnitude;
			direction.Normalize();

			Vector3 displacement = tr.position - startPosition.position;

			return Vector3.Dot( displacement, direction ) / length;
		}

19 View Source File : BaseEntity.cs
License : MIT License
Project Creator : deadgg

public bool IsInView(BaseEnreplacedy other, float tolerance)
        {
            var direction = (other.transform.position - transform.position).normalized;
            var dot = Vector3.Dot(direction, transform.forward);
            return (dot >= 1f - tolerance);
        }

19 View Source File : Teleport.cs
License : MIT License
Project Creator : dag10

private void UpdatePointer()
		{
			Vector3 pointerStart = pointerStartTransform.position;
			Vector3 pointerEnd;
			Vector3 pointerDir = pointerStartTransform.forward;
			bool hitSomething = false;
			bool showPlayAreaPreview = false;
			Vector3 playerFeetOffset = player.trackingOriginTransform.position - player.feetPositionGuess;

			Vector3 arcVelocity = pointerDir * arcDistance;

			TeleportMarkerBase hitTeleportMarker = null;

			//Check pointer angle
			float dotUp = Vector3.Dot( pointerDir, Vector3.up );
			float dotForward = Vector3.Dot( pointerDir, player.hmdTransform.forward );
			bool pointerAtBadAngle = false;
			if ( ( dotForward > 0 && dotUp > 0.75f ) || ( dotForward < 0.0f && dotUp > 0.5f ) )
			{
				pointerAtBadAngle = true;
			}

			//Trace to see if the pointer hit anything
			RaycastHit hitInfo;
			teleportArc.SetArcData( pointerStart, arcVelocity, true, pointerAtBadAngle );
			if ( teleportArc.DrawArc( out hitInfo ) )
			{
				hitSomething = true;
				hitTeleportMarker = hitInfo.collider.GetComponentInParent<TeleportMarkerBase>();
			}

			if ( pointerAtBadAngle )
			{
				hitTeleportMarker = null;
			}

			HighlightSelected( hitTeleportMarker );

			if ( hitTeleportMarker != null ) //Hit a teleport marker
			{
				if ( hitTeleportMarker.locked )
				{
					teleportArc.SetColor( pointerLockedColor );
#if (UNITY_5_4)
					pointerLineRenderer.SetColors( pointerLockedColor, pointerLockedColor );
#else
					pointerLineRenderer.startColor = pointerLockedColor;
					pointerLineRenderer.endColor = pointerLockedColor;
#endif
					destinationReticleTransform.gameObject.SetActive( false );
				}
				else
				{
					teleportArc.SetColor( pointerValidColor );
#if (UNITY_5_4)
					pointerLineRenderer.SetColors( pointerValidColor, pointerValidColor );
#else
					pointerLineRenderer.startColor = pointerValidColor;
					pointerLineRenderer.endColor = pointerValidColor;
#endif
					destinationReticleTransform.gameObject.SetActive( hitTeleportMarker.showReticle );
				}

				offsetReticleTransform.gameObject.SetActive( true );

				invalidReticleTransform.gameObject.SetActive( false );

				pointedAtTeleportMarker = hitTeleportMarker;
				pointedAtPosition = hitInfo.point;

				if ( showPlayAreaMarker )
				{
					//Show the play area marker if this is a teleport area
					TeleportArea teleportArea = pointedAtTeleportMarker as TeleportArea;
					if ( teleportArea != null && !teleportArea.locked && playAreaPreviewTransform != null )
					{
						Vector3 offsetToUse = playerFeetOffset;

						//Adjust the actual offset to prevent the play area marker from moving too much
						if ( !movedFeetFarEnough )
						{
							float distanceFromStartingOffset = Vector3.Distance( playerFeetOffset, startingFeetOffset );
							if ( distanceFromStartingOffset < 0.1f )
							{
								offsetToUse = startingFeetOffset;
							}
							else if ( distanceFromStartingOffset < 0.4f )
							{
								offsetToUse = Vector3.Lerp( startingFeetOffset, playerFeetOffset, ( distanceFromStartingOffset - 0.1f ) / 0.3f );
							}
							else
							{
								movedFeetFarEnough = true;
							}
						}

						playAreaPreviewTransform.position = pointedAtPosition + offsetToUse;

						showPlayAreaPreview = true;
					}
				}

				pointerEnd = hitInfo.point;
			}
			else //Hit neither
			{
				destinationReticleTransform.gameObject.SetActive( false );
				offsetReticleTransform.gameObject.SetActive( false );

				teleportArc.SetColor( pointerInvalidColor );
#if (UNITY_5_4)
				pointerLineRenderer.SetColors( pointerInvalidColor, pointerInvalidColor );
#else
				pointerLineRenderer.startColor = pointerInvalidColor;
				pointerLineRenderer.endColor = pointerInvalidColor;
#endif
				invalidReticleTransform.gameObject.SetActive( !pointerAtBadAngle );

				//Orient the invalid reticle to the normal of the trace hit point
				Vector3 normalToUse = hitInfo.normal;
				float angle = Vector3.Angle( hitInfo.normal, Vector3.up );
				if ( angle < 15.0f )
				{
					normalToUse = Vector3.up;
				}
				invalidReticleTargetRotation = Quaternion.FromToRotation( Vector3.up, normalToUse );
				invalidReticleTransform.rotation = Quaternion.Slerp( invalidReticleTransform.rotation, invalidReticleTargetRotation, 0.1f );

				//Scale the invalid reticle based on the distance from the player
				float distanceFromPlayer = Vector3.Distance( hitInfo.point, player.hmdTransform.position );
				float invalidReticleCurrentScale = Util.RemapNumberClamped( distanceFromPlayer, invalidReticleMinScaleDistance, invalidReticleMaxScaleDistance, invalidReticleMinScale, invalidReticleMaxScale );
				invalidReticleScale.x = invalidReticleCurrentScale;
				invalidReticleScale.y = invalidReticleCurrentScale;
				invalidReticleScale.z = invalidReticleCurrentScale;
				invalidReticleTransform.transform.localScale = invalidReticleScale;

				pointedAtTeleportMarker = null;

				if ( hitSomething )
				{
					pointerEnd = hitInfo.point;
				}
				else
				{
					pointerEnd = teleportArc.GetArcPositionAtTime( teleportArc.arcDuration );
				}

				//Debug floor
				if ( debugFloor )
				{
					floorDebugSphere.gameObject.SetActive( false );
					floorDebugLine.gameObject.SetActive( false );
				}
			}

			if ( playAreaPreviewTransform != null )
			{
				playAreaPreviewTransform.gameObject.SetActive( showPlayAreaPreview );
			}

			if ( !showOffsetReticle )
			{
				offsetReticleTransform.gameObject.SetActive( false );
			}

			destinationReticleTransform.position = pointedAtPosition;
			invalidReticleTransform.position = pointerEnd;
			onActivateObjectTransform.position = pointerEnd;
			onDeactivateObjectTransform.position = pointerEnd;
			offsetReticleTransform.position = pointerEnd - playerFeetOffset;

			reticleAudioSource.transform.position = pointedAtPosition;

			pointerLineRenderer.SetPosition( 0, pointerStart );
			pointerLineRenderer.SetPosition( 1, pointerEnd );
		}

19 View Source File : MathUtils.cs
License : MIT License
Project Creator : dag10

public static Vector3 ClosestPointOnLineSegmentToPoint(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
        {
            Vector3 v = lineEnd - lineStart;
            Vector3 w = point - lineStart;

            float c1 = Vector3.Dot(w, v);
            if (c1 <= 0)
            {
                return lineStart;
            }

            float c2 = Vector3.Dot(v, v);
            if (c2 <= c1)
            {
                return lineEnd;
            }

            float b = c1 / c2;

            Vector3 pointB = lineStart + (v * b);

            return pointB;
        }

19 View Source File : GvrPointerGraphicRaycaster.cs
License : MIT License
Project Creator : harshitjuneja

public override void Raycast(PointerEventData eventData, List<RaycastResult> resultAppendList) {
    if (canvas == null) {
      return;
    }

    if (eventCamera == null) {
      return;
    }

    if (!IsPointerAvailable()) {
      return;
    }

    if (canvas.renderMode != RenderMode.WorldSpace) {
      Debug.LogError("GvrPointerGraphicRaycaster requires that the canvas renderMode is set to WorldSpace.");
      return;
    }

    Ray ray = GetRay();
    float hitDistance = float.MaxValue;

    if (blockingObjects != BlockingObjects.None) {
      float dist = eventCamera.farClipPlane - eventCamera.nearClipPlane;

      if (blockingObjects == BlockingObjects.ThreeD || blockingObjects == BlockingObjects.All) {
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, dist, blockingMask)) {
          hitDistance = hit.distance;
        }
      }

      if (blockingObjects == BlockingObjects.TwoD || blockingObjects == BlockingObjects.All) {
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, dist, blockingMask);

        if (hit.collider != null) {
          hitDistance = hit.fraction * dist;
        }
      }
    }

    raycastResults.Clear();
    Ray finalRay;
    Raycast(canvas, ray, eventCamera, MaxPointerDistance, raycastResults, out finalRay);

    for (int index = 0; index < raycastResults.Count; index++) {
      GameObject go = raycastResults[index].gameObject;
      bool appendGraphic = true;

      if (ignoreReversedGraphics) {
        // If we have a camera compare the direction against the cameras forward.
        Vector3 cameraFoward = eventCamera.transform.rotation * Vector3.forward;
        Vector3 dir = go.transform.rotation * Vector3.forward;
        appendGraphic = Vector3.Dot(cameraFoward, dir) > 0;
      }

      if (appendGraphic) {
        float distance = 0;

        Transform trans = go.transform;
        Vector3 transForward = trans.forward;
        // http://geomalgorithms.com/a06-_intersect-2.html
        float transDot = Vector3.Dot(transForward, trans.position - finalRay.origin);
        float rayDot = Vector3.Dot(transForward, finalRay.direction);
        distance = transDot / rayDot;

        // Check to see if the go is behind the camera.
        if (distance < 0) {
          continue;
        }

        if (distance >= hitDistance) {
          continue;
        }

        Vector3 hitPosition = finalRay.origin + (finalRay.direction * distance);

        RaycastResult castResult = new RaycastResult
        {
          gameObject = go,
          module = this,
          distance = distance,
          worldPosition = hitPosition,
          screenPosition = eventCamera.WorldToScreenPoint(hitPosition),
          index = resultAppendList.Count,
          depth = raycastResults[index].depth,
          sortingLayer = canvas.sortingLayerID,
          sortingOrder = canvas.sortingOrder
        };
        resultAppendList.Add(castResult);
      }
    }
  }

19 View Source File : SimulationStep2Patch.cs
License : MIT License
Project Creator : CitiesSkylinesMods

[UsedImplicitly]
        public static bool Prefix(TrainAI __instance,
                                  VehicleInfo ___m_info,
                                  ushort vehicleID,
                                  ref Vehicle vehicleData,
                                  ref Vehicle.Frame frameData,
                                  ushort leaderID,
                                  ref Vehicle leaderData,
                                  int lodPhysics) {
            bool reversed = (leaderData.m_flags & Vehicle.Flags.Reversed) != 0;
            ushort frontVehicleId = (!reversed) ? vehicleData.m_leadingVehicle : vehicleData.m_trailingVehicle;
            VehicleInfo vehicleInfo = leaderID != vehicleID ? leaderData.Info : ___m_info;
            TrainAI trainAi = vehicleInfo.m_vehicleAI as TrainAI;

            if (frontVehicleId != 0) {
                frameData.m_position += frameData.m_velocity * 0.4f;
            } else {
                frameData.m_position += frameData.m_velocity * 0.5f;
            }

            frameData.m_swayPosition += frameData.m_swayVelocity * 0.5f;

            Vector3 posBeforeWheelRot = frameData.m_position;
            Vector3 posAfterWheelRot = frameData.m_position;
            Vector3 wheelBaseRot = frameData.m_rotation
                               * new Vector3(0f, 0f, ___m_info.m_generatedInfo.m_wheelBase * 0.5f);

            if (reversed) {
                posBeforeWheelRot -= wheelBaseRot;
                posAfterWheelRot += wheelBaseRot;
            } else {
                posBeforeWheelRot += wheelBaseRot;
                posAfterWheelRot -= wheelBaseRot;
            }

            float acceleration = ___m_info.m_acceleration;
            float braking = ___m_info.m_braking;
            float curSpeed = frameData.m_velocity.magnitude;

            Vector3 beforeRotToTargetPos1Diff = (Vector3)vehicleData.m_targetPos1 - posBeforeWheelRot;
            float beforeRotToTargetPos1DiffSqrMag = beforeRotToTargetPos1Diff.sqrMagnitude;

            Quaternion curInvRot = Quaternion.Inverse(frameData.m_rotation);
            Vector3 curveTangent = curInvRot * frameData.m_velocity;

            Vector3 forward = Vector3.forward;
            Vector3 targetMotion = Vector3.zero;
            float targetSpeed = 0f;
            float motionFactor = 0.5f;

            if (frontVehicleId != 0) {
                VehicleManager vehMan = VehicleManager.instance;
                Vehicle.Frame frontVehLastFrameData = vehMan.m_vehicles.m_buffer[frontVehicleId].GetLastFrameData();
                VehicleInfo frontVehInfo = vehMan.m_vehicles.m_buffer[frontVehicleId].Info;
                float attachOffset;

                if ((vehicleData.m_flags & Vehicle.Flags.Inverted) != 0 != reversed) {
                    attachOffset = ___m_info.m_attachOffsetBack - (___m_info.m_generatedInfo.m_size.z * 0.5f);
                } else {
                    attachOffset = ___m_info.m_attachOffsetFront - (___m_info.m_generatedInfo.m_size.z * 0.5f);
                }

                float frontAttachOffset;

                if ((vehMan.m_vehicles.m_buffer[frontVehicleId].m_flags & Vehicle.Flags.Inverted) != 0 != reversed) {
                    frontAttachOffset = frontVehInfo.m_attachOffsetFront -
                                        (frontVehInfo.m_generatedInfo.m_size.z * 0.5f);
                } else {
                    frontAttachOffset =
                        (frontVehInfo.m_attachOffsetBack - (frontVehInfo.m_generatedInfo.m_size.z * 0.5f));
                }

                Vector3 posMinusAttachOffset = frameData.m_position;
                if (reversed) {
                    posMinusAttachOffset += frameData.m_rotation * new Vector3(0f, 0f, attachOffset);
                } else {
                    posMinusAttachOffset -= frameData.m_rotation * new Vector3(0f, 0f, attachOffset);
                }

                Vector3 frontPosPlusAttachOffset = frontVehLastFrameData.m_position;
                if (reversed) {
                    frontPosPlusAttachOffset -= frontVehLastFrameData.m_rotation
                                                * new Vector3(0f, 0f, frontAttachOffset);
                } else {
                    frontPosPlusAttachOffset += frontVehLastFrameData.m_rotation
                                                * new Vector3(0f, 0f, frontAttachOffset);
                }

                Vector3 frontPosMinusWheelBaseRot = frontVehLastFrameData.m_position;
                wheelBaseRot = frontVehLastFrameData.m_rotation * new Vector3(
                                   0f,
                                   0f,
                                   frontVehInfo.m_generatedInfo.m_wheelBase * 0.5f);
                if (reversed) {
                    frontPosMinusWheelBaseRot += wheelBaseRot;
                } else {
                    frontPosMinusWheelBaseRot -= wheelBaseRot;
                }

                if (Vector3.Dot(
                        vehicleData.m_targetPos1 - vehicleData.m_targetPos0,
                        (Vector3)vehicleData.m_targetPos0 - posAfterWheelRot) < 0f
                    && vehicleData.m_path != 0u
                    && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == 0)
                {
                    int someIndex = -1;
                    UpdatePathTargetPositions(
                        trainAi,
                        vehicleID,
                        ref vehicleData,
                        vehicleData.m_targetPos0,
                        posAfterWheelRot,
                        0,
                        ref leaderData,
                        ref someIndex,
                        0,
                        0,
                        Vector3.SqrMagnitude(posAfterWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f,
                        1f);
                    beforeRotToTargetPos1DiffSqrMag = 0f;
                }

                float maxAttachDist = Mathf.Max(Vector3.Distance(posMinusAttachOffset,
                                                               frontPosPlusAttachOffset),
                                              2f);
                const float ONE = 1f;
                float maxAttachSqrDist = maxAttachDist * maxAttachDist;
                const float ONE_SQR = ONE * ONE;
                int i = 0;
                if (beforeRotToTargetPos1DiffSqrMag < maxAttachSqrDist) {
                    if (vehicleData.m_path != 0u
                        && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == 0) {
                        UpdatePathTargetPositions(
                            trainAi,
                            vehicleID,
                            ref vehicleData,
                            posAfterWheelRot,
                            posBeforeWheelRot,
                            0,
                            ref leaderData,
                            ref i,
                            1,
                            2,
                            maxAttachSqrDist,
                            ONE_SQR);
                    }

                    while (i < 4) {
                        vehicleData.SetTargetPos(i, vehicleData.GetTargetPos(i - 1));
                        i++;
                    }

                    beforeRotToTargetPos1Diff = (Vector3)vehicleData.m_targetPos1 - posBeforeWheelRot;
                    beforeRotToTargetPos1DiffSqrMag = beforeRotToTargetPos1Diff.sqrMagnitude;
                }

                if (vehicleData.m_path != 0u) {
                    NetManager netMan = NetManager.instance;
                    byte pathPosIndex = vehicleData.m_pathPositionIndex;
                    byte lastPathOffset = vehicleData.m_lastPathOffset;
                    if (pathPosIndex == 255) {
                        pathPosIndex = 0;
                    }

                    PathManager pathMan = PathManager.instance;
                    if (pathMan.m_pathUnits.m_buffer[vehicleData.m_path]
                               .GetPosition(pathPosIndex >> 1, out PathUnit.Position curPathPos)) {
                        netMan.m_segments.m_buffer[curPathPos.m_segment].AddTraffic(
                            Mathf.RoundToInt(___m_info.m_generatedInfo.m_size.z * 3f),
                            GetNoiseLevel(trainAi));

                        if ((pathPosIndex & 1) == 0 || lastPathOffset == 0 ||
                            (leaderData.m_flags & Vehicle.Flags.WaitingPath) != 0) {
                            uint laneId = PathManager.GetLaneID(curPathPos);
                            if (laneId != 0u) {
                                netMan.m_lanes.m_buffer[laneId].ReserveSpace(___m_info.m_generatedInfo.m_size.z);
                            }
                        } else if (pathMan.m_pathUnits.m_buffer[vehicleData.m_path]
                                          .GetNextPosition(pathPosIndex >> 1, out PathUnit.Position nextPathPos)) {
                            // NON-STOCK CODE START
                            ushort transitNodeId;

                            if (curPathPos.m_offset < 128) {
                                transitNodeId = netMan.m_segments.m_buffer[curPathPos.m_segment].m_startNode;
                            } else {
                                transitNodeId = netMan.m_segments.m_buffer[curPathPos.m_segment].m_endNode;
                            }

                            if (VehicleBehaviorManager.Instance.IsSpaceReservationAllowed(
                                transitNodeId,
                                curPathPos,
                                nextPathPos)) {
                                // NON-STOCK CODE END
                                uint nextLaneId = PathManager.GetLaneID(nextPathPos);
                                if (nextLaneId != 0u) {
                                    netMan.m_lanes.m_buffer[nextLaneId].ReserveSpace(___m_info.m_generatedInfo.m_size.z);
                                }
                            } // NON-STOCK CODE
                        }
                    }
                }

                beforeRotToTargetPos1Diff = curInvRot * beforeRotToTargetPos1Diff;
                float negTotalAttachLen =
                    -(((___m_info.m_generatedInfo.m_wheelBase +
                        frontVehInfo.m_generatedInfo.m_wheelBase) * 0.5f) + attachOffset +
                      frontAttachOffset);
                bool hasPath = false;

                if (vehicleData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == 0) {
                    if (Line3.Intersect(
                        posBeforeWheelRot,
                        vehicleData.m_targetPos1,
                        frontPosMinusWheelBaseRot,
                        negTotalAttachLen,
                        out float u1,
                        out float u2)) {
                        targetMotion = beforeRotToTargetPos1Diff
                                       * Mathf.Clamp(Mathf.Min(u1, u2) / 0.6f, 0f, 2f);
                    } else {
                        Line3.DistanceSqr(
                            posBeforeWheelRot,
                            vehicleData.m_targetPos1,
                            frontPosMinusWheelBaseRot,
                            out u1);
                        targetMotion = beforeRotToTargetPos1Diff * Mathf.Clamp(u1 / 0.6f, 0f, 2f);
                    }

                    hasPath = true;
                }

                if (hasPath) {
                    if (Vector3.Dot(
                            frontPosMinusWheelBaseRot - posBeforeWheelRot,
                            posBeforeWheelRot - posAfterWheelRot) < 0f) {
                        motionFactor = 0f;
                    }
                } else {
                    float frontPosBeforeToAfterWheelRotDist = Vector3.Distance(
                        frontPosMinusWheelBaseRot,
                        posBeforeWheelRot);
                    motionFactor = 0f;
                    targetMotion = curInvRot
                                   * ((frontPosMinusWheelBaseRot - posBeforeWheelRot)
                                      * (Mathf.Max(0f, frontPosBeforeToAfterWheelRotDist - negTotalAttachLen)
                                         / Mathf.Max(1f, frontPosBeforeToAfterWheelRotDist * 0.6f)));
                }
            } else {
                float estimatedFrameDist = (curSpeed + acceleration)
                                         * (0.5f + (0.5f * (curSpeed + acceleration) / braking));
                float maxSpeedAdd = Mathf.Max(curSpeed + acceleration, 2f);
                float meanSpeedAdd = Mathf.Max((estimatedFrameDist - maxSpeedAdd) / 2f, 1f);
                float maxSpeedAddSqr = maxSpeedAdd * maxSpeedAdd;
                float meanSpeedAddSqr = meanSpeedAdd * meanSpeedAdd;

                if (Vector3.Dot(
                        vehicleData.m_targetPos1 - vehicleData.m_targetPos0,
                        (Vector3)vehicleData.m_targetPos0 - posAfterWheelRot) < 0f
                    && vehicleData.m_path != 0u
                    && (leaderData.m_flags & (Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped)) == 0)
                {
                    int someIndex = -1;
                    UpdatePathTargetPositions(
                        trainAi,
                        vehicleID,
                        ref vehicleData,
                        vehicleData.m_targetPos0,
                        posAfterWheelRot,
                        leaderID,
                        ref leaderData,
                        ref someIndex,
                        0,
                        0,
                        Vector3.SqrMagnitude(posAfterWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f,
                        1f);
                    beforeRotToTargetPos1DiffSqrMag = 0f;
                }

                int posIndex = 0;
                bool flag3 = false;
                if ((beforeRotToTargetPos1DiffSqrMag < maxSpeedAddSqr
                     || vehicleData.m_targetPos3.w < 0.01f)
                    && (leaderData.m_flags & (Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped)) == 0)
                {
                    if (vehicleData.m_path != 0u) {
                        UpdatePathTargetPositions(
                            trainAi,
                            vehicleID,
                            ref vehicleData,
                            posAfterWheelRot,
                            posBeforeWheelRot,
                            leaderID,
                            ref leaderData,
                            ref posIndex,
                            1,
                            4,
                            maxSpeedAddSqr,
                            meanSpeedAddSqr);
                    }
                    if (posIndex < 4) {
                        flag3 = true;
                        while (posIndex < 4) {
                            vehicleData.SetTargetPos(posIndex, vehicleData.GetTargetPos(posIndex - 1));
                            posIndex++;
                        }
                    }

                    beforeRotToTargetPos1Diff = (Vector3)vehicleData.m_targetPos1 - posBeforeWheelRot;
                    beforeRotToTargetPos1DiffSqrMag = beforeRotToTargetPos1Diff.sqrMagnitude;
                }

                if ((leaderData.m_flags & (Vehicle.Flags.WaitingPath
                                           | Vehicle.Flags.Stopped)) == 0
                    && ___m_info.m_vehicleType != VehicleInfo.VehicleType.Monorail) {
                    ForceTrafficLights(__instance, vehicleID, ref vehicleData, curSpeed > 0.1f);
                    // NON-STOCK CODE
                }

                if (vehicleData.m_path != 0u) {
                    NetManager netMan = Singleton<NetManager>.instance;
                    byte pathPosIndex = vehicleData.m_pathPositionIndex;
                    byte lastPathOffset = vehicleData.m_lastPathOffset;
                    if (pathPosIndex == 255) {
                        pathPosIndex = 0;
                    }

                    PathManager pathMan = Singleton<PathManager>.instance;
                    if (pathMan.m_pathUnits.m_buffer[vehicleData.m_path]
                               .GetPosition(pathPosIndex >> 1, out PathUnit.Position curPathPos))
                    {
                        netMan.m_segments.m_buffer[curPathPos.m_segment]
                              .AddTraffic(Mathf.RoundToInt(___m_info.m_generatedInfo.m_size.z * 3f),
                                          GetNoiseLevel(trainAi));

                        if ((pathPosIndex & 1) == 0
                            || lastPathOffset == 0
                            || (leaderData.m_flags & Vehicle.Flags.WaitingPath) != 0)
                        {
                            uint laneId = PathManager.GetLaneID(curPathPos);
                            if (laneId != 0u) {
                                netMan.m_lanes.m_buffer[laneId].ReserveSpace(___m_info.m_generatedInfo.m_size.z, vehicleID);
                            }
                        } else if (pathMan.m_pathUnits.m_buffer[vehicleData.m_path]
                                          .GetNextPosition(pathPosIndex >> 1, out PathUnit.Position nextPathPos)) {
                            // NON-STOCK CODE START
                            ushort transitNodeId;
                            transitNodeId = curPathPos.m_offset < 128
                                                ? netMan.m_segments.m_buffer[curPathPos.m_segment].m_startNode
                                                : netMan.m_segments.m_buffer[curPathPos.m_segment].m_endNode;

                            if (VehicleBehaviorManager.Instance.IsSpaceReservationAllowed(
                                transitNodeId,
                                curPathPos,
                                nextPathPos)) {
                                // NON-STOCK CODE END
                                uint nextLaneId = PathManager.GetLaneID(nextPathPos);
                                if (nextLaneId != 0u) {
                                    netMan.m_lanes.m_buffer[nextLaneId].ReserveSpace(
                                        ___m_info.m_generatedInfo.m_size.z, vehicleID);
                                }
                            } // NON-STOCK CODE
                        }
                    }
                }

                float maxSpeed;

                maxSpeed = (leaderData.m_flags & Vehicle.Flags.Stopped) != 0
                               ? 0f
                               : Mathf.Min(vehicleData.m_targetPos1.w, GetMaxSpeed(leaderID, ref leaderData));

                beforeRotToTargetPos1Diff = curInvRot * beforeRotToTargetPos1Diff;
                if (reversed) {
                    beforeRotToTargetPos1Diff = -beforeRotToTargetPos1Diff;
                }

                bool blocked = false;
                float forwardLen = 0f;

                if (beforeRotToTargetPos1DiffSqrMag > 1f) {
                    forward = VectorUtils.NormalizeXZ(beforeRotToTargetPos1Diff, out forwardLen);

                    if (forwardLen > 1f) {
                        Vector3 fwd = beforeRotToTargetPos1Diff;
                        maxSpeedAdd = Mathf.Max(curSpeed, 2f);
                        maxSpeedAddSqr = maxSpeedAdd * maxSpeedAdd;
                        if (beforeRotToTargetPos1DiffSqrMag > maxSpeedAddSqr) {
                            float num20 = maxSpeedAdd / Mathf.Sqrt(beforeRotToTargetPos1DiffSqrMag);
                            fwd.x *= num20;
                            fwd.y *= num20;
                        }

                        if (fwd.z < -1f) {
                            if (vehicleData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == 0) {
                                Vector3 targetPos0TargetPos1Diff = vehicleData.m_targetPos1 - vehicleData.m_targetPos0;
                                targetPos0TargetPos1Diff = curInvRot * targetPos0TargetPos1Diff;
                                if (reversed) {
                                    targetPos0TargetPos1Diff = -targetPos0TargetPos1Diff;
                                }

                                if (targetPos0TargetPos1Diff.z < -0.01f) {
                                    if (beforeRotToTargetPos1Diff.z < Mathf.Abs(beforeRotToTargetPos1Diff.x) * -10f) {
                                        if (curSpeed < 0.01f) {
                                            Reverse(leaderID, ref leaderData);
                                            return false;
                                        }

                                        fwd.z = 0f;
                                        beforeRotToTargetPos1Diff = Vector3.zero;
                                        maxSpeed = 0f;
                                    } else {
                                        posBeforeWheelRot =
                                            posAfterWheelRot +
                                            Vector3.Normalize(
                                                vehicleData.m_targetPos1 -
                                                vehicleData.m_targetPos0) *
                                            ___m_info.m_generatedInfo.m_wheelBase;
                                        posIndex = -1;
                                        UpdatePathTargetPositions(
                                            trainAi,
                                            vehicleID,
                                            ref vehicleData,
                                            vehicleData.m_targetPos0,
                                            vehicleData.m_targetPos1,
                                            leaderID,
                                            ref leaderData,
                                            ref posIndex,
                                            0,
                                            0,
                                            Vector3.SqrMagnitude(
                                                vehicleData.m_targetPos1 -
                                                vehicleData.m_targetPos0) + 1f,
                                            1f);
                                    }
                                } else {
                                    posIndex = -1;
                                    UpdatePathTargetPositions(
                                        trainAi,
                                        vehicleID,
                                        ref vehicleData,
                                        vehicleData.m_targetPos0,
                                        posAfterWheelRot,
                                        leaderID,
                                        ref leaderData,
                                        ref posIndex,
                                        0,
                                        0,
                                        Vector3.SqrMagnitude(
                                            posAfterWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f,
                                        1f);
                                    vehicleData.m_targetPos1 = posBeforeWheelRot;
                                    fwd.z = 0f;
                                    beforeRotToTargetPos1Diff = Vector3.zero;
                                    maxSpeed = 0f;
                                }
                            }

                            motionFactor = 0f;
                        }

                        forward = VectorUtils.NormalizeXZ(fwd, out forwardLen);
                        float curve = Mathf.PI / 2f * (1f - forward.z);
                        if (forwardLen > 1f) {
                            curve /= forwardLen;
                        }

                        maxSpeed = Mathf.Min(
                            maxSpeed,
                            CalculateTargetSpeed(
                                __instance,
                                vehicleID,
                                ref vehicleData,
                                1000f,
                                curve));

                        float targetDist = forwardLen;
                        maxSpeed = Mathf.Min(
                            maxSpeed,
                            CalculateMaxSpeed(
                                targetDist,
                                vehicleData.m_targetPos2.w,
                                braking));
                        targetDist += VectorUtils.LengthXZ(vehicleData.m_targetPos2 - vehicleData.m_targetPos1);
                        maxSpeed = Mathf.Min(maxSpeed,
                                             CalculateMaxSpeed(targetDist,
                                                               vehicleData.m_targetPos3.w,
                                                               braking));
                        targetDist += VectorUtils.LengthXZ(vehicleData.m_targetPos3 - vehicleData.m_targetPos2);
                        maxSpeed = Mathf.Min(maxSpeed,
                                             CalculateMaxSpeed(targetDist, 0f, braking));

                        if (maxSpeed < curSpeed) {
                            float brake = Mathf.Max(acceleration, Mathf.Min(braking, curSpeed));
                            targetSpeed = Mathf.Max(maxSpeed, curSpeed - brake);
                        } else {
                            float accel = Mathf.Max(acceleration, Mathf.Min(braking, -curSpeed));
                            targetSpeed = Mathf.Min(maxSpeed, curSpeed + accel);
                        }
                    }
                } else if (curSpeed < 0.1f && flag3 &&
                           vehicleInfo.m_vehicleAI.ArriveAtDestination(leaderID, ref leaderData)) {
                    leaderData.Unspawn(leaderID);
                    return false;
                }

                if ((leaderData.m_flags & Vehicle.Flags.Stopped) == 0 && maxSpeed < 0.1f) {
                    blocked = true;
                }

                if (blocked) {
                    leaderData.m_blockCounter = (byte)Mathf.Min(leaderData.m_blockCounter + 1, 255);
                } else {
                    leaderData.m_blockCounter = 0;
                }

                if (forwardLen > 1f) {
                    if (reversed) {
                        forward = -forward;
                    }

                    targetMotion = forward * targetSpeed;
                } else {
                    if (reversed) {
                        beforeRotToTargetPos1Diff = -beforeRotToTargetPos1Diff;
                    }

                    Vector3 vel = Vector3.ClampMagnitude((beforeRotToTargetPos1Diff * 0.5f) - curveTangent, braking);
                    targetMotion = curveTangent + vel;
                }
            }

            Vector3 springs = targetMotion - curveTangent;
            Vector3 targetAfterWheelRotMotion = frameData.m_rotation * targetMotion;
            Vector3 posAfterWheelRotToTargetDiff = Vector3.Normalize((Vector3)vehicleData.m_targetPos0 - posAfterWheelRot)
                                               * (targetMotion.magnitude * motionFactor);
            posBeforeWheelRot += targetAfterWheelRotMotion;
            posAfterWheelRot += posAfterWheelRotToTargetDiff;

            Vector3 targetPos;
            if (reversed) {
                frameData.m_rotation = Quaternion.LookRotation(posAfterWheelRot - posBeforeWheelRot);
                targetPos = posBeforeWheelRot + (frameData.m_rotation * new Vector3(
                                                     0f,
                                                     0f,
                                                     ___m_info.m_generatedInfo.m_wheelBase * 0.5f));
            } else {
                frameData.m_rotation = Quaternion.LookRotation(posBeforeWheelRot - posAfterWheelRot);
                targetPos = posBeforeWheelRot - (frameData.m_rotation * new Vector3(
                                                     0f,
                                                     0f,
                                                     ___m_info.m_generatedInfo.m_wheelBase * 0.5f));
            }

            frameData.m_velocity = targetPos - frameData.m_position;

            if (frontVehicleId != 0) {
                frameData.m_position += frameData.m_velocity * 0.6f;
            } else {
                frameData.m_position += frameData.m_velocity * 0.5f;
            }

            frameData.m_swayVelocity =
                ((frameData.m_swayVelocity * (1f - ___m_info.m_dampers)) - (springs * (1f - ___m_info.m_springs)))
                - (frameData.m_swayPosition * ___m_info.m_springs);
            frameData.m_swayPosition += frameData.m_swayVelocity * 0.5f;
            frameData.m_steerAngle = 0f;
            frameData.m_travelDistance += targetMotion.z;
            frameData.m_lightIntensity.x = (!reversed) ? 5f : 0f;
            frameData.m_lightIntensity.y = (!reversed) ? 0f : 5f;
            frameData.m_lightIntensity.z = 0f;
            frameData.m_lightIntensity.w = 0f;
            frameData.m_underground = (vehicleData.m_flags & Vehicle.Flags.Underground) != 0;
            frameData.m_transition = (vehicleData.m_flags & Vehicle.Flags.Transition) != 0;

            // base.SimulationStep(vehicleID, ref vehicleData, ref frameData, leaderID, ref leaderData, lodPhysics);
            return false;
        }

19 View Source File : MalbersTools.cs
License : MIT License
Project Creator : Interactml

public static float AngleAroundAxis(Vector3 dirA, Vector3 dirB, Vector3 axis)
        {
            // Project A and B onto the plane orthogonal target axis
            dirA = dirA - Vector3.Project(dirA, axis);
            dirB = dirB - Vector3.Project(dirB, axis);

            // Find (positive) angle between A and B
            float angle = Vector3.Angle(dirA, dirB);

            // Return angle multiplied with 1 or -1
            return angle * (Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) < 0 ? -1 : 1);
        }

19 View Source File : FocusSquare.cs
License : MIT License
Project Creator : codeyuan666

void Update () {

		//use center of screen for focusing
		Vector3 center = new Vector3(Screen.width/2, Screen.height/2, findingSquareDist);

		#if UNITY_EDITOR
		Ray ray = Camera.main.ScreenPointToRay (center);
		RaycastHit hit;

		//we'll try to hit one of the plane collider gameobjects that were generated by the plugin
		//effectively similar to calling HitTest with ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent
		if (Physics.Raycast (ray, out hit, maxRayDistance, collisionLayerMask)) {
			//we're going to get the position from the contact point
			foundSquare.transform.position = hit.point;
			Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", foundSquare.transform.position.x, foundSquare.transform.position.y, foundSquare.transform.position.z));

			//and the rotation from the transform of the plane collider
			SquareState = FocusState.Found;
			foundSquare.transform.rotation = hit.transform.rotation;
			return;
		}


		#else
		var screenPosition = Camera.main.ScreenToViewportPoint(center);
		ARPoint point = new ARPoint {
			x = screenPosition.x,
			y = screenPosition.y
		};

		// prioritize reults types
		ARHitTestResultType[] resultTypes = {
			ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent, 
			// if you want to use infinite planes use this:
			//ARHitTestResultType.ARHitTestResultTypeExistingPlane,
			//ARHitTestResultType.ARHitTestResultTypeHorizontalPlane, 
			//ARHitTestResultType.ARHitTestResultTypeFeaturePoint
		}; 

		foreach (ARHitTestResultType resultType in resultTypes)
		{
			if (HitTestWithResultType (point, resultType))
			{
				SquareState = FocusState.Found;
				return;
			}
		}

		#endif

		//if you got here, we have not found a plane, so if camera is facing below horizon, display the focus "finding" square
		if (trackingInitialized) {
			SquareState = FocusState.Finding;

			//check camera forward is facing downward
			if (Vector3.Dot(Camera.main.transform.forward, Vector3.down) > 0)
			{

				//position the focus finding square a distance from camera and facing up
				findingSquare.transform.position = Camera.main.ScreenToWorldPoint(center);

				//vector from camera to focussquare
				Vector3 vecToCamera = findingSquare.transform.position - Camera.main.transform.position;

				//find vector that is orthogonal to camera vector and up vector
				Vector3 vecOrthogonal = Vector3.Cross(vecToCamera, Vector3.up);

				//find vector orthogonal to both above and up vector to find the forward vector in basis function
				Vector3 vecForward = Vector3.Cross(vecOrthogonal, Vector3.up);


				findingSquare.transform.rotation = Quaternion.LookRotation(vecForward,Vector3.up);

			}
			else
			{
				//we will not display finding square if camera is not facing below horizon
				findingSquare.SetActive(false);
			}

		}

	}

19 View Source File : CharacterMotor.cs
License : MIT License
Project Creator : deadgg

public CharacterMotorState Simulate(Vector3 moveDirection, bool shouldJump)
    {
        var deltaTime = Zapnet.Network.FixedDeltaTime;
        var velocity = state.velocity;

        velocity = ApplyInputVelocityChange(velocity, moveDirection);
        velocity = ApplyGravityAndJumping(velocity, shouldJump);

        var moveDistance = Vector3.zero;
        var currentMovementOffset = velocity * deltaTime;
        var lastPosition = transform.position;
        var pushDownOffset = Mathf.Max(_controller.stepOffset, new Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude);

        if (state.isGrounded)
        {
            currentMovementOffset = currentMovementOffset - (pushDownOffset * Vector3.up);
        }

        if (!Physics.autoSyncTransforms)
        {
            Physics.SyncTransforms();
        }

        _groundNormal = Vector3.zero;
        _controller.Move(Vector3.zero);

        state.collisionFlags = _controller.Move(currentMovementOffset);
        state.lastHitPoint = state.hitPoint;
        _lastGroundNormal = _groundNormal;

        var oldHorizontalVelocity = new Vector3(velocity.x, 0, velocity.z);

        state.velocity = (transform.position - lastPosition) / deltaTime;

        var newHorizontalVelocity = new Vector3(state.velocity.x, 0, state.velocity.z);

        if (oldHorizontalVelocity == Vector3.zero)
        {
            state.velocity = new Vector3(0, state.velocity.y, 0);
        }
        else
        {
            float projectedNewVelocity = Vector3.Dot(newHorizontalVelocity, oldHorizontalVelocity) / oldHorizontalVelocity.sqrMagnitude;
            state.velocity = (oldHorizontalVelocity * Mathf.Clamp01(projectedNewVelocity)) + (state.velocity.y * Vector3.up);
        }

        if (state.velocity.y < (velocity.y - 0.001f))
        {
            if (state.velocity.y < 0)
            {
                state.velocity.y = velocity.y;
            }
            else
            {
                state.holdingJumpButton = false;
            }
        }

        if (state.isGrounded && !IsGroundedTest())
        {
            state.isGrounded = false;
            transform.position = transform.position + (pushDownOffset * Vector3.up);
        }
        else
        {
            if (!state.isGrounded && IsGroundedTest())
            {
                state.isGrounded = true;
                state.isJumping = false;
            }
        }

        return state;
    }

19 View Source File : CircularDrive.cs
License : MIT License
Project Creator : dag10

private void ComputeAngle( Hand hand )
		{
			Vector3 toHandProjected = ComputeToTransformProjected( hand.hoverSphereTransform );

			if ( !toHandProjected.Equals( lastHandProjected ) )
			{
				float absAngleDelta = Vector3.Angle( lastHandProjected, toHandProjected );

				if ( absAngleDelta > 0.0f )
				{
					if ( frozen )
					{
						float frozenSqDist = ( hand.hoverSphereTransform.position - frozenHandWorldPos ).sqrMagnitude;
						if ( frozenSqDist > frozenSqDistanceMinMaxThreshold.x )
						{
							outAngle = frozenAngle + Random.Range( -1.0f, 1.0f );

							float magnitude = Util.RemapNumberClamped( frozenSqDist, frozenSqDistanceMinMaxThreshold.x, frozenSqDistanceMinMaxThreshold.y, 0.0f, 1.0f );
							if ( magnitude > 0 )
							{
								StartCoroutine( HapticPulses( hand.controller, magnitude, 10 ) );
							}
							else
							{
								StartCoroutine( HapticPulses( hand.controller, 0.5f, 10 ) );
							}

							if ( frozenSqDist >= frozenSqDistanceMinMaxThreshold.y )
							{
								onFrozenDistanceThreshold.Invoke();
							}
						}
					}
					else
					{
						Vector3 cross = Vector3.Cross( lastHandProjected, toHandProjected ).normalized;
						float dot = Vector3.Dot( worldPlaneNormal, cross );

						float signedAngleDelta = absAngleDelta;

						if ( dot < 0.0f )
						{
							signedAngleDelta = -signedAngleDelta;
						}

						if ( limited )
						{
							float angleTmp = Mathf.Clamp( outAngle + signedAngleDelta, minAngle, maxAngle );

							if ( outAngle == minAngle )
							{
								if ( angleTmp > minAngle && absAngleDelta < minMaxAngularThreshold )
								{
									outAngle = angleTmp;
									lastHandProjected = toHandProjected;
								}
							}
							else if ( outAngle == maxAngle )
							{
								if ( angleTmp < maxAngle && absAngleDelta < minMaxAngularThreshold )
								{
									outAngle = angleTmp;
									lastHandProjected = toHandProjected;
								}
							}
							else if ( angleTmp == minAngle )
							{
								outAngle = angleTmp;
								lastHandProjected = toHandProjected;
								onMinAngle.Invoke();
								if ( freezeOnMin )
								{
									Freeze( hand );
								}
							}
							else if ( angleTmp == maxAngle )
							{
								outAngle = angleTmp;
								lastHandProjected = toHandProjected;
								onMaxAngle.Invoke();
								if ( freezeOnMax )
								{
									Freeze( hand );
								}
							}
							else
							{
								outAngle = angleTmp;
								lastHandProjected = toHandProjected;
							}
						}
						else
						{
							outAngle += signedAngleDelta;
							lastHandProjected = toHandProjected;
						}
					}
				}
			}
		}

19 View Source File : LeanPlane.cs
License : GNU General Public License v3.0
Project Creator : Cytoid

private bool Raycast(Vector3 point, Vector3 normal, Ray ray, ref float distance)
		{
			var b = Vector3.Dot(ray.direction, normal);

			if (Mathf.Approximately(b, 0.0f) == true)
			{
				return false;
			}

			var d = -Vector3.Dot(normal, point);
			var a = -Vector3.Dot(ray.origin, normal) - d;

			distance = a / b;

			return distance > 0.0f;
		}

19 View Source File : NavMeshLinkEditor.cs
License : MIT License
Project Creator : DKaravolos

public void OnSceneGUI()
        {
            var navLink = (NavMeshLink)target;
            if (!navLink.enabled)
                return;

            var mat = UnscaledLocalToWorldMatrix(navLink.transform);

            var startPt = mat.MultiplyPoint(navLink.startPoint);
            var endPt = mat.MultiplyPoint(navLink.endPoint);
            var midPt = Vector3.Lerp(startPt, endPt, 0.35f);
            var startSize = HandleUtility.GetHandleSize(startPt);
            var endSize = HandleUtility.GetHandleSize(endPt);
            var midSize = HandleUtility.GetHandleSize(midPt);

            var zup = Quaternion.FromToRotation(Vector3.forward, Vector3.up);
            var right = mat.MultiplyVector(CalcLinkRight(navLink));

            var oldColor = Handles.color;
            Handles.color = s_HandleColor;

            Vector3 pos;

            if (navLink.GetInstanceID() == s_SelectedID && s_SelectedPoint == 0)
            {
                EditorGUI.BeginChangeCheck();
                Handles.CubeHandleCap(0, startPt, zup, 0.1f * startSize, Event.current.type);
                pos = Handles.PositionHandle(startPt, navLink.transform.rotation);
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(navLink, "Move link point");
                    navLink.startPoint = mat.inverse.MultiplyPoint(pos);
                }
            }
            else
            {
                if (Handles.Button(startPt, zup, 0.1f * startSize, 0.1f * startSize, Handles.CubeHandleCap))
                {
                    s_SelectedPoint = 0;
                    s_SelectedID = navLink.GetInstanceID();
                }
            }

            if (navLink.GetInstanceID() == s_SelectedID && s_SelectedPoint == 1)
            {
                EditorGUI.BeginChangeCheck();
                Handles.CubeHandleCap(0, endPt, zup, 0.1f * startSize, Event.current.type);
                pos = Handles.PositionHandle(endPt, navLink.transform.rotation);
                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(navLink, "Move link point");
                    navLink.endPoint = mat.inverse.MultiplyPoint(pos);
                }
            }
            else
            {
                if (Handles.Button(endPt, zup, 0.1f * endSize, 0.1f * endSize, Handles.CubeHandleCap))
                {
                    s_SelectedPoint = 1;
                    s_SelectedID = navLink.GetInstanceID();
                }
            }

            EditorGUI.BeginChangeCheck();
            pos = Handles.Slider(midPt + right * navLink.width * 0.5f, right, midSize * 0.03f, Handles.DotHandleCap, 0);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(navLink, "Adjust link width");
                navLink.width = Mathf.Max(0.0f, 2.0f * Vector3.Dot(right, (pos - midPt)));
            }

            EditorGUI.BeginChangeCheck();
            pos = Handles.Slider(midPt - right * navLink.width * 0.5f, -right, midSize * 0.03f, Handles.DotHandleCap, 0);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(navLink, "Adjust link width");
                navLink.width = Mathf.Max(0.0f, 2.0f * Vector3.Dot(-right, (pos - midPt)));
            }

            Handles.color = oldColor;
        }

19 View Source File : Vector3.cs
License : MIT License
Project Creator : bbepis

public static Vector3 Reflect( Vector3 inDirection, Vector3 inNormal )
      {
         return -2f * Dot( inNormal, inDirection ) * inNormal + inDirection;
      }

19 View Source File : WaypointProgressTracker.cs
License : MIT License
Project Creator : Donut-Studios

private void Update()
        {
            if (progressStyle == ProgressStyle.SmoothAlongRoute)
            {
                // determine the position we should currently be aiming for
                // (this is different to the current progress position, it is a a certain amount ahead along the route)
                // we use lerp as a simple way of smoothing out the speed over time.
                if (Time.deltaTime > 0)
                {
                    speed = Mathf.Lerp(speed, (lastPosition - transform.position).magnitude/Time.deltaTime,
                                       Time.deltaTime);
                }
                target.position =
                    circuit.GetRoutePoint(progressDistance + lookAheadForTargetOffset + lookAheadForTargetFactor*speed)
                           .position;
                target.rotation =
                    Quaternion.LookRotation(
                        circuit.GetRoutePoint(progressDistance + lookAheadForSpeedOffset + lookAheadForSpeedFactor*speed)
                               .direction);


                // get our current progress along the route
                progressPoint = circuit.GetRoutePoint(progressDistance);
                Vector3 progressDelta = progressPoint.position - transform.position;
                if (Vector3.Dot(progressDelta, progressPoint.direction) < 0)
                {
                    progressDistance += progressDelta.magnitude*0.5f;
                }

                lastPosition = transform.position;
            }
            else
            {
                // point to point mode. Just increase the waypoint if we're close enough:

                Vector3 targetDelta = target.position - transform.position;
                if (targetDelta.magnitude < pointToPointThreshold)
                {
                    progressNum = (progressNum + 1)%circuit.Waypoints.Length;
                }


                target.position = circuit.Waypoints[progressNum].position;
                target.rotation = circuit.Waypoints[progressNum].rotation;

                // get our current progress along the route
                progressPoint = circuit.GetRoutePoint(progressDistance);
                Vector3 progressDelta = progressPoint.position - transform.position;
                if (Vector3.Dot(progressDelta, progressPoint.direction) < 0)
                {
                    progressDistance += progressDelta.magnitude;
                }
                lastPosition = transform.position;
            }
        }

19 View Source File : MathUtils.cs
License : MIT License
Project Creator : dag10

public static Vector3 NearestPointToLines(Ray p, Ray q)
        {
            float a = Vector3.Dot(p.direction, p.direction);
            float b = Vector3.Dot(p.direction, q.direction);
            float c = Vector3.Dot(q.direction, q.direction);
            Vector3 w0 = p.origin - q.origin;
            float den = a * c - b * b;
            float epsilon = 0.00001f;
            if (den < epsilon)
            {
                // parallel, so just average origins
                return 0.5f * (p.origin + q.origin);
            }
            float d = Vector3.Dot(p.direction, w0);
            float e = Vector3.Dot(q.direction, w0);
            float sc = (b * e - c * d) / den;
            float tc = (a * e - b * d) / den;
            Vector3 point = 0.5f * (p.origin + sc * p.direction + q.origin + tc * q.direction);
            return point;
        }

19 View Source File : SimpleCharacterControl.cs
License : MIT License
Project Creator : harshitjuneja

private void OnCollisionEnter(Collision collision)
    {
        ContactPoint[] contactPoints = collision.contacts;
        for(int i = 0; i < contactPoints.Length; i++)
        {
            if (Vector3.Dot(contactPoints[i].normal, Vector3.up) > 0.5f)
            {
                if (!m_collisions.Contains(collision.collider)) {
                    m_collisions.Add(collision.collider);
                }
                m_isGrounded = true;
            }
        }
    }

19 View Source File : Vector3.cs
License : MIT License
Project Creator : AnotherEnd15

public static void OrthoNormalize(ref Vector3 normal, ref Vector3 tangent)
        {
            float num1 = Vector3.magnitudeStatic(ref normal);
            if (num1 > (double) Mathf.Epsilon)
                normal /= num1;
            else
                normal = new Vector3(1f, 0.0f, 0.0f);
            float num2 = Vector3.Dot(normal, tangent);
            tangent -= num2 * normal;
            float num3 = Vector3.magnitudeStatic(ref tangent);
            if (num3 < (double) Mathf.Epsilon)
                tangent = Vector3.orthoNormalVectorFast(ref normal);
            else
                tangent /= num3;
        }

19 View Source File : MalbersTools.cs
License : MIT License
Project Creator : Interactml

public static float HorizontalAngle(Vector3 From, Vector3 To, Vector3 Up)
        {
            float lAngle = Mathf.Atan2(Vector3.Dot(Up, Vector3.Cross(From, To)), Vector3.Dot(From, To));
            lAngle *= Mathf.Rad2Deg;

            if (Mathf.Abs(lAngle) < 0.0001f) { lAngle = 0f; }

            return lAngle;
        }

19 View Source File : Longbow.cs
License : MIT License
Project Creator : dag10

private void HandAttachedUpdate( Hand hand )
		{
			// Reset transform since we cheated it right after getting poses on previous frame
			transform.localPosition = Vector3.zero;
			transform.localRotation = Quaternion.idenreplacedy;

			// Update handedness guess
			EvaluateHandedness();

			if ( nocked )
			{
				deferNewPoses = true;

				Vector3 nockToarrowHand = ( arrowHand.arrowNockTransform.parent.position - nockRestTransform.position ); // Vector from bow nock transform to arrowhand nock transform - used to align bow when drawing

				// Align bow
				// Time lerp value used for ramping into drawn bow orientation
				float lerp = Util.RemapNumberClamped( Time.time, nockLerpStartTime, ( nockLerpStartTime + lerpDuration ), 0f, 1f );

				float pullLerp = Util.RemapNumberClamped( nockToarrowHand.magnitude, minPull, maxPull, 0f, 1f ); // Normalized current state of bow draw 0 - 1

				Vector3 arrowNockTransformToHeadset = ( ( Player.instance.hmdTransform.position + ( Vector3.down * 0.05f ) ) - arrowHand.arrowNockTransform.parent.position ).normalized;
				Vector3 arrowHandPosition = ( arrowHand.arrowNockTransform.parent.position + ( ( arrowNockTransformToHeadset * drawOffset ) * pullLerp ) ); // Use this line to lerp arrowHand nock position
				//Vector3 arrowHandPosition = arrowHand.arrowNockTransform.position; // Use this line if we don't want to lerp arrowHand nock position

				Vector3 pivotToString = ( arrowHandPosition - pivotTransform.position ).normalized;
				Vector3 pivotToLowerHandle = ( handleTransform.position - pivotTransform.position ).normalized;
				bowLeftVector = -Vector3.Cross( pivotToLowerHandle, pivotToString );
				pivotTransform.rotation = Quaternion.Lerp( nockLerpStartRotation, Quaternion.LookRotation( pivotToString, bowLeftVector ), lerp );

				// Move nock position
				if ( Vector3.Dot( nockToarrowHand, -nockTransform.forward ) > 0 )
				{
					float distanceToarrowHand = nockToarrowHand.magnitude * lerp;

					nockTransform.localPosition = new Vector3( 0f, 0f, Mathf.Clamp( -distanceToarrowHand, -maxPull, 0f ) );

					nockDistanceTravelled = -nockTransform.localPosition.z;

					arrowVelocity = Util.RemapNumber( nockDistanceTravelled, minPull, maxPull, arrowMinVelocity, arrowMaxVelocity );

					drawTension = Util.RemapNumberClamped( nockDistanceTravelled, 0, maxPull, 0f, 1f );

					this.bowDrawLinearMapping.value = drawTension; // Send drawTension value to LinearMapping script, which drives the bow draw animation

					if ( nockDistanceTravelled > minPull )
					{
						pulled = true;
					}
					else
					{
						pulled = false;
					}

					if ( ( nockDistanceTravelled > ( lastTickDistance + hapticDistanceThreshold ) ) || nockDistanceTravelled < ( lastTickDistance - hapticDistanceThreshold ) )
					{
						ushort hapticStrength = (ushort)Util.RemapNumber( nockDistanceTravelled, 0, maxPull, bowPullPulseStrengthLow, bowPullPulseStrengthHigh );
						hand.controller.TriggerHapticPulse( hapticStrength );
						hand.otherHand.controller.TriggerHapticPulse( hapticStrength );

						drawSound.PlayBowTensionClicks( drawTension );

						lastTickDistance = nockDistanceTravelled;
					}

					if ( nockDistanceTravelled >= maxPull )
					{
						if ( Time.time > nextStrainTick )
						{
							hand.controller.TriggerHapticPulse( 400 );
							hand.otherHand.controller.TriggerHapticPulse( 400 );

							drawSound.PlayBowTensionClicks( drawTension );

							nextStrainTick = Time.time + Random.Range( minStrainTickTime, maxStrainTickTime );
						}
					}
				}
				else
				{
					nockTransform.localPosition = new Vector3( 0f, 0f, 0f );

					this.bowDrawLinearMapping.value = 0f;
				}
			}
			else
			{
				if ( lerpBackToZeroRotation )
				{
					float lerp = Util.RemapNumber( Time.time, lerpStartTime, lerpStartTime + lerpDuration, 0, 1 );

					pivotTransform.localRotation = Quaternion.Lerp( lerpStartRotation, Quaternion.idenreplacedy, lerp );

					if ( lerp >= 1 )
					{
						lerpBackToZeroRotation = false;
					}
				}
			}
		}

19 View Source File : Teleport.cs
License : MIT License
Project Creator : dag10

private void UpdatePointer()
		{
			Vector3 pointerStart = pointerStartTransform.position;
			Vector3 pointerEnd;
			Vector3 pointerDir = pointerStartTransform.forward;
			bool hitSomething = false;
			bool showPlayAreaPreview = false;
			Vector3 playerFeetOffset = player.trackingOriginTransform.position - player.feetPositionGuess;

			Vector3 arcVelocity = pointerDir * arcDistance;

			TeleportMarkerBase hitTeleportMarker = null;

			//Check pointer angle
			float dotUp = Vector3.Dot( pointerDir, Vector3.up );
			float dotForward = Vector3.Dot( pointerDir, player.hmdTransform.forward );
			bool pointerAtBadAngle = false;
			if ( ( dotForward > 0 && dotUp > 0.75f ) || ( dotForward < 0.0f && dotUp > 0.5f ) )
			{
				pointerAtBadAngle = true;
			}

			//Trace to see if the pointer hit anything
			RaycastHit hitInfo;
			teleportArc.SetArcData( pointerStart, arcVelocity, true, pointerAtBadAngle );
			if ( teleportArc.DrawArc( out hitInfo ) )
			{
				hitSomething = true;
				hitTeleportMarker = hitInfo.collider.GetComponentInParent<TeleportMarkerBase>();
			}

			if ( pointerAtBadAngle )
			{
				hitTeleportMarker = null;
			}

			HighlightSelected( hitTeleportMarker );

			if ( hitTeleportMarker != null ) //Hit a teleport marker
			{
				if ( hitTeleportMarker.locked )
				{
					teleportArc.SetColor( pointerLockedColor );
#if (UNITY_5_4)
					pointerLineRenderer.SetColors( pointerLockedColor, pointerLockedColor );
#else
					pointerLineRenderer.startColor = pointerLockedColor;
					pointerLineRenderer.endColor = pointerLockedColor;
#endif
					destinationReticleTransform.gameObject.SetActive( false );
				}
				else
				{
					teleportArc.SetColor( pointerValidColor );
#if (UNITY_5_4)
					pointerLineRenderer.SetColors( pointerValidColor, pointerValidColor );
#else
					pointerLineRenderer.startColor = pointerValidColor;
					pointerLineRenderer.endColor = pointerValidColor;
#endif
					destinationReticleTransform.gameObject.SetActive( hitTeleportMarker.showReticle );
				}

				offsetReticleTransform.gameObject.SetActive( true );

				invalidReticleTransform.gameObject.SetActive( false );

				pointedAtTeleportMarker = hitTeleportMarker;
				pointedAtPosition = hitInfo.point;

				if ( showPlayAreaMarker )
				{
					//Show the play area marker if this is a teleport area
					TeleportArea teleportArea = pointedAtTeleportMarker as TeleportArea;
					if ( teleportArea != null && !teleportArea.locked && playAreaPreviewTransform != null )
					{
						Vector3 offsetToUse = playerFeetOffset;

						//Adjust the actual offset to prevent the play area marker from moving too much
						if ( !movedFeetFarEnough )
						{
							float distanceFromStartingOffset = Vector3.Distance( playerFeetOffset, startingFeetOffset );
							if ( distanceFromStartingOffset < 0.1f )
							{
								offsetToUse = startingFeetOffset;
							}
							else if ( distanceFromStartingOffset < 0.4f )
							{
								offsetToUse = Vector3.Lerp( startingFeetOffset, playerFeetOffset, ( distanceFromStartingOffset - 0.1f ) / 0.3f );
							}
							else
							{
								movedFeetFarEnough = true;
							}
						}

						playAreaPreviewTransform.position = pointedAtPosition + offsetToUse;

						showPlayAreaPreview = true;
					}
				}

				pointerEnd = hitInfo.point;
			}
			else //Hit neither
			{
				destinationReticleTransform.gameObject.SetActive( false );
				offsetReticleTransform.gameObject.SetActive( false );

				teleportArc.SetColor( pointerInvalidColor );
#if (UNITY_5_4)
				pointerLineRenderer.SetColors( pointerInvalidColor, pointerInvalidColor );
#else
				pointerLineRenderer.startColor = pointerInvalidColor;
				pointerLineRenderer.endColor = pointerInvalidColor;
#endif
				invalidReticleTransform.gameObject.SetActive( !pointerAtBadAngle );

				//Orient the invalid reticle to the normal of the trace hit point
				Vector3 normalToUse = hitInfo.normal;
				float angle = Vector3.Angle( hitInfo.normal, Vector3.up );
				if ( angle < 15.0f )
				{
					normalToUse = Vector3.up;
				}
				invalidReticleTargetRotation = Quaternion.FromToRotation( Vector3.up, normalToUse );
				invalidReticleTransform.rotation = Quaternion.Slerp( invalidReticleTransform.rotation, invalidReticleTargetRotation, 0.1f );

				//Scale the invalid reticle based on the distance from the player
				float distanceFromPlayer = Vector3.Distance( hitInfo.point, player.hmdTransform.position );
				float invalidReticleCurrentScale = Util.RemapNumberClamped( distanceFromPlayer, invalidReticleMinScaleDistance, invalidReticleMaxScaleDistance, invalidReticleMinScale, invalidReticleMaxScale );
				invalidReticleScale.x = invalidReticleCurrentScale;
				invalidReticleScale.y = invalidReticleCurrentScale;
				invalidReticleScale.z = invalidReticleCurrentScale;
				invalidReticleTransform.transform.localScale = invalidReticleScale;

				pointedAtTeleportMarker = null;

				if ( hitSomething )
				{
					pointerEnd = hitInfo.point;
				}
				else
				{
					pointerEnd = teleportArc.GetArcPositionAtTime( teleportArc.arcDuration );
				}

				//Debug floor
				if ( debugFloor )
				{
					floorDebugSphere.gameObject.SetActive( false );
					floorDebugLine.gameObject.SetActive( false );
				}
			}

			if ( playAreaPreviewTransform != null )
			{
				playAreaPreviewTransform.gameObject.SetActive( showPlayAreaPreview );
			}

			if ( !showOffsetReticle )
			{
				offsetReticleTransform.gameObject.SetActive( false );
			}

			destinationReticleTransform.position = pointedAtPosition;
			invalidReticleTransform.position = pointerEnd;
			onActivateObjectTransform.position = pointerEnd;
			onDeactivateObjectTransform.position = pointerEnd;
			offsetReticleTransform.position = pointerEnd - playerFeetOffset;

			reticleAudioSource.transform.position = pointedAtPosition;

			pointerLineRenderer.SetPosition( 0, pointerStart );
			pointerLineRenderer.SetPosition( 1, pointerEnd );
		}

19 View Source File : Vector3.cs
License : MIT License
Project Creator : AnotherEnd15

public static void OrthoNormalize(ref Vector3 normal, ref Vector3 tangent, ref Vector3 binormal)
        {
            float num1 = Vector3.magnitudeStatic(ref normal);
            if (num1 > (double) Mathf.Epsilon)
                normal /= num1;
            else
                normal = new Vector3(1f, 0.0f, 0.0f);
            float num2 = Vector3.Dot(normal, tangent);
            tangent -= num2 * normal;
            float num3 = Vector3.magnitudeStatic(ref tangent);
            if (num3 > (double) Mathf.Epsilon)
                tangent /= num3;
            else
                tangent = Vector3.orthoNormalVectorFast(ref normal);
            float num4 = Vector3.Dot(tangent, binormal);
            float num5 = Vector3.Dot(normal, binormal);
            binormal -= num5 * normal + num4 * tangent;
            float num6 = Vector3.magnitudeStatic(ref binormal);
            if (num6 > (double) Mathf.Epsilon)
                binormal /= num6;
            else
                binormal = Vector3.Cross(normal, tangent);
        }

19 View Source File : BodyCollider.cs
License : MIT License
Project Creator : dag10

void FixedUpdate()
		{
			float distanceFromFloor = Vector3.Dot( head.localPosition, Vector3.up );
			capsuleCollider.height = Mathf.Max( capsuleCollider.radius, distanceFromFloor );
			transform.localPosition = head.localPosition - 0.5f * distanceFromFloor * Vector3.up;
		}

19 View Source File : LeanPath.cs
License : GNU General Public License v3.0
Project Creator : Cytoid

private Vector3 GetClosestPoint(Vector3 position, Vector3 origin, Vector3 direction)
		{
			var denom = Vector3.Dot(direction, direction);

			// If the line doesn't point anywhere, return origin
			if (denom == 0.0f)
			{
				return origin;
			}

			var dist01 = Vector3.Dot(position - origin, direction) / denom;

			return origin + direction * Mathf.Clamp01(dist01);
		}

19 View Source File : SteamVR_Utils.cs
License : MIT License
Project Creator : dag10

public static void TakeStereoScreenshot(uint screenshotHandle, GameObject target, int cellSize, float ipd, ref string previewFilename, ref string VRFilename)
	{
		const int width = 4096;
		const int height = width / 2;
		const int halfHeight = height / 2;

		var texture = new Texture2D(width, height * 2, TextureFormat.ARGB32, false);

		var timer = new System.Diagnostics.Stopwatch();

		Camera tempCamera = null;

		timer.Start();

		var camera = target.GetComponent<Camera>();
		if (camera == null)
		{
			if (tempCamera == null)
				tempCamera = new GameObject().AddComponent<Camera>();
			camera = tempCamera;
		}

		// Render preview texture
		const int previewWidth = 2048;
		const int previewHeight = 2048;
		var previewTexture = new Texture2D(previewWidth, previewHeight, TextureFormat.ARGB32, false);
		var targetPreviewTexture = new RenderTexture(previewWidth, previewHeight, 24);

		var oldTargetTexture = camera.targetTexture;
		var oldOrthographic = camera.orthographic;
		var oldFieldOfView = camera.fieldOfView;
		var oldAspect = camera.aspect;
		var oldstereoTargetEye = camera.stereoTargetEye;
		camera.stereoTargetEye = StereoTargetEyeMask.None;
		camera.fieldOfView = 60.0f;
		camera.orthographic = false;
		camera.targetTexture = targetPreviewTexture;
		camera.aspect = 1.0f;
		camera.Render();

		// copy preview texture
		RenderTexture.active = targetPreviewTexture;
		previewTexture.ReadPixels(new Rect(0, 0, targetPreviewTexture.width, targetPreviewTexture.height), 0, 0);
		RenderTexture.active = null;
		camera.targetTexture = null;
		Object.DestroyImmediate(targetPreviewTexture);

		var fx = camera.gameObject.AddComponent<SteamVR_SphericalProjection>();

		var oldPosition = target.transform.localPosition;
		var oldRotation = target.transform.localRotation;
		var basePosition = target.transform.position;
		var baseRotation = Quaternion.Euler(0, target.transform.rotation.eulerAngles.y, 0);

		var transform = camera.transform;

		int vTotal = halfHeight / cellSize;
		float dv = 90.0f / vTotal; // vertical degrees per segment
		float dvHalf = dv / 2.0f;

		var targetTexture = new RenderTexture(cellSize, cellSize, 24);
		targetTexture.wrapMode = TextureWrapMode.Clamp;
		targetTexture.antiAliasing = 8;

		camera.fieldOfView = dv;
		camera.orthographic = false;
		camera.targetTexture = targetTexture;
		camera.aspect = oldAspect;
		camera.stereoTargetEye = StereoTargetEyeMask.None;

		// Render sections of a sphere using a rectilinear projection
		// and resample using a sphereical projection into a single panorama
		// texture per eye.  We break into sections in order to keep the eye
		// separation similar around the sphere.  Rendering alternates between
		// top and bottom sections, sweeping horizontally around the sphere,
		// alternating left and right eyes.
		for (int v = 0; v < vTotal; v++)
		{
			var pitch = 90.0f - (v * dv) - dvHalf;
			var uTotal = width / targetTexture.width;
			var du = 360.0f / uTotal; // horizontal degrees per segment
			var duHalf = du / 2.0f;

			var vTarget = v * halfHeight / vTotal;

			for (int i = 0; i < 2; i++) // top, bottom
			{
				if (i == 1)
				{
					pitch = -pitch;
					vTarget = height - vTarget - cellSize;
				}

				for (int u = 0; u < uTotal; u++)
				{
					var yaw = -180.0f + (u * du) + duHalf;

					var uTarget = u * width / uTotal;

					var vTargetOffset = 0;
					var xOffset = -ipd / 2 * Mathf.Cos(pitch * Mathf.Deg2Rad);

					for (int j = 0; j < 2; j++) // left, right
					{
						if (j == 1)
						{
							vTargetOffset = height;
							xOffset = -xOffset;
						}

						var offset = baseRotation * Quaternion.Euler(0, yaw, 0) * new Vector3(xOffset, 0, 0);
						transform.position = basePosition + offset;

						var direction = Quaternion.Euler(pitch, yaw, 0.0f);
						transform.rotation = baseRotation * direction;

						// vector pointing to center of this section
						var N = direction * Vector3.forward;

						// horizontal span of this section in degrees
						var phi0 = yaw - (du / 2);
						var phi1 = phi0 + du;

						// vertical span of this section in degrees
						var theta0 = pitch + (dv / 2);
						var theta1 = theta0 - dv;

						var midPhi = (phi0 + phi1) / 2;
						var baseTheta = Mathf.Abs(theta0) < Mathf.Abs(theta1) ? theta0 : theta1;

						// vectors pointing to corners of image closes to the equator
						var V00 = Quaternion.Euler(baseTheta, phi0, 0.0f) * Vector3.forward;
						var V01 = Quaternion.Euler(baseTheta, phi1, 0.0f) * Vector3.forward;

						// vectors pointing to top and bottom midsection of image
						var V0M = Quaternion.Euler(theta0, midPhi, 0.0f) * Vector3.forward;
						var V1M = Quaternion.Euler(theta1, midPhi, 0.0f) * Vector3.forward;

						// intersection points for each of the above
						var P00 = V00 / Vector3.Dot(V00, N);
						var P01 = V01 / Vector3.Dot(V01, N);
						var P0M = V0M / Vector3.Dot(V0M, N);
						var P1M = V1M / Vector3.Dot(V1M, N);

						// calculate basis vectors for plane
						var P00_P01 = P01 - P00;
						var P0M_P1M = P1M - P0M;

						var uMag = P00_P01.magnitude;
						var vMag = P0M_P1M.magnitude;

						var uScale = 1.0f / uMag;
						var vScale = 1.0f / vMag;

						var uAxis = P00_P01 * uScale;
						var vAxis = P0M_P1M * vScale;

						// update material constant buffer
						fx.Set(N, phi0, phi1, theta0, theta1,
							uAxis, P00, uScale,
							vAxis, P0M, vScale);

						camera.aspect = uMag / vMag;
						camera.Render();

						RenderTexture.active = targetTexture;
						texture.ReadPixels(new Rect(0, 0, targetTexture.width, targetTexture.height), uTarget, vTarget + vTargetOffset);
						RenderTexture.active = null;                 
					}

					// Update progress
					var progress = (float)( v * ( uTotal * 2.0f ) + u + i*uTotal) / (float)(vTotal * ( uTotal * 2.0f ) );
					OpenVR.Screenshots.UpdateScreenshotProgress(screenshotHandle, progress);
				}
			}
		}

		// 100% flush
		OpenVR.Screenshots.UpdateScreenshotProgress(screenshotHandle, 1.0f);

		// Save textures to disk.
		// Add extensions
		previewFilename += ".png";
		VRFilename += ".png";

		// Preview
		previewTexture.Apply();
		System.IO.File.WriteAllBytes(previewFilename, previewTexture.EncodeToPNG());

		// VR
		texture.Apply();
		System.IO.File.WriteAllBytes(VRFilename, texture.EncodeToPNG());

		// Cleanup.
		if (camera != tempCamera)
		{
			camera.targetTexture = oldTargetTexture;
			camera.orthographic = oldOrthographic;
			camera.fieldOfView = oldFieldOfView;
			camera.aspect = oldAspect;
			camera.stereoTargetEye = oldstereoTargetEye;

			target.transform.localPosition = oldPosition;
			target.transform.localRotation = oldRotation;
		}
		else
		{
			tempCamera.targetTexture = null;
		}

		Object.DestroyImmediate(targetTexture);
		Object.DestroyImmediate(fx);

		timer.Stop();
		Debug.Log(string.Format("Screenshot took {0} seconds.", timer.Elapsed));

		if (tempCamera != null)
		{
			Object.DestroyImmediate(tempCamera.gameObject);
		}

		Object.DestroyImmediate(previewTexture);
		Object.DestroyImmediate(texture);
	}

19 View Source File : SteamVR_Controller.cs
License : MIT License
Project Creator : dag10

public static int GetDeviceIndex(DeviceRelation relation,
		ETrackedDeviceClreplaced deviceClreplaced = ETrackedDeviceClreplaced.Controller,
		int relativeTo = (int)OpenVR.k_unTrackedDeviceIndex_Hmd) // use -1 for absolute tracking space
	{
		var result = -1;

		var invXform = ((uint)relativeTo < OpenVR.k_unMaxTrackedDeviceCount) ?
			Input(relativeTo).transform.GetInverse() : SteamVR_Utils.RigidTransform.idenreplacedy;

		var system = OpenVR.System;
		if (system == null)
			return result;

		var best = -float.MaxValue;
		for (int i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++)
		{
			if (i == relativeTo || system.GetTrackedDeviceClreplaced((uint)i) != deviceClreplaced)
				continue;

			var device = Input(i);
			if (!device.connected)
				continue;

			if (relation == DeviceRelation.First)
				return i;

			float score;

			var pos = invXform * device.transform.pos;
			if (relation == DeviceRelation.FarthestRight)
			{
				score = pos.x;
			}
			else if (relation == DeviceRelation.FarthestLeft)
			{
				score = -pos.x;
			}
			else
			{
				var dir = new Vector3(pos.x, 0.0f, pos.z).normalized;
				var dot = Vector3.Dot(dir, Vector3.forward);
				var cross = Vector3.Cross(dir, Vector3.forward);
				if (relation == DeviceRelation.Leftmost)
				{
					score = (cross.y > 0.0f) ? 2.0f - dot : dot;
				}
				else
				{
					score = (cross.y < 0.0f) ? 2.0f - dot : dot;
				}
			}
			
			if (score > best)
			{
				result = i;
				best = score;
			}
		}

		return result;
	}

19 View Source File : LeanPath.cs
License : GNU General Public License v3.0
Project Creator : Cytoid

private float GetClosestDistance(Ray ray, Vector3 point)
		{
			var denom = Vector3.Dot(ray.direction, ray.direction);

			// If the ray doesn't point anywhere, return distance from origin to point
			if (denom == 0.0f)
			{
				return Vector3.Distance(ray.origin, point);
			}

			var dist01 = Vector3.Dot(point - ray.origin, ray.direction) / denom;

			return Vector3.Distance(point, ray.GetPoint(dist01));
		}

19 View Source File : MathExtra.cs
License : MIT License
Project Creator : deadgg

public static Vector3 ProjectPointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
    {
        var rightHand = point - lineStart;
        var difference = lineEnd - lineStart;
        var magnitude = difference.magnitude;
        var leftHand = difference;

        if (magnitude > 1E-06f)
        {
            leftHand = (leftHand / magnitude);
        }

        var dot = Mathf.Clamp(Vector3.Dot(leftHand, rightHand), 0f, magnitude);

        return (lineStart + (leftHand * dot));
    }

19 View Source File : Vector3.cs
License : MIT License
Project Creator : AnotherEnd15

public static void Project(ref Vector3 vector, ref Vector3 onNormal, out Vector3 result)
        {
            result = onNormal * Vector3.Dot(vector, onNormal) / Vector3.Dot(onNormal, onNormal);
        }

19 View Source File : NavMeshLinkEditor.cs
License : MIT License
Project Creator : DKaravolos

void AlignTransformToEndPoints(NavMeshLink navLink)
        {
            var mat = UnscaledLocalToWorldMatrix(navLink.transform);

            var worldStartPt = mat.MultiplyPoint(navLink.startPoint);
            var worldEndPt = mat.MultiplyPoint(navLink.endPoint);

            var forward = worldEndPt - worldStartPt;
            var up = navLink.transform.up;

            // Flatten
            forward -= Vector3.Dot(up, forward) * up;

            var transform = navLink.transform;
            transform.rotation = Quaternion.LookRotation(forward, up);
            transform.position = (worldEndPt + worldStartPt) * 0.5f;
            transform.localScale = Vector3.one;

            navLink.startPoint = transform.InverseTransformPoint(worldStartPt);
            navLink.endPoint = transform.InverseTransformPoint(worldEndPt);
        }

19 View Source File : MathUtils.cs
License : MIT License
Project Creator : dag10

public static Vector3 ClosestPointOnLineToPoint(Vector3 point, Vector3 linePointA, Vector3 linePointB)
        {
            Vector3 v = linePointB - linePointA;
            Vector3 w = point - linePointA;

            float c1 = Vector3.Dot(w, v);
            float c2 = Vector3.Dot(v, v);
            float b = c1 / c2;

            Vector3 pointB = linePointA + (v * b);

            return pointB;
        }

19 View Source File : SlendermanAI.cs
License : MIT License
Project Creator : Donut-Studios

void Update()
	{
		// is the player looking at me?
		bool inView = Vector3.Dot(Vector3.forward, player_transform.InverseTransformPoint(my_transform.position)) > 0;

		// is the player too close to me?
		bool isClose = Vector3.Distance(player_transform.position, my_transform.position) < 7;

		// if player isn't looking at me and I'm not too close, move towards player
		if(!(inView || isClose))
		{
			// move towards the player
			moveTo(player);
		}
		// if player is looking at me, teleport behind player
		if(inView)
		{
			transform.LookAt(player_transform);
			Transform copy_transform = my_transform;
			copy_transform.RotateAround(player_transform.position, player_transform.right, 100.0f);
			moveTo(copy_transform.position);
			// // obtain location behind player
			// tr = player_transform.forward;
			// behind_player.z -= 10;
			// my_transform.position = behind_player;
		}
	}

19 View Source File : Vector3.cs
License : MIT License
Project Creator : AnotherEnd15

private static float magnitudeStatic(ref Vector3 inV)
        {
            return (float) Math.Sqrt(Vector3.Dot(inV, inV));
        }

19 View Source File : SlendermanAI.cs
License : MIT License
Project Creator : Donut-Studios

void Update()
	{
		// is the player looking at me?
		bool inView = Vector3.Dot(Vector3.forward, player_transform.InverseTransformPoint(my_transform.position)) > 0;

		// is the player too close to me?
		bool isClose = Vector3.Distance(player_transform.position, my_transform.position) < 7;

		// if player isn't looking at me and I'm not too close, move towards player
		if(!(inView || isClose))
		{
			// move towards the player
			moveTo(player);
		}
		// if player is looking at me, teleport behind player
		if(inView)
		{
			transform.LookAt(player_transform);
			Transform copy_transform = my_transform;
			copy_transform.RotateAround(player_transform.position, player_transform.right, 100.0f);
			moveTo(copy_transform.position);
		}
	}

19 View Source File : MathUtils.cs
License : MIT License
Project Creator : dag10

public static bool TestPlanesAABB(Plane[] planes, int planeMask, Bounds bounds, out bool entirelyInside)
        {
            int planeIndex = 0;
            int entirelyInsideCount = 0;
            Vector3 boundsCenter = bounds.center;  // center of bounds
            Vector3 boundsExtent = bounds.extents; // half diagonal
                                                   // do intersection test for each active frame
            int mask = 1;

            // while active frames
            while (mask <= planeMask)
            {
                // if active
                if ((uint)(planeMask & mask) != 0)
                {
                    Plane p = planes[planeIndex];
                    Vector3 n = p.normal;
                    n.x = Mathf.Abs(n.x);
                    n.y = Mathf.Abs(n.y);
                    n.z = Mathf.Abs(n.z);

                    float distance = p.GetDistanceToPoint(boundsCenter);
                    float radius = Vector3.Dot(boundsExtent, n);

                    if (distance + radius < 0)
                    {
                        // behind clip plane
                        entirelyInside = false;
                        return false;
                    }

                    if (distance > radius)
                    {
                        entirelyInsideCount++;
                    }
                }

                mask += mask;
                planeIndex++;
            }

            entirelyInside = entirelyInsideCount == planes.Length;
            return true;
        }

19 View Source File : CameraMotionBlur.cs
License : MIT License
Project Creator : GlaireDaggers

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (false == CheckResources ()) {
                Graphics.Blit (source, destination);
                return;
            }

            if (filterType == MotionBlurFilter.CameraMotion)
                StartFrame ();

            // use if possible new RG format ... fallback to half otherwise
            var rtFormat= SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf;

            // get temp textures
            RenderTexture velBuffer = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat);
            int tileWidth = 1;
            int tileHeight = 1;
            maxVelocity = Mathf.Max (2.0f, maxVelocity);

            float _maxVelocity = maxVelocity; // calculate 'k'
            // note: 's' is hardcoded in shaders except for DX11 path

            // auto DX11 fallback!
            bool fallbackFromDX11 = filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null;

            if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) {
                maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS);
                tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
                tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
                _maxVelocity = velBuffer.width/tileWidth;
            }
            else {
                tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
                tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
                _maxVelocity = velBuffer.width/tileWidth;
            }

            RenderTexture tileMax  = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
            RenderTexture neighbourMax  = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
            velBuffer.filterMode = FilterMode.Point;
            tileMax.filterMode = FilterMode.Point;
            neighbourMax.filterMode = FilterMode.Point;
            if (noiseTexture) noiseTexture.filterMode = FilterMode.Point;
            source.wrapMode = TextureWrapMode.Clamp;
            velBuffer.wrapMode = TextureWrapMode.Clamp;
            neighbourMax.wrapMode = TextureWrapMode.Clamp;
            tileMax.wrapMode = TextureWrapMode.Clamp;

            // calc correct viewprj matrix
            CalculateViewProjection ();

            // just started up?
            if (gameObject.activeInHierarchy && !wasActive) {
                Remember ();
            }
            wasActive = gameObject.activeInHierarchy;

            // matrices
            Matrix4x4 invViewPrj = Matrix4x4.Inverse (currentViewProjMat);
            motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj);
            motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
            motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);

            motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity);
            motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);
            motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
            motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
            motionBlurMaterial.SetFloat ("_Jitter", jitter);

            // texture samplers
            motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
            motionBlurMaterial.SetTexture ("_VelTex", velBuffer);
            motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);
            motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax);

            if (preview) {
                // generate an artifical 'previous' matrix to simulate blur look
                Matrix4x4 viewMat = _camera.worldToCameraMatrix;
                Matrix4x4 offset = Matrix4x4.idenreplacedy;
                offset.SetTRS(previewScale * 0.3333f, Quaternion.idenreplacedy, Vector3.one); // using only translation
                Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true);
                prevViewProjMat = projMat * offset * viewMat;
                motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
                motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);
            }

            if (filterType == MotionBlurFilter.CameraMotion)
            {
                // build blur vector to be used in shader to create a global blur direction
                Vector4 blurVector = Vector4.zero;

                float lookUpDown = Vector3.Dot (transform.up, Vector3.up);
                Vector3 distanceVector = prevFramePos-transform.position;

                float distMag = distanceVector.magnitude;

                float farHeur = 1.0f;

                // pitch (vertical)
                farHeur = (Vector3.Angle (transform.up, prevFrameUp) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.x =  rotationScale * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp)));

                // yaw #1 (horizontal, faded by pitch)
                farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.y = rotationScale * lookUpDown * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));

                // yaw #2 (when looking down, faded by 1-pitch)
                farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));

                if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) {
                    // forward (probably most important)
                    blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f);
                    // jump (maybe scale down further)
                    blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f);
                    // strafe (maybe scale down further)
                    blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f);
                }

                if (preview) // crude approximation
                    motionBlurMaterial.SetVector ("_BlurDirectionPacked", new Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * _camera.fieldOfView);
                else
                    motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector);
            }
            else {
                // generate velocity buffer
                Graphics.Blit (source, velBuffer, motionBlurMaterial, 0);

                // patch up velocity buffer:

                // exclude certain layers (e.g. skinned objects as we cant really support that atm)

                Camera cam = null;
                if (excludeLayers.value != 0)// || dynamicLayers.value)
                    cam = GetTmpCam ();

                if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) {
                    cam.targetTexture = velBuffer;
                    cam.cullingMask = excludeLayers;
                    cam.RenderWithShader (replacementClear, "");
                }
            }

            if (!preview && Time.frameCount != prevFrameCount) {
                // remember current transformation data for next frame
                prevFrameCount = Time.frameCount;
                Remember ();
            }

            source.filterMode = FilterMode.Bilinear;

            // debug vel buffer:
            if (showVelocity) {
                // generate tile max and neighbour max
                //Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                //Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);
                motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale);
                Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1);
            }
            else {
                if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) {
                    // need to reset some parameters for dx11 shader
                    dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
                    dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
                    dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter);

                    // texture samplers
                    dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
                    dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer);
                    dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);

                    dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );
                    dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0);
                    Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1);

                    // final blur
                    Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2);
                }
                else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) {
                    // 'reconstructing' properly integrated color
                    motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                    Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);

                    // final blur
                    Graphics.Blit (source, destination, motionBlurMaterial, 4);
                }
                else if (filterType == MotionBlurFilter.CameraMotion) {
                    // orange box style motion blur
                    Graphics.Blit (source, destination, motionBlurMaterial, 6);
                }
                else if (filterType == MotionBlurFilter.ReconstructionDisc) {
                    // dof style motion blur defocuing and ellipse around the princical blur direction
                    // 'reconstructing' properly integrated color
                    motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                    Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);

                    Graphics.Blit (source, destination, motionBlurMaterial, 7);
                }
                else {
                    // simple & fast blur (low quality): just blurring along velocity
                    Graphics.Blit (source, destination, motionBlurMaterial, 5);
                }
            }

            // cleanup
            RenderTexture.ReleaseTemporary (velBuffer);
            RenderTexture.ReleaseTemporary (tileMax);
            RenderTexture.ReleaseTemporary (neighbourMax);
        }

19 View Source File : SimulationStep2Patch.cs
License : MIT License
Project Creator : CitiesSkylinesMods

[UsedImplicitly]
        public static bool Prefix(TrainAI __instance,
                                  VehicleInfo ___m_info,
                                  ushort vehicleID,
                                  ref Vehicle vehicleData,
                                  ref Vehicle.Frame frameData,
                                  ushort leaderID,
                                  ref Vehicle leaderData,
                                  int lodPhysics) {
            bool reversed = (leaderData.m_flags & Vehicle.Flags.Reversed) != 0;
            ushort frontVehicleId = (!reversed) ? vehicleData.m_leadingVehicle : vehicleData.m_trailingVehicle;
            VehicleInfo vehicleInfo = leaderID != vehicleID ? leaderData.Info : ___m_info;
            TrainAI trainAi = vehicleInfo.m_vehicleAI as TrainAI;

            if (frontVehicleId != 0) {
                frameData.m_position += frameData.m_velocity * 0.4f;
            } else {
                frameData.m_position += frameData.m_velocity * 0.5f;
            }

            frameData.m_swayPosition += frameData.m_swayVelocity * 0.5f;

            Vector3 posBeforeWheelRot = frameData.m_position;
            Vector3 posAfterWheelRot = frameData.m_position;
            Vector3 wheelBaseRot = frameData.m_rotation
                               * new Vector3(0f, 0f, ___m_info.m_generatedInfo.m_wheelBase * 0.5f);

            if (reversed) {
                posBeforeWheelRot -= wheelBaseRot;
                posAfterWheelRot += wheelBaseRot;
            } else {
                posBeforeWheelRot += wheelBaseRot;
                posAfterWheelRot -= wheelBaseRot;
            }

            float acceleration = ___m_info.m_acceleration;
            float braking = ___m_info.m_braking;
            float curSpeed = frameData.m_velocity.magnitude;

            Vector3 beforeRotToTargetPos1Diff = (Vector3)vehicleData.m_targetPos1 - posBeforeWheelRot;
            float beforeRotToTargetPos1DiffSqrMag = beforeRotToTargetPos1Diff.sqrMagnitude;

            Quaternion curInvRot = Quaternion.Inverse(frameData.m_rotation);
            Vector3 curveTangent = curInvRot * frameData.m_velocity;

            Vector3 forward = Vector3.forward;
            Vector3 targetMotion = Vector3.zero;
            float targetSpeed = 0f;
            float motionFactor = 0.5f;

            if (frontVehicleId != 0) {
                VehicleManager vehMan = VehicleManager.instance;
                Vehicle.Frame frontVehLastFrameData = vehMan.m_vehicles.m_buffer[frontVehicleId].GetLastFrameData();
                VehicleInfo frontVehInfo = vehMan.m_vehicles.m_buffer[frontVehicleId].Info;
                float attachOffset;

                if ((vehicleData.m_flags & Vehicle.Flags.Inverted) != 0 != reversed) {
                    attachOffset = ___m_info.m_attachOffsetBack - (___m_info.m_generatedInfo.m_size.z * 0.5f);
                } else {
                    attachOffset = ___m_info.m_attachOffsetFront - (___m_info.m_generatedInfo.m_size.z * 0.5f);
                }

                float frontAttachOffset;

                if ((vehMan.m_vehicles.m_buffer[frontVehicleId].m_flags & Vehicle.Flags.Inverted) != 0 != reversed) {
                    frontAttachOffset = frontVehInfo.m_attachOffsetFront -
                                        (frontVehInfo.m_generatedInfo.m_size.z * 0.5f);
                } else {
                    frontAttachOffset =
                        (frontVehInfo.m_attachOffsetBack - (frontVehInfo.m_generatedInfo.m_size.z * 0.5f));
                }

                Vector3 posMinusAttachOffset = frameData.m_position;
                if (reversed) {
                    posMinusAttachOffset += frameData.m_rotation * new Vector3(0f, 0f, attachOffset);
                } else {
                    posMinusAttachOffset -= frameData.m_rotation * new Vector3(0f, 0f, attachOffset);
                }

                Vector3 frontPosPlusAttachOffset = frontVehLastFrameData.m_position;
                if (reversed) {
                    frontPosPlusAttachOffset -= frontVehLastFrameData.m_rotation
                                                * new Vector3(0f, 0f, frontAttachOffset);
                } else {
                    frontPosPlusAttachOffset += frontVehLastFrameData.m_rotation
                                                * new Vector3(0f, 0f, frontAttachOffset);
                }

                Vector3 frontPosMinusWheelBaseRot = frontVehLastFrameData.m_position;
                wheelBaseRot = frontVehLastFrameData.m_rotation * new Vector3(
                                   0f,
                                   0f,
                                   frontVehInfo.m_generatedInfo.m_wheelBase * 0.5f);
                if (reversed) {
                    frontPosMinusWheelBaseRot += wheelBaseRot;
                } else {
                    frontPosMinusWheelBaseRot -= wheelBaseRot;
                }

                if (Vector3.Dot(
                        vehicleData.m_targetPos1 - vehicleData.m_targetPos0,
                        (Vector3)vehicleData.m_targetPos0 - posAfterWheelRot) < 0f
                    && vehicleData.m_path != 0u
                    && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == 0)
                {
                    int someIndex = -1;
                    UpdatePathTargetPositions(
                        trainAi,
                        vehicleID,
                        ref vehicleData,
                        vehicleData.m_targetPos0,
                        posAfterWheelRot,
                        0,
                        ref leaderData,
                        ref someIndex,
                        0,
                        0,
                        Vector3.SqrMagnitude(posAfterWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f,
                        1f);
                    beforeRotToTargetPos1DiffSqrMag = 0f;
                }

                float maxAttachDist = Mathf.Max(Vector3.Distance(posMinusAttachOffset,
                                                               frontPosPlusAttachOffset),
                                              2f);
                const float ONE = 1f;
                float maxAttachSqrDist = maxAttachDist * maxAttachDist;
                const float ONE_SQR = ONE * ONE;
                int i = 0;
                if (beforeRotToTargetPos1DiffSqrMag < maxAttachSqrDist) {
                    if (vehicleData.m_path != 0u
                        && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == 0) {
                        UpdatePathTargetPositions(
                            trainAi,
                            vehicleID,
                            ref vehicleData,
                            posAfterWheelRot,
                            posBeforeWheelRot,
                            0,
                            ref leaderData,
                            ref i,
                            1,
                            2,
                            maxAttachSqrDist,
                            ONE_SQR);
                    }

                    while (i < 4) {
                        vehicleData.SetTargetPos(i, vehicleData.GetTargetPos(i - 1));
                        i++;
                    }

                    beforeRotToTargetPos1Diff = (Vector3)vehicleData.m_targetPos1 - posBeforeWheelRot;
                    beforeRotToTargetPos1DiffSqrMag = beforeRotToTargetPos1Diff.sqrMagnitude;
                }

                if (vehicleData.m_path != 0u) {
                    NetManager netMan = NetManager.instance;
                    byte pathPosIndex = vehicleData.m_pathPositionIndex;
                    byte lastPathOffset = vehicleData.m_lastPathOffset;
                    if (pathPosIndex == 255) {
                        pathPosIndex = 0;
                    }

                    PathManager pathMan = PathManager.instance;
                    if (pathMan.m_pathUnits.m_buffer[vehicleData.m_path]
                               .GetPosition(pathPosIndex >> 1, out PathUnit.Position curPathPos)) {
                        netMan.m_segments.m_buffer[curPathPos.m_segment].AddTraffic(
                            Mathf.RoundToInt(___m_info.m_generatedInfo.m_size.z * 3f),
                            GetNoiseLevel(trainAi));

                        if ((pathPosIndex & 1) == 0 || lastPathOffset == 0 ||
                            (leaderData.m_flags & Vehicle.Flags.WaitingPath) != 0) {
                            uint laneId = PathManager.GetLaneID(curPathPos);
                            if (laneId != 0u) {
                                netMan.m_lanes.m_buffer[laneId].ReserveSpace(___m_info.m_generatedInfo.m_size.z);
                            }
                        } else if (pathMan.m_pathUnits.m_buffer[vehicleData.m_path]
                                          .GetNextPosition(pathPosIndex >> 1, out PathUnit.Position nextPathPos)) {
                            // NON-STOCK CODE START
                            ushort transitNodeId;

                            if (curPathPos.m_offset < 128) {
                                transitNodeId = netMan.m_segments.m_buffer[curPathPos.m_segment].m_startNode;
                            } else {
                                transitNodeId = netMan.m_segments.m_buffer[curPathPos.m_segment].m_endNode;
                            }

                            if (VehicleBehaviorManager.Instance.IsSpaceReservationAllowed(
                                transitNodeId,
                                curPathPos,
                                nextPathPos)) {
                                // NON-STOCK CODE END
                                uint nextLaneId = PathManager.GetLaneID(nextPathPos);
                                if (nextLaneId != 0u) {
                                    netMan.m_lanes.m_buffer[nextLaneId].ReserveSpace(___m_info.m_generatedInfo.m_size.z);
                                }
                            } // NON-STOCK CODE
                        }
                    }
                }

                beforeRotToTargetPos1Diff = curInvRot * beforeRotToTargetPos1Diff;
                float negTotalAttachLen =
                    -(((___m_info.m_generatedInfo.m_wheelBase +
                        frontVehInfo.m_generatedInfo.m_wheelBase) * 0.5f) + attachOffset +
                      frontAttachOffset);
                bool hasPath = false;

                if (vehicleData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == 0) {
                    if (Line3.Intersect(
                        posBeforeWheelRot,
                        vehicleData.m_targetPos1,
                        frontPosMinusWheelBaseRot,
                        negTotalAttachLen,
                        out float u1,
                        out float u2)) {
                        targetMotion = beforeRotToTargetPos1Diff
                                       * Mathf.Clamp(Mathf.Min(u1, u2) / 0.6f, 0f, 2f);
                    } else {
                        Line3.DistanceSqr(
                            posBeforeWheelRot,
                            vehicleData.m_targetPos1,
                            frontPosMinusWheelBaseRot,
                            out u1);
                        targetMotion = beforeRotToTargetPos1Diff * Mathf.Clamp(u1 / 0.6f, 0f, 2f);
                    }

                    hasPath = true;
                }

                if (hasPath) {
                    if (Vector3.Dot(
                            frontPosMinusWheelBaseRot - posBeforeWheelRot,
                            posBeforeWheelRot - posAfterWheelRot) < 0f) {
                        motionFactor = 0f;
                    }
                } else {
                    float frontPosBeforeToAfterWheelRotDist = Vector3.Distance(
                        frontPosMinusWheelBaseRot,
                        posBeforeWheelRot);
                    motionFactor = 0f;
                    targetMotion = curInvRot
                                   * ((frontPosMinusWheelBaseRot - posBeforeWheelRot)
                                      * (Mathf.Max(0f, frontPosBeforeToAfterWheelRotDist - negTotalAttachLen)
                                         / Mathf.Max(1f, frontPosBeforeToAfterWheelRotDist * 0.6f)));
                }
            } else {
                float estimatedFrameDist = (curSpeed + acceleration)
                                         * (0.5f + (0.5f * (curSpeed + acceleration) / braking));
                float maxSpeedAdd = Mathf.Max(curSpeed + acceleration, 2f);
                float meanSpeedAdd = Mathf.Max((estimatedFrameDist - maxSpeedAdd) / 2f, 1f);
                float maxSpeedAddSqr = maxSpeedAdd * maxSpeedAdd;
                float meanSpeedAddSqr = meanSpeedAdd * meanSpeedAdd;

                if (Vector3.Dot(
                        vehicleData.m_targetPos1 - vehicleData.m_targetPos0,
                        (Vector3)vehicleData.m_targetPos0 - posAfterWheelRot) < 0f
                    && vehicleData.m_path != 0u
                    && (leaderData.m_flags & (Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped)) == 0)
                {
                    int someIndex = -1;
                    UpdatePathTargetPositions(
                        trainAi,
                        vehicleID,
                        ref vehicleData,
                        vehicleData.m_targetPos0,
                        posAfterWheelRot,
                        leaderID,
                        ref leaderData,
                        ref someIndex,
                        0,
                        0,
                        Vector3.SqrMagnitude(posAfterWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f,
                        1f);
                    beforeRotToTargetPos1DiffSqrMag = 0f;
                }

                int posIndex = 0;
                bool flag3 = false;
                if ((beforeRotToTargetPos1DiffSqrMag < maxSpeedAddSqr
                     || vehicleData.m_targetPos3.w < 0.01f)
                    && (leaderData.m_flags & (Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped)) == 0)
                {
                    if (vehicleData.m_path != 0u) {
                        UpdatePathTargetPositions(
                            trainAi,
                            vehicleID,
                            ref vehicleData,
                            posAfterWheelRot,
                            posBeforeWheelRot,
                            leaderID,
                            ref leaderData,
                            ref posIndex,
                            1,
                            4,
                            maxSpeedAddSqr,
                            meanSpeedAddSqr);
                    }
                    if (posIndex < 4) {
                        flag3 = true;
                        while (posIndex < 4) {
                            vehicleData.SetTargetPos(posIndex, vehicleData.GetTargetPos(posIndex - 1));
                            posIndex++;
                        }
                    }

                    beforeRotToTargetPos1Diff = (Vector3)vehicleData.m_targetPos1 - posBeforeWheelRot;
                    beforeRotToTargetPos1DiffSqrMag = beforeRotToTargetPos1Diff.sqrMagnitude;
                }

                if ((leaderData.m_flags & (Vehicle.Flags.WaitingPath
                                           | Vehicle.Flags.Stopped)) == 0
                    && ___m_info.m_vehicleType != VehicleInfo.VehicleType.Monorail) {
                    ForceTrafficLights(__instance, vehicleID, ref vehicleData, curSpeed > 0.1f);
                    // NON-STOCK CODE
                }

                if (vehicleData.m_path != 0u) {
                    NetManager netMan = Singleton<NetManager>.instance;
                    byte pathPosIndex = vehicleData.m_pathPositionIndex;
                    byte lastPathOffset = vehicleData.m_lastPathOffset;
                    if (pathPosIndex == 255) {
                        pathPosIndex = 0;
                    }

                    PathManager pathMan = Singleton<PathManager>.instance;
                    if (pathMan.m_pathUnits.m_buffer[vehicleData.m_path]
                               .GetPosition(pathPosIndex >> 1, out PathUnit.Position curPathPos))
                    {
                        netMan.m_segments.m_buffer[curPathPos.m_segment]
                              .AddTraffic(Mathf.RoundToInt(___m_info.m_generatedInfo.m_size.z * 3f),
                                          GetNoiseLevel(trainAi));

                        if ((pathPosIndex & 1) == 0
                            || lastPathOffset == 0
                            || (leaderData.m_flags & Vehicle.Flags.WaitingPath) != 0)
                        {
                            uint laneId = PathManager.GetLaneID(curPathPos);
                            if (laneId != 0u) {
                                netMan.m_lanes.m_buffer[laneId].ReserveSpace(___m_info.m_generatedInfo.m_size.z, vehicleID);
                            }
                        } else if (pathMan.m_pathUnits.m_buffer[vehicleData.m_path]
                                          .GetNextPosition(pathPosIndex >> 1, out PathUnit.Position nextPathPos)) {
                            // NON-STOCK CODE START
                            ushort transitNodeId;
                            transitNodeId = curPathPos.m_offset < 128
                                                ? netMan.m_segments.m_buffer[curPathPos.m_segment].m_startNode
                                                : netMan.m_segments.m_buffer[curPathPos.m_segment].m_endNode;

                            if (VehicleBehaviorManager.Instance.IsSpaceReservationAllowed(
                                transitNodeId,
                                curPathPos,
                                nextPathPos)) {
                                // NON-STOCK CODE END
                                uint nextLaneId = PathManager.GetLaneID(nextPathPos);
                                if (nextLaneId != 0u) {
                                    netMan.m_lanes.m_buffer[nextLaneId].ReserveSpace(
                                        ___m_info.m_generatedInfo.m_size.z, vehicleID);
                                }
                            } // NON-STOCK CODE
                        }
                    }
                }

                float maxSpeed;

                maxSpeed = (leaderData.m_flags & Vehicle.Flags.Stopped) != 0
                               ? 0f
                               : Mathf.Min(vehicleData.m_targetPos1.w, GetMaxSpeed(leaderID, ref leaderData));

                beforeRotToTargetPos1Diff = curInvRot * beforeRotToTargetPos1Diff;
                if (reversed) {
                    beforeRotToTargetPos1Diff = -beforeRotToTargetPos1Diff;
                }

                bool blocked = false;
                float forwardLen = 0f;

                if (beforeRotToTargetPos1DiffSqrMag > 1f) {
                    forward = VectorUtils.NormalizeXZ(beforeRotToTargetPos1Diff, out forwardLen);

                    if (forwardLen > 1f) {
                        Vector3 fwd = beforeRotToTargetPos1Diff;
                        maxSpeedAdd = Mathf.Max(curSpeed, 2f);
                        maxSpeedAddSqr = maxSpeedAdd * maxSpeedAdd;
                        if (beforeRotToTargetPos1DiffSqrMag > maxSpeedAddSqr) {
                            float num20 = maxSpeedAdd / Mathf.Sqrt(beforeRotToTargetPos1DiffSqrMag);
                            fwd.x *= num20;
                            fwd.y *= num20;
                        }

                        if (fwd.z < -1f) {
                            if (vehicleData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == 0) {
                                Vector3 targetPos0TargetPos1Diff = vehicleData.m_targetPos1 - vehicleData.m_targetPos0;
                                targetPos0TargetPos1Diff = curInvRot * targetPos0TargetPos1Diff;
                                if (reversed) {
                                    targetPos0TargetPos1Diff = -targetPos0TargetPos1Diff;
                                }

                                if (targetPos0TargetPos1Diff.z < -0.01f) {
                                    if (beforeRotToTargetPos1Diff.z < Mathf.Abs(beforeRotToTargetPos1Diff.x) * -10f) {
                                        if (curSpeed < 0.01f) {
                                            Reverse(leaderID, ref leaderData);
                                            return false;
                                        }

                                        fwd.z = 0f;
                                        beforeRotToTargetPos1Diff = Vector3.zero;
                                        maxSpeed = 0f;
                                    } else {
                                        posBeforeWheelRot =
                                            posAfterWheelRot +
                                            Vector3.Normalize(
                                                vehicleData.m_targetPos1 -
                                                vehicleData.m_targetPos0) *
                                            ___m_info.m_generatedInfo.m_wheelBase;
                                        posIndex = -1;
                                        UpdatePathTargetPositions(
                                            trainAi,
                                            vehicleID,
                                            ref vehicleData,
                                            vehicleData.m_targetPos0,
                                            vehicleData.m_targetPos1,
                                            leaderID,
                                            ref leaderData,
                                            ref posIndex,
                                            0,
                                            0,
                                            Vector3.SqrMagnitude(
                                                vehicleData.m_targetPos1 -
                                                vehicleData.m_targetPos0) + 1f,
                                            1f);
                                    }
                                } else {
                                    posIndex = -1;
                                    UpdatePathTargetPositions(
                                        trainAi,
                                        vehicleID,
                                        ref vehicleData,
                                        vehicleData.m_targetPos0,
                                        posAfterWheelRot,
                                        leaderID,
                                        ref leaderData,
                                        ref posIndex,
                                        0,
                                        0,
                                        Vector3.SqrMagnitude(
                                            posAfterWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f,
                                        1f);
                                    vehicleData.m_targetPos1 = posBeforeWheelRot;
                                    fwd.z = 0f;
                                    beforeRotToTargetPos1Diff = Vector3.zero;
                                    maxSpeed = 0f;
                                }
                            }

                            motionFactor = 0f;
                        }

                        forward = VectorUtils.NormalizeXZ(fwd, out forwardLen);
                        float curve = Mathf.PI / 2f * (1f - forward.z);
                        if (forwardLen > 1f) {
                            curve /= forwardLen;
                        }

                        maxSpeed = Mathf.Min(
                            maxSpeed,
                            CalculateTargetSpeed(
                                __instance,
                                vehicleID,
                                ref vehicleData,
                                1000f,
                                curve));

                        float targetDist = forwardLen;
                        maxSpeed = Mathf.Min(
                            maxSpeed,
                            CalculateMaxSpeed(
                                targetDist,
                                vehicleData.m_targetPos2.w,
                                braking));
                        targetDist += VectorUtils.LengthXZ(vehicleData.m_targetPos2 - vehicleData.m_targetPos1);
                        maxSpeed = Mathf.Min(maxSpeed,
                                             CalculateMaxSpeed(targetDist,
                                                               vehicleData.m_targetPos3.w,
                                                               braking));
                        targetDist += VectorUtils.LengthXZ(vehicleData.m_targetPos3 - vehicleData.m_targetPos2);
                        maxSpeed = Mathf.Min(maxSpeed,
                                             CalculateMaxSpeed(targetDist, 0f, braking));

                        if (maxSpeed < curSpeed) {
                            float brake = Mathf.Max(acceleration, Mathf.Min(braking, curSpeed));
                            targetSpeed = Mathf.Max(maxSpeed, curSpeed - brake);
                        } else {
                            float accel = Mathf.Max(acceleration, Mathf.Min(braking, -curSpeed));
                            targetSpeed = Mathf.Min(maxSpeed, curSpeed + accel);
                        }
                    }
                } else if (curSpeed < 0.1f && flag3 &&
                           vehicleInfo.m_vehicleAI.ArriveAtDestination(leaderID, ref leaderData)) {
                    leaderData.Unspawn(leaderID);
                    return false;
                }

                if ((leaderData.m_flags & Vehicle.Flags.Stopped) == 0 && maxSpeed < 0.1f) {
                    blocked = true;
                }

                if (blocked) {
                    leaderData.m_blockCounter = (byte)Mathf.Min(leaderData.m_blockCounter + 1, 255);
                } else {
                    leaderData.m_blockCounter = 0;
                }

                if (forwardLen > 1f) {
                    if (reversed) {
                        forward = -forward;
                    }

                    targetMotion = forward * targetSpeed;
                } else {
                    if (reversed) {
                        beforeRotToTargetPos1Diff = -beforeRotToTargetPos1Diff;
                    }

                    Vector3 vel = Vector3.ClampMagnitude((beforeRotToTargetPos1Diff * 0.5f) - curveTangent, braking);
                    targetMotion = curveTangent + vel;
                }
            }

            Vector3 springs = targetMotion - curveTangent;
            Vector3 targetAfterWheelRotMotion = frameData.m_rotation * targetMotion;
            Vector3 posAfterWheelRotToTargetDiff = Vector3.Normalize((Vector3)vehicleData.m_targetPos0 - posAfterWheelRot)
                                               * (targetMotion.magnitude * motionFactor);
            posBeforeWheelRot += targetAfterWheelRotMotion;
            posAfterWheelRot += posAfterWheelRotToTargetDiff;

            Vector3 targetPos;
            if (reversed) {
                frameData.m_rotation = Quaternion.LookRotation(posAfterWheelRot - posBeforeWheelRot);
                targetPos = posBeforeWheelRot + (frameData.m_rotation * new Vector3(
                                                     0f,
                                                     0f,
                                                     ___m_info.m_generatedInfo.m_wheelBase * 0.5f));
            } else {
                frameData.m_rotation = Quaternion.LookRotation(posBeforeWheelRot - posAfterWheelRot);
                targetPos = posBeforeWheelRot - (frameData.m_rotation * new Vector3(
                                                     0f,
                                                     0f,
                                                     ___m_info.m_generatedInfo.m_wheelBase * 0.5f));
            }

            frameData.m_velocity = targetPos - frameData.m_position;

            if (frontVehicleId != 0) {
                frameData.m_position += frameData.m_velocity * 0.6f;
            } else {
                frameData.m_position += frameData.m_velocity * 0.5f;
            }

            frameData.m_swayVelocity =
                ((frameData.m_swayVelocity * (1f - ___m_info.m_dampers)) - (springs * (1f - ___m_info.m_springs)))
                - (frameData.m_swayPosition * ___m_info.m_springs);
            frameData.m_swayPosition += frameData.m_swayVelocity * 0.5f;
            frameData.m_steerAngle = 0f;
            frameData.m_travelDistance += targetMotion.z;
            frameData.m_lightIntensity.x = (!reversed) ? 5f : 0f;
            frameData.m_lightIntensity.y = (!reversed) ? 0f : 5f;
            frameData.m_lightIntensity.z = 0f;
            frameData.m_lightIntensity.w = 0f;
            frameData.m_underground = (vehicleData.m_flags & Vehicle.Flags.Underground) != 0;
            frameData.m_transition = (vehicleData.m_flags & Vehicle.Flags.Transition) != 0;

            // base.SimulationStep(vehicleID, ref vehicleData, ref frameData, leaderID, ref leaderData, lodPhysics);
            return false;
        }

19 View Source File : SimpleCharacterControl.cs
License : MIT License
Project Creator : harshitjuneja

private void OnCollisionStay(Collision collision)
    {
        ContactPoint[] contactPoints = collision.contacts;
        bool validSurfaceNormal = false;
        for (int i = 0; i < contactPoints.Length; i++)
        {
            if (Vector3.Dot(contactPoints[i].normal, Vector3.up) > 0.5f)
            {
                validSurfaceNormal = true; break;
            }
        }

        if(validSurfaceNormal)
        {
            m_isGrounded = true;
            if (!m_collisions.Contains(collision.collider))
            {
                m_collisions.Add(collision.collider);
            }
        } else
        {
            if (m_collisions.Contains(collision.collider))
            {
                m_collisions.Remove(collision.collider);
            }
            if (m_collisions.Count == 0) { m_isGrounded = false; }
        }
    }

19 View Source File : SteamVR_SkyboxEditor.cs
License : MIT License
Project Creator : dag10

public override void OnInspectorGUI()
	{
		DrawDefaultInspector();

		EditorGUILayout.HelpBox(helpText, MessageType.Info);

		if (GUILayout.Button("Take snapshot"))
		{
			var directions = new Quaternion[] {
				Quaternion.LookRotation(Vector3.forward),
				Quaternion.LookRotation(Vector3.back),
				Quaternion.LookRotation(Vector3.left),
				Quaternion.LookRotation(Vector3.right),
				Quaternion.LookRotation(Vector3.up, Vector3.back),
				Quaternion.LookRotation(Vector3.down, Vector3.forward)
			};

			Camera tempCamera = null;
			foreach (SteamVR_Skybox target in targets)
			{
				var targetScene = target.gameObject.scene;
                var sceneName = Path.GetFileNameWithoutExtension(targetScene.path);
				var scenePath = Path.GetDirectoryName(targetScene.path);
				var replacedetPath = scenePath + "/" + sceneName;
				if (!replacedetDatabase.IsValidFolder(replacedetPath))
				{
					var guid = replacedetDatabase.CreateFolder(scenePath, sceneName);
					replacedetPath = replacedetDatabase.GUIDToreplacedetPath(guid);
				}

				var camera = target.GetComponent<Camera>();
				if (camera == null)
				{
					if (tempCamera == null)
						tempCamera = new GameObject().AddComponent<Camera>();
					camera = tempCamera;
				}

				var targetTexture = camera.targetTexture;
				if (camera.targetTexture == null)
				{
					targetTexture = new RenderTexture(1024, 1024, 24);
					targetTexture.antiAliasing = 8;
					camera.targetTexture = targetTexture;
				}

				var oldPosition = target.transform.localPosition;
				var oldRotation = target.transform.localRotation;
				var baseRotation = target.transform.rotation;

				var t = camera.transform;
				t.position = target.transform.position;
				camera.orthographic = false;
				camera.fieldOfView = 90;

				for (int i = 0; i < directions.Length; i++)
				{
					t.rotation = baseRotation * directions[i];
					camera.Render();

					// Copy to texture and save to disk.
					RenderTexture.active = targetTexture;
					var texture = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.ARGB32, false);
					texture.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
					texture.Apply();
					RenderTexture.active = null;

					var replacedetName = string.Format(nameFormat, replacedetPath, target.name, i);
					System.IO.File.WriteAllBytes(replacedetName, texture.EncodeToPNG());
				}
	
				if (camera != tempCamera)
				{
					target.transform.localPosition = oldPosition;
					target.transform.localRotation = oldRotation;
				}
			}

			if (tempCamera != null)
			{
				Object.DestroyImmediate(tempCamera.gameObject);
			}

			// Now that everything has be written out, reload the replacedociated replacedets and replacedign them.
			replacedetDatabase.Refresh();
			foreach (SteamVR_Skybox target in targets)
			{
				var targetScene = target.gameObject.scene;
				var sceneName = Path.GetFileNameWithoutExtension(targetScene.path);
				var scenePath = Path.GetDirectoryName(targetScene.path);
				var replacedetPath = scenePath + "/" + sceneName;

				for (int i = 0; i < directions.Length; i++)
				{
					var replacedetName = string.Format(nameFormat, replacedetPath, target.name, i);
					var importer = replacedetImporter.GetAtPath(replacedetName) as TextureImporter;
#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
					importer.textureFormat = TextureImporterFormat.RGB24;
#else
					importer.textureCompression = TextureImporterCompression.Uncompressed;
#endif
					importer.wrapMode = TextureWrapMode.Clamp;
					importer.mipmapEnabled = false;
					importer.SaveAndReimport();

					var texture = replacedetDatabase.LoadreplacedetAtPath<Texture>(replacedetName);
					target.SetTextureByIndex(i, texture);
				}
			}
		}
		else if (GUILayout.Button("Take stereo snapshot"))
		{
			const int width = 4096;
			const int height = width / 2;
			const int halfHeight = height / 2;

			var textures = new Texture2D[] {
				new Texture2D(width, height, TextureFormat.ARGB32, false),
				new Texture2D(width, height, TextureFormat.ARGB32, false) };

			var timer = new System.Diagnostics.Stopwatch();

			Camera tempCamera = null;
			foreach (SteamVR_Skybox target in targets)
			{
				timer.Start();

				var targetScene = target.gameObject.scene;
				var sceneName = Path.GetFileNameWithoutExtension(targetScene.path);
				var scenePath = Path.GetDirectoryName(targetScene.path);
				var replacedetPath = scenePath + "/" + sceneName;
				if (!replacedetDatabase.IsValidFolder(replacedetPath))
				{
					var guid = replacedetDatabase.CreateFolder(scenePath, sceneName);
					replacedetPath = replacedetDatabase.GUIDToreplacedetPath(guid);
				}

				var camera = target.GetComponent<Camera>();
				if (camera == null)
				{
					if (tempCamera == null)
						tempCamera = new GameObject().AddComponent<Camera>();
					camera = tempCamera;
				}

				var fx = camera.gameObject.AddComponent<SteamVR_SphericalProjection>();

				var oldTargetTexture = camera.targetTexture;
				var oldOrthographic = camera.orthographic;
				var oldFieldOfView = camera.fieldOfView;
				var oldAspect = camera.aspect;

				var oldPosition = target.transform.localPosition;
				var oldRotation = target.transform.localRotation;
				var basePosition = target.transform.position;
				var baseRotation = target.transform.rotation;

				var transform = camera.transform;

				int cellSize = int.Parse(target.StereoCellSize.ToString().Substring(1));
	            float ipd = target.StereoIpdMm / 1000.0f;
				int vTotal = halfHeight / cellSize;
				float dv = 90.0f / vTotal; // vertical degrees per segment
				float dvHalf = dv / 2.0f;

				var targetTexture = new RenderTexture(cellSize, cellSize, 24);
				targetTexture.wrapMode = TextureWrapMode.Clamp;
				targetTexture.antiAliasing = 8;

				camera.fieldOfView = dv;
				camera.orthographic = false;
				camera.targetTexture = targetTexture;

				// Render sections of a sphere using a rectilinear projection
				// and resample using a sphereical projection into a single panorama
				// texture per eye.  We break into sections in order to keep the eye
				// separation similar around the sphere.  Rendering alternates between
				// top and bottom sections, sweeping horizontally around the sphere,
				// alternating left and right eyes.
				for (int v = 0; v < vTotal; v++)
				{
					var pitch = 90.0f - (v * dv) - dvHalf;
					var uTotal = width / targetTexture.width;
                    var du = 360.0f / uTotal; // horizontal degrees per segment
					var duHalf = du / 2.0f;

					var vTarget = v * halfHeight / vTotal;

					for (int i = 0; i < 2; i++) // top, bottom
					{
						if (i == 1)
						{
							pitch = -pitch;
							vTarget = height - vTarget - cellSize;
                        }

						for (int u = 0; u < uTotal; u++)
						{
							var yaw = -180.0f + (u * du) + duHalf;

							var uTarget = u * width / uTotal;

							var xOffset = -ipd / 2 * Mathf.Cos(pitch * Mathf.Deg2Rad);

							for (int j = 0; j < 2; j++) // left, right
							{
								var texture = textures[j];

								if (j == 1)
								{
									xOffset = -xOffset;
								}

								var offset = baseRotation * Quaternion.Euler(0, yaw, 0) * new Vector3(xOffset, 0, 0);
								transform.position = basePosition + offset;

								var direction = Quaternion.Euler(pitch, yaw, 0.0f);
								transform.rotation = baseRotation * direction;

								// vector pointing to center of this section
								var N = direction * Vector3.forward;

								// horizontal span of this section in degrees
								var phi0 = yaw - (du / 2);
								var phi1 = phi0 + du;

								// vertical span of this section in degrees
								var theta0 = pitch + (dv / 2);
								var theta1 = theta0 - dv;

								var midPhi = (phi0 + phi1) / 2;
								var baseTheta = Mathf.Abs(theta0) < Mathf.Abs(theta1) ? theta0 : theta1;

								// vectors pointing to corners of image closes to the equator
								var V00 = Quaternion.Euler(baseTheta, phi0, 0.0f) * Vector3.forward;
								var V01 = Quaternion.Euler(baseTheta, phi1, 0.0f) * Vector3.forward;

								// vectors pointing to top and bottom midsection of image
								var V0M = Quaternion.Euler(theta0, midPhi, 0.0f) * Vector3.forward;
								var V1M = Quaternion.Euler(theta1, midPhi, 0.0f) * Vector3.forward;

								// intersection points for each of the above
								var P00 = V00 / Vector3.Dot(V00, N);
								var P01 = V01 / Vector3.Dot(V01, N);
								var P0M = V0M / Vector3.Dot(V0M, N);
								var P1M = V1M / Vector3.Dot(V1M, N);

								// calculate basis vectors for plane
								var P00_P01 = P01 - P00;
								var P0M_P1M = P1M - P0M;

								var uMag = P00_P01.magnitude;
								var vMag = P0M_P1M.magnitude;

								var uScale = 1.0f / uMag;
								var vScale = 1.0f / vMag;

								var uAxis = P00_P01 * uScale;
								var vAxis = P0M_P1M * vScale;

								// update material constant buffer
								fx.Set(N, phi0, phi1, theta0, theta1,
									uAxis, P00, uScale,
									vAxis, P0M, vScale);

								camera.aspect = uMag / vMag;
								camera.Render();

								RenderTexture.active = targetTexture;
								texture.ReadPixels(new Rect(0, 0, targetTexture.width, targetTexture.height), uTarget, vTarget);
								RenderTexture.active = null;
							}
						}
					}
                }

				// Save textures to disk.
				for (int i = 0; i < 2; i++)
				{
					var texture = textures[i];

					texture.Apply();
					var replacedetName = string.Format(nameFormat, replacedetPath, target.name, i);
					File.WriteAllBytes(replacedetName, texture.EncodeToPNG());
				}

				// Cleanup.
				if (camera != tempCamera)
				{
					camera.targetTexture = oldTargetTexture;
					camera.orthographic = oldOrthographic;
					camera.fieldOfView = oldFieldOfView;
					camera.aspect = oldAspect;

					target.transform.localPosition = oldPosition;
					target.transform.localRotation = oldRotation;
                }
				else
				{
					tempCamera.targetTexture = null;
				}

				DestroyImmediate(targetTexture);
				DestroyImmediate(fx);

				timer.Stop();
				Debug.Log(string.Format("Screenshot took {0} seconds.", timer.Elapsed));
			}

			if (tempCamera != null)
			{
				DestroyImmediate(tempCamera.gameObject);
			}

			DestroyImmediate(textures[0]);
			DestroyImmediate(textures[1]);

			// Now that everything has be written out, reload the replacedociated replacedets and replacedign them.
			replacedetDatabase.Refresh();
			foreach (SteamVR_Skybox target in targets)
			{
				var targetScene = target.gameObject.scene;
				var sceneName = Path.GetFileNameWithoutExtension(targetScene.path);
				var scenePath = Path.GetDirectoryName(targetScene.path);
				var replacedetPath = scenePath + "/" + sceneName;

				for (int i = 0; i < 2; i++)
				{
					var replacedetName = string.Format(nameFormat, replacedetPath, target.name, i);
					var importer = replacedetImporter.GetAtPath(replacedetName) as TextureImporter;
					importer.mipmapEnabled = false;
					importer.wrapMode = TextureWrapMode.Repeat;
#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
					importer.SetPlatformTextureSettings("Standalone", width, TextureImporterFormat.RGB24);
#else
					var settings = importer.GetPlatformTextureSettings("Standalone");
					settings.textureCompression = TextureImporterCompression.Uncompressed;
					settings.maxTextureSize = width;
					importer.SetPlatformTextureSettings(settings);
#endif
					importer.SaveAndReimport();

					var texture = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(replacedetName);
					target.SetTextureByIndex(i, texture);
				}
			}
		}
	}

19 View Source File : MWater.cs
License : MIT License
Project Creator : Interactml

public void OnWillRenderObject()
        {
            if (!enabled || !GetComponent<Renderer>() || !GetComponent<Renderer>().sharedMaterial ||
                !GetComponent<Renderer>().enabled)
            {
                return;
            }

            Camera cam = Camera.current;
            if (!cam)
            {
                return;
            }

            // Safeguard from recursive water reflections.
            if (s_InsideWater)
            {
                return;
            }
            s_InsideWater = true;

            // Actual water rendering mode depends on both the current setting AND
            // the hardware support. There's no point in rendering refraction textures
            // if they won't be visible in the end.
            m_HardwareWaterSupport = FindHardwareWaterSupport();
            WaterMode mode = GereplacederMode();

            Camera reflectionCamera, refractionCamera;
            CreateWaterObjects(cam, out reflectionCamera, out refractionCamera);

            // find out the reflection plane: position and normal in world space
            Vector3 pos = transform.position;
            Vector3 normal = transform.up;

            // Optionally disable pixel lights for reflection/refraction
            int oldPixelLightCount = QualitySettings.pixelLightCount;
            if (disablePixelLights)
            {
                QualitySettings.pixelLightCount = 0;
            }

            UpdateCameraModes(cam, reflectionCamera);
            UpdateCameraModes(cam, refractionCamera);

            // Render reflection if needed
            if (mode >= WaterMode.Reflective)
            {
                // Reflect camera around reflection plane
                float d = -Vector3.Dot(normal, pos) - clipPlaneOffset;
                Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);

                Matrix4x4 reflection = Matrix4x4.zero;
                CalculateReflectionMatrix(ref reflection, reflectionPlane);
                Vector3 oldpos = cam.transform.position;
                Vector3 newpos = reflection.MultiplyPoint(oldpos);
                reflectionCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;

                // Setup oblique projection matrix so that near plane is our reflection
                // plane. This way we clip everything below/above it for free.
                Vector4 clipPlane = CameraSpacePlane(reflectionCamera, pos, normal, 1.0f);
                reflectionCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane);

                // Set custom culling matrix from the current camera
                reflectionCamera.cullingMatrix = cam.projectionMatrix * cam.worldToCameraMatrix;

                reflectionCamera.cullingMask = ~(1 << 4) & reflectLayers.value; // never render water layer
                reflectionCamera.targetTexture = m_ReflectionTexture;
                bool oldCulling = GL.invertCulling;
                GL.invertCulling = !oldCulling;
                reflectionCamera.transform.position = newpos;
                Vector3 euler = cam.transform.eulerAngles;
                reflectionCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z);
                try
                {
                    reflectionCamera.Render();
                }
                catch
                { }

                reflectionCamera.transform.position = oldpos;
                GL.invertCulling = oldCulling;
                GetComponent<Renderer>().sharedMaterial.SetTexture("_ReflectionTex", m_ReflectionTexture);
                }

            // Render refraction
            if (mode >= WaterMode.Refractive)
            {
                refractionCamera.worldToCameraMatrix = cam.worldToCameraMatrix;

                // Setup oblique projection matrix so that near plane is our reflection
                // plane. This way we clip everything below/above it for free.
                Vector4 clipPlane = CameraSpacePlane(refractionCamera, pos, normal, -1.0f);
                refractionCamera.projectionMatrix = cam.CalculateObliqueMatrix(clipPlane);

                // Set custom culling matrix from the current camera
                refractionCamera.cullingMatrix = cam.projectionMatrix * cam.worldToCameraMatrix;

                refractionCamera.cullingMask = ~(1 << 4) & refractLayers.value; // never render water layer
                refractionCamera.targetTexture = m_RefractionTexture;
                refractionCamera.transform.position = cam.transform.position;
                refractionCamera.transform.rotation = cam.transform.rotation;
                try
                {
                    refractionCamera.Render();
                }
                catch
                {
                    throw new Exception("");
                }
            GetComponent<Renderer>().sharedMaterial.SetTexture("_RefractionTex", m_RefractionTexture);
            }

            // Restore pixel light count
            if (disablePixelLights)
            {
                QualitySettings.pixelLightCount = oldPixelLightCount;
            }

            // Setup shader keywords based on water mode
            switch (mode)
            {
                case WaterMode.Simple:
                    Shader.EnableKeyword("WATER_SIMPLE");
                    Shader.DisableKeyword("WATER_REFLECTIVE");
                    Shader.DisableKeyword("WATER_REFRACTIVE");
                    break;
                case WaterMode.Reflective:
                    Shader.DisableKeyword("WATER_SIMPLE");
                    Shader.EnableKeyword("WATER_REFLECTIVE");
                    Shader.DisableKeyword("WATER_REFRACTIVE");
                    break;
                case WaterMode.Refractive:
                    Shader.DisableKeyword("WATER_SIMPLE");
                    Shader.DisableKeyword("WATER_REFLECTIVE");
                    Shader.EnableKeyword("WATER_REFRACTIVE");
                    break;
            }

            s_InsideWater = false;
        }

19 View Source File : Bullet.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void Launch(Vector3 v, Vector3 v2, string launcher_ref, bool isLeft, HERO hero, bool leviMode = false)
    {
        if (this.phase == 2)
        {
            return;
        }
        this.master = hero;
        this.velocity = v;
        float f = Mathf.Acos(Vector3.Dot(v.normalized, v2.normalized)) * 57.29578f;
        if (Mathf.Abs(f) > 90f)
        {
            this.velocity2 = Vectors.zero;
        }
        else
        {
            this.velocity2 = Vector3.Project(v2, v);
        }
        switch (launcher_ref)
        {
            case "hookRefL1":
                this.myRef = hero.hookRefL1;
                break;

            case "hookRefL2":
                this.myRef = hero.hookRefL2;
                break;

            case "hookRefR1":
                this.myRef = hero.hookRefR1;
                break;

            case "hookRefR2":
                this.myRef = hero.hookRefR2;
                break;
        }
        myRefT = myRef.transform;
        this.nodes = new List<Vector3>();
        this.nodes.Add(myRefT.position);
        this.phase = 0;
        this.leviMode = leviMode;
        this.left = isLeft;
        if (IN_GAME_MAIN_CAMERA.GameType != GameType.Single && BasePV.IsMine)
        {
            BasePV.RPC("myMasterIs", PhotonTargets.Others, new object[] { hero.BasePV.viewID, launcher_ref });
            BasePV.RPC("setVelocityAndLeft", PhotonTargets.Others, new object[] { v, this.velocity2, this.left });
        }
        baseT.position = myRefT.position;
        baseT.rotation = Quaternion.LookRotation(v.normalized);
    }

19 View Source File : AnimalMovement.cs
License : MIT License
Project Creator : Interactml

protected virtual void Falling()
        {
            // fall_Point = Chest_Pivot_Point;
            // if (!Fly)
            fall_Point = Main_Pivot_Point + (T_Forward * (Shift ? GroundSpeed + 1 : GroundSpeed) * FallRayDistance * ScaleFactor); //Calculate ahead the falling ray

            if (FrameCounter % FallRayInterval != 0) return;         //Skip to reduce aditional raycasting

            //Don't Calcultate Fall Ray if the animal on any of these states    
            if (AnimState == AnimTag.Sleep ||
                AnimState == AnimTag.Action ||
                AnimState == AnimTag.Swim ||
                AnimState == AnimTag.Idle ||
                swim == true ||
                underwater) return;


            float Multiplier = Pivot_Multiplier;

            if (AnimState == AnimTag.Jump || AnimState == AnimTag.Fall || AnimState == AnimTag.Fly)
            {
                Multiplier *= FallRayMultiplier;
            }

           

            //Set the Fall Ray a bit farther from the front feet.
            if (Physics.Raycast(fall_Point, -T_Up, out FallRayCast, Multiplier, GroundLayer))
            {
                if (debug)
                {
                    Debug.DrawRay(fall_Point, -T_Up * Multiplier, Color.magenta);
                    MalbersTools.DebugPlane(FallRayCast.point, 0.1f, Color.magenta, true);
                }

                float fallSlopeAngle = Vector3.Angle(FallRayCast.normal, Vector3.up);
                fallSlopeAngle *= Vector3.Dot(T_ForwardNoY, FallRayCast.normal) > 0 ? 1 : -1; //Calcualte the Fall Angle Positive or Negative

                if ((fallSlopeAngle > maxAngleSlope) || (!frontray && !backray))        //found something but there's no BACK/FrontRay
                {
                    fall = true;
                    return;
                }

                fall = false;

                CheckForLanding();

                if (AnimState == AnimTag.SwimJump) Swim = false;            //in case is jumping from the water to the ground ***Important
            }
            else
            {
                fall = true;
                FallRayCast.normal = UpVector;    //if there's no fall ray Reset the Fall Normal to the Horizontal Terrain
                if (debug)
                {
                    MalbersTools.DebugPlane(fall_Point + (-T_Up * Multiplier), 0.1f, Color.gray, true);
                    Debug.DrawRay(fall_Point, -T_Up * Multiplier, Color.gray);
                }
            }
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : dag10

public static Vector3 ClosestPointOnLine( Vector3 vA, Vector3 vB, Vector3 vPoint )
		{
			var vVector1 = vPoint - vA;
			var vVector2 = ( vB - vA ).normalized;

			var d = Vector3.Distance( vA, vB );
			var t = Vector3.Dot( vVector2, vVector1 );

			if ( t <= 0 )
				return vA;

			if ( t >= d )
				return vB;

			var vVector3 = vVector2 * t;

			var vClosestPoint = vA + vVector3;

			return vClosestPoint;
		}

19 View Source File : ExtSegmentEndManager.cs
License : MIT License
Project Creator : CitiesSkylinesMods

private ArrowDirection CalculateArrowDirection(Vector3 sourceDir, Vector3 targetDir) {
            sourceDir.y = 0;
            sourceDir.Normalize();

            targetDir.y = 0;
            targetDir.Normalize();
            float c = Vector3.Cross(sourceDir, targetDir).y;

            if (c >= 0.5f) {
                // [+30°, +150°]
                return ArrowDirection.Left;
            }

            if (c <= -0.5f) {
                // [-30°, -150°]
                return ArrowDirection.Right;
            }

            // Handle cases (-30°, +30°) / (-150°, -180°] / (+150°, +180°]
            float d = Vector3.Dot(sourceDir, targetDir);
            if (d > 0) {
                // (-30°, +30°)
                if (c > 0) {
                    // (0°, 30°]
                    return ArrowDirection.Left;
                }

                if (c < 0) {
                    // (0°, -30°]
                    return ArrowDirection.Right;
                }

                // [0°]
                return ArrowDirection.Turn;
            }

            // (-150°, -180°] / (+150°, +180°]
            return ArrowDirection.Forward;
        }

19 View Source File : CameraMotionBlur.cs
License : Apache License 2.0
Project Creator : activey

void OnRenderImage (RenderTexture source, RenderTexture destination) {
            if (false == CheckResources ()) {
                Graphics.Blit (source, destination);
                return;
            }

            if (filterType == MotionBlurFilter.CameraMotion)
                StartFrame ();

            // use if possible new RG format ... fallback to half otherwise
            var rtFormat= SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf;

            // get temp textures
            RenderTexture velBuffer = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat);
            int tileWidth = 1;
            int tileHeight = 1;
            maxVelocity = Mathf.Max (2.0f, maxVelocity);

            float _maxVelocity = maxVelocity; // calculate 'k'
            // note: 's' is hardcoded in shaders except for DX11 path

            // auto DX11 fallback!
            bool fallbackFromDX11 = filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null;

            if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) {
                maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS);
                tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
                tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
                _maxVelocity = velBuffer.width/tileWidth;
            }
            else {
                tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity);
                tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity);
                _maxVelocity = velBuffer.width/tileWidth;
            }

            RenderTexture tileMax  = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
            RenderTexture neighbourMax  = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat);
            velBuffer.filterMode = FilterMode.Point;
            tileMax.filterMode = FilterMode.Point;
            neighbourMax.filterMode = FilterMode.Point;
            if (noiseTexture) noiseTexture.filterMode = FilterMode.Point;
            source.wrapMode = TextureWrapMode.Clamp;
            velBuffer.wrapMode = TextureWrapMode.Clamp;
            neighbourMax.wrapMode = TextureWrapMode.Clamp;
            tileMax.wrapMode = TextureWrapMode.Clamp;

            // calc correct viewprj matrix
            CalculateViewProjection ();

            // just started up?
            if (gameObject.activeInHierarchy && !wasActive) {
                Remember ();
            }
            wasActive = gameObject.activeInHierarchy;

            // matrices
            Matrix4x4 invViewPrj = Matrix4x4.Inverse (currentViewProjMat);
            motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj);
            motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
            motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);
			if(_camera.stereoEnabled)
			{
				Matrix4x4[] invStereoViewPrj = new Matrix4x4[2];
				invStereoViewPrj[0] = Matrix4x4.Inverse(currentStereoViewProjMat[0]);
				invStereoViewPrj[1] = Matrix4x4.Inverse(currentStereoViewProjMat[1]);

				Matrix4x4 combined = prevStereoViewProjMat[0] * invStereoViewPrj[0];
				motionBlurMaterial.SetMatrix("_StereoToPrevViewProjCombined0", combined);
				motionBlurMaterial.SetMatrix("_StereoToPrevViewProjCombined1", prevStereoViewProjMat[1] * invStereoViewPrj[1]);
			}

            motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity);
            motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);
            motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
            motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
            motionBlurMaterial.SetFloat ("_Jitter", jitter);

            // texture samplers
            motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
            motionBlurMaterial.SetTexture ("_VelTex", velBuffer);
            motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);
            motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax);

            if (preview) {
                // generate an artificial 'previous' matrix to simulate blur look
                Matrix4x4 viewMat = _camera.worldToCameraMatrix;
                Matrix4x4 offset = Matrix4x4.idenreplacedy;
                offset.SetTRS(previewScale * 0.3333f, Quaternion.idenreplacedy, Vector3.one); // using only translation
                Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true);
                prevViewProjMat = projMat * offset * viewMat;
                motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat);
                motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj);
            }

            if (filterType == MotionBlurFilter.CameraMotion)
            {
                // build blur vector to be used in shader to create a global blur direction
                Vector4 blurVector = Vector4.zero;

                float lookUpDown = Vector3.Dot (transform.up, Vector3.up);
                Vector3 distanceVector = prevFramePos-transform.position;

                float distMag = distanceVector.magnitude;

                float farHeur = 1.0f;

                // pitch (vertical)
                farHeur = (Vector3.Angle (transform.up, prevFrameUp) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.x =  rotationScale * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp)));

                // yaw #1 (horizontal, faded by pitch)
                farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.y = rotationScale * lookUpDown * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));

                // yaw #2 (when looking down, faded by 1-pitch)
                farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f);
                blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;//Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward)));

                if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) {
                    // forward (probably most important)
                    blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f);
                    // jump (maybe scale down further)
                    blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f);
                    // strafe (maybe scale down further)
                    blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f);
                }

                if (preview) // crude approximation
                    motionBlurMaterial.SetVector ("_BlurDirectionPacked", new Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * _camera.fieldOfView);
                else
                    motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector);
            }
            else {
                // generate velocity buffer
                Graphics.Blit (source, velBuffer, motionBlurMaterial, 0);

                // patch up velocity buffer:

                // exclude certain layers (e.g. skinned objects as we cant really support that atm)

                Camera cam = null;
                if (excludeLayers.value != 0)// || dynamicLayers.value)
                    cam = GetTmpCam ();

                if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) {
                    cam.targetTexture = velBuffer;
                    cam.cullingMask = excludeLayers;
                    cam.RenderWithShader (replacementClear, "");
                }
            }

            if (!preview && Time.frameCount != prevFrameCount) {
                // remember current transformation data for next frame
                prevFrameCount = Time.frameCount;
                Remember ();
            }

            source.filterMode = FilterMode.Bilinear;

            // debug vel buffer:
            if (showVelocity) {
                // generate tile max and neighbour max
                //Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                //Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);
                motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale);
                Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1);
            }
            else {
                if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) {
                    // need to reset some parameters for dx11 shader
                    dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity);
                    dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale);
                    dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter);

                    // texture samplers
                    dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture);
                    dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer);
                    dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax);

                    dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );
                    dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity);

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0);
                    Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1);

                    // final blur
                    Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2);
                }
                else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) {
                    // 'reconstructing' properly integrated color
                    motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                    Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);

                    // final blur
                    Graphics.Blit (source, destination, motionBlurMaterial, 4);
                }
                else if (filterType == MotionBlurFilter.CameraMotion) {
                    // orange box style motion blur
                    Graphics.Blit (source, destination, motionBlurMaterial, 6);
                }
                else if (filterType == MotionBlurFilter.ReconstructionDisc) {
                    // dof style motion blur defocuing and ellipse around the princical blur direction
                    // 'reconstructing' properly integrated color
                    motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) );

                    // generate tile max and neighbour max
                    Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2);
                    Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3);

                    Graphics.Blit (source, destination, motionBlurMaterial, 7);
                }
                else {
                    // simple & fast blur (low quality): just blurring along velocity
                    Graphics.Blit (source, destination, motionBlurMaterial, 5);
                }
            }

            // cleanup
            RenderTexture.ReleaseTemporary (velBuffer);
            RenderTexture.ReleaseTemporary (tileMax);
            RenderTexture.ReleaseTemporary (neighbourMax);
        }

19 View Source File : VortexAffector.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public override void Update()
    {
        Vector3 vector = this.Node.GetLocalPosition() - this.Node.Owner.EmitPoint;
        float magnitude = vector.magnitude;
        if (magnitude == 0f)
        {
            return;
        }
        float d = Vector3.Dot(this.Direction, vector);
        vector -= d * this.Direction;
        Vector3 vector2 = Vectors.zero;
        if (vector == Vectors.zero)
        {
            vector2 = vector;
        }
        else
        {
            vector2 = Vector3.Cross(this.Direction, vector).normalized;
        }
        float elapsedTime = this.Node.GetElapsedTime();
        float num;
        if (this.UseCurve)
        {
            num = this.VortexCurve.Evaluate(elapsedTime);
        }
        else
        {
            num = this.Magnitude;
        }
        vector2 *= num * Time.deltaTime;
        this.Node.Position += vector2;
    }

19 View Source File : Vector3.cs
License : MIT License
Project Creator : AnotherEnd15

public static Vector3 Project(Vector3 vector, Vector3 onNormal)
        {
            return onNormal * Vector3.Dot(vector, onNormal) / Vector3.Dot(onNormal, onNormal);
        }

19 View Source File : LeanPath.cs
License : GNU General Public License v3.0
Project Creator : Cytoid

private Vector3 GetClosestPoint(Ray ray, Vector3 origin, Vector3 direction)
		{
			var crossA = Vector3.Cross(ray.direction, direction);
			var denom  = Vector3.Dot(crossA, crossA);

			// If lines are parallel, we can return any point on line
			if (denom == 0.0f)
			{
				return origin;
			}

			var crossB = Vector3.Cross(ray.direction, ray.origin - origin);
			var dist01 = Vector3.Dot(crossA, crossB) / denom;

			return origin + direction * Mathf.Clamp01(dist01);
		}

19 View Source File : SteamVR_Utils.cs
License : MIT License
Project Creator : dag10

public static float InverseLerp(Vector3 A, Vector3 B, Vector3 result)
	{
		return Vector3.Dot(result - A, B - A);
	}

See More Examples