Beispiel #1
0
    void Awake()
    {
        activator = GetComponentInChildren<Activator>();
        eye = GetComponentInChildren<Eye>();
        inventory = GetComponentInChildren<Inventory>();
        lastPositionKeeper = GetComponentInChildren<LastPositionKeeper>();
        head = GetComponentInChildren<Head>();
        cameraPlace = GetComponentInChildren<CameraPlace>();
        undo = GetComponentInChildren<Undo>();
        characterController = GetComponentInChildren<CharacterController>();
        rewind = GetComponentInChildren<Rewind>();
        slowmo = GetComponentInChildren<Slowmo>();
        gravity = GetComponentInChildren<Gravity>();

        all.Add(this);
    }
Beispiel #2
0
        void ProcessBezierPathInput(Event e)
        {
            // Find which handle mouse is over. Start by looking at previous handle index first, as most likely to still be closest to mouse
            int previousMouseOverHandleIndex = (mouseOverHandleIndex == -1) ? 0 : mouseOverHandleIndex;

            mouseOverHandleIndex = -1;
            for (int i = 0; i < bezierPath.NumPoints; i += 3)
            {
                int     handleIndex     = (previousMouseOverHandleIndex + i) % bezierPath.NumPoints;
                float   handleRaDefeses = GetHandleDiameter(globalDisplaySettings.anchorSize * data.bezierHandleScale, bezierPath[handleIndex]) / 2f;
                Vector3 pos             = MathUtility.TransformPoint(bezierPath[handleIndex], creator.transform, bezierPath.Space);
                float   dst             = HandleUtility.DistanceToCircle(pos, handleRaDefeses);
                if (dst == 0)
                {
                    mouseOverHandleIndex = handleIndex;
                    break;
                }
            }

            // Shift-left click (when mouse not over a handle) to split or add segment
            if (mouseOverHandleIndex == -1)
            {
                if (e.type == EventType.MouseDown && e.button == 0 && e.shift)
                {
                    UpdatePathMouseInfo();
                    // Insert point along selected segment
                    if (selectedSegmentIndex != -1 && selectedSegmentIndex < bezierPath.NumSegments)
                    {
                        Vector3 newPathPoint = pathMouseInfo.closestWorldPointToMouse;
                        newPathPoint = MathUtility.InverseTransformPoint(newPathPoint, creator.transform, bezierPath.Space);
                        Undo.RecordObject(creator, "Split segment");
                        bezierPath.SplitSegment(newPathPoint, selectedSegmentIndex, pathMouseInfo.timeOnBezierSegment);
                    }
                    // If path is not a closed loop, add new point on to the end of the path
                    else if (!bezierPath.IsClosed)
                    {
                        // insert new point at same dst from scene camera as the point that comes before it (for a 3d path)
                        float   dstCamToEndpoint = (Camera.current.transform.position - bezierPath[bezierPath.NumPoints - 1]).magnitude;
                        Vector3 newPathPoint     = MouseUtility.GetMouseWorldPosition(bezierPath.Space, dstCamToEndpoint);
                        newPathPoint = MathUtility.InverseTransformPoint(newPathPoint, creator.transform, bezierPath.Space);

                        Undo.RecordObject(creator, "Add segment");
                        if (e.control || e.command)
                        {
                            bezierPath.AddSegmentToStart(newPathPoint);
                        }
                        else
                        {
                            bezierPath.AddSegmentToEnd(newPathPoint);
                        }
                    }
                }
            }

            // Control click or backspace/delete to remove point
            if (e.keyCode == KeyCode.Backspace || e.keyCode == KeyCode.Delete || ((e.control || e.command) && e.type == EventType.MouseDown && e.button == 0))
            {
                if (mouseOverHandleIndex != -1)
                {
                    Undo.RecordObject(creator, "Delete segment");
                    bezierPath.DeleteSegment(mouseOverHandleIndex);
                    if (mouseOverHandleIndex == handleIndexToDisplayAsTransform)
                    {
                        handleIndexToDisplayAsTransform = -1;
                    }
                    mouseOverHandleIndex = -1;
                    Repaint();
                }
            }

            // Holding shift and moving mouse (but mouse not over a handle/dragging a handle)
            if (draggingHandleIndex == -1 && mouseOverHandleIndex == -1)
            {
                bool shiftDown = e.shift && !shiftLastFrame;
                if (shiftDown || ((e.type == EventType.MouseMove || e.type == EventType.MouseDrag) && e.shift))
                {
                    UpdatePathMouseInfo();

                    if (pathMouseInfo.mouseDstToLine < segmentSelectDistanceThreshold)
                    {
                        if (pathMouseInfo.closestSegmentIndex != selectedSegmentIndex)
                        {
                            selectedSegmentIndex = pathMouseInfo.closestSegmentIndex;
                            HandleUtility.Repaint();
                        }
                    }
                    else
                    {
                        selectedSegmentIndex = -1;
                        HandleUtility.Repaint();
                    }
                }
            }

            shiftLastFrame = e.shift;
        }
Beispiel #3
0
    public override void OnInspectorGUI()
    {
        comment = ((GameObjectComments)target).comment;
        comment = EditorGUILayout.TextArea(comment, style, options);         // Draw the text area
        // Record undo object when the text has changed
        if (comment.Equals(previousComment) == false)
        {
            Undo.RecordObject(target, "Comment Edit");
            previousComment = comment;
        }
        ((GameObjectComments)target).comment = comment;

        if (EditorGUIUtility.editingTextField)  // Show options when editing
        {
            style.richText = false;             // Show rich text tags

            GUILayout.BeginHorizontal();
            // Bold button
            if (GUILayout.Button("Bold"))
            {
                GUIUtility.keyboardControl = 0;
                Undo.RecordObject(target, "Bold Tag");
                comment = comment + "<b></b>";
                ((GameObjectComments)target).comment = comment;
            }

            // Italics button
            if (GUILayout.Button("Italics"))
            {
                GUIUtility.keyboardControl = 0;
                Undo.RecordObject(target, "Italics Tag");
                comment = comment + "<i></i>";
                ((GameObjectComments)target).comment = comment;
            }
            GUILayout.EndHorizontal();

            // Size button and text field
            GUILayout.BeginHorizontal();
            GUILayout.Label("Size");

            fontSize = ((GameObjectComments)target).fontSize;
            fontSize = EditorGUILayout.IntField(fontSize);  // Text box for font size
            if (fontSize != previousFontSize)               // Record object if the font size has changed
            {
                Undo.RecordObject(target, "Font Size");
                previousFontSize = fontSize;
            }
            ((GameObjectComments)target).fontSize = fontSize;

            GUILayout.Space(Screen.width / 10);

            if (GUILayout.Button("Add size tag"))
            {
                GUIUtility.keyboardControl = 0;
                Undo.RecordObject(target, "Size Tag");
                comment = comment + "<size=" + fontSize + "></size>";
                ((GameObjectComments)target).comment = comment;
            }
            GUILayout.EndHorizontal();


            // Color button and drop down
            GUILayout.BeginHorizontal();
            GUILayout.Label("Color");

            colorSelectedIndex = ((GameObjectComments)target).colorSelectedIndex;
            colorSelectedIndex = EditorGUILayout.Popup(colorSelectedIndex, colors); // Drop down menu for colors
            if (colorSelectedIndex != previousColorSelectedIndex)                   // Record object if the selected index has changed
            {
                Undo.RecordObject(target, "Color Selection");
                previousColorSelectedIndex = colorSelectedIndex;
            }
            ((GameObjectComments)target).colorSelectedIndex = colorSelectedIndex;

            GUILayout.Space(Screen.width / 10);

            if (GUILayout.Button("Add color tag"))
            {
                GUIUtility.keyboardControl = 0;
                Undo.RecordObject(target, "Color Tag");
                comment = comment + "<color=" + colors[colorSelectedIndex] + "></color>";
                ((GameObjectComments)target).comment = comment;
            }
            GUILayout.EndHorizontal();
        }
        else
        {
            style.richText = true;
        }
    }
