Esempio n. 1
1
    // Use this for initialization
    void Awake()
    {
        player = GameObject.FindGameObjectWithTag ("Player").transform;
        playerOrgin = player.position;

        path2 = new []{ new Vector3(10.0f,20.0f,40f), new Vector3(10f,10f,20f),
            playerOrgin, new Vector3(0f,10f,-10f), new Vector3( 0f, -5f, -20f), new Vector3(10f,-10f,5f),
            new Vector3(5f,5f,15f), new Vector3(0f,20f,20f)};

        path3 = new []{ new Vector3(30.0f,6.0f,60f), new Vector3(9f,40f,40f),
            new Vector3(15.2f,2f,20f), new Vector3(0f,0f,5f), new Vector3( 4f, 7f, -30f), new Vector3(16f,4f, 5f)};

        path4 = new []{ new Vector3(20.0f,30.0f,60f), new Vector3(5f,70f,40f),
            new Vector3(28.2f,21f,20f), new Vector3(0f,0f,5f), new Vector3( 4f, 7f, -30f), new Vector3(16f,4f, 5f)};

        path5 = new []{ new Vector3(20.0f,30.0f,60f), new Vector3(5f,-70f,30f),
            new Vector3(11.2f,16f,20f), new Vector3(0f,0f,5f), new Vector3( 4f, -17f, -30f), new Vector3(16f,4f, 5f)};

        aiShip = FindObjectOfType <Rigidbody> ();
        launcher = GetComponent<MLauncher> ();

        path = path2;
        target = path[0];
        bound = new Bounds (path[0], new Vector3(1f,1f,1f));
    }
    public void checkPlayerObjectCollision(Bounds playerBounds)
    {
        if (tileMapData != null)
        {
            currentNodeIndex = tileMapData.checkObjectCollision(playerBounds) + 1;
            if (currentNodeIndex > 0)
            {
                currentNode = (ZoneTreeNode)zoneTree.getNodeCheckingRootBranchList(currentNodeIndex);
                if (currentNode != null)
                {
                    //Enter battles automatically
                    if (currentNode.content.nodeType == ZoneNodeType.Battle)
                    {
                        ZoneNodeButtonClick();
                    }

                    panelText.text = currentNode.content.nodeName + " " + currentNode.content.description;
                    panelButton.enabled = true;
                }
                else
                {
                    panelText.text = "";
                    panelButton.enabled = false;
                }
            }
            else
            {
                panelText.text = "";
                panelButton.enabled = false;
            }

        }
    }
    private List<Vector3> DynamicSetupList(float minX, float maxX, float minZ, float maxZ, Bounds bR, Bounds bM)
    {
        List<Vector3> checkList = new List<Vector3>();
        float Tilesize = Pathfinder.Instance.Tilesize;

        for (float i = minZ; i < maxZ; i += Tilesize / 2)
        {
            for (float j = minX; j < maxX; j += Tilesize / 2)
            {
                for (float k = bR.min.y; k < bR.max.y; k += Tilesize)
                {
                    if (k > lowestY)
                    {
                        Vector3 local = transform.InverseTransformPoint(new Vector3(j, k, i));

                        if (bM.Contains(local))
                        {
                            checkList.Add(new Vector3(j, k, i));
                        }
                    }
                }
            }
        }
        return checkList;
    }
Esempio n. 4
0
    // IN: Object (single element array)
    // OUT: Location
    public Vector3 BEHIND(object[] args)
    {
        Vector3 outValue = Vector3.zero;
        if (args [0] is GameObject) {	// behind an object
            GameObject obj = ((GameObject)args [0]);

            Bounds bounds = new Bounds ();

            bounds = Helper.GetObjectWorldSize (obj);

            GameObject camera = GameObject.Find ("Main Camera");
            float povDir = cameraRelativeDirections ? camera.transform.eulerAngles.y : 0.0f;
            Vector3 rayStart = new Vector3 (0.0f, 0.0f,
                Mathf.Abs(bounds.size.z));
            rayStart = Quaternion.Euler (0.0f, povDir, 0.0f) * rayStart;
            rayStart += obj.transform.position;
            outValue = Helper.RayIntersectionPoint (rayStart, obj);

            Debug.Log ("behind: " + Helper.VectorToParsable (outValue));
        }
        else if (args [0] is Vector3) {	// behind a location
            outValue = (Vector3)args[0];
        }

        return outValue;
    }
Esempio n. 5
0
    // Update is called once per frame
    void Update()
    {
        // I.E We've moved somewhere.
        if (HasShipMoved(20)) {
            Bounds generateDistance = new Bounds (Ship.transform.position, Vector3.one * VIEW_DISTANCE);
            foreach (ChunkObject c in StreamSource.GetObjects(generateDistance))
            {
                if (!LiveObjects.Exists(i => i.transform.position == c.Position))
                {
                    GameObject GO = PhotonNetwork.InstantiateSceneObject(c.ChunkObjectType, c.Position, c.Rotation,0, null);
                    GO.transform.localScale = new Vector3(400,400,400);
                    LiveObjects.Add(GO);
                    GO.transform.parent = this.transform;
                }
            }
            for (var i = LiveObjects.Count() - 1; i >= 0; i--) {
                //Replace your Where(...)
                var go = LiveObjects[i];
                if (!generateDistance.Intersects(new Bounds(go.transform.position,new Vector3(3,3,3))))
                    continue;

                Debug.Log ("Deleting" + LiveObjects[i].transform.position.ToString ());
                GameObject reference = LiveObjects[i];
                LiveObjects.RemoveAt(i);
                PhotonNetwork.Destroy (reference);
                //body of foreach loop goes here
            }
            oldShipPosition = Ship.transform.position;
        }
    }
Esempio n. 6
0
    /// <summary>
    /// Calculate the combined bounds of all widgets attached to the specified game object or its children (in world space).
    /// </summary>
    public static Bounds CalculateAbsoluteWidgetBounds(Transform trans)
    {
        UIWidget[] widgets = trans.GetComponentsInChildren<UIWidget>() as UIWidget[];

        Bounds b = new Bounds(trans.transform.position, Vector3.zero);
        bool first = true;

        foreach (UIWidget w in widgets)
        {
            Vector2 size = w.relativeSize;
            Vector2 offset = w.pivotOffset;
            float x = (offset.x + 0.5f) * size.x;
            float y = (offset.y - 0.5f) * size.y;
            size *= 0.5f;

            Transform wt = w.cachedTransform;
            Vector3 v0 = wt.TransformPoint(new Vector3(x - size.x, y - size.y, 0f));

            // 'Bounds' can never start off with nothing, apparently, and including the origin point is wrong.
            if (first)
            {
                first = false;
                b = new Bounds(v0, Vector3.zero);
            }
            else
            {
                b.Encapsulate(v0);
            }

            b.Encapsulate(wt.TransformPoint(new Vector3(x - size.x, y + size.y, 0f)));
            b.Encapsulate(wt.TransformPoint(new Vector3(x + size.x, y - size.y, 0f)));
            b.Encapsulate(wt.TransformPoint(new Vector3(x + size.x, y + size.y, 0f)));
        }
        return b;
    }
Esempio n. 7
0
    public static Bounds GetBounds(Renderer r)
    {
        if (r is SkinnedMeshRenderer) {
            SkinnedMeshRenderer smr = r as SkinnedMeshRenderer;
            Mesh mesh = smr.sharedMesh;

            Vector3[] vertices = mesh.vertices;
            if (vertices.Length <= 0) {
                return r.bounds;
            }
            int idx = 0;
            Vector3 min, max;
            min = max = r.transform.TransformPoint (vertices [idx++]);

            for (int i = idx; i < vertices.Length; i++) {
                Vector3 v = vertices [i];
                Vector3 V = r.transform.TransformPoint (v);
                for (int n = 0; n < 3; n++) {
                    if (V [n] > max [n])
                        max [n] = V [n];
                    if (V [n] < min [n])
                        min [n] = V [n];
                }
            }

            Bounds b = new Bounds ();;
            b.SetMinMax (min, max);
            return b;

        } else {
            return r.bounds;
        }
    }
Esempio n. 8
0
    /// <summary>
    /// 	- Debugs an axis-aligned bounding box.
    /// </summary>
    /// <param name='bounds'>
    /// 	- The bounds to debug.
    /// </param>
    /// <param name='color'>
    /// 	- The color of the bounds.
    /// </param>
    /// <param name='duration'>
    /// 	- How long to draw the bounds.
    /// </param>
    /// <param name='depthTest'>
    /// 	- Whether or not the bounds should be faded when behind other objects.
    /// </param>
    public static void DebugBounds(Bounds bounds, Color color, float duration, bool depthTest)
    {
        Vector3 center = bounds.center;

        float x = bounds.extents.x;
        float y = bounds.extents.y;
        float z = bounds.extents.z;

        Vector3 ruf = center+new Vector3(x,y,z);
        Vector3 rub = center+new Vector3(x,y,-z);
        Vector3 luf = center+new Vector3(-x,y,z);
        Vector3 lub = center+new Vector3(-x,y,-z);

        Vector3 rdf = center+new Vector3(x,-y,z);
        Vector3 rdb = center+new Vector3(x,-y,-z);
        Vector3 lfd = center+new Vector3(-x,-y,z);
        Vector3 lbd = center+new Vector3(-x,-y,-z);

        Debug.DrawLine(ruf, luf, color, duration, depthTest);
        Debug.DrawLine(ruf, rub, color, duration, depthTest);
        Debug.DrawLine(luf, lub, color, duration, depthTest);
        Debug.DrawLine(rub, lub, color, duration, depthTest);

        Debug.DrawLine(ruf, rdf, color, duration, depthTest);
        Debug.DrawLine(rub, rdb, color, duration, depthTest);
        Debug.DrawLine(luf, lfd, color, duration, depthTest);
        Debug.DrawLine(lub, lbd, color, duration, depthTest);

        Debug.DrawLine(rdf, lfd, color, duration, depthTest);
        Debug.DrawLine(rdf, rdb, color, duration, depthTest);
        Debug.DrawLine(lfd, lbd, color, duration, depthTest);
        Debug.DrawLine(lbd, rdb, color, duration, depthTest);
    }
Esempio n. 9
0
    private Camera viewCamera; // Gets the main camera for worldspacetoscreenspace calculations.

    #endregion Fields

    #region Methods

    // Gets the mesh origin and farthest extents as a Rect
    public Rect BoundsToScreenRect(Bounds bounds)
    {
        Vector3 origin = Camera.main.WorldToScreenPoint(new Vector3(bounds.min.x, bounds.max.y, 0f));
        Vector3 extent = Camera.main.WorldToScreenPoint(new Vector3(bounds.max.x, bounds.min.y, 0f));

        return new Rect(origin.x, Screen.height - origin.y, extent.x - origin.x, origin.y - extent.y);
    }
Esempio n. 10
0
 public static void DebugDrawCube(Vector3 center, Vector3 size, Color c)
 {
     /*
      *      4-----5
      *     /|    /|
      * y  7-----6 |
      * |  | 0---|-1
      * |  |/    |/
      * |  3-----2
      * | z
      * |/_______x
      */
     Bounds bounds = new Bounds(center, size);
     Vector3 p3 = bounds.min;
     Vector3 p5 = bounds.max;
     Vector3 p0 = new Vector3(p3.x, p3.y, p5.z);
     Vector3 p1 = new Vector3(p5.x, p3.y, p5.z);
     Vector3 p2 = new Vector3(p5.x, p3.y, p3.z);
     Vector3 p4 = new Vector3(p3.x, p5.y, p5.z);
     Vector3 p6 = new Vector3(p5.x, p5.y, p3.z);
     Vector3 p7 = new Vector3(p3.x, p5.y, p3.z);
     Debug.DrawLine(p0, p1, c);
     Debug.DrawLine(p1, p2, c);
     Debug.DrawLine(p2, p3, c);
     Debug.DrawLine(p3, p0, c);
     Debug.DrawLine(p4, p5, c);
     Debug.DrawLine(p5, p6, c);
     Debug.DrawLine(p6, p7, c);
     Debug.DrawLine(p7, p4, c);
     Debug.DrawLine(p0, p4, c);
     Debug.DrawLine(p1, p5, c);
     Debug.DrawLine(p2, p6, c);
     Debug.DrawLine(p3, p7, c);
 }