Beispiel #4
0
        public void BlockChange(short clientId, short x, short y, short z, Block type, Block lastType, bool undo, bool physics, bool send, short priority)
        {
            if (!HCSettings.Building)
                return;

            SetBlockId(x, y, z, (byte)(type.Id), clientId);

            if (undo) {
                NetworkClient client;

                ServerCore.Nh.IntLoggedClients.TryGetValue(clientId, out client);

                if (client != null) {
                    if (client.CS.CurrentIndex == -1)
                        client.CS.CurrentIndex = 0;

                    if (client.CS.CurrentIndex != (client.CS.UndoObjects.Count - 1)) {
                        for (var i = client.CS.CurrentIndex; i < client.CS.UndoObjects.Count - 1; i++)
                            client.CS.UndoObjects.RemoveAt(i);
                    }

                    if (client.CS.UndoObjects.Count >= 50000)
                        client.CS.UndoObjects.RemoveAt(0);

                    var newUndo = new Undo {X = x, Y = y, Z = z, OldBlock = lastType, NewBlock = type};

                    client.CS.UndoObjects.Add(newUndo);
                    client.CS.CurrentIndex = client.CS.UndoObjects.Count - 1;
                }
            }

            if (send)
                BlockchangeQueue.Enqueue(new QueueItem(x, y, z, priority));

            if (!physics || !HCSettings.Physics)
                return;

            var randomGen = new Random();

            for (short ix = -1; ix < 2; ix++) {
                for (short iy = -1; iy < 2; iy++) {
                    for (short iz = -1; iz < 2; iz++) {

                        if (!BlockInBounds((short)(x + ix), (short)(y + iy), (short)(z + iz)))
                            continue;

                        var index = BlockIndex(x + ix, y + iy, z + iz);

                        if ((_physicsBitmask[index / 8] & (1 << (index % 8))) != 0)
                            continue;

                        var blockQueue = GetBlock((short)(x + ix), (short)(y + iy), (short)(z + iz));

                        if (blockQueue.Physics <= 0 && string.IsNullOrEmpty(blockQueue.PhysicsPlugin))
                            continue;

                        _physicsBitmask[index/8] = (byte)(_physicsBitmask[index/8] | (1 << (index%8)));
                        PhysicsQueue.Enqueue(new QueueItem((short)(x + ix), (short)(y + iy), (short)(z + iz), DateTime.UtcNow.AddMilliseconds(blockQueue.PhysicsDelay + randomGen.Next(blockQueue.PhysicsRandom))));
                    }
                }
            }
        }
    private void ScaledSizePropertyField(SerializedProperty scaleProperty, GUIContent content)
    {
        bool    guiEnabled = GUI.enabled;
        bool    enabled    = GUI.enabled;
        Vector3 meshSize   = GetWorldMeshSize((Transform)this.target);

        if (this.targets.Length > 1)
        {
            foreach (Transform obj1 in this.targets)
            {
                foreach (Transform obj2 in this.targets)
                {
                    if (obj1.parent == obj2)
                    {
                        enabled = false;
                    }
                }
            }
            foreach (Transform obj1 in this.targets)
            {
                if (meshSize != GetWorldMeshSize((Transform)obj1))
                {
                    EditorGUI.showMixedValue = true;
                    break;
                }
            }
        }

        if (meshSize == Vector3.zero)
        {
            return;
        }

        EditorGUILayout.Space();
        EditorGUI.BeginChangeCheck();

        // convert to local scale
        Transform t           = (Transform)this.target;
        Vector3   lossy2local = new Vector3(t.localScale.x / t.lossyScale.x, t.localScale.y / t.lossyScale.y, t.localScale.z / t.lossyScale.z);

        meshSize = Vector3.Scale(meshSize, lossy2local);

        enabled     = enabled && !EditorGUI.showMixedValue;
        GUI.enabled = enabled;
        Vector3 size = EditorGUILayout.Vector3Field(content, meshSize);

        GUI.enabled = guiEnabled;
        if (!enabled)
        {
            return;
        }

        // don't update if any component is 0
        if (size.x == 0)
        {
            return;
        }
        if (size.y == 0)
        {
            return;
        }
        if (size.z == 0)
        {
            return;
        }

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObjects(this.targets, "Scale Changed");
            foreach (UnityEngine.Object obj in this.targets)
            {
                t        = (Transform)obj;
                meshSize = GetWorldMeshSize(t);
                if (meshSize == Vector3.zero)
                {
                    continue;
                }
                lossy2local  = new Vector3(t.localScale.x / t.lossyScale.x, t.localScale.y / t.lossyScale.y, t.localScale.z / t.lossyScale.z);
                meshSize     = Vector3.Scale(meshSize, lossy2local);
                t.localScale = Vector3.Scale(t.localScale, new Vector3(size.x / meshSize.x, size.y / meshSize.y, size.z / meshSize.z));
            }
            scaleProperty.serializedObject.SetIsDifferentCacheDirty();
        }
    }
        public void OnSceneGUI()
        {
            var navLink = (NavMeshLink)target;

            if (!navLink.enabled)
            {
                return;
            }

            var mat = UnscaledLocalToWorldMatrix(navLink.transform);

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

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

            var oldColor = Handles.color;

            Handles.color = s_HandleColor;

            Vector3 pos;

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

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

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

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

            Handles.color = oldColor;
        }
        public List<ResponseDetails> ProcessECKTransaction(
                        TransactionType _TT //Required
                        , ElectronicCheckingTransaction _ECKtransaction
                        , List<String> _BatchIds //Conditional : A list of one or more batch Ids to capture.
                        , List<Capture> _CaptureDifferenceData
                        , Undo _UDifferenceData //Conditional : Only used for an Undo. Otherwise null
                        , bool _SendAcknowledge)
        {
            List<Response> _Response = new List<Response>();
            try
            {
                CheckTokenExpire();//Make sure the current token is valid

                //if (_TT == TransactionType.AuthorizeAndCapture)
                if (_TT == TransactionType.Authorize)
                {
                    if (CredentialRequired())
                        _ECKtransaction.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.Authorize(_sessionToken, _ECKtransaction, _applicationProfileId, _merchantProfileId, _serviceId));
                    //Always Verify that the requested amount and approved amount are the same.

                    ElectronicCheckingTransactionResponse ECKR = new ElectronicCheckingTransactionResponse();
                    ECKR = (ElectronicCheckingTransactionResponse)_Response[0];
                    if (_ECKtransaction.TransactionData.Amount != ECKR.Amount)
                        MessageBox.Show("The transaction was approved for " + ECKR.Amount
                            + " which is an amount not equal to than the requested amount of " + _ECKtransaction.TransactionData.Amount
                            + ". Please provide alternate payment to complete transaction");
                }
                //if (_TT == TransactionType.Capture)
                if (_TT == TransactionType.CaptureAll)
                {
                    _CaptureDifferenceData = new List<Capture>();
                    Capture cap = new Capture();
                    if (CredentialRequired())
                        cap.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    cap.TransactionId = "-1";
                    _CaptureDifferenceData.Add(cap);
                    _Response = Cwsbc.CaptureAll(_sessionToken, _CaptureDifferenceData, _BatchIds, _applicationProfileId,
                                                 _merchantProfileId, _serviceId);
                }
                if (_TT == TransactionType.CaptureAllAsync)
                {
                    _CaptureDifferenceData = new List<Capture>();
                    Capture cap = new Capture();
                    if (CredentialRequired())
                        cap.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    cap.TransactionId = "-1";
                    _CaptureDifferenceData.Add(cap);
                    _Response.Add(Cwsbc.CaptureAllAsync(_sessionToken, _CaptureDifferenceData, _BatchIds, _applicationProfileId, _merchantProfileId, _serviceId));
                }

                //if (_TT == TransactionType.CaptureSelective)
                //if (_TT == TransactionType.CaptureSelectiveAsync)
                //if (_TT == TransactionType.ReturnById)
                //if (_TT == TransactionType.Return)
                //if (_TT == TransactionType.Adjust)
                if (_TT == TransactionType.Undo)
                {
                    if (CredentialRequired())
                        _UDifferenceData.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.Undo(_sessionToken, _UDifferenceData, _applicationProfileId, _serviceId));
                }
                if (_TT == TransactionType.QueryAccount)
                {
                    if (CredentialRequired())
                        _ECKtransaction.Addendum = CredentialsRequired(_serviceId, _credUserName, _credPassword);
                    _Response.Add(Cwsbc.QueryAccount(_sessionToken, _ECKtransaction, _applicationProfileId, _merchantProfileId, _serviceId));
                }

                //if (_TT == TransactionType.Verify)

                List<ResponseDetails> RD = new List<ResponseDetails>();//Convert the response to response details so that we can report on the UI
                if (_Response != null)
                {
                    foreach (Response r in _Response)
                    {
                        if (_SendAcknowledge && r.TransactionId.Length > 0)
                            Cwsbc.Acknowledge(_sessionToken, r.TransactionId, _applicationProfileId, _serviceId);

                        ResponseDetails RDN = new ResponseDetails(0.00M, r, _TT.ToString(), _serviceId, _merchantProfileId, true, TypeCardType.NotSet, "");
                        MessageBox.Show(ProcessResponse(ref RDN));//Pass as reference so we can extract more values from the response
                        RD.Add(RDN);
                    }
                }

                return RD;
            }
            catch (EndpointNotFoundException)
            {
                //In this case the SvcEndpoint was not available. Try the same logic again with the alternate Endpoint
                try
                {
                    SetTxnEndpoint();//Change the endpoint to use the backup.

                    //TODO : Add a copy of the code above once fully tested out.

                    return null;

                }
                catch (EndpointNotFoundException)
                {
                    MessageBox.Show("Neither the primary or secondary endpoints are available. Unable to process.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to AuthorizeAndCapture\r\nError Message : " + ex.Message, "AuthorizeAndCapture Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (System.TimeoutException te)
            {
                //A timeout has occured. Prompt the user if they'd like to query for the last transaction submitted
                if (_ECKtransaction != null)
                {
                    DialogResult Result;
                    Result = MessageBox.Show("A timeout has occured. Would you like to query 'RequestTransaction' to obtain transactions with the exact same TenderData? To avoid duplicate charges your code will need to reconcile transactions.",
                                "Request Transaction", MessageBoxButtons.YesNo);
                    if (Result == DialogResult.Yes)
                    {
                        RequestTransaction(_ECKtransaction.TenderData);
                    }
                    else { throw te; }
                }
                else { throw te; }
            }
            catch (Exception ex)
            {
                string strErrorId;
                string strErrorMessage;
                if (_FaultHandler.handleTxnFault(ex, out strErrorId, out strErrorMessage))
                { MessageBox.Show(strErrorId + " : " + strErrorMessage); }
                else { MessageBox.Show(ex.Message); }
            }

            return null;
        }
        private void cmdUndo_Click(object sender, EventArgs e)
        {//The Undo() operation is used to void (Credit Card) or reverse (PIN Debit) a transaction that has been previously authorized.
            if (ChkLstTransactionsProcessed.CheckedItems.Count == 0) { MessageBox.Show("Please Select (Check) transactions for Undo"); return; }
            //Check to see if this transaction type is supported
            if (!SupportedTxnTypes.Undo) { MessageBox.Show("Undo Not Supported"); Cursor = Cursors.Default; return; }

            Cursor = Cursors.WaitCursor;

            //First verify if all transactions selected are "Authorize" transactions
            List<ResponseDetails> txnsToProcess = new List<ResponseDetails>();
            foreach (object itemChecked in ChkLstTransactionsProcessed.CheckedItems)
            {
                if (((ResponseDetails)(itemChecked)).TransactionType != TransactionType.Authorize.ToString())
                {
                    MessageBox.Show("All selected messages must be of type Authorize");
                    Cursor = Cursors.Default;
                    return;
                }
                txnsToProcess.Add(((ResponseDetails)(itemChecked)));
            }

            if (_bcs != null) //Process a BankCard Transaction
            {
                try
                {
                    //Now process each message selected
                    foreach (ResponseDetails _RD in txnsToProcess)
                    {
                        BankcardUndo uTransaction = new BankcardUndo();
                        //Let's Undo or Void the transaction
                        uTransaction.TransactionId = _RD.Response.TransactionId;
                        if (chkProcessAsPINDebitTxn.Checked)
                            uTransaction.PINDebitReason = PINDebitUndoReason.ResponseTimeout;
                        processResponse(Helper.ProcessBCPTransaction(TransactionType.Undo, null, null, null, null, null, uTransaction, null, null, ChkAcknowledge.Checked, false));
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { Cursor = Cursors.Default; }
            }
            if (_svas != null) //Process a Stored Value Transaction
            {
                try
                {
                    //Now process each message selected
                    foreach (ResponseDetails _RD in txnsToProcess)
                    {
                        Undo uTransaction = new Undo();
                        //Now Let's Undo or Void the transaction
                        uTransaction.TransactionId = _RD.Response.TransactionId;
                        processResponse(Helper.ProcessSVATransaction(TransactionType.Undo, null, null, null, null, uTransaction, ChkAcknowledge.Checked));
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { Cursor = Cursors.Default; }
            }
            else if (_ecks != null) //Process as a Check transaction
            {
                try
                {
                    if (_checkTxn.Length < 1) { MessageBox.Show("You must have a valid Check transaction before performing an Undo."); return; }

                    //Now process each message selected
                    foreach (ResponseDetails _RD in txnsToProcess)
                    {
                        Undo uECKCheck = new Undo();
                        uECKCheck.TransactionId = _RD.Response.TransactionId;
                        processResponse(Helper.ProcessECKTransaction(TransactionType.Undo, null, null, null, uECKCheck, ChkAcknowledge.Checked));
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                finally { Cursor = Cursors.Default; }
            }
        }
Beispiel #9
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// </summary>

    public void OnSceneGUI()
    {
        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }

        mWidget = target as UIWidget;

        Transform t = mWidget.cachedTransform;

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);

        Action actionUnderMouse = mAction;

        Vector3[] handles = GetHandles(mWidget.worldCorners);

        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        // If the widget is anchored, draw the anchors
        if (mWidget.isAnchored)
        {
            DrawAnchorHandle(mWidget.leftAnchor, mWidget.cachedTransform, handles, 0, id);
            DrawAnchorHandle(mWidget.topAnchor, mWidget.cachedTransform, handles, 1, id);
            DrawAnchorHandle(mWidget.rightAnchor, mWidget.cachedTransform, handles, 2, id);
            DrawAnchorHandle(mWidget.bottomAnchor, mWidget.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mWidget) && mWidget.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, mWidget.width, mWidget.height);
            }
        }

        // Presence of the legacy stretch component prevents resizing
        bool canResize = (mWidget.GetComponent <UIStretch>() == null);

        bool[] resizable = new bool[8];

        resizable[4] = canResize;               // left
        resizable[5] = canResize;               // top
        resizable[6] = canResize;               // right
        resizable[7] = canResize;               // bottom

        UILabel lbl = mWidget as UILabel;

        if (lbl != null)
        {
            if (lbl.overflowMethod == UILabel.Overflow.ResizeFreely)
            {
                resizable[4] = false;                   // left
                resizable[5] = false;                   // top
                resizable[6] = false;                   // right
                resizable[7] = false;                   // bottom
            }
            else if (lbl.overflowMethod == UILabel.Overflow.ResizeHeight)
            {
                resizable[5] = false;                   // top
                resizable[7] = false;                   // bottom
            }
        }

        if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnHeight)
        {
            resizable[4] = false;
            resizable[6] = false;
        }
        else if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnWidth)
        {
            resizable[5] = false;
            resizable[7] = false;
        }

        resizable[0] = resizable[7] && resizable[4];         // bottom-left
        resizable[1] = resizable[5] && resizable[4];         // top-left
        resizable[2] = resizable[5] && resizable[6];         // top-right
        resizable[3] = resizable[7] && resizable[6];         // bottom-right

        UIWidget.Pivot pivotUnderMouse = GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], mWidget.pivot == pivotPoints[i], resizable[i], id);
                    }

                    if ((v1 - v0).magnitude > 80f)
                    {
                        if (mWidget.leftAnchor.target == null || mWidget.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], mWidget.pivot == pivotPoints[4], resizable[4], id);
                        }

                        if (mWidget.rightAnchor.target == null || mWidget.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], mWidget.pivot == pivotPoints[6], resizable[6], id);
                        }
                    }

                    if ((v3 - v0).magnitude > 80f)
                    {
                        if (mWidget.topAnchor.target == null || mWidget.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], mWidget.pivot == pivotPoints[5], resizable[5], id);
                        }

                        if (mWidget.bottomAnchor.target == null || mWidget.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], mWidget.pivot == pivotPoints[7], resizable[7], id);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            mStartMouse     = e.mousePosition;
            mAllowSelection = true;

            if (e.button == 1)
            {
                if (e.modifiers == 0)
                {
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
            else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(handles, out mStartDrag))
            {
                mWorldPos      = t.position;
                mLocalPos      = t.localPosition;
                mStartRot      = t.localRotation.eulerAngles;
                mStartDir      = mStartDrag - t.position;
                mStartWidth    = mWidget.width;
                mStartHeight   = mWidget.height;
                mStartLeft.x   = mWidget.leftAnchor.relative;
                mStartLeft.y   = mWidget.leftAnchor.absolute;
                mStartRight.x  = mWidget.rightAnchor.relative;
                mStartRight.y  = mWidget.rightAnchor.absolute;
                mStartBottom.x = mWidget.bottomAnchor.relative;
                mStartBottom.y = mWidget.bottomAnchor.absolute;
                mStartTop.x    = mWidget.topAnchor.relative;
                mStartTop.y    = mWidget.topAnchor.absolute;

                mDragPivot            = pivotUnderMouse;
                mActionUnderMouse     = actionUnderMouse;
                GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                e.Use();
            }
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != Action.None || mActionUnderMouse != Action.None)
                {
                    Vector3 pos;

                    if (Raycast(handles, out pos))
                    {
                        if (mAction == Action.None && mActionUnderMouse != Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == Action.Move)
                                {
                                    NGUISnap.Recalculate(mWidget);
                                }
                                else if (mActionUnderMouse == Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == Action.Scale)
                                {
                                    mStartWidth  = mWidget.width;
                                    mStartHeight = mWidget.height;
                                    mDragPivot   = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mWidget);

                            // Reset the widget before adjusting anything
                            t.position     = mWorldPos;
                            mWidget.width  = mStartWidth;
                            mWidget.height = mStartHeight;
                            mWidget.leftAnchor.Set(mStartLeft.x, mStartLeft.y);
                            mWidget.rightAnchor.Set(mStartRight.x, mStartRight.y);
                            mWidget.bottomAnchor.Set(mStartBottom.x, mStartBottom.y);
                            mWidget.topAnchor.Set(mStartTop.x, mStartTop.y);

                            if (mAction == Action.Move)
                            {
                                // Move the widget
                                t.position = mWorldPos + (pos - mStartDrag);

                                // Snap the widget
                                Vector3 after = NGUISnap.Snap(t.localPosition, mWidget.localCorners, e.modifiers != EventModifiers.Control);

                                // Calculate the final delta
                                Vector3 localDelta = (after - mLocalPos);

                                // Restore the position
                                t.position = mWorldPos;

                                // Adjust the widget by the delta
                                NGUIMath.MoveRect(mWidget, localDelta.x, localDelta.y);
                            }
                            else if (mAction == Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == Action.Scale)
                            {
                                // Move the widget
                                t.position = mWorldPos + (pos - mStartDrag);

                                // Calculate the final delta
                                Vector3 localDelta = (t.localPosition - mLocalPos);

                                // Restore the position
                                t.position = mWorldPos;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                NGUIMath.ResizeWidget(mWidget, mDragPivot, localDelta.x, localDelta.y, 2, 2);
                                ReEvaluateAnchorType();
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = Action.None;
                mAction           = Action.None;
            }
            else if (mAllowSelection)
            {
                BetterList <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.size > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = Action.None;
                    mAction           = Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Beispiel #10
0
 // Remove itself from the patch.
 public void RemoveFromPatch(Patch patch)
 {
     Undo.DestroyObjectImmediate(_instance.gameObject);
 }
        //Displays all variables for the currently selected profile and initializes each variable's context menu
        void VariablesPane(Rect variablesPaneRect)
        {
            DrawOutline(variablesPaneRect, 1);
            Event evt = Event.current;

            AddressableAssetProfileSettings.BuildProfile selectedProfile = GetSelectedProfile();

            if (selectedProfile == null)
            {
                return;
            }
            if (evt.isMouse || evt.isKey)
            {
                m_ProfileTreeView.lastClickedProfile = ProfileIndex;
            }

            //ensures amount of visible text is not affected by label width
            float fieldWidth = variablesPaneRect.width - (2 * k_ItemRectPadding) + m_LabelWidth + m_FieldBufferWidth;

            if (!EditorGUIUtility.labelWidth.Equals(m_LabelWidth))
            {
                EditorGUIUtility.labelWidth = m_LabelWidth;
            }

            int maxLabelLen = 0;
            int maxFieldLen = 0;

            GUILayout.BeginArea(variablesPaneRect);
            EditorGUI.indentLevel++;
            List <ProfileGroupType> groupTypes      = CreateGroupTypes(selectedProfile);
            HashSet <string>        drawnGroupTypes = new HashSet <string>();

            //Displaying Path Groups
            foreach (ProfileGroupType groupType in groupTypes)
            {
                bool?foldout;
                m_foldouts.TryGetValue(groupType.GroupTypePrefix, out foldout);
                GUILayout.Space(5);
                m_foldouts[groupType.GroupTypePrefix] = EditorGUILayout.Foldout(foldout != null ? foldout.Value : true, groupType.GroupTypePrefix, true);
                //Specific Grouped variables
                List <ProfileGroupType.GroupTypeVariable> pathVariables = new List <ProfileGroupType.GroupTypeVariable>();
                pathVariables.Add(groupType.GetVariableBySuffix("BuildPath"));
                drawnGroupTypes.Add(groupType.GetName(groupType.GetVariableBySuffix("BuildPath")));
                pathVariables.Add(groupType.GetVariableBySuffix("LoadPath"));
                drawnGroupTypes.Add(groupType.GetName(groupType.GetVariableBySuffix("LoadPath")));

                if (m_foldouts[groupType.GroupTypePrefix].Value)
                {
                    EditorGUI.indentLevel++;

                    //Displaying Path Groups
                    foreach (var variable in pathVariables)
                    {
                        Rect   newPathRect = EditorGUILayout.BeginVertical();
                        string newPath     = EditorGUILayout.TextField(groupType.GetName(variable), variable.Value);
                        EditorGUILayout.EndVertical();
                        if (evt.type == EventType.ContextClick)
                        {
                            CreateVariableContextMenu(variablesPaneRect, newPathRect, settings.profileSettings.GetProfileDataByName(groupType.GetName(variable)), evt);
                        }
                        if (newPath != variable.Value && ProfileIndex == m_ProfileTreeView.lastClickedProfile)
                        {
                            Undo.RecordObject(settings, "Variable value changed");
                            settings.profileSettings.SetValue(selectedProfile.id, groupType.GetName(variable), newPath);
                            AddressableAssetUtility.OpenAssetIfUsingVCIntegration(settings);
                        }
                    }
                    EditorGUI.indentLevel--;
                }
            }

            //Display all other variables
            for (var i = 0; i < settings.profileSettings.profileEntryNames.Count; i++)
            {
                AddressableAssetProfileSettings.ProfileIdData curVariable = settings.profileSettings.profileEntryNames[i];
                if (!drawnGroupTypes.Contains(curVariable.ProfileName))
                {
                    GUILayout.Space(5);
                    Rect   newValueRect = EditorGUILayout.BeginVertical();
                    string newValue     = EditorGUILayout.TextField(curVariable.ProfileName, selectedProfile.values[i].value);
                    EditorGUILayout.EndVertical();
                    if (newValue != selectedProfile.values[i].value && ProfileIndex == m_ProfileTreeView.lastClickedProfile)
                    {
                        Undo.RecordObject(settings, "Variable value changed");
                        settings.profileSettings.SetValue(selectedProfile.id, settings.profileSettings.profileEntryNames[i].ProfileName, newValue);
                        AddressableAssetUtility.OpenAssetIfUsingVCIntegration(settings);
                    }

                    if (evt.type == EventType.ContextClick)
                    {
                        CreateVariableContextMenu(variablesPaneRect, newValueRect, curVariable, evt);
                    }
                }
                maxLabelLen = Math.Max(maxLabelLen, curVariable.ProfileName.Length);
            }

            EditorGUI.indentLevel--;
            GUILayout.EndArea();

            //Update the label width to the maximum of the minimum acceptable label width and the amount of
            //space required to contain the longest variable name
            m_LabelWidth       = Mathf.Max(maxLabelLen * k_ApproxCharWidth, k_MinLabelWidth);
            m_FieldBufferWidth = Mathf.Clamp((maxFieldLen * k_ApproxCharWidth) - fieldWidth, 0f, float.MaxValue);
        }
 void DeleteVariable(AddressableAssetProfileSettings.ProfileIdData toBeDeleted)
 {
     Undo.RecordObject(settings, "Profile Variable Deleted");
     settings.profileSettings.RemoveValue(toBeDeleted.Id);
     AddressableAssetUtility.OpenAssetIfUsingVCIntegration(settings);
 }
Beispiel #13
0
        void CopyData()
        {
            Undo.RecordObject(destination.obj, "复制,From " + source.obj.name + " to " + destination.obj.name);

            //获取信息
            FieldInfo fromField = source.GetField();
            FieldInfo toField   = destination.GetField();

            System.Type type = fromField.FieldType;

            if (type == typeof(int) || type == typeof(float) || type == typeof(Color) || type == typeof(bool))
            {
                toField.SetValue(destination.obj, fromField.GetValue(source.obj));
            }
            else if (type == typeof(GUIStyle))
            {
                System.Type[] constructorTypes  = { type };
                object[]      constructorParams = { fromField.GetValue(source.obj) };
                toField.SetValue(destination.obj, type.GetConstructor(constructorTypes).Invoke(constructorParams));
            }
            else if (type == typeof(AnimationCurve))
            {
                AnimationCurve  fromC   = fromField.GetValue(source.obj) as AnimationCurve;
                Keyframe[]      keys    = fromC.keys;
                List <Keyframe> keyList = new List <Keyframe>();
                foreach (Keyframe k in keys)
                {
                    keyList.Add(new Keyframe(k.time, k.value, k.inTangent, k.outTangent));
                }
                toField.SetValue(destination.obj, new AnimationCurve(keyList.ToArray()));
            }
            else if (type == typeof(Gradient))
            {
                Gradient           fromG = fromField.GetValue(source.obj) as Gradient;
                Gradient           value = new Gradient();
                GradientAlphaKey[] aKeys = new GradientAlphaKey[fromG.alphaKeys.Length];
                GradientColorKey[] cKeys = new GradientColorKey[fromG.colorKeys.Length];
                for (int i = 0; i < fromG.alphaKeys.Length; i++)
                {
                    aKeys[i] = fromG.alphaKeys[i];
                }
                for (int i = 0; i < fromG.colorKeys.Length; i++)
                {
                    cKeys[i] = fromG.colorKeys[i];
                }
                value.SetKeys(cKeys, aKeys);
                toField.SetValue(destination.obj, value);
            }
            else
            {
                object so = fromField.GetValue(source.obj);
                foreach (FieldInfo f in type.GetFields())
                {
                    Debug.Log("FieldType:" + f.FieldType + ";value:" + f.GetValue(so));
                }
                Debug.LogAssertion("不支持的类型! type:" + type + " ; from " + fromField.Name + " to " + toField.Name);
                return;
            }
            EditorUtility.SetDirty(destination.obj);
            Debug.Log("复制成功! type:" + type + " ; from " + fromField.Name + " to " + toField.Name);
        }
Beispiel #14
0
        public override void OnInspectorGUI()
        {
            GUILayout.BeginHorizontal();
            EditorGUILayout.HelpBox("State Count:" + _target.StateNames.Count, MessageType.Info);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            Toggle(_target.IsAutoRegister, out _target.IsAutoRegister, "Auto Register");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Name: ");
            TextField(_target.Name, out _target.Name);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Data: ");
            if (GUILayout.Button(_target.Data, "MiniPopup"))
            {
                GenericMenu gm    = new GenericMenu();
                List <Type> types = GlobalTools.GetTypesInRunTimeAssemblies();
                gm.AddItem(new GUIContent("<None>"), _target.Data == "<None>", () =>
                {
                    Undo.RecordObject(target, "Set FSM Data Class");
                    _target.Data = "<None>";
                    HasChanged();
                });
                for (int i = 0; i < types.Count; i++)
                {
                    if (types[i].BaseType == typeof(FSMData))
                    {
                        int j = i;
                        gm.AddItem(new GUIContent(types[j].FullName), _target.Data == types[j].FullName, () =>
                        {
                            Undo.RecordObject(target, "Set FSM Data Class");
                            _target.Data = types[j].FullName;
                            HasChanged();
                        });
                    }
                }
                gm.ShowAsContext();
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUI.enabled = _target.DefaultStateName != "";
            GUILayout.Label("Default: " + _target.DefaultStateName);
            GUI.enabled = true;
            GUILayout.FlexibleSpace();
            GUI.enabled = _target.StateNames.Count > 0;
            if (GUILayout.Button("Set Default", "MiniPopup"))
            {
                GenericMenu gm = new GenericMenu();
                for (int i = 0; i < _target.StateNames.Count; i++)
                {
                    int j = i;
                    gm.AddItem(new GUIContent(_target.StateNames[j]), _target.DefaultStateName == _target.StateNames[j], () =>
                    {
                        Undo.RecordObject(target, "Set FSM Default State");
                        _target.DefaultState     = _target.States[j];
                        _target.DefaultStateName = _target.StateNames[j];
                        HasChanged();
                    });
                }
                gm.ShowAsContext();
            }
            GUI.enabled = true;
            GUILayout.EndHorizontal();

            for (int i = 0; i < _target.StateNames.Count; i++)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label(string.Format("{0}.{1}", i + 1, _target.StateNames[i]));
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Edit", "minibuttonleft"))
                {
                    if (_stateTypes.ContainsKey(_target.States[i]))
                    {
                        UnityEngine.Object classFile = AssetDatabase.LoadAssetAtPath(_stateTypes[_target.States[i]], typeof(TextAsset));
                        if (classFile)
                        {
                            AssetDatabase.OpenAsset(classFile);
                        }
                        else
                        {
                            GlobalTools.LogError("没有找到 " + _target.States[i] + " 脚本文件!");
                        }
                    }
                    else
                    {
                        GlobalTools.LogError("没有找到 " + _target.States[i] + " 脚本文件!");
                    }
                }
                if (GUILayout.Button("Delete", "minibuttonright"))
                {
                    Undo.RecordObject(target, "Delete FSM State");
                    if (_target.DefaultStateName == _target.StateNames[i])
                    {
                        _target.DefaultState     = "";
                        _target.DefaultStateName = "";
                    }

                    _target.States.RemoveAt(i);
                    _target.StateNames.RemoveAt(i);

                    if (_target.DefaultStateName == "" && _target.StateNames.Count > 0)
                    {
                        _target.DefaultState     = _target.States[0];
                        _target.DefaultStateName = _target.StateNames[0];
                    }
                    HasChanged();
                }
                GUILayout.EndHorizontal();
            }

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Add State", "MiniPopup"))
            {
                GenericMenu gm    = new GenericMenu();
                List <Type> types = GlobalTools.GetTypesInRunTimeAssemblies();
                for (int i = 0; i < types.Count; i++)
                {
                    if (types[i].BaseType == typeof(FiniteState))
                    {
                        int    j         = i;
                        string stateName = types[j].FullName;
                        FiniteStateNameAttribute fsmAtt = types[j].GetCustomAttribute <FiniteStateNameAttribute>();
                        if (fsmAtt != null)
                        {
                            stateName = fsmAtt.Name;
                        }

                        if (_target.States.Contains(types[j].FullName))
                        {
                            gm.AddDisabledItem(new GUIContent(stateName));
                        }
                        else
                        {
                            gm.AddItem(new GUIContent(stateName), false, () =>
                            {
                                Undo.RecordObject(target, "Add FSM State");
                                _target.States.Add(types[j].FullName);
                                _target.StateNames.Add(stateName);

                                if (_target.DefaultStateName == "")
                                {
                                    _target.DefaultState     = _target.States[0];
                                    _target.DefaultStateName = _target.StateNames[0];
                                }
                                HasChanged();
                            });
                        }
                    }
                }
                gm.ShowAsContext();
            }
            GUILayout.EndHorizontal();

            base.OnInspectorGUI();
        }
Beispiel #15
0
        protected override void OnInspectorDefaultGUI()
        {
            base.OnInspectorDefaultGUI();

            GUILayout.BeginHorizontal();
            EditorGUILayout.HelpBox("Network Manager, implementing basic network client with socket!", MessageType.Info);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            TextField(Target.ServerIP, out Target.ServerIP, "Server IP");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            IntField(Target.ServerPort, out Target.ServerPort, "Server Port");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            TextField(Target.ClientIP, out Target.ClientIP, "Client IP");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            IntField(Target.ClientPort, out Target.ClientPort, "Client Port");
            GUILayout.EndHorizontal();

            GUILayout.BeginVertical(EditorGlobalTools.Styles.Box);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Enabled Channels:");
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            for (int i = 0; i < Target.ChannelTypes.Count; i++)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label((i + 1) + "." + Target.ChannelTypes[i]);
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Delete", EditorStyles.miniButton))
                {
                    Undo.RecordObject(target, "Delete Channel");
                    Target.ChannelTypes.RemoveAt(i);
                    HasChanged();
                }
                GUILayout.EndHorizontal();
            }

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Add Channel", EditorGlobalTools.Styles.MiniPopup))
            {
                GenericMenu gm    = new GenericMenu();
                List <Type> types = GlobalTools.GetTypesInRunTimeAssemblies();
                for (int i = 0; i < types.Count; i++)
                {
                    if (types[i].IsSubclassOf(typeof(ProtocolChannelBase)))
                    {
                        int j = i;
                        if (Target.ChannelTypes.Contains(types[j].FullName))
                        {
                            gm.AddDisabledItem(new GUIContent(types[j].FullName));
                        }
                        else
                        {
                            gm.AddItem(new GUIContent(types[j].FullName), false, () =>
                            {
                                Undo.RecordObject(target, "Add Channel");
                                Target.ChannelTypes.Add(types[j].FullName);
                                HasChanged();
                            });
                        }
                    }
                }
                gm.ShowAsContext();
            }
            GUILayout.EndHorizontal();

            GUILayout.EndVertical();
        }
Beispiel #16
0
        private void DrawConnectors(Rect p_rect)
        {
            GUISkin skin = DashEditorCore.Skin;

            // Inputs
            int count = InputCount;
            for (int i = 0; i < count; i++)
            {
                bool isConnected = Graph.HasInputConnected(this, i);
                GUI.color = isConnected
                    ? DashEditorCore.EditorConfig.theme.ConnectorInputConnectedColor
                    : DashEditorCore.EditorConfig.theme.ConnectorInputDisconnectedColor;

                if (IsExecuting)
                    GUI.color = Color.cyan;

                var connectorRect = GetConnectorRect(true, i);
                
                if (GUI.Button(connectorRect, "", skin.GetStyle(isConnected ? "NodeConnectorOn" : "NodeConnectorOff")))
                {
                    if (Event.current.button == 0)
                    {
                        if (Graph.connectingNode != null && Graph.connectingNode != this)
                        {
                            Undo.RegisterCompleteObjectUndo(_graph, "Connect node");
                            Graph.Connect(this, i, Graph.connectingNode, Graph.connectingOutputIndex);
                            DashEditorCore.SetDirty();
                            Graph.connectingNode = null;
                        }
                    }
                }
            }
            
            // Outputs
            for (int i = 0; i < OutputCount; i++)
            {
                bool isConnected = Graph.HasOutputConnected(this, i);
                GUI.color = isConnected
                    ? DashEditorCore.EditorConfig.theme.ConnectorOutputConnectedColor
                    : DashEditorCore.EditorConfig.theme.ConnectorOutputDisconnectedColor;

                if (Graph.connectingNode == this && Graph.connectingOutputIndex == i)
                    GUI.color = Color.green;

                var connectorRect = GetConnectorRect(false, i);
                
                if (connectorRect.Contains(Event.current.mousePosition - new Vector2(p_rect.x, p_rect.y)))
                    GUI.color = Color.green;

                if (OutputLabels != null && OutputLabels.Length > i && DashEditorCore.DetailsVisible)
                {
                    GUIStyle style = new GUIStyle();
                    style.normal.textColor = Color.white;
                    style.alignment = TextAnchor.MiddleRight;
                    GUI.Label(new Rect(connectorRect.x - 100, connectorRect.y, 100, 20), OutputLabels[i], style);
                }

                if (GUI.Button(connectorRect, "", skin.GetStyle(isConnected ? "NodeConnectorOn" : "NodeConnectorOff")))
                {
                    Graph.connectingOutputIndex = i;
                    Graph.connectingNode = this;
                }
            }

            GUI.color = Color.white;
        }
        private void DoLockMesh(Transform t, bool recursive, int depth = 0)
        {
            if (t == null)
            {
                return;
            }

            if (recursive)
            {
                for (int i = 0; i < t.childCount; ++i)
                {
                    DoLockMesh(t.GetChild(i), recursive, depth + 1);
                }
            }

            var renderer = t.GetComponent <MudRenderer>();

            if (renderer == null)
            {
                return;
            }

            var prevMeshGenerationRenderableMeshMode = renderer.MeshGenerationRenderableMeshMode;

            if (MeshGenerationCreateNewObject.boolValue)
            {
                renderer.MeshGenerationRenderableMeshMode = MudRendererBase.RenderableMeshMode.MeshRenderer;
            }

            if (MeshGenerationCreateCollider.boolValue)
            {
                renderer.AddCollider(renderer.gameObject, false, null, MeshGenerationForceConvexCollider.boolValue, MeshGenerationCreateRigidBody.boolValue);
            }

            renderer.LockMesh(MeshGenerationAutoRigging.boolValue, false, null, (MudRendererBase.UVGenerationMode)MeshGenerationUVGeneration.intValue);

            if (MeshGenerationCreateNewObject.boolValue)
            {
                renderer.MeshGenerationRenderableMeshMode = prevMeshGenerationRenderableMeshMode;
            }

            if (GenerateMeshAssetByEditor.boolValue)
            {
                string rootFolder   = "Assets";
                string assetsFolder = "MudBun Generated Assets";
                string folderPath   = $"{rootFolder}/{assetsFolder}";
                string assetName    = renderer.GenerateMeshAssetByEditorName;

                if (!AssetDatabase.IsValidFolder(folderPath))
                {
                    AssetDatabase.CreateFolder(rootFolder, assetsFolder);
                }

                Mesh     mesh                = null;
                Material mat                 = null;
                var      meshFilter          = renderer.GetComponent <MeshFilter>();
                var      meshRenderer        = renderer.GetComponent <MeshRenderer>();
                var      skinnedMeshRenderer = renderer.GetComponent <SkinnedMeshRenderer>();
                if (meshRenderer != null)
                {
                    if (meshFilter != null)
                    {
                        mesh = meshFilter.sharedMesh;
                    }
                    mat = meshRenderer.sharedMaterial;
                }
                else if (skinnedMeshRenderer != null)
                {
                    mesh = skinnedMeshRenderer.sharedMesh;
                    mat  = skinnedMeshRenderer.sharedMaterial;
                }

                if (mesh != null)
                {
                    string meshAssetPath = $"{folderPath}/{assetName}.mesh";
                    AssetDatabase.CreateAsset(mesh, meshAssetPath);
                    AssetDatabase.Refresh();

                    Debug.Log($"MudBun: Saved mesh asset - \"{folderPath}/{assetName}.mesh\"");

                    // somehow serialized properties get invalidated after asset database operations
                    InitSerializedProperties();

                    var savedMesh = AssetDatabase.LoadAssetAtPath <Mesh>(meshAssetPath);
                    if (savedMesh != null)
                    {
                        if (meshFilter != null)
                        {
                            meshFilter.sharedMesh = savedMesh;
                        }
                    }
                }

                if (mat != null)
                {
                    if (meshRenderer != null)
                    {
                        meshRenderer.sharedMaterial = mat;
                    }
                    else if (skinnedMeshRenderer != null)
                    {
                        skinnedMeshRenderer.sharedMaterial = mat;
                    }
                }
            }

            if (depth == 0 &&
                MeshGenerationCreateNewObject.boolValue)
            {
                var clone = Instantiate(renderer.gameObject);
                clone.name = renderer.name + " (Locked Mesh Clone)";

                if (MeshGenerationAutoRigging.boolValue)
                {
                    var cloneRenderer = clone.GetComponent <MudRenderer>();
                    cloneRenderer.RescanBrushersImmediate();
                    cloneRenderer.DestoryAllBrushesImmediate();
                }
                else
                {
                    DestroyAllChildren(clone.transform);
                }

                Undo.RegisterCreatedObjectUndo(clone, clone.name);
                DestroyImmediate(clone.GetComponent <MudRenderer>());
                Selection.activeObject = clone;

                renderer.UnlockMesh();
            }
        }
Beispiel #18
0
 public void AddUndo(Undo u)
 {
     undo.AddFirst(u);
     if (undo.Count > 100) undo.RemoveLast();
     redo.Clear();
     UpdateUndoButtons();
 }
        void InitializeBakingSetList()
        {
            m_BakingSets                     = new ReorderableList(sceneData.bakingSets, typeof(ProbeVolumeSceneData.BakingSet), false, false, true, true);
            m_BakingSets.multiSelect         = false;
            m_BakingSets.drawElementCallback = (rect, index, active, focused) =>
            {
                // Draw the renamable label for the baking set name
                string key = k_RenameFocusKey + index;
                if (Event.current.type == EventType.MouseDown && GUI.GetNameOfFocusedControl() != key)
                {
                    m_RenameSelectedBakingSet = false;
                }
                if (Event.current.type == EventType.MouseDown && Event.current.clickCount == 2)
                {
                    if (rect.Contains(Event.current.mousePosition))
                    {
                        m_RenameSelectedBakingSet = true;
                    }
                }
                if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
                {
                    m_RenameSelectedBakingSet = false;
                }

                var set = sceneData.bakingSets[index];

                if (m_RenameSelectedBakingSet)
                {
                    EditorGUI.BeginChangeCheck();
                    GUI.SetNextControlName(key);
                    set.name = EditorGUI.DelayedTextField(rect, set.name, EditorStyles.boldLabel);
                    if (EditorGUI.EndChangeCheck())
                    {
                        m_RenameSelectedBakingSet = false;

                        // Rename profile asset to match name:
                        AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(set.profile), set.name);
                        set.profile.name = set.name;
                    }
                }
                else
                {
                    EditorGUI.LabelField(rect, set.name, EditorStyles.boldLabel);
                }
            };
            m_BakingSets.elementHeightCallback = _ => EditorGUIUtility.singleLineHeight;
            m_BakingSets.onSelectCallback      = OnBakingSetSelected;

            m_BakingSets.onAddCallback = (list) =>
            {
                Undo.RegisterCompleteObjectUndo(sceneData.parentAsset, "Added new baking set");
                sceneData.CreateNewBakingSet("New Baking Set");
                UpdateSceneData();
                OnBakingSetSelected(list);
            };

            m_BakingSets.onRemoveCallback = (list) =>
            {
                if (m_BakingSets.count == 1)
                {
                    EditorUtility.DisplayDialog("Can't delete baking set", "You can't delete the last Baking set. You need to have at least one.", "Ok");
                    return;
                }
                if (EditorUtility.DisplayDialog("Delete the selected baking set?", $"Deleting the baking set will also delete it's profile asset on disk.\nDo you really want to delete the baking set '{sceneData.bakingSets[list.index].name}'?\n\nYou cannot undo the delete assets action.", "Yes", "Cancel"))
                {
                    var pathToDelete = AssetDatabase.GetAssetPath(sceneData.bakingSets[list.index].profile);
                    if (!String.IsNullOrEmpty(pathToDelete))
                    {
                        AssetDatabase.DeleteAsset(pathToDelete);
                    }
                    Undo.RegisterCompleteObjectUndo(sceneData.parentAsset, "Deleted baking set");
                    ReorderableList.defaultBehaviours.DoRemoveButton(list);
                    UpdateSceneData();
                    // A new set will be selected automatically, so we perform the same operations as if we did the selection explicitly.
                    OnBakingSetSelected(m_BakingSets);
                }
            };

            m_BakingSets.index = Mathf.Clamp(EditorPrefs.GetInt(k_SelectedBakingSetKey, 0), 0, m_BakingSets.count - 1);

            OnBakingSetSelected(m_BakingSets);
        }
Beispiel #20
0
 //////////////////////////////////////////////////////////////////////////
 // Undo
 //////////////////////////////////////////////////////////////////////////
 /// <summary>
 /// Pushback a token which will be the next read.
 /// </summary>
 public void undo(int type, object val, int line)
 {
     if (m_undo != null) throw new System.InvalidOperationException("only one pushback supported");
       m_undo = new Undo(type, val, line);
 }
        void InitializeBakingStatesList()
        {
            m_BakingStates                       = new ReorderableList(GetCurrentBakingSet().bakingStates, typeof(string), true, false, true, true);
            m_BakingStates.multiSelect           = false;
            m_BakingStates.elementHeightCallback = _ => EditorGUIUtility.singleLineHeight;
            m_BakingStates.drawElementCallback   = (rect, index, active, focused) =>
            {
                var bakingSet = GetCurrentBakingSet();

                // Status
                var status = bakingStatesStatuses[index];
                if (status != BakingStateStatus.Valid)
                {
                    var  label       = Styles.bakingStateStatusLabel[(int)status];
                    var  style       = status == BakingStateStatus.OutOfDate ? Styles.labelRed : EditorStyles.label;
                    Rect invalidRect = new Rect(rect)
                    {
                        xMin = rect.xMax - style.CalcSize(label).x - 3
                    };
                    rect.xMax = invalidRect.xMin;

                    using (new EditorGUI.DisabledScope(status != BakingStateStatus.OutOfDate))
                        EditorGUI.LabelField(invalidRect, label, style);
                }

                // Event
                string key = k_RenameFocusKey + index;
                if (Event.current.type == EventType.MouseDown && GUI.GetNameOfFocusedControl() != key)
                {
                    m_RenameSelectedBakingState = false;
                }
                if (Event.current.type == EventType.MouseDown && Event.current.clickCount == 2)
                {
                    if (rect.Contains(Event.current.mousePosition))
                    {
                        m_RenameSelectedBakingState = true;
                    }
                }
                if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
                {
                    m_RenameSelectedBakingState = false;
                }

                // Name
                var stateName = bakingSet.bakingStates[index];
                if (!m_RenameSelectedBakingState || !active)
                {
                    EditorGUI.LabelField(rect, stateName);
                }
                else
                {
                    // Renaming
                    EditorGUI.BeginChangeCheck();
                    GUI.SetNextControlName(key);
                    var name = EditorGUI.DelayedTextField(rect, stateName, EditorStyles.boldLabel);
                    if (EditorGUI.EndChangeCheck())
                    {
                        m_RenameSelectedBakingState = false;
                        if (AllSetScenesAreLoaded() || EditorUtility.DisplayDialog("Rename Baking State", "Some scenes in the baking set contain probe volumes but are not loaded.\nRenaming the baking state may require you to rebake the scene.", "Rename", "Cancel"))
                        {
                            try
                            {
                                AssetDatabase.StartAssetEditing();

                                foreach (var data in ProbeReferenceVolume.instance.perSceneDataList)
                                {
                                    if (bakingSet.sceneGUIDs.Contains(sceneData.GetSceneGUID(data.gameObject.scene)))
                                    {
                                        data.RenameBakingState(stateName, name);
                                    }
                                }
                                bakingSet.bakingStates[index]             = name;
                                ProbeReferenceVolume.instance.bakingState = name;
                            }
                            finally
                            {
                                AssetDatabase.StopAssetEditing();
                                foreach (var data in ProbeReferenceVolume.instance.perSceneDataList)
                                {
                                    data.ResolveCells();
                                }
                            }
                        }
                    }
                }
            };

            m_BakingStates.onSelectCallback = (ReorderableList list) =>
            {
                ProbeReferenceVolume.instance.bakingState = GetCurrentBakingSet().bakingStates[list.index];
                SceneView.RepaintAll();
                Repaint();
            };

            m_BakingStates.onReorderCallback = (ReorderableList list) => UpdateBakingStatesStatuses();

            m_BakingStates.onAddCallback = (list) =>
            {
                Undo.RegisterCompleteObjectUndo(sceneData.parentAsset, "Added new baking state");
                var state = GetCurrentBakingSet().CreateBakingState("New Baking State");
                m_BakingStates.index = GetCurrentBakingSet().bakingStates.IndexOf(state);
                m_BakingStates.onSelectCallback(m_BakingStates);
                UpdateBakingStatesStatuses();
            };

            m_BakingStates.onRemoveCallback = (list) =>
            {
                if (m_BakingStates.count == 1)
                {
                    EditorUtility.DisplayDialog("Can't delete baking state", "You can't delete the last Baking state. You need to have at least one.", "Ok");
                    return;
                }
                if (!EditorUtility.DisplayDialog("Delete the selected baking state?", $"Deleting the baking state will also delete corresponding baked data on disk.\nDo you really want to delete the baking state '{GetCurrentBakingSet().bakingStates[list.index]}'?\n\nYou cannot undo the delete assets action.", "Yes", "Cancel"))
                {
                    return;
                }
                var set   = GetCurrentBakingSet();
                var state = set.bakingStates[list.index];
                if (!set.RemoveBakingState(state))
                {
                    return;
                }
                try
                {
                    AssetDatabase.StartAssetEditing();
                    foreach (var data in ProbeReferenceVolume.instance.perSceneDataList)
                    {
                        if (set.sceneGUIDs.Contains(sceneData.GetSceneGUID(data.gameObject.scene)))
                        {
                            data.RemoveBakingState(state);
                        }
                    }
                }
                finally
                {
                    AssetDatabase.StopAssetEditing();
                    ProbeReferenceVolume.instance.bakingState = set.bakingStates[0];
                    UpdateBakingStatesStatuses();
                }
            };

            m_BakingStates.index = GetCurrentBakingSet().bakingStates.IndexOf(ProbeReferenceVolume.instance.bakingState);
            UpdateBakingStatesStatuses();
        }
Beispiel #22
0
    public override void OnInspectorGUI()
    {
        (this.target as CFX_SpawnSystem).hideObjectsInHierarchy = GUILayout.Toggle((this.target as CFX_SpawnSystem).hideObjectsInHierarchy, "Hide Preloaded Objects in Hierarchy");

        GUI.SetNextControlName("DragDropBox");
        EditorGUILayout.HelpBox("Drag GameObjects you want to preload here!\n\nTIP:\nUse the Inspector Lock at the top right to be able to drag multiple objects at once!", MessageType.None);

        for (int i = 0; i < (this.target as CFX_SpawnSystem).objectsToPreload.Length; i++)
        {
            GUILayout.BeginHorizontal();

            (this.target as CFX_SpawnSystem).objectsToPreload[i] = (GameObject)EditorGUILayout.ObjectField((this.target as CFX_SpawnSystem).objectsToPreload[i], typeof(GameObject), true);
            EditorGUILayout.LabelField(new GUIContent("times", "Number of times to copy the effect\nin the pool, i.e. the max number of\ntimes the object will be used\nsimultaneously"), GUILayout.Width(40));
            int nb = EditorGUILayout.IntField("", (this.target as CFX_SpawnSystem).objectsToPreloadTimes[i], GUILayout.Width(50));
            if (nb < 1)
            {
                nb = 1;
            }
            (this.target as CFX_SpawnSystem).objectsToPreloadTimes[i] = nb;

            if (GUI.changed)
            {
                EditorUtility.SetDirty(target);
            }

            if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(24)))
            {
                Object preloadedObject = (this.target as CFX_SpawnSystem).objectsToPreload[i];
                string objectName      = (preloadedObject == null) ? "" : preloadedObject.name;
                Undo.RecordObject(target, string.Format("Remove {0} from Spawn System", objectName));

                ArrayUtility.RemoveAt <GameObject>(ref (this.target as CFX_SpawnSystem).objectsToPreload, i);
                ArrayUtility.RemoveAt <int>(ref (this.target as CFX_SpawnSystem).objectsToPreloadTimes, i);

                EditorUtility.SetDirty(target);
            }

            GUILayout.EndHorizontal();
        }

        if (Event.current.type == EventType.DragPerform || Event.current.type == EventType.DragUpdated)
        {
            DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

            if (Event.current.type == EventType.DragPerform)
            {
                foreach (Object o in DragAndDrop.objectReferences)
                {
                    if (o is GameObject)
                    {
                        bool already = false;
                        foreach (GameObject otherObj in (this.target as CFX_SpawnSystem).objectsToPreload)
                        {
                            if (o == otherObj)
                            {
                                already = true;
                                Debug.LogWarning("CFX_SpawnSystem: Object has already been added: " + o.name);
                                break;
                            }
                        }

                        if (!already)
                        {
                            Undo.RecordObject(target, string.Format("Add {0} to Spawn System", o.name));

                            ArrayUtility.Add <GameObject>(ref (this.target as CFX_SpawnSystem).objectsToPreload, (GameObject)o);
                            ArrayUtility.Add <int>(ref (this.target as CFX_SpawnSystem).objectsToPreloadTimes, 1);

                            EditorUtility.SetDirty(target);
                        }
                    }
                }
            }
        }
    }
        void OnBakingSetSelected(ReorderableList list)
        {
            // Update left panel data
            EditorPrefs.SetInt(k_SelectedBakingSetKey, list.index);
            var set = GetCurrentBakingSet();

            m_ScenesInSet = new ReorderableList(set.sceneGUIDs, typeof(string), true, true, true, true);
            m_ScenesInSet.drawHeaderCallback  = (rect) => EditorGUI.LabelField(rect, "Scenes", EditorStyles.largeLabel);
            m_ScenesInSet.multiSelect         = true;
            m_ScenesInSet.drawElementCallback = (rect, index, active, focused) =>
            {
                float CalcLabelWidth(GUIContent c, GUIStyle s) => c.image ? s.CalcSize(c).x - c.image.width + rect.height : s.CalcSize(c).x;

                var guid = set.sceneGUIDs[index];
                // Find scene name from GUID:
                var scene = FindSceneData(guid);

                var  sceneLabel     = (scene.asset != null) ? new GUIContent(scene.asset.name, Styles.sceneIcon) : Styles.sceneNotFound;
                Rect sceneLabelRect = new Rect(rect)
                {
                    width = CalcLabelWidth(sceneLabel, EditorStyles.boldLabel)
                };
                EditorGUI.LabelField(sceneLabelRect, sceneLabel, EditorStyles.boldLabel);
                if (Event.current.type == EventType.MouseDown && sceneLabelRect.Contains(Event.current.mousePosition))
                {
                    EditorGUIUtility.PingObject(scene.asset);
                }

                // display the probe volume icon in the scene if it have one
                Rect probeVolumeIconRect = rect;
                probeVolumeIconRect.xMin = rect.xMax - k_ProbeVolumeIconSize;
                if (sceneData.hasProbeVolumes.TryGetValue(scene.guid, out bool hasProbeVolumes) && hasProbeVolumes)
                {
                    EditorGUI.LabelField(probeVolumeIconRect, new GUIContent(Styles.probeVolumeIcon));
                }

                // Display the lighting settings of the first scene (it will be used for baking)
                if (index == 0)
                {
                    var   lightingLabel        = Styles.sceneLightingSettings;
                    float middle               = (sceneLabelRect.xMax + probeVolumeIconRect.xMin) * 0.5f;
                    Rect  lightingSettingsRect = new Rect(rect)
                    {
                        xMin = middle - CalcLabelWidth(lightingLabel, EditorStyles.label) * 0.5f
                    };
                    EditorGUI.LabelField(lightingSettingsRect, lightingLabel);
                }
            };
            m_ScenesInSet.onAddCallback = (list) =>
            {
                // TODO: replace this generic menu by a mini-window with a search bar
                var menu = new GenericMenu();

                RefreshSceneAssets();
                foreach (var scene in m_ScenesInProject)
                {
                    if (set.sceneGUIDs.Contains(scene.guid))
                    {
                        continue;
                    }

                    menu.AddItem(new GUIContent(scene.asset.name), false, () =>
                    {
                        TryAddScene(scene);
                    });
                }

                if (menu.GetItemCount() == 0)
                {
                    menu.AddDisabledItem(new GUIContent("No available scenes"));
                }

                menu.ShowAsContext();
            };
            m_ScenesInSet.onRemoveCallback = (list) =>
            {
                Undo.RegisterCompleteObjectUndo(sceneData.parentAsset, "Deleted scene in baking set");
                ReorderableList.defaultBehaviours.DoRemoveButton(list);
                UpdateSceneData(); // Should not be needed on top of the Update call.
                UpdateBakingStatesStatuses();
            };

            void TryAddScene(SceneData scene)
            {
                // Don't allow the same scene in two different sets
                Undo.RegisterCompleteObjectUndo(sceneData.parentAsset, "Added scene in baking set");
                var setWithScene = sceneData.bakingSets.FirstOrDefault(s => s.sceneGUIDs.Contains(scene.guid));

                if (setWithScene != null)
                {
                    if (EditorUtility.DisplayDialog("Move Scene to baking set", $"The scene '{scene.asset.name}' was already added in the baking set '{setWithScene.name}'. Do you want to move it to the current set?", "Yes", "Cancel"))
                    {
                        setWithScene.sceneGUIDs.Remove(scene.guid);
                        set.sceneGUIDs.Add(scene.guid);
                    }
                }
                else
                {
                    set.sceneGUIDs.Add(scene.guid);
                }

                sceneData.SyncBakingSetSettings();
                UpdateSceneData();
                UpdateBakingStatesStatuses();
            }

            InitializeBakingStatesList();
        }
Beispiel #24
0
		protected override void Editor_OnGUI(Rect rect, SerializedProperty property, GUIContent label)
		{
			if (_target == null)
			{
				_target = property.serializedObject.targetObject;
				_undoString = _target.ToString();
				_propertyInfo = Reflection.GetPropertyInfo(_target, _propertyName);

				if (_propertyInfo == null)
				{
					EditorGUI.LabelField(rect, label.text, "Can not find property.");
				}
				else if (drawer.fieldInfo.FieldType != _propertyInfo.PropertyType)
				{
					_propertyInfo = null;
					EditorGUI.LabelField(rect, label.text, "Property type is not same as field.");
				}
				else if (!_propertyInfo.CanRead || !_propertyInfo.CanWrite)
				{
					_propertyInfo = null;
					EditorGUI.LabelField(rect, label.text, "Property can not read or write.");
				}
			}

			if (_propertyInfo == null) return;

			EditorGUI.BeginChangeCheck();
			object value = _propertyInfo.GetValue(_target, null);

			switch (property.propertyType)
			{
				case SerializedPropertyType.AnimationCurve:
					{
						value = EditorGUI.CurveField(rect, label, (AnimationCurve)value);
						break;
					}
				case SerializedPropertyType.Boolean:
					{
						value = EditorGUI.Toggle(rect, label, (bool)value);
						break;
					}
				case SerializedPropertyType.Bounds:
					{
						value = EditorGUI.BoundsField(rect, label, (Bounds)value);
						break;
					}
				case SerializedPropertyType.Color:
					{
						value = EditorGUI.ColorField(rect, label, (Color)value);
						break;
					}
				case SerializedPropertyType.Enum:
					{
						value = EditorGUI.EnumPopup(rect, label, (Enum)value);
						break;
					}
				case SerializedPropertyType.Float:
					{
						value = EditorGUI.FloatField(rect, label, (float)value);
						break;
					}
				case SerializedPropertyType.Integer:
					{
						value = EditorGUI.IntField(rect, label, (int)value);
						break;
					}
				case SerializedPropertyType.ObjectReference:
					{
						value = EditorGUI.ObjectField(
							rect,
							label,
							value as UnityEngine.Object,
							_propertyInfo.PropertyType,
							!EditorUtility.IsPersistent(_target));
						break;
					}
				case SerializedPropertyType.Rect:
					{
						value = EditorGUI.RectField(rect, label, (Rect)value);
						break;
					}
				case SerializedPropertyType.String:
					{
						value = EditorGUI.TextField(rect, label, (string)value);
						break;
					}
				case SerializedPropertyType.Vector2:
					{
						value = EditorGUI.Vector2Field(rect, label, (Vector2)value);
						break;
					}
				case SerializedPropertyType.Vector3:
					{
						value = EditorGUI.Vector3Field(rect, label, (Vector3)value);
						break;
					}
				case SerializedPropertyType.Vector4:
					{
						value = EditorGUI.Vector4Field(rect, label.text, (Vector4)value);
						break;
					}
				default:
					{
						EditorGUI.LabelField(rect, label.text, "Type is not supported.");
						break;
					}
			}

			if (EditorGUI.EndChangeCheck())
			{
				Undo.RecordObject(_target, _undoString);
				_propertyInfo.SetValue(_target, value, null);
				EditorUtility.SetDirty(_target);
			}
		}
    void Input()
    {
        Event   guiEvent = Event.current;
        Vector3 mousePos = HandleUtility.GUIPointToWorldRay(guiEvent.mousePosition).origin;

        mousePos.z = 0;

        if (guiEvent.type == EventType.MouseDown && guiEvent.button == 0 && guiEvent.shift && !mode3D)
        {
            if (selectedSegmentIndex != -1)
            {
                Undo.RecordObject(creator, "Split segment");
                Path.SplitSegment(mousePos, selectedSegmentIndex);
            }
            else if (!Path.IsClosed)
            {
                Undo.RecordObject(creator, "Add segment");
                Path.AddSegment(mousePos);
            }
        }

        if (guiEvent.type == EventType.MouseDown && guiEvent.button == 1)
        {
            float minDstToAnchor     = creator.anchorDiameter * 2f;
            int   closestAnchorIndex = -1;

            for (int i = 0; i < Path.NumPoints; i += 3)
            {
                float dst = Vector3.Distance(mousePos, Path[i]);
                if (dst < minDstToAnchor)
                {
                    minDstToAnchor     = dst;
                    closestAnchorIndex = i;
                }
            }

            if (closestAnchorIndex != -1)
            {
                Undo.RecordObject(creator, "Delete segment");
                Path.DeleteSegment(closestAnchorIndex);
            }
        }

        if (guiEvent.type == EventType.MouseMove && !mode3D)
        {
            float minDstToSegment         = segmentSelectDistanceThreshold;
            int   newSelectedSegmentIndex = -1;

            for (int i = 0; i < Path.NumSegments; i++)
            {
                Vector3[] points = Path.GetPointsInSegment(i);
                float     dst    = HandleUtility.DistancePointBezier(mousePos, points[0], points[3], points[1], points[2]);
                if (dst < minDstToSegment)
                {
                    minDstToSegment         = dst;
                    newSelectedSegmentIndex = i;
                }
            }

            if (newSelectedSegmentIndex != selectedSegmentIndex)
            {
                selectedSegmentIndex = newSelectedSegmentIndex;
                HandleUtility.Repaint();
            }
        }

        HandleUtility.AddDefaultControl(0);
    }