Esempio n. 11
0
 public void CalculateBounds()
 {
     if (connectedBody == null)
     {
         _bodyBounds = new Bounds();
         return;
     }
     AABB aabb_full = new AABB();
     bool combine = false;
     for (int i = 0; i < connectedBody.FixtureList.Count; i++)
     {
         for (int j = 0; j < connectedBody.FixtureList[i].Shape.ChildCount; j++)
         {
             AABB aabb;
             connectedBody.FixtureList[i].Shape.ComputeAABB(out aabb, ref connectedBody.Xf, j);
             if (!combine)
             {
                 combine = true;
                 aabb_full = aabb;
             }
             else
             {
                 aabb_full.Combine(ref aabb);
             }
         }
     }
     _bodyBounds = Bounds.FromAABB(ref aabb_full, to2dMode, GetSize());
 }
Esempio n. 12
0
 public void CalculateBounds()
 {
     selectionBounds = new Bounds(transform.position, Vector3.zero);
     foreach(Renderer r in GetComponentsInChildren< Renderer >()) {
         selectionBounds.Encapsulate(r.bounds);
     }
 }
Esempio n. 13
0
    void CheckOffscreen()
    {
        //if bounds are still tehir default value
        if (bounds.size == Vector3.zero)
        {
            //then set them
            bounds = Utils.CombineBoundsOfChildren(this.gameObject);
            //Also find the diff between bounds.center & transform.position
            boundsCenterOffset = bounds.center - transform.position;
        }

        //every time, update teh bounds to the ucrrent positon
        bounds.center = transform.position + boundsCenterOffset;
        //check to see wehether the bounds are completely offscreen
        Vector3 off = Utils.ScreenBoundsCheck(bounds, BoundsTest.offScreen);
        if (off != Vector3.zero)
        {
            //if this enemy has gone off the bottom edge of the screen
            if (off.y < 0)
            {
                //then destroy it
                Destroy(this.gameObject);
            }
        }
    }
Esempio n. 14
0
    //for moving object based on gaze coordinates from tracker
    //based on resolution of window
    //receives object, renderer, bounds script, and data script
    //returns vector3 position in world coordinates
    public Vector3 positionObjectWithRendererBoundsData(GameObject theObject, Renderer theRenderer, Bounds theBounds, GazeDataManager theData) {
        //verify the gaze data
        if (theData.gazeCoords != null) {
            //convert gaze coords to screen coords
            Point2D screenCoords = DataUtilities.gazePointToWindowPoint(theData.gazeCoords);

            //convert window coords to viewport coords
            Point2D viewCoords = DataUtilities.windowPointToViewPoint(screenCoords);
            Vector3 viewVector = new Vector3((float)viewCoords.X, (float)(viewCoords.Y), 0);

            //check bounds
            //use the object with the outermost bounds and a renderer to make the check
            Vector3 boundsVector = theBounds.checkBoundsForRenderer(theRenderer, viewVector);

            //convert viewport vector to world position vector
            Vector3 worldPos = Camera.main.ViewportToWorldPoint(boundsVector);
            worldPos.z = theObject.transform.position.z; //maintain z position for object

            //return new world position
            return worldPos;

        }
        //error
        else {
            //Debug.Log("[GazeMove] Null gaze data, " + theObject.name + " cannot be positioned");
            return Vector3.zero;
        }
    } //end function
Esempio n. 15
0
 public override object ReadJson( Type objectType, Dictionary<string,object> values)
 {
     Bounds b = new Bounds();
         b.center = new Vector3(	CastFloat(values["cx"]),CastFloat(values["cy"]),CastFloat(values["cz"]));
         b.extents = new Vector3(CastFloat(values["ex"]),CastFloat(values["ey"]),CastFloat(values["ez"]));
         return b;
 }
Esempio n. 16
0
	void CreateGrid() {
		GameObject floorTiles = new GameObject("Floor Tiles"); // An object to store the tiles in the Hiearchy. Just for tidyness ;).
		floorTiles.AddComponent<LevelInfo>(); // This should be done manually for the designed floors.

		Bounds levelBounds = new Bounds();
		int nrTiles = this.transform.childCount;
		for (int i = 0; i < nrTiles; i++) {
			Transform child = transform.GetChild(i);

			if (child.GetComponent<Renderer>())
				levelBounds.Encapsulate(child.GetComponent<Renderer>().bounds);

            //TODO fixa så att det även funkar med cubeworld utan en tom box i dem
       //     else if (child.GetComponentInChildren<Renderer>())
       //         levelBounds.Encapsulate(child.GetComponent<Renderer>().bounds);
		}

		Vector3 size = levelBounds.size;
		
		_gridManager.CreateGrid((int)size.x + 1, (int)size.z + 1);
		for (int i = 0; i < nrTiles; i++) {
			BaseTile tile = transform.GetChild(i).GetComponent<BaseTile>();
			tile.Init(_gridManager);
			_gridManager.AddTile(tile);
		}

		Object[] allUnits = Object.FindObjectsOfType<BaseUnit>();
		for (int i = 0; i < allUnits.Length; i++) {
			BaseUnit bu = allUnits[i] as BaseUnit;
			bu.Init(_gridManager);
			BaseTile tile = _gridManager.GetTile(bu.transform.position);
			DebugAux.Assert(tile != null, "Can't have a unit placed on a non-tile " + bu);
			BaseTile.TeleportTo(bu, null, tile);
		}
	}
Esempio n. 17
0
        public void Update()
        {
            var newBounds = Bounds.Translate(Velocity);

            if (Playfield.Bounds.Contains(newBounds))
                Bounds = newBounds;
        }
 public static Vector3 GetPointInBounds(Bounds bounds)
 {
     float x = Random.Range(bounds.center.x, bounds.center.x + bounds.extents.x);
     float y = Random.Range(bounds.center.y, bounds.center.y + bounds.extents.y);
     float z = Random.Range(bounds.center.z, bounds.center.z + bounds.extents.z);
     return new Vector3(x, y, z);
 }
Esempio n. 19
0
	public void Start () {
		// Capture the bounds of the collider while it is closed
		bounds = GetComponent<Collider>().bounds;

		// Initially open the door
		SetState(open);
	}
Esempio n. 20
0
    public void Query(Vector3 pos, float radius, UKList<IUKSpatialObject> result)
    {
        var b = new Bounds(pos, Vector3.one * radius * 2f);

        int minx = Mathf.FloorToInt(b.min.x / CELL_SIZE);
        int miny = Mathf.FloorToInt(b.min.y / CELL_SIZE);
        int minz = Mathf.FloorToInt(b.min.z / CELL_SIZE);

        int maxx = Mathf.FloorToInt(b.max.x / CELL_SIZE);
        int maxy = Mathf.FloorToInt(b.max.y / CELL_SIZE);
        int maxz = Mathf.FloorToInt(b.max.z / CELL_SIZE);

        for (int z = minz; z <= maxz; ++z) {
            for (int y = miny; y <= maxy; ++y) {
                for (int x = minx; x <= maxx; ++x) {
                    var h = CalculateHash(x,y,z);
                    if (spatialHashTable.ContainsKey(h)) {
                        var l = spatialHashTable[h];
                        foreach(var p in l) {
                            result.Add(p.Key);
                        }
                    }
                }
            }
        }
    }
Esempio n. 21
0
	public static Bounds calculateWorldBounds(GameObject go)
	{
		if (null == go) { return new Bounds(Vector3.zero, Vector3.zero); }

		Vector2 min = new Vector2(float.MaxValue, float.MaxValue);
		Vector2 max = new Vector2(float.MinValue, float.MinValue);
		Vector3 v;

		RectTransform[] rts = go.GetComponentsInChildren<RectTransform>();
		if (rts.Length == 0) return new Bounds(go.transform.position, Vector3.zero);

		for (int i = 0, imax = rts.Length; i < imax; ++i)
		{
			RectTransform t = rts[i];
			if (!t.gameObject.activeSelf) { continue; }

			Vector3[] corners = new Vector3[4];
			t.GetWorldCorners(corners);

			for (int j = 0; j < 4; ++j)
			{
				v = corners[j];
				if (v.x > max.x) max.x = v.x;
				if (v.y > max.y) max.y = v.y;

				if (v.x < min.x) min.x = v.x;
				if (v.y < min.y) min.y = v.y;
			}
		}

		Bounds b = new Bounds(min, Vector3.zero);
		b.Encapsulate(max);

		return b;
	}
    public void DoUpdateGraphs()
    {
        if (col == null) { return; }

        isWaitingForUpdate = false;
        Bounds newBounds = col.bounds;

        //if (!simple) {
            Bounds merged = newBounds;
            merged.Encapsulate (prevBounds);

            if (BoundsVolume (merged) < BoundsVolume (newBounds)+BoundsVolume(prevBounds)) {
                AstarPath.active.UpdateGraphs (merged);
            } else {
                AstarPath.active.UpdateGraphs (prevBounds);
                AstarPath.active.UpdateGraphs (newBounds);
            }
        /*} else {
            GraphUpdateObject guo = new GraphUpdateObject (prevBounds);
            guo.updatePhysics = false;
            guo.modifyWalkability = true;
            guo.setWalkability = true;

            AstarPath.active.UpdateGraphs (guo);
        }*/

        prevBounds = newBounds;
    }
 private void Start()
 {
     if (this.template != null)
     {
         int num = 0;
         Bounds bounds = new Bounds();
         for (int i = 0; i < this.maxRows; i++)
         {
             for (int j = 0; j < this.maxColumns; j++)
             {
                 GameObject obj2 = NGUITools.AddChild(base.gameObject, this.template);
                 obj2.transform.localPosition = new Vector3(this.padding + ((j + 0.5f) * this.spacing), -this.padding - ((i + 0.5f) * this.spacing), 0f);
                 UIStorageSlot component = obj2.GetComponent<UIStorageSlot>();
                 if (component != null)
                 {
                     component.storage = this;
                     component.slot = num;
                 }
                 bounds.Encapsulate(new Vector3((this.padding * 2f) + ((j + 1) * this.spacing), (-this.padding * 2f) - ((i + 1) * this.spacing), 0f));
                 if (++num >= this.maxItemCount)
                 {
                     if (this.background != null)
                     {
                         this.background.transform.localScale = bounds.size;
                     }
                     return;
                 }
             }
         }
         if (this.background != null)
         {
             this.background.transform.localScale = bounds.size;
         }
     }
 }
Esempio n. 24
0
    public static char CollisionDectection(Bounds moi, Bounds toi)
    {
        char sides;

        Vector3 moiMax = moi.max;
        Vector3 moiMin = moi.min;

        Vector3 toiMax = toi.max;
        Vector3 toiMin = toi.min;

        //toiMax
        Vector3 maxMinusMin = new Vector3(Mathf.Abs(moiMax.x - toiMin.x),Mathf.Abs(moiMax.y - toiMin.y),Mathf.Abs(moiMax.z - toiMin.z));
        Vector3 minMinusMax = new Vector3(Mathf.Abs(moiMin.x - toiMax.x),Mathf.Abs(moiMin.y - toiMax.y),Mathf.Abs(moiMin.z - toiMax.z));

        if(maxMinusMin.x <= maxMinusMin.y &&
           maxMinusMin.x <= minMinusMax.y)
            return 'r';
        if(minMinusMax.x <= minMinusMax.y &&
           minMinusMax.x <= maxMinusMin.y)
            return 'l';
        if(maxMinusMin.y <= minMinusMax.x &&
           maxMinusMin.y <= maxMinusMin.x)
            return 'u';
        if(minMinusMax.y <= minMinusMax.x &&
           minMinusMax.y <= maxMinusMin.x)
            return 'd';

        return 'n';
    }
    static void FitToChildren()
    {
        foreach (GameObject rootGameObject in Selection.gameObjects)
        {
            if (!(rootGameObject.GetComponent<Collider>() is BoxCollider))
                continue;

            bool hasBounds = false;
            Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);

            for (int i = 0; i < rootGameObject.transform.childCount; ++i)
            {
                Renderer childRenderer = rootGameObject.transform.GetChild(i).GetComponent<Renderer>();
                if (childRenderer != null)
                {
                    if (hasBounds)
                    {
                        bounds.Encapsulate(childRenderer.bounds);
                    }
                    else
                    {
                        bounds = childRenderer.bounds;
                        hasBounds = true;
                    }
                }
            }

            BoxCollider collider = (BoxCollider)rootGameObject.GetComponent<Collider>();
            collider.center = bounds.center - rootGameObject.transform.position;
            collider.size = bounds.size;
        }
    }
Esempio n. 26
0
    static bool GetBoundWithChildren( Transform parent, ref Bounds pBound, ref bool initBound )
    {
        Bounds bound = new Bounds();
        bool didOne = false;

        if( parent.gameObject.renderer != null )
        {
            bound = parent.gameObject.renderer.bounds;
            if( initBound )
            {
                pBound.Encapsulate( bound.min );
                pBound.Encapsulate( bound.max );
            }
            else
            {
                pBound.min = new Vector3( bound.min.x, bound.min.y, bound.min.z );
                pBound.max = new Vector3( bound.max.x, bound.max.y, bound.max.z );
                initBound = true;
            }
            didOne = true;
        }

        foreach( Transform child in parent )
        {
            if( GetBoundWithChildren( child, ref pBound, ref initBound ))
                didOne = true;
        }

        return didOne;
    }
Esempio n. 27
0
 // Use this for initialization
 public void Start()
 {
     renderer = this.GetComponent<SpriteRenderer>();
     rigidbody = this.GetComponent<Rigidbody2D>();
     bounds = limitsUniverse.GetComponent<Renderer>().bounds;
     animator = this.GetComponent<Animator>();
 }
Esempio n. 28
0
	// sets up the inventory with as many items
	// as maxItemSlot. the background can be seen
	// if it contains a UISprite. 
	void InitializeInventory()
	{
		int    count = 0; 
		Bounds bound = new Bounds();

		BackgroundSettings();
		for(int y = 0; y < m_MaxRows; ++y)
		{
			for(int x = 0; x < m_MaxColumns; ++x)
			{
				GameObject go = NGUITools.AddChild(gameObject, m_Template);

				UISprite sprite = go.GetComponent<UISprite> () as UISprite;

				int width  = sprite.width;
				int height = sprite.height; 
				go.transform.localPosition = new Vector3 ( width * (x + 0.5f) * m_Spacing, 
				                                          -(height * ( y + 0.5f ) * m_Padding),
				                                          0f);

				InventoryItem slot = go.GetComponent<InventoryItem>();

				if(slot != null)
				{
					slot.Slot = count;
				} 

				InventoryData.AddSlot(go);

				++count;
			}
		}
	}
    private float m_ZoomAmountMultiplier = 2; // a multiplier for the FOV amount. The default of 2 makes the field of view twice as wide as required to fit the target.

    #endregion Fields

    #region Methods

    public static float MaxBoundsExtent(Transform obj, bool includeEffects)
    {
        // get the maximum bounds extent of object, including all child renderers,
            // but excluding particles and trails, for FOV zooming effect.

            var renderers = obj.GetComponentsInChildren<Renderer>();

            Bounds bounds = new Bounds();
            bool initBounds = false;
            foreach (Renderer r in renderers)
            {
                if (!((r is TrailRenderer) || (r is ParticleRenderer) || (r is ParticleSystemRenderer)))
                {
                    if (!initBounds)
                    {
                        initBounds = true;
                        bounds = r.bounds;
                    }
                    else
                    {
                        bounds.Encapsulate(r.bounds);
                    }
                }
            }
            float max = Mathf.Max(bounds.extents.x, bounds.extents.y, bounds.extents.z);
            return max;
    }
Esempio n. 30
0
    public static Bounds CombineBoundsOfChildren(GameObject go)
    {
        // Create an empty Bounds b
        Bounds b = new Bounds(Vector3.zero, Vector3.zero);
        // If this GameObject has a Renderer Component...
        if (go.GetComponent<Renderer>() != null)
        {
            // Expand b to contain the Renderer's Bounds
            b = BoundsUnion(b, go.GetComponent<Renderer>().bounds);
        }
        // If this GameObject has a Collider Component...
        if (go.GetComponent<Collider>() != null)
        {
            // Expand b to contain the Collider's Bounds
            b = BoundsUnion(b, go.GetComponent<Collider>().bounds);
        }
        // Iterate through each child of this gameObject.transform
        foreach (Transform t in go.transform)
        {
            // Expand b to contain their Bounds as well
            b = BoundsUnion(b, CombineBoundsOfChildren(t.gameObject));
        }

        return (b);
    }
Esempio n. 31
0
        private void showGameObjectPreview()
        {
            if (toShowInstance == null)
            {
                return;
            }

            //all comonents
            List <Component> toShow_components = new List <Component>(toShowInstance.GetComponentsInChildren <Component>());

            //removes all components but meshes
            foreach (Component comp in toShow_components)
            {
                //Debug.Log(comp.GetType());
                //if comp is not a mesh or a transform component or interactive component
                if (!comp.GetType().Equals(typeof(Mesh)) &&
                    !comp.GetType().Equals(typeof(Renderer)) &&
                    !comp.GetType().Equals(typeof(MeshRenderer)) &&
                    !comp.GetType().Equals(typeof(TextMesh)) &&
                    !comp.GetType().Equals(typeof(MeshFilter)) &&
                    !comp.GetType().Equals(typeof(Transform)) &&
                    !comp.GetType().Equals(typeof(Vector3InteractiveTheme)) &&
                    !comp.GetType().Equals(typeof(ColorInteractiveTheme)) &&
                    !comp.GetType().Equals(typeof(StringInteractiveTheme)) &&
                    !comp.GetType().Equals(typeof(TextureInteractiveTheme)) &&
                    !comp.GetType().Equals(typeof(ButtonFocusShowHideWidget)) &&
                    !comp.GetType().Equals(typeof(ButtonThemeWidget)) &&
                    !comp.GetType().Equals(typeof(ButtonThemeWidgetLabel)) &&
                    !comp.GetType().Equals(typeof(ButtonThemeWidgetOutline)) &&
                    !comp.GetType().Equals(typeof(ElementSelectedActiveWidget)) &&
                    !comp.GetType().Equals(typeof(LabelTheme)) &&
                    !comp.GetType().Equals(typeof(LoadingAnimation)) &&
                    !comp.GetType().Equals(typeof(SliderGestureControl)) &&
                    !comp.GetType().Equals(typeof(RectTransform)) &&//canvas
                    !comp.GetType().Equals(typeof(Canvas)) &&
                    !comp.GetType().Equals(typeof(CanvasScaler)) &&
                    !comp.GetType().Equals(typeof(GraphicRaycaster)) &&
                    !comp.GetType().Equals(typeof(Text)) &&
                    !comp.GetType().Equals(typeof(CanvasRenderer)))
                {
                    if (Application.isPlaying) //Application.isPlaying
                    {                          //if called from inspector, use destroyimmediate
                        Destroy(comp);
                        try
                        {
                            //MonoBehaviour b = (MonoBehaviour)comp;
                            //b.enabled = false;
                            //Destroy(b);
                        }
                        catch { }
                    }
                    else
                    {
                        DestroyImmediate(comp);
                    }
                }
            }


            //bounds of original obj
            Bounds toShow_Instance_Bounds = BoundsUtils.getBounds(toShowInstance);


            Vector3 newScale = toShowInstance.transform.localScale;

            //use the smallest resize
            if (targetSizeHeight / toShow_Instance_Bounds.size.y < targetSizeLenght / toShow_Instance_Bounds.size.x)
            {
                //calc a new scale based on targetSizeHeight
                newScale.y = targetSizeHeight * newScale.y / toShow_Instance_Bounds.size.y;
                newScale.x = targetSizeHeight * newScale.x / toShow_Instance_Bounds.size.y;
                newScale.z = targetSizeHeight * newScale.z / toShow_Instance_Bounds.size.y;
            }
            else
            {
                //calc a new scale based on targetSizeLenght
                newScale.y = targetSizeLenght * newScale.y / toShow_Instance_Bounds.size.x;
                newScale.x = targetSizeLenght * newScale.x / toShow_Instance_Bounds.size.x;
                newScale.z = targetSizeLenght * newScale.z / toShow_Instance_Bounds.size.x;
            }

            //set new scale
            toShowInstance.transform.localScale = newScale;


            //applies the scale resize to the go
            // toShow_Instance.transform.localScale = toShow_Instance.transform.lossyScale / scaleFactor;

            //apply the offset
            toShowInstance.transform.localPosition    = offset;
            toShowInstance.transform.localEulerAngles = Vector3.zero;
        }