Beispiel #26
0
        public void MoveBlock(short x, short y, short z, short x2, short y2, short z2, bool undo, bool physics, short priority)
        {
            if (!HCSettings.Building)
                return;

            if (!BlockInBounds(x, y, z) || !BlockInBounds(x2, y2, z2))
                return;

            //if ((0 > x || CWMap.SizeX <= x) || (0 > z || CWMap.SizeY <= z) || (0 > y || CWMap.SizeZ <= y) || (0 > x2 || CWMap.SizeX <= x2) || (0 > z2 || CWMap.SizeY <= z2) || (0 > y2 || CWMap.SizeZ <= y2))
            //    return;

            var block1 = GetBlock(x, y, z);
            var block2 = GetBlock(x2, y2, z2);

            SetBlockId(x, y, z, 0, -1);

            var pid = (short) (HCSettings.History ? History.GetLastPlayer(x, z, y) : -1);

            SetBlockId(x2, y2, z2, (byte)(block1.Id), pid);

            if (undo && HCSettings.History) {
                var lastPlayer = History.GetLastPlayer(x, z, y);
                NetworkClient client;

                ServerCore.Nh.IntLoggedClients.TryGetValue(lastPlayer, out client);

                if (client != null) {
                    if (client.CS.CurrentIndex == -1)
                        client.CS.CurrentIndex = 0;

                    if (client.CS.CurrentIndex != (client.CS.UndoObjects.Count - 1)) {
                        for (var i = client.CS.CurrentIndex; i < client.CS.UndoObjects.Count - 1; i++)
                            client.CS.UndoObjects.RemoveAt(i);
                    }

                    if (client.CS.UndoObjects.Count >= 50000)
                        client.CS.UndoObjects.RemoveAt(0);

                    var newUndo = new Undo {
                        X = x,
                        Y = y,
                        Z = z,
                        OldBlock = block1,
                        NewBlock = ServerCore.Blockholder.GetBlock(0)
                    };
                    var newUndo2 = new Undo {X = x2, Y = y2, Z = z2, OldBlock = block2, NewBlock = block1};

                    client.CS.UndoObjects.Add(newUndo);
                    client.CS.UndoObjects.Add(newUndo2);
                    client.CS.CurrentIndex = client.CS.UndoObjects.Count - 1;
                }
            }

            BlockchangeQueue.Enqueue(new QueueItem(x, y, z, priority));
            BlockchangeQueue.Enqueue(new QueueItem(x2, y2, z2, priority));

            if (!physics || !HCSettings.Physics)
                return;

            var randomGen = new Random();

            for (short ix = -1; ix < 2; ix++) {
                for (short iy = -1; iy < 2; iy++) {
                    for (short iz = -1; iz < 2; iz++) {

                        if (!BlockInBounds((short)(x + ix), (short)(y + iy), (short)(z + iz)))
                            continue;

                        if (!BlockInBounds((short)(x2 + ix), (short)(y2 + iy), (short)(z2 + iz)))
                            continue;

                        var index = BlockIndex(x + ix, y + iy, z + iz);
                        var index2 = BlockIndex(x2 + ix, y2 + iy, z2 + iz);

                        if ((_physicsBitmask[index / 8] & (1 << (index % 8))) != 0)
                            continue;

                        if ((_physicsBitmask[index2 / 8] & (1 << (index2 % 8))) != 0)
                            continue;

                        var blockQueue = GetBlock((short)(x + ix), (short)(y + iy), (short)(z + iz));
                        var blockQueue2 = GetBlock((short)(x2 + ix), (short)(y2 + iy), (short)(z2 + iz));

                        if (blockQueue.Physics > 0 || !string.IsNullOrEmpty(blockQueue.PhysicsPlugin)) {
                            _physicsBitmask[index / 8] = (byte)(_physicsBitmask[index / 8] | (1 << (index % 8)));
                            PhysicsQueue.Enqueue(new QueueItem((short) (x + ix), (short) (y + iy), (short) (z + iz),
                                DateTime.UtcNow.AddMilliseconds(blockQueue.PhysicsDelay +
                                                                randomGen.Next(blockQueue.PhysicsRandom))));
                        }

                        if (blockQueue2.Physics <= 0 && string.IsNullOrEmpty(blockQueue2.PhysicsPlugin))
                            continue;

                        _physicsBitmask[index2 / 8] = (byte)(_physicsBitmask[index2 / 8] | (1 << (index2 % 8)));
                        PhysicsQueue.Enqueue(new QueueItem((short)(x2 + ix), (short)(y2 + iy), (short)(z2 + iz), DateTime.UtcNow.AddMilliseconds(blockQueue2.PhysicsDelay + randomGen.Next(blockQueue2.PhysicsRandom))));
                    }
                }
            }
        }
        public GraphElementSearcherDatabase AddProperties(Type type, BindingFlags bindingFlags)
        {
            SearcherItem parent = null;

            foreach (PropertyInfo propertyInfo in type.GetProperties(bindingFlags)
                     .OrderBy(p => p.Name)
                     .Where(p => p.GetCustomAttribute <ObsoleteAttribute>() == null &&
                            p.GetCustomAttribute <HiddenAttribute>() == null))
            {
                var children = new List <SearcherItem>();

                if (propertyInfo.GetIndexParameters().Length > 0) // i.e : Vector2.this[int]
                {
                    children.Add(new GraphNodeModelSearcherItem(
                                     new PropertySearcherItemData(propertyInfo),
                                     data => data.CreateFunctionCallNode(propertyInfo.GetMethod),
                                     propertyInfo.Name
                                     ));
                }
                else
                {
                    if (propertyInfo.CanRead)
                    {
                        if (propertyInfo.GetMethod.IsStatic)
                        {
                            if (propertyInfo.CanWrite)
                            {
                                children.Add(new GraphNodeModelSearcherItem(
                                                 new PropertySearcherItemData(propertyInfo),
                                                 data => data.CreateFunctionCallNode(propertyInfo.GetMethod),
                                                 propertyInfo.Name
                                                 ));
                            }
                            else
                            {
                                children.Add(new GraphNodeModelSearcherItem(
                                                 new PropertySearcherItemData(propertyInfo),
                                                 data => data.CreateSystemConstantNode(type, propertyInfo),
                                                 propertyInfo.Name
                                                 ));
                            }
                        }
                        else
                        {
                            children.Add(new GraphNodeModelSearcherItem(
                                             new PropertySearcherItemData(propertyInfo),
                                             data =>
                            {
                                var getPropertyGroupModel = data.CreateGetPropertyGroupNode();
                                Undo.RegisterCompleteObjectUndo(getPropertyGroupModel.SerializableAsset, "Add Member");
                                getPropertyGroupModel.AddMember(propertyInfo.GetUnderlyingType(), propertyInfo.Name);
                                EditorUtility.SetDirty(getPropertyGroupModel.SerializableAsset);

                                return(getPropertyGroupModel);
                            },
                                             propertyInfo.Name
                                             ));
                        }
                    }

                    if (propertyInfo.CanWrite)
                    {
                        children.Add(new StackNodeModelSearcherItem(
                                         new PropertySearcherItemData(propertyInfo),
                                         data => data.CreateFunctionCallNode(propertyInfo.SetMethod),
                                         propertyInfo.Name
                                         ));
                    }
                }

                if (children.Count == 0)
                {
                    continue;
                }

                if (parent == null)
                {
                    parent = SearcherItemUtility.GetItemFromPath(Items, type.FriendlyName(false));
                }

                foreach (SearcherItem child in children)
                {
                    parent.AddChild(child);
                }
            }

            return(this);
        }