Esempio n. 32
0
        protected override void UpdateOverride()
        {
            base.UpdateOverride();
            if (Editor.Tools.IsViewing)
            {
                SelectedAxis = RuntimeHandleAxis.None;
                return;
            }

            if (!IsWindowActive || !Window.IsPointerOver)
            {
                return;
            }
            IRTE editor = Editor;

            if (IsDragging)
            {
                if (SnapToGround && SelectedAxis != RuntimeHandleAxis.Y)
                {
                    SnapActiveTargetsToGround(ActiveTargets, Window.Camera, true);
                    transform.position = Targets[0].position;
                }
            }

            if (HightlightOnHover && !IsDragging && !IsPointerDown)
            {
                SelectedAxis = Hit();
            }

            if (IsInVertexSnappingMode || Editor.Tools.IsSnapping)
            {
                Vector2 mousePosition;
                if (Window.Pointer.XY(HandlePosition, out mousePosition))
                {
                    if (editor.Tools.SnappingMode == SnappingMode.BoundingBox)
                    {
                        if (IsDragging)
                        {
                            SelectedAxis = RuntimeHandleAxis.Snap;
                            if (m_prevMousePosition != mousePosition)
                            {
                                m_prevMousePosition = mousePosition;
                                float   minDistance   = float.MaxValue;
                                Vector3 minPoint      = Vector3.zero;
                                bool    minPointFound = false;
                                for (int i = 0; i < m_allExposedToEditor.Length; ++i)
                                {
                                    ExposeToEditor exposeToEditor = m_allExposedToEditor[i];
                                    Bounds         bounds         = exposeToEditor.Bounds;
                                    m_boundingBoxCorners[0] = bounds.center + new Vector3(bounds.extents.x, bounds.extents.y, bounds.extents.z);
                                    m_boundingBoxCorners[1] = bounds.center + new Vector3(bounds.extents.x, bounds.extents.y, -bounds.extents.z);
                                    m_boundingBoxCorners[2] = bounds.center + new Vector3(bounds.extents.x, -bounds.extents.y, bounds.extents.z);
                                    m_boundingBoxCorners[3] = bounds.center + new Vector3(bounds.extents.x, -bounds.extents.y, -bounds.extents.z);
                                    m_boundingBoxCorners[4] = bounds.center + new Vector3(-bounds.extents.x, bounds.extents.y, bounds.extents.z);
                                    m_boundingBoxCorners[5] = bounds.center + new Vector3(-bounds.extents.x, bounds.extents.y, -bounds.extents.z);
                                    m_boundingBoxCorners[6] = bounds.center + new Vector3(-bounds.extents.x, -bounds.extents.y, bounds.extents.z);
                                    m_boundingBoxCorners[7] = bounds.center + new Vector3(-bounds.extents.x, -bounds.extents.y, -bounds.extents.z);
                                    GetMinPoint(ref minDistance, ref minPoint, ref minPointFound, exposeToEditor.BoundsObject.transform);
                                }

                                if (minPointFound)
                                {
                                    HandlePosition = minPoint;
                                }
                            }
                        }
                        else
                        {
                            SelectedAxis = RuntimeHandleAxis.None;
                            if (m_prevMousePosition != mousePosition)
                            {
                                m_prevMousePosition = mousePosition;

                                float   minDistance   = float.MaxValue;
                                Vector3 minPoint      = Vector3.zero;
                                bool    minPointFound = false;
                                for (int i = 0; i < m_snapTargets.Length; ++i)
                                {
                                    Transform snapTarget = m_snapTargets[i];
                                    Bounds    bounds     = m_snapTargetsBounds[i];

                                    m_boundingBoxCorners[0] = bounds.center + new Vector3(bounds.extents.x, bounds.extents.y, bounds.extents.z);
                                    m_boundingBoxCorners[1] = bounds.center + new Vector3(bounds.extents.x, bounds.extents.y, -bounds.extents.z);
                                    m_boundingBoxCorners[2] = bounds.center + new Vector3(bounds.extents.x, -bounds.extents.y, bounds.extents.z);
                                    m_boundingBoxCorners[3] = bounds.center + new Vector3(bounds.extents.x, -bounds.extents.y, -bounds.extents.z);
                                    m_boundingBoxCorners[4] = bounds.center + new Vector3(-bounds.extents.x, bounds.extents.y, bounds.extents.z);
                                    m_boundingBoxCorners[5] = bounds.center + new Vector3(-bounds.extents.x, bounds.extents.y, -bounds.extents.z);
                                    m_boundingBoxCorners[6] = bounds.center + new Vector3(-bounds.extents.x, -bounds.extents.y, bounds.extents.z);
                                    m_boundingBoxCorners[7] = bounds.center + new Vector3(-bounds.extents.x, -bounds.extents.y, -bounds.extents.z);
                                    if (Targets[i] != null)
                                    {
                                        GetMinPoint(ref minDistance, ref minPoint, ref minPointFound, snapTarget);
                                    }
                                }

                                if (minPointFound)
                                {
                                    m_handleOffset = minPoint - transform.position;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (IsDragging)
                        {
                            SelectedAxis = RuntimeHandleAxis.Snap;
                            if (m_prevMousePosition != mousePosition)
                            {
                                m_prevMousePosition = mousePosition;

                                Ray        ray = Window.Pointer;
                                RaycastHit hitInfo;

                                LayerMask layerMask = (1 << Physics.IgnoreRaycastLayer);
                                layerMask = ~layerMask;

                                for (int i = 0; i < m_snapTargets.Length; ++i)
                                {
                                    m_targetLayers[i] = m_snapTargets[i].gameObject.layer;
                                    m_snapTargets[i].gameObject.layer = Physics.IgnoreRaycastLayer;
                                }

                                GameObject closestObject = null;
                                if (Physics.Raycast(ray, out hitInfo, float.PositiveInfinity, layerMask))
                                {
                                    closestObject = hitInfo.collider.gameObject;
                                }
                                else
                                {
                                    float minDistance = float.MaxValue;
                                    for (int i = 0; i < m_allExposedToEditor.Length; ++i)
                                    {
                                        ExposeToEditor exposedToEditor = m_allExposedToEditor[i];
                                        Bounds         bounds          = exposedToEditor.Bounds;

                                        m_boundingBoxCorners[0] = bounds.center + new Vector3(bounds.extents.x, bounds.extents.y, bounds.extents.z);
                                        m_boundingBoxCorners[1] = bounds.center + new Vector3(bounds.extents.x, bounds.extents.y, -bounds.extents.z);
                                        m_boundingBoxCorners[2] = bounds.center + new Vector3(bounds.extents.x, -bounds.extents.y, bounds.extents.z);
                                        m_boundingBoxCorners[3] = bounds.center + new Vector3(bounds.extents.x, -bounds.extents.y, -bounds.extents.z);
                                        m_boundingBoxCorners[4] = bounds.center + new Vector3(-bounds.extents.x, bounds.extents.y, bounds.extents.z);
                                        m_boundingBoxCorners[5] = bounds.center + new Vector3(-bounds.extents.x, bounds.extents.y, -bounds.extents.z);
                                        m_boundingBoxCorners[6] = bounds.center + new Vector3(-bounds.extents.x, -bounds.extents.y, bounds.extents.z);
                                        m_boundingBoxCorners[7] = bounds.center + new Vector3(-bounds.extents.x, -bounds.extents.y, -bounds.extents.z);

                                        for (int j = 0; j < m_boundingBoxCorners.Length; ++j)
                                        {
                                            Vector2 screenPoint;
                                            if (Window.Pointer.WorldToScreenPoint(HandlePosition, exposedToEditor.BoundsObject.transform.TransformPoint(m_boundingBoxCorners[j]), out screenPoint))
                                            {
                                                float distance = (screenPoint - mousePosition).magnitude;
                                                if (distance < minDistance)
                                                {
                                                    closestObject = exposedToEditor.gameObject;
                                                    minDistance   = distance;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (closestObject != null)
                                {
                                    float     minDistance   = float.MaxValue;
                                    Vector3   minPoint      = Vector3.zero;
                                    bool      minPointFound = false;
                                    Transform meshTransform;
                                    Mesh      mesh = GetMesh(closestObject, out meshTransform);
                                    GetMinPoint(meshTransform, ref minDistance, ref minPoint, ref minPointFound, mesh);

                                    if (minPointFound)
                                    {
                                        HandlePosition = minPoint;
                                    }
                                }

                                for (int i = 0; i < m_snapTargets.Length; ++i)
                                {
                                    m_snapTargets[i].gameObject.layer = m_targetLayers[i];
                                }
                            }
                        }
                        else
                        {
                            SelectedAxis = RuntimeHandleAxis.None;
                            if (m_prevMousePosition != mousePosition)
                            {
                                m_prevMousePosition = mousePosition;

                                float   minDistance   = float.MaxValue;
                                Vector3 minPoint      = Vector3.zero;
                                bool    minPointFound = false;
                                for (int i = 0; i < RealTargets.Length; ++i)
                                {
                                    Transform snapTarget = RealTargets[i];
                                    Transform meshTranform;
                                    Mesh      mesh = GetMesh(snapTarget.gameObject, out meshTranform);
                                    GetMinPoint(meshTranform, ref minDistance, ref minPoint, ref minPointFound, mesh);
                                }
                                if (minPointFound)
                                {
                                    m_handleOffset = minPoint - transform.position;
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 33
0
 private void OnGUI()
 {
     b = EditorGUILayout.BoundsField("", b);
 }
Esempio n. 34
0
 /// <summary>Returns true if the layout is a simple rectangle, i.e. not rotated</summary>
 protected bool IsOrthogonal()
 {
     return(Vertices[0].ApproxEqual(Bounds.Location) && Vertices[1].ApproxEqual(Bounds.TopRight()));
     // Not sure if it's actually necessary to check more than one point
 }
Esempio n. 35
0
 public BoxConstraint(Point point, Bounds bounds) :
     base()
 {
     this.bounds = bounds;
     this.point  = point;
 }
Esempio n. 36
0
 void Start()
 {
     shipBounds     = ContentBounds.Box(this.gameObject).Value;
     gameController = GameObject.FindWithTag("GameController")
                      .GetComponent <GameControllerScript>();
 }
Esempio n. 37
0
        public void Apply()
        {
            if (AstarPath.active == null)
            {
                Debug.LogError("There is no AstarPath object in the scene");
                return;
            }
            GraphUpdateObject graphUpdateObject;

            if (this.points == null || this.points.Length == 0)
            {
                Collider component  = base.GetComponent <Collider>();
                Renderer component2 = base.GetComponent <Renderer>();
                Bounds   bounds;
                if (component != null)
                {
                    bounds = component.bounds;
                }
                else
                {
                    if (!(component2 != null))
                    {
                        Debug.LogWarning("Cannot apply GraphUpdateScene, no points defined and no renderer or collider attached");
                        return;
                    }
                    bounds = component2.bounds;
                }
                if (bounds.size.y < this.minBoundsHeight)
                {
                    bounds.size = new Vector3(bounds.size.x, this.minBoundsHeight, bounds.size.z);
                }
                graphUpdateObject = new GraphUpdateObject(bounds);
            }
            else
            {
                GraphUpdateShape graphUpdateShape = new GraphUpdateShape();
                graphUpdateShape.convex = this.convex;
                Vector3[] array = this.points;
                if (!this.useWorldSpace)
                {
                    array = new Vector3[this.points.Length];
                    Matrix4x4 localToWorldMatrix = base.transform.localToWorldMatrix;
                    for (int i = 0; i < array.Length; i++)
                    {
                        array[i] = localToWorldMatrix.MultiplyPoint3x4(this.points[i]);
                    }
                }
                graphUpdateShape.points = array;
                Bounds bounds2 = graphUpdateShape.GetBounds();
                if (bounds2.size.y < this.minBoundsHeight)
                {
                    bounds2.size = new Vector3(bounds2.size.x, this.minBoundsHeight, bounds2.size.z);
                }
                graphUpdateObject       = new GraphUpdateObject(bounds2);
                graphUpdateObject.shape = graphUpdateShape;
            }
            this.firstApplied = true;
            graphUpdateObject.modifyWalkability     = this.modifyWalkability;
            graphUpdateObject.setWalkability        = this.setWalkability;
            graphUpdateObject.addPenalty            = this.penaltyDelta;
            graphUpdateObject.updatePhysics         = this.updatePhysics;
            graphUpdateObject.updateErosion         = this.updateErosion;
            graphUpdateObject.resetPenaltyOnPhysics = this.resetPenaltyOnPhysics;
            graphUpdateObject.modifyTag             = this.modifyTag;
            graphUpdateObject.setTag = this.setTag;
            AstarPath.active.UpdateGraphs(graphUpdateObject);
        }
Esempio n. 38
0
        private void BeginSnap()
        {
            if (Window.Camera == null)
            {
                return;
            }

            if (Model != null && Model is PositionHandleModel)
            {
                ((PositionHandleModel)Model).IsVertexSnapping = true;
            }

            HashSet <Transform> snapTargetsHS    = new HashSet <Transform>();
            List <Transform>    snapTargets      = new List <Transform>();
            List <Bounds>       snapTargetBounds = new List <Bounds>();

            if (Target != null)
            {
                for (int i = 0; i < RealTargets.Length; ++i)
                {
                    Transform target = RealTargets[i];
                    if (target != null)
                    {
                        snapTargets.Add(target);
                        snapTargetsHS.Add(target);

                        ExposeToEditor exposeToEditor = target.GetComponent <ExposeToEditor>();
                        if (exposeToEditor != null)
                        {
                            snapTargetBounds.Add(exposeToEditor.Bounds);
                        }
                        else
                        {
                            MeshFilter filter = target.GetComponent <MeshFilter>();
                            if (filter != null && filter.sharedMesh != null)
                            {
                                snapTargetBounds.Add(filter.sharedMesh.bounds);
                            }
                            else
                            {
                                SkinnedMeshRenderer smr = target.GetComponent <SkinnedMeshRenderer>();
                                if (smr != null && smr.sharedMesh != null)
                                {
                                    snapTargetBounds.Add(smr.sharedMesh.bounds);
                                }
                                else
                                {
                                    Bounds b = new Bounds(Vector3.zero, Vector3.zero);
                                    snapTargetBounds.Add(b);
                                }
                            }
                        }
                    }
                }
            }


            m_snapTargets       = snapTargets.ToArray();
            m_targetLayers      = new int[m_snapTargets.Length];
            m_snapTargetsBounds = snapTargetBounds.ToArray();


            Plane[]               frustumPlanes         = GeometryUtility.CalculateFrustumPlanes(Window.Camera);
            ExposeToEditor[]      exposeToEditorObjects = FindObjectsOfType <ExposeToEditor>();
            List <ExposeToEditor> insideOfFrustum       = new List <ExposeToEditor>();

            for (int i = 0; i < exposeToEditorObjects.Length; ++i)
            {
                ExposeToEditor exposeToEditor = exposeToEditorObjects[i];
                if (exposeToEditor.CanSnap)
                {
                    if (GeometryUtility.TestPlanesAABB(frustumPlanes, new Bounds(exposeToEditor.transform.TransformPoint(exposeToEditor.Bounds.center), Vector3.zero)))
                    {
                        if (!snapTargetsHS.Contains(exposeToEditor.transform))
                        {
                            insideOfFrustum.Add(exposeToEditor);
                        }
                    }
                }
            }
            m_allExposedToEditor = insideOfFrustum.ToArray();
        }
Esempio n. 39
0
    // Tests to see whether lilB is inside bigB
    public static Vector3 BoundsInBoundsCheck(Bounds bigB, Bounds lilB, BoundsTest test = BoundsTest.onScreen)
    {
        // Get the center of lilB
        Vector3 pos = lilB.center;

        // Initialize the offset at [0,0,0]
        Vector3 off = Vector3.zero;

        switch (test)
        {
// The center test determines what off (offset) would have to be applied to lilB to move its center back inside bigB
        case BoundsTest.center:
            // if the center is contained, return Vector3.zero
            if (bigB.Contains(pos))
            {
                return(Vector3.zero);
            }
            // if not contained, find the offset
            if (pos.x > bigB.max.x)
            {
                off.x = pos.x - bigB.max.x;
            }
            else if (pos.x < bigB.min.x)
            {
                off.x = pos.x - bigB.min.x;
            }
            if (pos.y > bigB.max.y)
            {
                off.y = pos.y - bigB.max.y;
            }
            else if (pos.y < bigB.min.y)
            {
                off.y = pos.y - bigB.min.y;
            }
            if (pos.z > bigB.max.z)
            {
                off.z = pos.z - bigB.max.z;
            }
            else if (pos.z < bigB.min.z)
            {
                off.z = pos.z - bigB.min.z;
            }
            return(off);

// The onScreen test determines what off would have to be applied to keep all of lilB inside bigB
        case BoundsTest.onScreen:
            // find whether bigB contains all of lilB
            if (bigB.Contains(lilB.min) && bigB.Contains(lilB.max))
            {
                return(Vector3.zero);
            }
            // if not, find the offset
            if (lilB.max.x > bigB.max.x)
            {
                off.x = lilB.max.x - bigB.max.x;
            }
            else if (lilB.min.x < bigB.min.x)
            {
                off.x = lilB.min.x - bigB.min.x;
            }
            if (lilB.max.y > bigB.max.y)
            {
                off.y = lilB.max.y - bigB.max.y;
            }
            else if (lilB.min.y < bigB.min.y)
            {
                off.y = lilB.min.y - bigB.min.y;
            }
            if (lilB.max.z > bigB.max.z)
            {
                off.z = lilB.max.z - bigB.max.z;
            }
            else if (lilB.min.z < bigB.min.z)
            {
                off.z = lilB.min.z - bigB.min.z;
            }
            return(off);

// The offScreen test determines what off would need to be applied to move any tiny part of lilB inside of bigB
        case BoundsTest.offScreen:
            // find whether bigB contains any of lilB
            bool cMin = bigB.Contains(lilB.min);
            bool cMax = bigB.Contains(lilB.max);
            if (cMin || cMax)
            {
                return(Vector3.zero);
            }
            // if not, find the offset
            if (lilB.min.x > bigB.max.x)
            {
                off.x = lilB.min.x - bigB.max.x;
            }
            else if (lilB.max.x < bigB.min.x)
            {
                off.x = lilB.max.x - bigB.min.x;
            }
            if (lilB.min.y > bigB.max.y)
            {
                off.y = lilB.min.y - bigB.max.y;
            }
            else if (lilB.max.y < bigB.min.y)
            {
                off.y = lilB.max.y - bigB.min.y;
            }
            if (lilB.min.z > bigB.max.z)
            {
                off.z = lilB.min.z - bigB.max.z;
            }
            else if (lilB.max.z < bigB.min.z)
            {
                off.z = lilB.max.z - bigB.min.z;
            }
            return(off);
        }

        return(Vector3.zero);
    }
Esempio n. 40
0
 public IEnumerator Scale(Transform thisTransform, float byThatMuch, float value, ScaleObject.ScaleType moveType)
 {
     _bounds = GameObjectBounds(thisTransform.gameObject);
     yield return(Scale(thisTransform, thisTransform.localScale, thisTransform.localScale * byThatMuch, value, moveType));
 }
Esempio n. 41
0
 protected virtual void Awake()
 {
     selectionBounds = ResourceManager.InvalidBounds;
     CalculateBounds();
 }
Esempio n. 42
0
 // Test to see whether Bounds are on screen.
 public static Vector3 ScreenBoundsCheck(Bounds bnd, BoundsTest test = BoundsTest.center)
 {
     // Call the more generic BoundsInBoundsCheck with camBounds as bigB
     return(BoundsInBoundsCheck(camBounds, bnd, test));
 }
Esempio n. 43
0
	/// <summary>
	/// Constrain the specified target to be within the panel's bounds.
	/// </summary>

	public bool ConstrainTargetToBounds (Transform target, bool immediate)
	{
		Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(cachedTransform, target);
		return ConstrainTargetToBounds(target, ref bounds, immediate);
	}
Esempio n. 44
0
 public abstract void SetBounds(Bounds newBounds);
Esempio n. 45
0
 public override void OnUpdate(ref ChiselBoxDefinition definition, Bounds bounds)
 {
     definition.settings.bounds = new ChiselAABB {
         Min = bounds.min, Max = bounds.max
     };
 }
Esempio n. 46
0
 public override void OnPaint(IChiselHandleRenderer renderer, Bounds bounds)
 {
     renderer.RenderBox(bounds);
     renderer.RenderBoxMeasurements(bounds);
 }
        private Bounds TransformBounds(Bounds oldBounds, Matrix4x4 matrix)
        {
            Bounds  bounds = new Bounds();
            Vector3 center, extents;

            center  = oldBounds.center;  //matrix.MultiplyPoint3x4(m.bounds.center);
            extents = oldBounds.extents; //matrix.MultiplyVector(m.bounds.size);

            /*size.x = Math.Abs(size.x);
            *  size.y = Math.Abs(size.y);
            *  size.z = Math.Abs(size.z);*/

            Vector3 boundPt;

            boundPt = center + extents;
            boundPt = matrix.MultiplyPoint3x4(boundPt);
            bounds.Encapsulate(boundPt);

            boundPt = center - extents;
            boundPt = matrix.MultiplyPoint3x4(boundPt);
            bounds.Encapsulate(boundPt);

            boundPt    = center;
            boundPt.x += extents.x;
            boundPt.y += extents.y;
            boundPt.z -= extents.z;
            boundPt    = matrix.MultiplyPoint3x4(boundPt);
            bounds.Encapsulate(boundPt);

            boundPt    = center;
            boundPt.x += extents.x;
            boundPt.y -= extents.y;
            boundPt.z += extents.z;
            boundPt    = matrix.MultiplyPoint3x4(boundPt);
            bounds.Encapsulate(boundPt);

            boundPt    = center;
            boundPt.x -= extents.x;
            boundPt.y += extents.y;
            boundPt.z += extents.z;
            boundPt    = matrix.MultiplyPoint3x4(boundPt);
            bounds.Encapsulate(boundPt);

            boundPt    = center;
            boundPt.x -= extents.x;
            boundPt.y -= extents.y;
            boundPt.z += extents.z;
            boundPt    = matrix.MultiplyPoint3x4(boundPt);
            bounds.Encapsulate(boundPt);

            boundPt    = center;
            boundPt.x -= extents.x;
            boundPt.y += extents.y;
            boundPt.z -= extents.z;
            boundPt    = matrix.MultiplyPoint3x4(boundPt);
            bounds.Encapsulate(boundPt);

            boundPt    = center;
            boundPt.x += extents.x;
            boundPt.y -= extents.y;
            boundPt.z -= extents.z;
            boundPt    = matrix.MultiplyPoint3x4(boundPt);

            bounds.Encapsulate(boundPt);

            return(bounds);
        }
Esempio n. 48
0
 private static Vector3 Transform(Vector3 vert, Bounds bounds)
 {
     return(bounds.center + Vector3.Scale(vert, bounds.size));
 }
 public void Voxelize(Bounds bounds)
 {
     Voxelize(mesh, bounds);
 }
    /// <summary>
    /// Display the drop-down list when the game object gets clicked on.
    /// </summary>

    void OnClick()
    {
        if (enabled && NGUITools.GetActive(gameObject) && mChild == null && atlas != null && font != null && items.Count > 0)
        {
            mLabelList.Clear();

            // Disable the navigation script
            handleEvents = true;

            // Automatically locate the panel responsible for this object
            if (mPanel == null)
            {
                mPanel = UIPanel.Find(transform, true);
            }

            // Calculate the dimensions of the object triggering the popup list so we can position it below it
            Transform myTrans = transform;
            Bounds    bounds  = NGUIMath.CalculateRelativeWidgetBounds(myTrans.parent, myTrans);

            // Create the root object for the list
            mChild       = new GameObject("Drop-down List");
            mChild.layer = gameObject.layer;
            UIPanel droplistPanel = mChild.AddComponent <UIPanel>();
            if (droplistPanel != null)
            {
                droplistPanel.depth = 700;
            }

            Transform t = mChild.transform;
            t.parent        = myTrans.parent;
            t.localPosition = bounds.min;
            t.localRotation = Quaternion.identity;
            t.localScale    = Vector3.one;

            // Add a sprite for the background
            mBackground       = NGUITools.AddSprite(mChild, atlas, backgroundSprite);
            mBackground.pivot = UIWidget.Pivot.TopLeft;
            mBackground.depth = NGUITools.CalculateNextDepth(mPanel.gameObject);
            mBackground.color = backgroundColor;

            // We need to know the size of the background sprite for padding purposes
            Vector4 bgPadding = mBackground.border;
            mBgBorder = bgPadding.y;

            mBackground.cachedTransform.localPosition = new Vector3(0f, bgPadding.y, 0f);

            // Add a sprite used for the selection
            mHighlight       = NGUITools.AddSprite(mChild, atlas, highlightSprite);
            mHighlight.pivot = UIWidget.Pivot.TopLeft;
            mHighlight.color = highlightColor;

            UISpriteData hlsp = mHighlight.GetAtlasSprite();
            if (hlsp == null)
            {
                return;
            }

            float          hlspHeight = hlsp.borderTop;
            float          labelHeight = font.size * font.pixelSize * textScale;
            float          x = 0f, y = -padding.y;
            List <UILabel> labels = new List <UILabel>();

            // 加个补丁,如果国际化过程导致无法选中默认值,则设置一个默认值。
            UILabel labelFirst  = null;
            bool    bFocusLabel = false;
            // Run through all items and create labels for each one
            for (int i = 0, imax = items.Count; i < imax; ++i)
            {
                string s        = items[i];
                string curDicID = "0";
                if (useDicTable)
                {
                    int id = 0;
                    if (int.TryParse(s, out id))
                    {
                        string val = Utils.GetDicByID(id);
                        s        = val;
                        curDicID = id.ToString();
                    }
                }

                UILabel lbl = NGUITools.AddWidget <UILabel>(mChild);
                lbl.pivot = UIWidget.Pivot.TopLeft;
                lbl.font  = font;
                lbl.text  = (isLocalized && Localization.instance != null) ? Localization.instance.Get(s) : s;
                lbl.color = textColor;
                lbl.cachedTransform.localPosition = new Vector3(bgPadding.x + padding.x, y, -1f);
                lbl.overflowMethod = UILabel.Overflow.ResizeFreely;

                Transform lblTrans = lbl.gameObject.transform;
                lblTrans.localPosition = new Vector3(lblTrans.localPosition.x, lblTrans.localPosition.y, 0);

                lbl.MakePixelPerfect();
                if (textScale != 1f)
                {
                    lbl.cachedTransform.localScale = Vector3.one * textScale;
                }
                labels.Add(lbl);

                y -= labelHeight;
                y -= padding.y;
                x  = Mathf.Max(x, labelHeight);

                // Add an event listener
                UIEventListener listener = UIEventListener.Get(lbl.gameObject);
                listener.onHover   = OnItemHover;
                listener.onPress   = OnItemPress;
                listener.parameter = s;

                // Move the selection here if this is the right label
                if (mSelectedItem == s || mSelectedItem == curDicID)
                {
                    Highlight(lbl, true);
                    bFocusLabel = true;
                }

                if (null == labelFirst)
                {
                    labelFirst = lbl;
                }
                // Add this label to the list
                mLabelList.Add(lbl);
            }

            if (!bFocusLabel && null != labelFirst)
            {
                Highlight(labelFirst, true);
            }

            // The triggering widget's width should be the minimum allowed width
            x = Mathf.Max(x, bounds.size.x - (bgPadding.x + padding.x) * 2f);

            Vector3 bcCenter = new Vector3(x * 0.5f, -labelHeight * 0.5f, 0f);
            Vector3 bcSize   = new Vector3(x, (labelHeight + padding.y), 1f);

            // Run through all labels and add colliders
            for (int i = 0, imax = labels.Count; i < imax; ++i)
            {
                UILabel     lbl = labels[i];
                BoxCollider bc  = NGUITools.AddWidgetCollider(lbl.gameObject);
                bcCenter.z = bc.center.z;
                bc.center  = bcCenter;
                bc.size    = bcSize;
            }

            x += (bgPadding.x + padding.x) * 2f;
            y -= bgPadding.y;

            // Scale the background sprite to envelop the entire set of items
            mBackground.width  = Mathf.RoundToInt(x);
            mBackground.height = Mathf.RoundToInt(-y + bgPadding.y);

            // Scale the highlight sprite to envelop a single item
            float scaleFactor = 2f * atlas.pixelSize;
            float w           = x - (bgPadding.x + padding.x) * 2f + hlsp.borderLeft * scaleFactor;
            float h           = labelHeight + hlspHeight * scaleFactor;
            mHighlight.width  = Mathf.RoundToInt(w);
            mHighlight.height = Mathf.RoundToInt(h);

            bool placeAbove = (position == Position.Above);

            if (position == Position.Auto)
            {
                UICamera cam = UICamera.FindCameraForLayer(gameObject.layer);

                if (cam != null)
                {
                    Vector3 viewPos = cam.cachedCamera.WorldToViewportPoint(myTrans.position);
                    placeAbove = (viewPos.y < 0.5f);
                }
            }

            // If the list should be animated, let's animate it by expanding it
            if (isAnimated)
            {
                float bottom = y + labelHeight;
                Animate(mHighlight, placeAbove, bottom);
                for (int i = 0, imax = labels.Count; i < imax; ++i)
                {
                    Animate(labels[i], placeAbove, bottom);
                }
                AnimateColor(mBackground);
                AnimateScale(mBackground, placeAbove, bottom);
            }

            // If we need to place the popup list above the item, we need to reposition everything by the size of the list
            if (placeAbove)
            {
                t.localPosition = new Vector3(bounds.min.x, bounds.max.y - y - bgPadding.y, bounds.min.z);
            }
        }
        else
        {
            OnSelect(false);
        }
    }
Esempio n. 51
0
 public BoundsKun(Bounds bounds)
 {
     this.m_center = new Vector3Kun(bounds.center);
     this.m_size   = new Vector3Kun(bounds.size);
 }
Esempio n. 52
0
 /// <summary>Returns a unique hash representing this resolution.</summary>
 /// <returns>A System.Int32 that may serve as a hash code for this resolution.</returns>
 public override int GetHashCode()
 {
     return(Bounds.GetHashCode() ^ bits_per_pixel ^ refresh_rate.GetHashCode());
 }
Esempio n. 53
0
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray        mouseToWorldRay = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;

            //Shoots a ray into the 3D world starting at our mouseposition
            if (Physics.Raycast(mouseToWorldRay, out hitInfo))
            {
                //We check if we clicked on an object with a Selectable component
                Selectable s = hitInfo.collider.GetComponent <Selectable>();
                if (s != null)
                {
                    //While holding the copyKey, we can add and remove objects from our selection
                    if (Input.GetKey(copyKey))
                    {
                        //Toggle the selection
                        UpdateSelection(s, !s.isSelected);
                    }
                    else
                    {
                        //If the copyKey was not held, we clear our current selection and select only this unit
                        ClearSelected();
                        UpdateSelection(s, true);
                    }

                    //If we clicked on a Selectable, we don't want to enable our SelectionBox
                    return;
                }
            }

            if (selectionBox == null)
            {
                return;
            }
            //Storing these variables for the selectionBox
            startScreenPos = Input.mousePosition;
            isSelecting    = true;
        }

        //If we never set the selectionBox variable in the inspector, we are simply not able to drag the selectionBox to easily select multiple objects. 'Regular' selection should still work
        if (selectionBox == null)
        {
            return;
        }

        //We finished our selection box when the key is released
        if (Input.GetMouseButtonUp(0))
        {
            isSelecting = false;
        }

        selectionBox.gameObject.SetActive(isSelecting);

        if (isSelecting)
        {
            Bounds b = new Bounds();
            //The center of the bounds is inbetween startpos and current pos
            b.center = Vector3.Lerp(startScreenPos, Input.mousePosition, 0.5f);
            //We make the size absolute (negative bounds don't contain anything)
            b.size = new Vector3(Mathf.Abs(startScreenPos.x - Input.mousePosition.x),
                                 Mathf.Abs(startScreenPos.y - Input.mousePosition.y),
                                 0);

            //To display our selectionbox image in the same place as our bounds
            rt.position  = b.center;
            rt.sizeDelta = canvas.transform.InverseTransformVector(b.size);

            //Looping through all the selectables in our world (automatically added/removed through the Selectable OnEnable/OnDisable)
            foreach (Selectable selectable in selectables)
            {
                //If the screenPosition of the worldobject is within our selection bounds, we can add it to our selection
                Vector3 screenPos = Camera.main.WorldToScreenPoint(selectable.transform.position);
                screenPos.z = 0;
                UpdateSelection(selectable, (b.Contains(screenPos)));
            }
        }
    }
        public static Mesh GetCorrectedMeshPloppableAsph(Mesh originalMesh, Mesh correctedInstance, out Bounds realBounds)
        {
            if (correctedInstance == null)
            {
                correctedInstance = originalMesh.InstantiateMesh();
            }
            Bounds  b = new Bounds();
            Vector3 noZFightingSurplus = new Vector3(0, 0.01f, 0);
            var     vertices           = new List <Vector3>();

            for (int i = 0; i < correctedInstance.vertices.Length; i++)
            {
                var vertex = originalMesh.vertices[i].PloppableAsphaltPosition() + noZFightingSurplus;
                vertices.Add(vertex);
                if (i == 0)
                {
                    b = new Bounds(vertex, Vector3.zero);
                }
                b.Encapsulate(vertex);
            }
            correctedInstance.SetVertices(vertices);
            realBounds = b;
            return(correctedInstance);
        }
Esempio n. 55
0
        public static Vector3 GetAlignedPosition(this Bounds bounds,
                                                 BoundsAlign xAlign,
                                                 BoundsAlign yAlign,
                                                 BoundsAlign zAlign)
        {
            Vector3 vector3;

            switch (xAlign)
            {
            case BoundsAlign.Min:
                vector3.x = bounds.min.x;
                break;

            case BoundsAlign.Center:
                vector3.x = bounds.center.x;
                break;

            case BoundsAlign.Max:
                vector3.x = bounds.max.x;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(xAlign), xAlign, null);
            }

            switch (yAlign)
            {
            case BoundsAlign.Min:
                vector3.y = bounds.min.y;
                break;

            case BoundsAlign.Center:
                vector3.y = bounds.center.y;
                break;

            case BoundsAlign.Max:
                vector3.y = bounds.max.y;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(yAlign), yAlign, null);
            }

            switch (zAlign)
            {
            case BoundsAlign.Min:
                vector3.z = bounds.min.z;
                break;

            case BoundsAlign.Center:
                vector3.z = bounds.center.z;
                break;

            case BoundsAlign.Max:
                vector3.z = bounds.max.z;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(zAlign), zAlign, null);
            }

            return(vector3);
        }
Esempio n. 56
0
        bool AvoideVessel(VesselWrapper vsl, Vector3d dir, float dist, Vector3d dV,
                          float r2, Bounds exhaust2, Transform refT2,
                          out Vector3d maneuver, float threshold = -1)
        {
            maneuver = Vector3d.zero;
            //filter vessels on non-collision courses
            var dVn            = dV.normalized;
            var cosA           = Mathf.Clamp(Vector3.Dot(dir, dVn), -1, 1);
            var collision_dist = threshold.Equals(0)?
                                 2 * dist - vsl.Geometry.DistToBounds(vsl.Physics.wCoM + dir * dist) -
                                 Mathf.Sqrt(exhaust2.SqrDistance(refT2.InverseTransformPoint(vsl.Physics.wCoM))) :
                                 Mathf.Max(vsl.Geometry.R, dist - vsl.Geometry.DistToBounds(vsl.Physics.wCoM + dir * dist)) +
                                 Mathf.Max(r2, dist - Mathf.Sqrt(exhaust2.SqrDistance(refT2.InverseTransformPoint(vsl.Physics.wCoM))));

//            vsl.Log("R {}, R2 {}; r {}, r2 {}", vsl.Geometry.R, r2,
//                    dist-vsl.DistToBounds(vsl.wCoM+dir*dist),
//                    dist-Mathf.Sqrt(exhaust2.SqrDistance(refT2.InverseTransformPoint(vsl.wCoM))));//debug
//            Utils.Log("{}: cosA: {}, threshold {}", vsl.vessel.vesselName, cosA, threshold);//debug
            if (cosA <= 0)
            {
                goto check_distance;
            }
            if (threshold < 0)
            {
                threshold = C.MinDistance;
            }
            var sinA           = Mathf.Sqrt(1 - cosA * cosA);
            var min_separation = dist * sinA;
            var sep_threshold  = collision_dist + threshold;

//            Utils.Log("{}: min_sep > sep_thresh: {} > {}, threshold {}",
//                      vsl.vessel.vesselName, min_separation, sep_threshold, threshold);//debug
            if (min_separation > sep_threshold)
            {
                goto check_distance;
            }
            //calculate time to collision
            var vDist = 0f;
            var alpha = Mathf.Acos(cosA);
            var dVm   = dV.magnitude;

            if (sinA <= 0)
            {
                vDist = dist - sep_threshold;
            }
            else if (dist > sep_threshold)
            {
                vDist = sep_threshold * Mathf.Sin(Mathf.Asin(min_separation / sep_threshold) - alpha) / sinA;
            }
            var vTime = Utils.ClampL(vDist, 0.1f) / dVm;

//                Utils.Log("{}: vTime > SafeTime: {} > {}",
//                          vsl.vessel.vesselName, vTime, CPS.SafeTime/Utils.Clamp(Mathf.Abs(Vector3.Dot(vsl.wMaxAngularA, dVn)), 0.01f, 1f));//debug
            if (vTime > SafeTime(vsl, dVn))
            {
                goto check_distance;
            }
            //calculate maneuver
            Vector3d side;

            if (cosA < 0.9)
            {
                side = (dVn * cosA - dir).normalized;
            }
            else if (Math.Abs(Vector3d.Dot(dVn, vsl.Physics.Up)) < 0.9)
            {
                side = Vector3d.Cross(dVn, vsl.Physics.Up).normalized;
            }
            else
            {
                side = Vector3d.Cross(dVn, vsl.OnPlanetParams.Fwd).normalized;
            }
//            if(dist > sep_threshold)
//            {
//                var beta = Mathf.Asin(sep_threshold/dist)-alpha;
//                maneuver = (Mathf.Sin(beta)*side + dVn*(Mathf.Cos(beta)-1)).normalized;
//            }
//            else
            maneuver  = side;
            maneuver += vsl.Physics.Up * Mathf.Sign(Vector3.Dot(dir, vsl.Physics.Up)) * (min_separation / sep_threshold - 1);
            maneuver *= (sep_threshold - min_separation) / Math.Sqrt(vTime);
//            maneuver = (-vsl.Up*Mathf.Sign(Vector3.Dot(dir, vsl.Up))*(1-min_separation/sep_threshold) +
//                        (dVn*cosA-dir).normalized).normalized * (sep_threshold-min_separation) / vTime;
//            vsl.Log("\ndist {}\ndV {}\nmaneuver: {}\n" +
//                    "vTime {}, vDist {}, min sep {}, sep_thresh {}",
//                    dir*dist, dV, maneuver, vTime, vDist, min_separation, sep_threshold);//debug
            #if DEBUG
            Collided |= dist < collision_dist;
            #endif
            //if distance is not safe, correct course anyway
check_distance:
            var collision = !maneuver.IsZero();
            dist         -= collision_dist;
            if (dist < threshold)
            {
                var dist_to_safe = Utils.ClampH(dist - threshold, -0.01f);
                var dc           = dir * dist_to_safe;
                if (vsl.HorizontalSpeed.NeededVector.sqrMagnitude > C.LatAvoidMinVelSqr)
                {
                    var lat_avoid = Vector3d.Cross(vsl.Physics.Up, vsl.HorizontalSpeed.NeededVector.normalized);
                    dc = Vector3d.Dot(dc, lat_avoid) >= 0?
                         lat_avoid * dist_to_safe :
                         lat_avoid * -dist_to_safe;
                }
                if (dc.sqrMagnitude > 0.25)
                {
                    maneuver += dc / C.SafeTime * 2;
                }
//                vsl.Log("adding safe distance correction: {}", dc/CPS.SafeTime*2);//debug
            }
//            #if DEBUG
//            Dir = dir*dist;
//            DeltaV = dV;
//            Maneuver = maneuver;
//            #endif
            return(collision);
        }
        private IEnumerator AnalyzeGeometry(GameObject avatarObject, IEnumerable <Renderer> renderers, AvatarPerformanceStats perfStats)
        {
            List <Renderer> lodGroupRendererIgnoreBuffer = new List <Renderer>(16);
            List <LODGroup> lodBuffer = new List <LODGroup>(16);

            ulong  polyCount = 0;
            Bounds bounds    = new Bounds(avatarObject.transform.position, Vector3.zero);

            yield return(ScanAvatarForComponentsOfType(avatarObject, lodBuffer));

            try
            {
                foreach (LODGroup lodGroup in lodBuffer)
                {
                    LOD[] lodLevels = lodGroup.GetLODs();

                    ulong highestLodPolyCount = 0;
                    foreach (LOD lod in lodLevels)
                    {
                        uint thisLodPolyCount = 0;
                        foreach (Renderer renderer in lod.renderers)
                        {
                            lodGroupRendererIgnoreBuffer.Add(renderer);
                            checked
                            {
                                thisLodPolyCount += CalculateRendererPolyCount(renderer);
                            }
                        }

                        if (thisLodPolyCount > highestLodPolyCount)
                        {
                            highestLodPolyCount = thisLodPolyCount;
                        }
                    }

                    checked
                    {
                        polyCount += highestLodPolyCount;
                    }
                }
            }
            catch (OverflowException e)
            {
                VRC.Core.Logger.Log("Overflow exception while analyzing geometry, assuming max value:" + e.ToString(), VRC.Core.DebugLevel.All);
                polyCount = uint.MaxValue;
            }

            Profiler.BeginSample("Calculate Total Polygon Count and Bounds");
            foreach (Renderer renderer in renderers)
            {
                Profiler.BeginSample("Single Renderer");
                if (renderer is MeshRenderer || renderer is SkinnedMeshRenderer)
                {
                    if (!RendererHasMesh(renderer))
                    {
                        Profiler.EndSample();
                        continue;
                    }

                    bounds.Encapsulate(renderer.bounds);
                }

                if (lodGroupRendererIgnoreBuffer.Contains(renderer))
                {
                    Profiler.EndSample();
                    continue;
                }

                polyCount += CalculateRendererPolyCount(renderer);
                Profiler.EndSample();
            }

            Profiler.EndSample();

            bounds.center -= avatarObject.transform.position;

            lodGroupRendererIgnoreBuffer.Clear();
            lodBuffer.Clear();

            perfStats.polyCount = polyCount > int.MaxValue ? int.MaxValue : (int)polyCount;
            perfStats.aabb      = bounds;
        }
Esempio n. 58
0
 public virtual void Show()
 {
     if (base.enabled && NGUITools.GetActive(base.gameObject) && UIPopupList.mChild == null && this.atlas != null && this.isValid && this.items.Count > 0)
     {
         this.mLabelList.Clear();
         base.StopCoroutine("CloseIfUnselected");
         UICamera.selectedObject = (UICamera.hoveredObject ?? base.gameObject);
         this.mSelection         = UICamera.selectedObject;
         this.source             = UICamera.selectedObject;
         if (this.source == null)
         {
             Debug.LogError("Popup list needs a source object...");
             return;
         }
         this.mOpenFrame = Time.frameCount;
         if (this.mPanel == null)
         {
             this.mPanel = UIPanel.Find(base.transform);
             if (this.mPanel == null)
             {
                 return;
             }
         }
         UIPopupList.mChild       = new GameObject("Drop-down List");
         UIPopupList.mChild.layer = base.gameObject.layer;
         UIPopupList.current      = this;
         Transform transform = UIPopupList.mChild.transform;
         transform.parent = this.mPanel.cachedTransform;
         Vector3 localPosition;
         Vector3 vector;
         Vector3 v;
         if (this.openOn == UIPopupList.OpenOn.Manual && this.mSelection != base.gameObject)
         {
             localPosition           = UICamera.lastEventPosition;
             vector                  = this.mPanel.cachedTransform.InverseTransformPoint(this.mPanel.anchorCamera.ScreenToWorldPoint(localPosition));
             v                       = vector;
             transform.localPosition = vector;
             localPosition           = transform.position;
         }
         else
         {
             Bounds bounds = NGUIMath.CalculateRelativeWidgetBounds(this.mPanel.cachedTransform, base.transform, false, false);
             vector = bounds.min;
             v      = bounds.max;
             transform.localPosition = vector;
             localPosition           = transform.position;
         }
         base.StartCoroutine("CloseIfUnselected");
         transform.localRotation = Quaternion.identity;
         transform.localScale    = Vector3.one;
         this.mBackground        = NGUITools.AddSprite(UIPopupList.mChild, this.atlas, this.backgroundSprite);
         this.mBackground.pivot  = UIWidget.Pivot.TopLeft;
         this.mBackground.depth  = NGUITools.CalculateNextDepth(this.mPanel.gameObject);
         this.mBackground.color  = this.backgroundColor;
         Vector4 border = this.mBackground.border;
         this.mBgBorder = border.y;
         this.mBackground.cachedTransform.localPosition = new Vector3(0f, border.y, 0f);
         this.mHighlight       = NGUITools.AddSprite(UIPopupList.mChild, this.atlas, this.highlightSprite);
         this.mHighlight.pivot = UIWidget.Pivot.TopLeft;
         this.mHighlight.color = this.highlightColor;
         UISpriteData atlasSprite = this.mHighlight.GetAtlasSprite();
         if (atlasSprite == null)
         {
             return;
         }
         float          num             = (float)atlasSprite.borderTop;
         float          num2            = (float)this.activeFontSize;
         float          activeFontScale = this.activeFontScale;
         float          num3            = num2 * activeFontScale;
         float          num4            = 0f;
         float          num5            = -this.padding.y;
         List <UILabel> list            = new List <UILabel>();
         if (!this.items.Contains(this.mSelectedItem))
         {
             this.mSelectedItem = null;
         }
         int i     = 0;
         int count = this.items.Count;
         while (i < count)
         {
             string  text    = this.items[i];
             UILabel uilabel = NGUITools.AddWidget <UILabel>(UIPopupList.mChild);
             uilabel.name         = i.ToString();
             uilabel.pivot        = UIWidget.Pivot.TopLeft;
             uilabel.bitmapFont   = this.bitmapFont;
             uilabel.trueTypeFont = this.trueTypeFont;
             uilabel.fontSize     = this.fontSize;
             uilabel.fontStyle    = this.fontStyle;
             string text2 = (!this.isLocalized) ? text : Localization.Get(text);
             if (this.toUpper)
             {
                 text2 = text2.ToUpper();
             }
             uilabel.text  = text2;
             uilabel.color = this.textColor;
             uilabel.cachedTransform.localPosition = new Vector3(border.x + this.padding.x - uilabel.pivotOffset.x, num5, -1f);
             uilabel.overflowMethod = UILabel.Overflow.ResizeFreely;
             uilabel.alignment      = this.alignment;
             list.Add(uilabel);
             num5 -= num3;
             num5 -= this.padding.y;
             num4  = Mathf.Max(num4, uilabel.printedSize.x);
             UIEventListener uieventListener = UIEventListener.Get(uilabel.gameObject);
             uieventListener.onHover   = new UIEventListener.BoolDelegate(this.OnItemHover);
             uieventListener.onPress   = new UIEventListener.BoolDelegate(this.OnItemPress);
             uieventListener.parameter = text;
             if (this.mSelectedItem == text || (i == 0 && string.IsNullOrEmpty(this.mSelectedItem)))
             {
                 this.Highlight(uilabel, true);
             }
             this.mLabelList.Add(uilabel);
             i++;
         }
         num4 = Mathf.Max(num4, v.x - vector.x - (border.x + this.padding.x) * 2f);
         float   num6    = num4;
         Vector3 vector2 = new Vector3(num6 * 0.5f, -num3 * 0.5f, 0f);
         Vector3 vector3 = new Vector3(num6, num3 + this.padding.y, 1f);
         int     j       = 0;
         int     count2  = list.Count;
         while (j < count2)
         {
             UILabel uilabel2 = list[j];
             NGUITools.AddWidgetCollider(uilabel2.gameObject);
             uilabel2.autoResizeBoxCollider = false;
             BoxCollider component = uilabel2.GetComponent <BoxCollider>();
             if (component != null)
             {
                 vector2.z        = component.center.z;
                 component.center = vector2;
                 component.size   = vector3;
             }
             else
             {
                 BoxCollider2D component2 = uilabel2.GetComponent <BoxCollider2D>();
                 component2.offset = vector2;
                 component2.size   = vector3;
             }
             j++;
         }
         int width = Mathf.RoundToInt(num4);
         num4 += (border.x + this.padding.x) * 2f;
         num5 -= border.y;
         this.mBackground.width  = Mathf.RoundToInt(num4);
         this.mBackground.height = Mathf.RoundToInt(-num5 + border.y);
         int k      = 0;
         int count3 = list.Count;
         while (k < count3)
         {
             UILabel uilabel3 = list[k];
             uilabel3.overflowMethod = UILabel.Overflow.ShrinkContent;
             uilabel3.width          = width;
             k++;
         }
         float num7 = 2f * this.atlas.pixelSize;
         float f    = num4 - (border.x + this.padding.x) * 2f + (float)atlasSprite.borderLeft * num7;
         float f2   = num3 + num * num7;
         this.mHighlight.width  = Mathf.RoundToInt(f);
         this.mHighlight.height = Mathf.RoundToInt(f2);
         bool flag = this.position == UIPopupList.Position.Above;
         if (this.position == UIPopupList.Position.Auto)
         {
             UICamera uicamera = UICamera.FindCameraForLayer(this.mSelection.layer);
             if (uicamera != null)
             {
                 flag = (uicamera.cachedCamera.WorldToViewportPoint(localPosition).y < 0.5f);
             }
         }
         if (this.isAnimated)
         {
             this.AnimateColor(this.mBackground);
             if (Time.timeScale == 0f || Time.timeScale >= 0.1f)
             {
                 float bottom = num5 + num3;
                 this.Animate(this.mHighlight, flag, bottom);
                 int l      = 0;
                 int count4 = list.Count;
                 while (l < count4)
                 {
                     this.Animate(list[l], flag, bottom);
                     l++;
                 }
                 this.AnimateScale(this.mBackground, flag, bottom);
             }
         }
         if (flag)
         {
             vector.y = v.y - border.y;
             v.y      = vector.y + (float)this.mBackground.height;
             v.x      = vector.x + (float)this.mBackground.width;
             transform.localPosition = new Vector3(vector.x, v.y - border.y, vector.z);
         }
         else
         {
             v.y      = vector.y + border.y;
             vector.y = v.y - (float)this.mBackground.height;
             v.x      = vector.x + (float)this.mBackground.width;
         }
         Transform parent = this.mPanel.cachedTransform.parent;
         if (parent != null)
         {
             vector = this.mPanel.cachedTransform.TransformPoint(vector);
             v      = this.mPanel.cachedTransform.TransformPoint(v);
             vector = parent.InverseTransformPoint(vector);
             v      = parent.InverseTransformPoint(v);
         }
         Vector3 b = (!this.mPanel.hasClipping) ? this.mPanel.CalculateConstrainOffset(vector, v) : Vector3.zero;
         localPosition           = transform.localPosition + b;
         localPosition.x         = Mathf.Round(localPosition.x);
         localPosition.y         = Mathf.Round(localPosition.y);
         transform.localPosition = localPosition;
     }
     else
     {
         this.OnSelect(false);
     }
 }
Esempio n. 59
0
        protected override void DrawWireframe()
        {
            if (this.radius <= 0f)
            {
                base.DrawWireframe();
                return;
            }

            var cameraPos = default(float3);
            var cameraFwd = new float3 {
                z = 1f
            };
            var cameraOrtho = true;

            if (Camera.current != null)
            {
                cameraPos   = Camera.current.transform.position;
                cameraFwd   = Camera.current.transform.forward;
                cameraOrtho = Camera.current.orthographic;
            }

            var size   = new float3(this.radius * 2f, this.radius * 2f, height);
            var radius = this.radius;
            var origin = (float3)this.center;
            var bounds = new Bounds(this.center, size);

            // Since the geometry is transformed by Handles.matrix during rendering, we transform the camera position
            // by the inverse matrix so that the two-shaded wireframe will have the proper orientation.
            var invMatrix     = Handles.inverseMatrix;
            var cameraCenter  = (float3)invMatrix.MultiplyPoint(cameraPos);
            var cameraForward = (float3)invMatrix.MultiplyVector(cameraFwd);

            bool isCameraInsideBox = Camera.current != null &&
                                     bounds.Contains(invMatrix.MultiplyPoint(cameraPos));

            PhysicsBoundsHandleUtility.DrawFace(origin, size * new float3(1f, 1f, 1f), radius, 0, axes, isCameraInsideBox);
            PhysicsBoundsHandleUtility.DrawFace(origin, size * new float3(-1f, 1f, 1f), radius, 0, axes, isCameraInsideBox);
            PhysicsBoundsHandleUtility.DrawFace(origin, size * new float3(1f, 1f, 1f), radius, 1, axes, isCameraInsideBox);
            PhysicsBoundsHandleUtility.DrawFace(origin, size * new float3(1f, -1f, 1f), radius, 1, axes, isCameraInsideBox);
            PhysicsBoundsHandleUtility.DrawFace(origin, size * new float3(1f, 1f, 1f), radius, 2, axes, isCameraInsideBox);
            PhysicsBoundsHandleUtility.DrawFace(origin, size * new float3(1f, 1f, -1f), radius, 2, axes, isCameraInsideBox);

            var corner = 0.5f * size - new float3(1f) * radius;
            var axisx  = new float3(1f, 0f, 0f);
            var axisy  = new float3(0f, 1f, 0f);
            var axisz  = new float3(0f, 0f, 1f);

            PhysicsBoundsHandleUtility.CalculateCornerHorizon(origin + corner * new float3(-1f, 1f, -1f), quaternion.LookRotation(-axisz, axisy), cameraCenter, cameraForward, cameraOrtho, radius, out s_Corners[0]);
            PhysicsBoundsHandleUtility.CalculateCornerHorizon(origin + corner * new float3(-1f, 1f, 1f), quaternion.LookRotation(-axisx, axisy), cameraCenter, cameraForward, cameraOrtho, radius, out s_Corners[1]);
            PhysicsBoundsHandleUtility.CalculateCornerHorizon(origin + corner * new float3(1f, 1f, 1f), quaternion.LookRotation(axisz, axisy), cameraCenter, cameraForward, cameraOrtho, radius, out s_Corners[2]);
            PhysicsBoundsHandleUtility.CalculateCornerHorizon(origin + corner * new float3(1f, 1f, -1f), quaternion.LookRotation(axisx, axisy), cameraCenter, cameraForward, cameraOrtho, radius, out s_Corners[3]);

            PhysicsBoundsHandleUtility.CalculateCornerHorizon(origin + corner * new float3(-1f, -1f, -1f), quaternion.LookRotation(-axisx, -axisy), cameraCenter, cameraForward, cameraOrtho, radius, out s_Corners[4]);
            PhysicsBoundsHandleUtility.CalculateCornerHorizon(origin + corner * new float3(-1f, -1f, 1f), quaternion.LookRotation(axisz, -axisy), cameraCenter, cameraForward, cameraOrtho, radius, out s_Corners[5]);
            PhysicsBoundsHandleUtility.CalculateCornerHorizon(origin + corner * new float3(1f, -1f, 1f), quaternion.LookRotation(axisx, -axisy), cameraCenter, cameraForward, cameraOrtho, radius, out s_Corners[6]);
            PhysicsBoundsHandleUtility.CalculateCornerHorizon(origin + corner * new float3(1f, -1f, -1f), quaternion.LookRotation(-axisz, -axisy), cameraCenter, cameraForward, cameraOrtho, radius, out s_Corners[7]);

            PhysicsBoundsHandleUtility.DrawCorner(s_Corners[0], new bool3(false, true, true));
            PhysicsBoundsHandleUtility.DrawCorner(s_Corners[3], new bool3(true, false, true));
            PhysicsBoundsHandleUtility.DrawCorner(s_Corners[4], new bool3(true, false, true));
            PhysicsBoundsHandleUtility.DrawCorner(s_Corners[7], new bool3(false, true, true));

            PhysicsBoundsHandleUtility.DrawCorner(s_Corners[1], new bool3(true, false, true));
            PhysicsBoundsHandleUtility.DrawCorner(s_Corners[2], new bool3(false, true, true));
            PhysicsBoundsHandleUtility.DrawCorner(s_Corners[5], new bool3(false, true, true));
            PhysicsBoundsHandleUtility.DrawCorner(s_Corners[6], new bool3(true, false, true));

            // Draw the horizon edges between the corners
            for (int upA = 3, upB = 0; upB < 4; upA = upB, upB++)
            {
                int dnA = upA + 4;
                int dnB = upB + 4;

                if (s_Corners[upA].splitAxis[0].z && s_Corners[upB].splitAxis[1].x)
                {
                    Handles.DrawLine(s_Corners[upA].points[0], s_Corners[upB].points[1]);
                }
                if (s_Corners[upA].splitAxis[1].z && s_Corners[upB].splitAxis[0].x)
                {
                    Handles.DrawLine(s_Corners[upA].points[1], s_Corners[upB].points[0]);
                }

                if (s_Corners[dnA].splitAxis[0].x && s_Corners[dnB].splitAxis[1].z)
                {
                    Handles.DrawLine(s_Corners[dnA].points[0], s_Corners[dnB].points[1]);
                }
                if (s_Corners[dnA].splitAxis[1].x && s_Corners[dnB].splitAxis[0].z)
                {
                    Handles.DrawLine(s_Corners[dnA].points[1], s_Corners[dnB].points[0]);
                }

                if (s_Corners[dnA].splitAxis[0].y && s_Corners[upA].splitAxis[1].y)
                {
                    Handles.DrawLine(s_Corners[dnA].points[0], s_Corners[upA].points[1]);
                }
                if (s_Corners[dnA].splitAxis[1].y && s_Corners[upA].splitAxis[0].y)
                {
                    Handles.DrawLine(s_Corners[dnA].points[1], s_Corners[upA].points[0]);
                }
            }
        }
    /// <summary>
    /// Update the values of the associated scroll bars.
    /// </summary>

    public void UpdateScrollbars(bool recalculateBounds)
    {
        if (mPanel == null)
        {
            return;
        }

        if (horizontalScrollBar != null || verticalScrollBar != null)
        {
            if (recalculateBounds)
            {
                mCalculatedBounds = false;
                mShouldMove       = shouldMove;
            }

            Bounds  b    = bounds;
            Vector2 bmin = b.min;
            Vector2 bmax = b.max;

            if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
            {
                Vector2 soft = mPanel.clipSoftness;
                bmin -= soft;
                bmax += soft;
            }

            if (horizontalScrollBar != null && bmax.x > bmin.x)
            {
                Vector4 clip    = mPanel.clipRange;
                float   extents = clip.z * 0.5f;
                float   min     = clip.x - extents - b.min.x;
                float   max     = b.max.x - extents - clip.x;

                float width = bmax.x - bmin.x;
                min = Mathf.Clamp01(min / width);
                max = Mathf.Clamp01(max / width);

                float sum = min + max;
                mIgnoreCallbacks                = true;
                horizontalScrollBar.barSize     = 1f - sum;
                horizontalScrollBar.scrollValue = (sum > 0.001f) ? min / sum : 0f;
                mIgnoreCallbacks                = false;
            }

            if (verticalScrollBar != null && bmax.y > bmin.y)
            {
                Vector4 clip    = mPanel.clipRange;
                float   extents = clip.w * 0.5f;
                float   min     = clip.y - extents - bmin.y;
                float   max     = bmax.y - extents - clip.y;

                float height = bmax.y - bmin.y;
                min = Mathf.Clamp01(min / height);
                max = Mathf.Clamp01(max / height);
                float sum = min + max;

                mIgnoreCallbacks              = true;
                verticalScrollBar.barSize     = 1f - sum;
                verticalScrollBar.scrollValue = (sum > 0.001f) ? 1f - min / sum : 0f;
                mIgnoreCallbacks              = false;
            }
        }
        else if (recalculateBounds)
        {
            mCalculatedBounds = false;
        }
    }