Beispiel #28
0
        void DrawBezierPathInspector()
        {
            using (var check = new EditorGUI.ChangeCheckScope()) {
                // Path options:
                data.showPathOptions = EditorGUILayout.Foldout(data.showPathOptions, new GUIContent("Bézier Path Options"), true, boldFoldoutStyle);
                if (data.showPathOptions)
                {
                    bezierPath.Space            = (PathSpace)EditorGUILayout.Popup("Space", (int)bezierPath.Space, spaceNames);
                    bezierPath.ControlPointMode = (BezierPath.ControlMode)EditorGUILayout.EnumPopup(new GUIContent("Control Mode"), bezierPath.ControlPointMode);
                    if (bezierPath.ControlPointMode == BezierPath.ControlMode.Automatic)
                    {
                        bezierPath.AutoControlLength = EditorGUILayout.Slider(new GUIContent("Control Spacing"), bezierPath.AutoControlLength, 0, 1);
                    }

                    bezierPath.IsClosed    = EditorGUILayout.Toggle("Closed Path", bezierPath.IsClosed);
                    data.showTransformTool = EditorGUILayout.Toggle(new GUIContent("Enable Transforms"), data.showTransformTool);

                    Tools.hidden = !data.showTransformTool;

                    // Check if out of bounds (can occur after undo operations)
                    if (handleIndexToDisplayAsTransform >= bezierPath.NumPoints)
                    {
                        handleIndexToDisplayAsTransform = -1;
                    }

                    // If a point has been selected
                    if (handleIndexToDisplayAsTransform != -1)
                    {
                        EditorGUILayout.LabelField("Selected Point:");

                        using (new EditorGUI.IndentLevelScope()) {
                            var currentPosition = creator.bezierPath[handleIndexToDisplayAsTransform];
                            var newPosition     = EditorGUILayout.Vector3Field("Position", currentPosition);
                            if (newPosition != currentPosition)
                            {
                                Undo.RecordObject(creator, "Move point");
                                creator.bezierPath.MovePoint(handleIndexToDisplayAsTransform, newPosition);
                            }
                            // Don't draw the angle field if we aren't selecting an anchor point/not in 3d space
                            if (handleIndexToDisplayAsTransform % 3 == 0 && creator.bezierPath.Space == PathSpace.xyz)
                            {
                                var anchorIndex  = handleIndexToDisplayAsTransform / 3;
                                var currentAngle = creator.bezierPath.GetAnchorNormalAngle(anchorIndex);
                                var newAngle     = EditorGUILayout.FloatField("Angle", currentAngle);
                                if (newAngle != currentAngle)
                                {
                                    Undo.RecordObject(creator, "Set Angle");
                                    creator.bezierPath.SetAnchorNormalAngle(anchorIndex, newAngle);
                                }
                            }
                        }
                    }

                    if (data.showTransformTool & (handleIndexToDisplayAsTransform == -1))
                    {
                        if (GUILayout.Button("Centre Transform"))
                        {
                            Vector3 worldCentre  = bezierPath.CalculateBoundsWithTransform(creator.transform).center;
                            Vector3 transformPos = creator.transform.position;
                            if (bezierPath.Space == PathSpace.xy)
                            {
                                transformPos = new Vector3(transformPos.x, transformPos.y, 0);
                            }
                            else if (bezierPath.Space == PathSpace.xz)
                            {
                                transformPos = new Vector3(transformPos.x, 0, transformPos.z);
                            }
                            Vector3 worldCentreToTransform = transformPos - worldCentre;

                            if (worldCentre != creator.transform.position)
                            {
                                //Undo.RecordObject (creator, "Centralize Transform");
                                if (worldCentreToTransform != Vector3.zero)
                                {
                                    Vector3 localCentreToTransform = MathUtility.InverseTransformVector(worldCentreToTransform, creator.transform, bezierPath.Space);
                                    for (int i = 0; i < bezierPath.NumPoints; i++)
                                    {
                                        bezierPath.SetPoint(i, bezierPath.GetPoint(i) + localCentreToTransform, true);
                                    }
                                }

                                creator.transform.position = worldCentre;
                                bezierPath.NotifyPathModified();
                            }
                        }
                    }

                    if (GUILayout.Button("Reset Path"))
                    {
                        Undo.RecordObject(creator, "Reset Path");
                        bool in2DEditorMode = EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D;
                        data.ResetBezierPath(creator.transform.position, in2DEditorMode);
                        EditorApplication.QueuePlayerLoopUpdate();
                    }

                    GUILayout.Space(inspectorSectionSpacing);
                }

                data.showNormals = EditorGUILayout.Foldout(data.showNormals, new GUIContent("Normals Options"), true, boldFoldoutStyle);
                if (data.showNormals)
                {
                    bezierPath.FlipNormals = EditorGUILayout.Toggle(new GUIContent("Flip Normals"), bezierPath.FlipNormals);
                    if (bezierPath.Space == PathSpace.xyz)
                    {
                        bezierPath.GlobalNormalsAngle = EditorGUILayout.Slider(new GUIContent("Global Angle"), bezierPath.GlobalNormalsAngle, 0, 360);

                        if (GUILayout.Button("Reset Normals"))
                        {
                            Undo.RecordObject(creator, "Reset Normals");
                            bezierPath.FlipNormals = false;
                            bezierPath.ResetNormalAngles();
                        }
                    }
                    GUILayout.Space(inspectorSectionSpacing);
                }

                // Editor display options
                data.showDisplayOptions = EditorGUILayout.Foldout(data.showDisplayOptions, new GUIContent("Display Options"), true, boldFoldoutStyle);
                if (data.showDisplayOptions)
                {
                    data.showPathBounds       = GUILayout.Toggle(data.showPathBounds, new GUIContent("Show Path Bounds"));
                    data.showPerSegmentBounds = GUILayout.Toggle(data.showPerSegmentBounds, new GUIContent("Show Segment Bounds"));
                    data.displayAnchorPoints  = GUILayout.Toggle(data.displayAnchorPoints, new GUIContent("Show Anchor Points"));
                    if (!(bezierPath.ControlPointMode == BezierPath.ControlMode.Automatic && globalDisplaySettings.hideAutoControls))
                    {
                        data.displayControlPoints = GUILayout.Toggle(data.displayControlPoints, new GUIContent("Show Control Points"));
                    }
                    data.keepConstantHandleSize = GUILayout.Toggle(data.keepConstantHandleSize, new GUIContent("Constant Point Size", constantSizeTooltip));
                    data.bezierHandleScale      = Mathf.Max(0, EditorGUILayout.FloatField(new GUIContent("Handle Scale"), data.bezierHandleScale));
                    DrawGlobalDisplaySettingsInspector();
                }

                if (check.changed)
                {
                    SceneView.RepaintAll();
                    EditorApplication.QueuePlayerLoopUpdate();
                }
            }
        }
Beispiel #29
0
    /// <summary>
    /// Handles & interaction.
    /// </summary>

    public void OnSceneGUI()
    {
        if (Selection.objects.Length > 1)
        {
            return;
        }

        UICamera cam = UICamera.FindCameraForLayer(mPanel.gameObject.layer);

#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
        if (cam == null || !cam.cachedCamera.isOrthoGraphic)
        {
            return;
        }
#else
        if (cam == null || !cam.cachedCamera.orthographic)
        {
            return;
        }
#endif

        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);
        Transform t    = mPanel.cachedTransform;

        Vector3[] handles = UIWidgetInspector.GetHandles(mPanel.worldCorners);

        // Time to figure out what kind of action is underneath the mouse
        UIWidgetInspector.Action actionUnderMouse = mAction;

        Color handlesColor = new Color(0.5f, 0f, 0.5f);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        if (mPanel.isAnchored)
        {
            UIWidgetInspector.DrawAnchorHandle(mPanel.leftAnchor, mPanel.cachedTransform, handles, 0, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.topAnchor, mPanel.cachedTransform, handles, 1, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.rightAnchor, mPanel.cachedTransform, handles, 2, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.bottomAnchor, mPanel.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mPanel) && mPanel.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, Mathf.RoundToInt(mPanel.width), Mathf.RoundToInt(mPanel.height));
            }
        }

        bool canResize = (mPanel.clipping != UIDrawCall.Clipping.None);

        // NOTE: Remove this part when it's possible to neatly resize rotated anchored panels.
        if (canResize && mPanel.isAnchored)
        {
            Quaternion rot = mPanel.cachedTransform.localRotation;
            if (Quaternion.Angle(rot, Quaternion.identity) > 0.01f)
            {
                canResize = false;
            }
        }

        bool[] resizable = new bool[8];

        resizable[4] = canResize;                    // left
        resizable[5] = canResize;                    // top
        resizable[6] = canResize;                    // right
        resizable[7] = canResize;                    // bottom

        resizable[0] = resizable[7] && resizable[4]; // bottom-left
        resizable[1] = resizable[5] && resizable[4]; // top-left
        resizable[2] = resizable[5] && resizable[6]; // top-right
        resizable[3] = resizable[7] && resizable[6]; // bottom-right

        UIWidget.Pivot pivotUnderMouse = UIWidgetInspector.GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], id, resizable[i]);
                    }

                    if (Mathf.Abs(v1.y - v0.y) > 80f)
                    {
                        if (mPanel.leftAnchor.target == null || mPanel.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], id, resizable[4]);
                        }

                        if (mPanel.rightAnchor.target == null || mPanel.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], id, resizable[6]);
                        }
                    }

                    if (Mathf.Abs(v3.x - v0.x) > 80f)
                    {
                        if (mPanel.topAnchor.target == null || mPanel.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], id, resizable[5]);
                        }

                        if (mPanel.bottomAnchor.target == null || mPanel.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], id, resizable[7]);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            if (actionUnderMouse != UIWidgetInspector.Action.None)
            {
                mStartMouse     = e.mousePosition;
                mAllowSelection = true;

                if (e.button == 1)
                {
                    if (e.modifiers == 0)
                    {
                        GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                        e.Use();
                    }
                }
                else if (e.button == 0 && actionUnderMouse != UIWidgetInspector.Action.None &&
                         UIWidgetInspector.Raycast(handles, out mStartDrag))
                {
                    mWorldPos             = t.position;
                    mLocalPos             = t.localPosition;
                    mStartRot             = t.localRotation.eulerAngles;
                    mStartDir             = mStartDrag - t.position;
                    mStartCR              = mPanel.baseClipRegion;
                    mDragPivot            = pivotUnderMouse;
                    mActionUnderMouse     = actionUnderMouse;
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == UIWidgetInspector.Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = UIWidgetInspector.Action.None;
                mAction           = UIWidgetInspector.Action.None;
            }
            else if (mAllowSelection)
            {
                List <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.Count > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != UIWidgetInspector.Action.None || mActionUnderMouse != UIWidgetInspector.Action.None)
                {
                    Vector3 pos;

                    if (UIWidgetInspector.Raycast(handles, out pos))
                    {
                        if (mAction == UIWidgetInspector.Action.None && mActionUnderMouse != UIWidgetInspector.Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == UIWidgetInspector.Action.Move)
                                {
                                    NGUISnap.Recalculate(mPanel);
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Scale)
                                {
                                    mStartCR   = mPanel.baseClipRegion;
                                    mDragPivot = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != UIWidgetInspector.Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mPanel);

                            if (mAction == UIWidgetInspector.Action.Move)
                            {
                                Vector3 before      = t.position;
                                Vector3 beforeLocal = t.localPosition;
                                t.position = mWorldPos + (pos - mStartDrag);
                                pos        = NGUISnap.Snap(t.localPosition, mPanel.localCorners,
                                                           e.modifiers != EventModifiers.Control) - beforeLocal;
                                t.position = before;

                                NGUIMath.MoveRect(mPanel, pos.x, pos.y);
                            }
                            else if (mAction == UIWidgetInspector.Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == UIWidgetInspector.Action.Scale)
                            {
                                // World-space delta since the drag started
                                Vector3 delta = pos - mStartDrag;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                AdjustClipping(mPanel, mLocalPos, mStartCR, delta, mDragPivot);
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != UIWidgetInspector.Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = UIWidgetInspector.Action.None;
                    mAction           = UIWidgetInspector.Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Beispiel #30
0
        void DrawHandle(int i)
        {
            Vector3 handlePosition = MathUtility.TransformPoint(bezierPath[i], creator.transform, bezierPath.Space);

            float anchorHandleSize  = GetHandleDiameter(globalDisplaySettings.anchorSize * data.bezierHandleScale, bezierPath[i]);
            float controlHandleSize = GetHandleDiameter(globalDisplaySettings.controlSize * data.bezierHandleScale, bezierPath[i]);

            bool  isAnchorPoint     = i % 3 == 0;
            bool  isInteractive     = isAnchorPoint || bezierPath.ControlPointMode != BezierPath.ControlMode.Automatic;
            float handleSize        = (isAnchorPoint) ? anchorHandleSize : controlHandleSize;
            bool  doTransformHandle = i == handleIndexToDisplayAsTransform;

            PathHandle.HandleColours handleColours = (isAnchorPoint) ? splineAnchorColours : splineControlColours;
            if (i == handleIndexToDisplayAsTransform)
            {
                handleColours.defaultColour = (isAnchorPoint) ? globalDisplaySettings.anchorSelected : globalDisplaySettings.controlSelected;
            }
            var cap = capFunctions[(isAnchorPoint) ? globalDisplaySettings.anchorShape : globalDisplaySettings.controlShape];

            PathHandle.HandleInputType handleInputType;
            handlePosition = PathHandle.DrawHandle(handlePosition, bezierPath.Space, isInteractive, handleSize, cap, handleColours, out handleInputType, i);

            if (doTransformHandle)
            {
                // Show normals rotate tool
                if (data.showNormals && Tools.current == Tool.Rotate && isAnchorPoint && bezierPath.Space == PathSpace.xyz)
                {
                    Handles.color = handlesStartCol;

                    int     attachedControlIndex = (i == bezierPath.NumPoints - 1) ? i - 1 : i + 1;
                    Vector3 dir             = (bezierPath[attachedControlIndex] - handlePosition).normalized;
                    float   handleRotOffset = (360 + bezierPath.GlobalNormalsAngle) % 360;
                    anchorAngleHandle.radius = handleSize * 3;
                    anchorAngleHandle.angle  = handleRotOffset + bezierPath.GetAnchorNormalAngle(i / 3);
                    Vector3   handleDirection = Vector3.Cross(dir, Vector3.up);
                    Matrix4x4 handleMatrix    = Matrix4x4.TRS(
                        handlePosition,
                        Quaternion.LookRotation(handleDirection, dir),
                        Vector3.one
                        );

                    using (new Handles.DrawingScope(handleMatrix)) {
                        // draw the handle
                        EditorGUI.BeginChangeCheck();
                        anchorAngleHandle.DrawHandle();
                        if (EditorGUI.EndChangeCheck())
                        {
                            Undo.RecordObject(creator, "Set angle");
                            bezierPath.SetAnchorNormalAngle(i / 3, anchorAngleHandle.angle - handleRotOffset);
                        }
                    }
                }
                else
                {
                    handlePosition = Handles.DoPositionHandle(handlePosition, Quaternion.identity);
                }
            }

            switch (handleInputType)
            {
            case PathHandle.HandleInputType.LMBDrag:
                draggingHandleIndex             = i;
                handleIndexToDisplayAsTransform = -1;
                Repaint();
                break;

            case PathHandle.HandleInputType.LMBRelease:
                draggingHandleIndex             = -1;
                handleIndexToDisplayAsTransform = -1;
                Repaint();
                break;

            case PathHandle.HandleInputType.LMBClick:
                draggingHandleIndex = -1;
                if (Event.current.shift)
                {
                    handleIndexToDisplayAsTransform = -1;     // disable move tool if new point added
                }
                else
                {
                    if (handleIndexToDisplayAsTransform == i)
                    {
                        handleIndexToDisplayAsTransform = -1;     // disable move tool if clicking on point under move tool
                    }
                    else
                    {
                        handleIndexToDisplayAsTransform = i;
                    }
                }
                Repaint();
                break;

            case PathHandle.HandleInputType.LMBPress:
                if (handleIndexToDisplayAsTransform != i)
                {
                    handleIndexToDisplayAsTransform = -1;
                    Repaint();
                }
                break;
            }

            Vector3 localHandlePosition = MathUtility.InverseTransformPoint(handlePosition, creator.transform, bezierPath.Space);

            if (bezierPath[i] != localHandlePosition)
            {
                Undo.RecordObject(creator, "Move point");
                bezierPath.MovePoint(i, localHandlePosition);
            }
        }
 //----------------------------------------------------------------------------------
 public override bool RemoveNodeFromFields(CommandNode node)
 {
     Undo.RecordObject(Data, "CaronteFX - Remove node from fields");
     return(Data.Field.RemoveNode(node));
 }
Beispiel #32
0
	public override void OnGUI (Rect rect, SerializedProperty prop, GUIContent label)
	{
		Undo.RecordObject(prop.serializedObject.targetObject, "Delegate Selection");

		SerializedProperty targetProp = prop.FindPropertyRelative("mTarget");
		SerializedProperty methodProp = prop.FindPropertyRelative("mMethodName");

		MonoBehaviour target = targetProp.objectReferenceValue as MonoBehaviour;
		string methodName = methodProp.stringValue;

		EditorGUI.indentLevel = prop.depth;
		EditorGUI.LabelField(rect, label);

		Rect lineRect = rect;
		lineRect.yMin = rect.yMin + lineHeight;
		lineRect.yMax = lineRect.yMin + lineHeight;

		EditorGUI.indentLevel = targetProp.depth;
		target = EditorGUI.ObjectField(lineRect, "Notify", target, typeof(MonoBehaviour), true) as MonoBehaviour;
		targetProp.objectReferenceValue = target;

		if (target != null && target.gameObject != null)
		{
			GameObject go = target.gameObject;
			List<Entry> list = EventDelegateEditor.GetMethods(go);

			int index = 0;
			int choice = 0;

			EventDelegate del = new EventDelegate();
			del.target = target;
			del.methodName = methodName;
			string[] names = PropertyReferenceDrawer.GetNames(list, del.ToString(), out index);

			lineRect.yMin += lineHeight;
			lineRect.yMax += lineHeight;
			choice = EditorGUI.Popup(lineRect, "Method", index, names);

			if (choice > 0 && choice != index)
			{
				Entry entry = list[choice - 1];
				target = entry.target as MonoBehaviour;
				methodName = entry.name;
				targetProp.objectReferenceValue = target;
				methodProp.stringValue = methodName;
			}

			SerializedProperty paramArrayProp = prop.FindPropertyRelative("mParameters");
			EventDelegate.Parameter[] ps = del.parameters;

			if (ps != null)
			{
				paramArrayProp.arraySize = ps.Length;
				for (int i = 0; i < ps.Length; i++)
				{
					EventDelegate.Parameter param = ps[i];
					SerializedProperty paramProp = paramArrayProp.GetArrayElementAtIndex(i);
					SerializedProperty objProp = paramProp.FindPropertyRelative("obj");
					SerializedProperty fieldProp = paramProp.FindPropertyRelative("field");

					param.obj = objProp.objectReferenceValue;
					param.field = fieldProp.stringValue;
					Object obj = param.obj;

					lineRect.yMin += lineHeight;
					lineRect.yMax += lineHeight;

					obj = EditorGUI.ObjectField(lineRect, "   Arg " + i, obj, typeof(Object), true);

					objProp.objectReferenceValue = obj;
					del.parameters[i].obj = obj;
					param.obj = obj;

					if (obj == null) continue;

					GameObject selGO = null;
					System.Type type = param.obj.GetType();
					if (type == typeof(GameObject)) selGO = param.obj as GameObject;
					else if (type.IsSubclassOf(typeof(Component))) selGO = (param.obj as Component).gameObject;

					if (selGO != null)
					{
						// Parameters must be exact -- they can't be converted like property bindings
						PropertyReferenceDrawer.filter = param.expectedType;
						PropertyReferenceDrawer.canConvert = false;
						List<PropertyReferenceDrawer.Entry> ents = PropertyReferenceDrawer.GetProperties(selGO, true, false);

						int selection;
						string[] props = EventDelegateEditor.GetNames(ents, NGUITools.GetFuncName(param.obj, param.field), out selection);

						lineRect.yMin += lineHeight;
						lineRect.yMax += lineHeight;
						int newSel = EditorGUI.Popup(lineRect, " ", selection, props);

						if (newSel != selection)
						{
							if (newSel == 0)
							{
								param.obj = selGO;
								param.field = null;

								objProp.objectReferenceValue = selGO;
								fieldProp.stringValue = null;
							}
							else
							{
								param.obj = ents[newSel - 1].target;
								param.field = ents[newSel - 1].name;

								objProp.objectReferenceValue = param.obj;
								fieldProp.stringValue = param.field;
							}
						}
					}
					else if (!string.IsNullOrEmpty(param.field))
						param.field = null;

					PropertyReferenceDrawer.filter = typeof(void);
					PropertyReferenceDrawer.canConvert = true;
				}
			}
		}
	}
Beispiel #33
0
    private void DrawHandles(Spline spline)
    {
        if (Event.current.alt || EditorGUI.actionKey)
        {
            return;
        }

        if (Tools.current == Tool.None || Tools.current == Tool.View)
        {
            return;
        }

        Handles.lighting = true;

        foreach (SplineNode node in spline.SplineNodes)
        {
            switch (Tools.current)
            {
            case Tool.Rotate:
                Undo.SetSnapshotTarget(node.transform, "Rotate Spline Node: " + node.name);

                Quaternion newRotation = Handles.RotationHandle(node.Rotation, node.Position);

                Handles.color = new Color(.2f, 0.4f, 1f, 1);
                Handles.ArrowCap(0, node.Position, Quaternion.LookRotation(node.transform.forward), HandleUtility.GetHandleSize(node.Position) * 0.5f);
                Handles.color = new Color(.3f, 1f, .20f, 1);
                Handles.ArrowCap(0, node.Position, Quaternion.LookRotation(node.transform.up), HandleUtility.GetHandleSize(node.Position) * 0.5f);
                Handles.color = Color.white;

                if (!GUI.changed)
                {
                    break;
                }

                node.Rotation = newRotation;

                EditorUtility.SetDirty(target);

                break;

            case Tool.Move:
            case Tool.Scale:
                Undo.SetSnapshotTarget(node.transform, "Move Spline Node: " + node.name);

                Vector3 newPosition = Handles.PositionHandle(node.Position, (Tools.pivotRotation == PivotRotation.Global) ? Quaternion.identity : node.transform.rotation);

                if (!GUI.changed)
                {
                    break;
                }

                node.Position = newPosition;

                EditorUtility.SetDirty(target);

                break;
            }

            CreateSnapshot( );
        }
    }
Beispiel #34
0
	void Awake(){
		Current = this;
	}
Beispiel #35
0
    private void HandleMouseInput(Spline spline)
    {
        if (!EditorGUI.actionKey)
        {
            toolSphereSize  = 10f;
            toolSphereAlpha = 0f;
            return;
        }
        else
        {
            toolSphereAlpha = Mathf.Lerp(toolSphereAlpha, 0.75f, deltaTime * 4f);
            toolSphereSize  = Mathf.Lerp(toolSphereSize, toolTargetSphereSize + Mathf.Sin(Time.realtimeSinceStartup * 2f) * 0.1f, deltaTime * 15f);
        }

        Ray     mouseRay    = Camera.current.ScreenPointToRay(new Vector2(Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 32f));
        float   splineParam = spline.GetClosestPointParamToRay(mouseRay, 3);
        Vector3 position    = spline.GetPositionOnSpline(splineParam);

        float currentDistance = Vector3.Cross(mouseRay.direction, position - mouseRay.origin).magnitude;

        SplineNode selectedNode = null;

        foreach (SplineNode node in spline.SplineNodes)
        {
            float newDistance = Vector3.Distance(node.Position, position);

            if (newDistance < currentDistance || newDistance < 0.2f * HandleUtility.GetHandleSize(node.Position))
            {
                currentDistance = newDistance;

                selectedNode = node;
            }
        }

        if (selectedNode != null)
        {
            position = selectedNode.Position;

            Handles.color = new Color(.7f, 0.15f, 0.1f, toolSphereAlpha);
            Handles.SphereCap(0, position, Quaternion.identity, HandleUtility.GetHandleSize(position) * 0.25f * toolSphereSize);

            Handles.color = Color.white;
            Handles.Label(LabelPosition2D(position, 0.3f), "Delete Node (" + selectedNode.gameObject.name + ")", sceneGUIStyleToolLabel);

            toolTargetSphereSize = 1.35f;
        }
        else
        {
            Handles.color = new Color(.5f, 1f, .1f, toolSphereAlpha);
            Handles.SphereCap(0, position, Quaternion.identity, HandleUtility.GetHandleSize(position) * 0.25f * toolSphereSize);

            Handles.color = Color.white;
            Handles.Label(LabelPosition2D(position, 0.3f), "Insert Node", sceneGUIStyleToolLabel);

            toolTargetSphereSize = 0.8f;
        }

        if (Event.current.type == EventType.mouseDown && Event.current.button == 1)
        {
            Undo.RegisterSceneUndo((selectedNode != null) ? "Delete Spline Node (" + selectedNode.name + ")" : "Insert Spline Node");

            if (selectedNode != null)
            {
                spline.RemoveSplineNode(selectedNode.gameObject);
                DestroyImmediate(selectedNode.gameObject);
            }
            else
            {
                InsertNode(spline, splineParam);
            }

            ApplyChangesToTarget(spline);
        }

        HandleUtility.Repaint( );
    }
        public override void OnInspectorGUI()
        {
            serializedObject.Update();
            LocalizedSprite elem = target as LocalizedSprite;

            Undo.RecordObject(elem, "Modified localized sprite");

            if (SupportedLanguages.Instance != null)
            {
                //display what this LocalizedSprite will translate:
                string willTranslate = "Will localize ";
                bool   ok            = true;
                if (elem.GetComponent <Image>())
                {
                    willTranslate += "UI Image component on";
                }
                else if (elem.GetComponent <SpriteRenderer>())
                {
                    willTranslate += "SpriteRenderer component on";
                }
                else
                {
                    ok = false;                    //can't do that ya'll!
                }
                willTranslate += "\nthis GameObject.";
                if (!ok)
                {
                    GUIStyle style = new GUIStyle();
                    style.wordWrap = true;
                    GUILayout.Label("LocalizedSprites need to be on a GameObject with a UI Image or SpriteRenderer component attached!", style);
                }
                GUILayout.Label(willTranslate);
                GUILayout.Space(10);

                foreach (SupportedLanguages.SupportedLanguage language in SupportedLanguages.Instance.supportedLanguages)
                {
                    GUILayout.Label("" + language.language);
                    bool found = false;
                    foreach (LocalizedSprite.Translation t in elem.translations)
                    {
                        if (t.language == language.language)
                        {
                            found = true;
                            if (language.language == SupportedLanguages.Instance.defaultLanguage)
                            {
                                if (!EditorApplication.isPlaying)
                                {
                                    t.contents = defaultContents(elem);
                                }
                                if (t.contents == null)
                                {
                                    t.contents = (Sprite)EditorGUILayout.ObjectField(t.contents, typeof(Sprite), true);
                                }
                                else
                                {
                                    GUILayout.Label("(uses default sprite " + t.contents.name + ")");
                                }
                            }
                            else
                            {
                                t.contents = (Sprite)EditorGUILayout.ObjectField(t.contents, typeof(Sprite), true);
                            }
                            break;
                        }
                    }
                    if (!found)
                    {
                        LocalizedSprite.Translation t = new LocalizedSprite.Translation();
                        t.language = language.language;
                        if (language.language == SupportedLanguages.Instance.defaultLanguage)
                        {
                            if (!EditorApplication.isPlaying)
                            {
                                t.contents = defaultContents(elem);
                            }
                            if (t.contents == null)
                            {
                                t.contents = (Sprite)EditorGUILayout.ObjectField(null, typeof(Sprite), true);
                            }
                            else
                            {
                                GUILayout.Label("(uses default sprite " + t.contents.name + ")");
                            }
                        }
                        else
                        {
                            t.contents = (Sprite)EditorGUILayout.ObjectField((Sprite)null, typeof(Sprite), true);
                        }
                        elem.translations.Add(t);
                    }
                }

                //check whether any translations are provided for unsupported languages, and delete them.
                foreach (LocalizedSprite.Translation t in elem.translations)
                {
                    bool found = false;
                    foreach (SupportedLanguages.SupportedLanguage lang in SupportedLanguages.Instance.supportedLanguages)
                    {
                        if (lang.language == t.language)
                        {
                            found = true;
                            break;
                        }
                    }
                    if (!found)
                    {
                        elem.translations.Remove(t);
                        Debug.LogWarning("Removed localized sprite " + t.language + " from " + elem.name);
                        break;
                    }
                }

                if (GUILayout.Button("Edit supported languages"))
                {
                    SupportedLanguages.ShowSupportedLanguagesMenu();
                }
            }
            else
            {
                if (GUILayout.Button("Create supported languages"))
                {
                    SupportedLanguages.ShowSupportedLanguagesMenu();
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
Beispiel #37
0
        public override void ShowGUI(Menu menu)
        {
            string apiPrefix = "(AC.PlayerMenus.GetElementWithName (\"" + menu.title + "\", \"" + title + "\") as AC.MenuJournal)";

            MenuSource source = menu.menuSource;

            CustomGUILayout.BeginVertical();

            journalType = (JournalType)CustomGUILayout.EnumPopup("Journal type:", journalType, apiPrefix + ".journalType", "What type of journal this is");
            if (journalType == JournalType.DisplayExistingJournal || journalType == JournalType.DisplayActiveDocument)
            {
                if (journalType == JournalType.DisplayExistingJournal)
                {
                    EditorGUILayout.HelpBox("This Journal will share pages from another Journal element in the same Menu.", MessageType.Info);
                    otherJournalTitle = CustomGUILayout.TextField("Existing element name:", otherJournalTitle, apiPrefix + ".otherJournalTitle", "The name of the Journal element within the same Menu that is used as reference");
                    pageOffset        = CustomGUILayout.IntField("Page offset #:", pageOffset, apiPrefix + ".pageOffset", "The difference in page index between this and the reference Journal");
                }

                if (pages == null || pages.Count != 1)
                {
                    pages.Clear();
                    pages.Add(new JournalPage());
                }

                showPage = 1;

                if (source == MenuSource.AdventureCreator)
                {
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("Placeholder text:", GUILayout.Width(146f));
                    pages[0].text = CustomGUILayout.TextArea(pages[0].text, GUILayout.MaxWidth(370f), apiPrefix + ".pages[0].text");
                    EditorGUILayout.EndHorizontal();
                }
            }
            else if (journalType == JournalType.NewJournal)
            {
                if (pages == null)
                {
                    pages = new List <JournalPage>();
                    pages.Clear();
                    pages.Add(new JournalPage());
                }
                numPages = pages.Count;

                for (int i = 0; i < pages.Count; i++)
                {
                    EditorGUILayout.BeginHorizontal();

                    if (pages[i].lineID >= 0)
                    {
                        CustomGUILayout.LabelField("Page #" + (i + 1).ToString() + ", Text ID #" + pages[i].lineID + ":", apiPrefix + ".pages[" + i.ToString() + "].text");
                    }
                    else
                    {
                        CustomGUILayout.LabelField("Page #" + (i + 1).ToString() + ":", apiPrefix + ".pages[" + i.ToString() + "].text");
                    }

                    if (GUILayout.Button("", CustomStyles.IconCog))
                    {
                        sideMenu = i;
                        SideMenu();
                    }
                    EditorGUILayout.EndHorizontal();

                    pages[i].text = CustomGUILayout.TextArea(pages[i].text, GUILayout.MaxWidth(370f), apiPrefix + ".pages[" + i.ToString() + "].text");
                    GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1));
                }

                if (GUILayout.Button("Create new page", EditorStyles.miniButton))
                {
                    Undo.RecordObject(this, "Create journal page");
                    pages.Add(new JournalPage());
                }

                numPages = pages.Count;

                CustomGUILayout.EndVertical();
                CustomGUILayout.BeginVertical();

                if (numPages > 1)
                {
                    showPage      = CustomGUILayout.IntSlider("Preview page #:", showPage, 1, numPages, apiPrefix + ".showPage", "The index number of the current page being shown ");
                    startFromPage = CustomGUILayout.Toggle("Start from this page?", startFromPage, apiPrefix + ".startFromPage", "If True, then the page index above will be the first open when the game begins");
                }
                else if (numPages == 1)
                {
                    showPage = 1;
                }
                else
                {
                    showPage = 0;
                }
            }

            if (source == MenuSource.AdventureCreator)
            {
                anchor      = (TextAnchor)CustomGUILayout.EnumPopup("Text alignment:", anchor, apiPrefix + ".anchor", "The text alignment");
                textEffects = (TextEffects)CustomGUILayout.EnumPopup("Text effect:", textEffects, apiPrefix + ".textEffects", "The special FX applied to the text");
                if (textEffects != TextEffects.None)
                {
                    outlineSize = CustomGUILayout.Slider("Effect size:", outlineSize, 1f, 5f, apiPrefix + ".outlineSize", "The outline thickness");
                }
            }
            else
            {
                CustomGUILayout.EndVertical();
                CustomGUILayout.BeginVertical();

                                #if TextMeshProIsPresent
                uiText = LinkedUiGUI <TMPro.TextMeshProUGUI> (uiText, "Linked Text:", source);
                                #else
                uiText = LinkedUiGUI <Text> (uiText, "Linked Text:", source);
                                #endif
            }

            if (journalType == JournalType.NewJournal)
            {
                actionListOnAddPage = (ActionListAsset)CustomGUILayout.ObjectField <ActionListAsset> ("ActionList on add page:", actionListOnAddPage, false, apiPrefix + ".actionListOnAddPage", "An ActionList to run whenever a new page is added");
            }

            CustomGUILayout.EndVertical();

            base.ShowGUI(menu);
        }
        public List<ResponseDetails> ProcessSVATransaction(
                         TransactionType _TT //Required
            , StoredValueTransaction _SVAtransaction //Conditional : Only used for an AuthorizeAndCapture, Authorize and ReturnUnlinked. Otherwise null
            , StoredValueManage _SVManage // Conditional : Only used to manage. Otherwise null
            , StoredValueCapture _SVDifferenceData //Conditional : Only used for a Capture. Otherwise null
            , StoredValueReturn _SVRDifferenceData //Conditional : Only used for a ReturnById. Otherwise null
            , Undo _UDifferenceData //Conditional : Only used for an Undo. Otherwise null
            , bool _SendAcknowledge)
        {
            List<Response> _Response = new List<Response>();
            try
            {
                CheckTokenExpire();//Make sure the current token is valid

                //if (_TT == TransactionType.AuthorizeAndCapture)
                if (_TT == TransactionType.Authorize)
                {
                    _Response.Add(Cwsbc.Authorize(_sessionToken, _SVAtransaction, _applicationProfileId, _merchantProfileId, _serviceId));
                    //Always Verify that the requested amount and approved amount are the same.
                    StoredValueTransactionResponse SVR = new StoredValueTransactionResponse();
                    SVR = (StoredValueTransactionResponse)_Response[0];
                    if (_SVAtransaction.TransactionData.Amount != SVR.Amount)
                        MessageBox.Show("The transaction was approved for " + SVR.Amount
                            + " which is an amount not equal to than the requested amount of " + _SVAtransaction.TransactionData.Amount
                            + ". Please provide alternate payment to complete transaction");
                }
                if (_TT == TransactionType.ManageAccountById)
                    _Response.Add(Cwsbc.ManageAccountById(_sessionToken, _SVManage, _applicationProfileId, _serviceId));
                if (_TT == TransactionType.ManageAccount)
                    _Response.Add(Cwsbc.ManageAccount(_sessionToken, _SVAtransaction, _applicationProfileId, _merchantProfileId, _serviceId));
                if (_TT == TransactionType.Capture)
                    _Response.Add(Cwsbc.Capture(_sessionToken, _SVDifferenceData, _applicationProfileId, _serviceId));
                if (_TT == TransactionType.ReturnById)
                    _Response.Add(Cwsbc.ReturnById(_sessionToken, _SVRDifferenceData, _applicationProfileId, _serviceId));
                if (_TT == TransactionType.Return)
                    _Response.Add(Cwsbc.ReturnUnlinked(_sessionToken, _SVAtransaction, _applicationProfileId, _merchantProfileId, _serviceId));
                if (_TT == TransactionType.Undo)
                    _Response.Add(Cwsbc.Undo(_sessionToken, _UDifferenceData, _applicationProfileId, _serviceId));
                if (_TT == TransactionType.QueryAccount)
                    _Response.Add(Cwsbc.QueryAccount(_sessionToken, _SVAtransaction, _applicationProfileId, _merchantProfileId, _serviceId));

                List<ResponseDetails> RD = new List<ResponseDetails>();//Convert the response to response details so that we can report on the UI
                if (_Response != null)
                {
                    foreach (Response r in _Response)
                    {
                        if (_SendAcknowledge && r.TransactionId.Length > 0)
                            Cwsbc.Acknowledge(_sessionToken, r.TransactionId, _applicationProfileId, _serviceId);

                        ResponseDetails RDN = new ResponseDetails(0.00M, r, _TT.ToString(), _serviceId, _merchantProfileId, true, TypeCardType.NotSet, "");
                        MessageBox.Show(ProcessResponse(ref RDN));//Pass as reference so we can extract more values from the response
                        RD.Add(RDN);
                    }
                }

                return RD;
            }
            catch (EndpointNotFoundException)
            {
                //In this case the SvcEndpoint was not available. Try the same logic again with the alternate Endpoint
                try
                {
                    SetTxnEndpoint();//Change the endpoint to use the backup.

                    //TODO : Add a copy of the code above once fully tested out.

                    return null;

                }
                catch (EndpointNotFoundException)
                {
                    MessageBox.Show("Neither the primary or secondary endpoints are available. Unable to process.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to AuthorizeAndCapture\r\nError Message : " + ex.Message, "AuthorizeAndCapture Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (System.TimeoutException te)
            {
                //A timeout has occured. Prompt the user if they'd like to query for the last transaction submitted
                if (_SVAtransaction != null)
                {
                    DialogResult Result;
                    Result = MessageBox.Show("A timeout has occured. Would you like to query 'RequestTransaction' to obtain transactions with the exact same TenderData? To avoid duplicate charges your code will need to reconcile transactions.",
                                "Request Transaction", MessageBoxButtons.YesNo);
                    if (Result == DialogResult.Yes)
                    {
                        RequestTransaction(_SVAtransaction.TenderData);
                    }
                    else { throw te; }
                }
                else { throw te; }
            }
            catch (Exception ex)
            {
                string strErrorId;
                string strErrorMessage;
                if (_FaultHandler.handleTxnFault(ex, out strErrorId, out strErrorMessage))
                { MessageBox.Show(strErrorId + " : " + strErrorMessage); }
                else { MessageBox.Show(ex.Message); }
            }

            return null;
        }
        /// <summary>
        /// Rebuilds / updates the collection layout.
        /// Update collection is called from the editor button on the inspector.
        /// </summary>
        public virtual void UpdateCollection()
        {
            // Check for empty nodes and remove them
            var emptyNodes = new List <ObjectCollectionNode>();

            for (int i = 0; i < NodeList.Count; i++)
            {
                if (NodeList[i].Transform == null || (IgnoreInactiveTransforms && !NodeList[i].Transform.gameObject.activeSelf) || NodeList[i].Transform.parent == null || !(NodeList[i].Transform.parent.gameObject == gameObject))
                {
                    emptyNodes.Add(NodeList[i]);
                }
            }

            // Now delete the empty nodes
            for (int i = 0; i < emptyNodes.Count; i++)
            {
                NodeList.Remove(emptyNodes[i]);
            }

            emptyNodes.Clear();

            // Check when children change and adjust
            for (int i = 0; i < transform.childCount; i++)
            {
                Transform child = transform.GetChild(i);
#if UNITY_EDITOR
                Undo.RecordObject(child, "ObjectCollection modify transform");
#endif
                if (!ContainsNode(child) && (child.gameObject.activeSelf || !IgnoreInactiveTransforms))
                {
                    NodeList.Add(new ObjectCollectionNode {
                        Name = child.name, Transform = child
                    });
                }
            }

            switch (SortType)
            {
            case CollationOrder.ChildOrder:
                NodeList.Sort((c1, c2) => (c1.Transform.GetSiblingIndex().CompareTo(c2.Transform.GetSiblingIndex())));
                break;

            case CollationOrder.Alphabetical:
                NodeList.Sort((c1, c2) => (string.CompareOrdinal(c1.Name, c2.Name)));
                break;

            case CollationOrder.AlphabeticalReversed:
                NodeList.Sort((c1, c2) => (string.CompareOrdinal(c1.Name, c2.Name)));
                NodeList.Reverse();
                break;

            case CollationOrder.ChildOrderReversed:
                NodeList.Sort((c1, c2) => (c1.Transform.GetSiblingIndex().CompareTo(c2.Transform.GetSiblingIndex())));
                NodeList.Reverse();
                break;
            }

            LayoutChildren();

            OnCollectionUpdated?.Invoke(this);
        }
Beispiel #40
0
 void Start()
 {
     m_PlayerColor = false;
     board = GameObject.Find ("Board").GetComponent<Board> ();
     undo = GameObject.Find("Undo").GetComponent<Undo>();
     gameInfo = GameObject.Find ("GameInfo").GetComponent<GameInfo>();
     ui = GameObject.Find ("Text").GetComponent<Ui>();
     SetTimeLimit = GameObject.Find ("TimeLimit").GetComponent<TimeLimit>();
 }
Beispiel #41
0
 ////////////////////////////////////////////////////////////////
 // Access
 ////////////////////////////////////////////////////////////////
 /// <summary>
 /// Read the next token from the stream.  The token is
 /// available via the 'type' and 'val' fields.  The line
 /// of the current token is available in 'line' field.
 /// Return the 'type' field or -1 if at end of stream.
 /// </summary>
 public int next()
 {
     if (m_undo != null) { m_undo.reset(this); m_undo = null; return m_type; }
       m_val = null;
       return m_type = doNext();
 }