Exemple #1
0
        void PropertiesWindow(int id = 2)
        {
            GUILayout.BeginVertical();

            if (listTypes != null && !string.IsNullOrEmpty(listTypes.SelectedItem))
            {
                if (selectedType != null)
                {
                    // Title
                    GUILayout.Space(2);
                    LabelHelper.TitleLabel(selectedType.Name);
                    LineHelper.Draw(Color.gray);

                    // Common
                    GUILayout.Space(2);
                    if (selectedType.BaseType != typeof(ObservableModel))
                    {
                        GUILayout.BeginHorizontal();
                        if (ColorButton.Draw("Edit View Logic (Handler)", CommonColor.LightBlue, GUILayout.Height(30)))
                        {
                            string handler = CodeGenerationHelper.GetScriptPathByType(selectedType);
                            handler = handler.Replace(".cs", ".Handler.cs");
                            UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(handler, 1);
                        }

                        if (ColorButton.Draw("Edit View (UI)", CommonColor.LightBlue, GUILayout.Height(30)))
                        {
                            GameObject         prefabInstance;
                            UnityEngine.Object obj = FindObjectOfType(selectedType);
                            if (obj != null)
                            {
                                prefabInstance = ((MonoBehaviour)obj).gameObject;
                            }
                            else
                            {
                                bool       isDialog     = selectedType.BaseType == typeof(UIManDialog);
                                string     prefabFolder = GetUIPrefabPath(selectedType, isDialog);
                                string     prefabFile   = selectedType.Name + PREFAB_EXT;
                                string     prefabPath   = Path.Combine(prefabFolder, prefabFile);
                                GameObject prefab       = AssetDatabase.LoadAssetAtPath <GameObject> (prefabPath);
                                if (prefab == null)
                                {
                                    prefab = FindAssetObject <GameObject> (selectedType.Name, PREFAB_EXT);
                                }

                                prefabInstance = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                                if (isDialog)
                                {
                                    prefabInstance.transform.SetParent(UIMan.Instance.dialogRoot, false);
                                }
                                else
                                {
                                    prefabInstance.transform.SetParent(UIMan.Instance.screenRoot, false);
                                }
                            }
                            Selection.activeGameObject = prefabInstance;
                        }

                        if (ColorButton.Draw("Delete", CommonColor.LightRed, GUILayout.Height(30)))
                        {
                            string cs      = CodeGenerationHelper.GetScriptPathByType(selectedType);
                            string handler = cs.Replace(".cs", ".Handler.cs");
                            AssetDatabase.DeleteAsset(cs);
                            AssetDatabase.DeleteAsset(handler);

                            bool   isDialog     = selectedType.BaseType == typeof(UIManDialog);
                            string prefabFolder = GetUIPrefabPath(selectedType, isDialog);
                            string prefabFile   = selectedType.Name + PREFAB_EXT;
                            string prefabPath   = UIManDefine.ASSETS_FOLDER + prefabFolder + prefabFile;
                            AssetDatabase.DeleteAsset(prefabPath);
                            AssetDatabase.Refresh();
                        }
                        GUILayout.EndHorizontal();
                        LineHelper.Draw(Color.gray);
                    }

                    // Base type
                    GUILayout.Space(10);
                    LabelHelper.HeaderLabel("Type");
                    LineHelper.Draw(Color.gray);
                    baseTypePopup.Draw();

                    if (baseTypePopup.SelectedItem != "ObservableModel")
                    {
                        if (!System.IO.File.Exists(handlerScriptPath))
                        {
                            if (GUILayout.Button("Generate Handler"))
                            {
                                string backupCode = CodeGenerationHelper.DeleteScript(handlerScriptPath);
                                GenerateViewModelHandler(backupCode, selectedType.BaseType.Name);
                            }
                        }
                    }

                    // Properties
                    GUILayout.Space(10);
                    LabelHelper.HeaderLabel("Properties");
                    LineHelper.Draw(Color.gray);

                    propertiesScrollPos = EditorGUILayout.BeginScrollView(propertiesScrollPos, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
                    if (propertiesDrawerCache.ContainsKey(selectedType))
                    {
                        EditablePropertyDrawer[] props = propertiesDrawerCache [selectedType];
                        for (int i = 0; i < props.Length; i++)
                        {
                            props [i].Draw(propertiesAreaWidth);
                        }
                    }
                    EditorGUILayout.EndScrollView();
                }

                GUILayout.Space(10);

                // Add property
                if (ColorButton.Draw("Add New Property", CommonColor.LightGreen, GUILayout.Height(30)))
                {
                    int    newIndex    = 0;
                    string strNewIndex = "";
                    for (int i = 0; i < selectedProperties.Length; i++)
                    {
                        if (selectedProperties [i].LastName.Contains("NewProperty"))
                        {
                            newIndex++;
                        }
                    }
                    if (newIndex > 0)
                    {
                        strNewIndex = newIndex.ToString();
                    }
                    CustomPropertyInfo newProperty = new CustomPropertyInfo("", typeof(string));
                    newProperty.LastName = "NewProperty" + strNewIndex;
                    ArrayUtility.Add <CustomPropertyInfo> (ref selectedProperties, newProperty);
                    CachePropertiesDrawer();
                }

                //Save all change
                CustomPropertyInfo[] changeList   = new CustomPropertyInfo[0];
                CustomPropertyInfo[] selectedList = new CustomPropertyInfo[0];
                for (int i = 0; i < selectedProperties.Length; i++)
                {
                    if (selectedProperties [i].HasChange)
                    {
                        ArrayUtility.Add(ref changeList, selectedProperties [i]);
                    }
                    if (selectedProperties [i].IsSelected)
                    {
                        ArrayUtility.Add(ref selectedList, selectedProperties [i]);
                    }
                }

                GUILayout.Space(10);
                LineHelper.Draw(Color.gray);
                GUILayout.Space(5);

                if (changeList.Length > 0)
                {
                    if (ColorButton.Draw("Save All Changes", CommonColor.LightGreen, GUILayout.Height(30)))
                    {
                        for (int i = 0; i < changeList.Length; i++)
                        {
                            changeList [i].CommitChange();
                        }
                        SaveCurrentType(true, baseTypePopup.SelectedItem);
                    }
                }

                if (selectedList.Length > 0)
                {
                    if (ColorButton.Draw("Delete Selected Properties", CommonColor.LightRed, GUILayout.Height(30)))
                    {
                        for (int i = 0; i < selectedList.Length; i++)
                        {
                            ArrayUtility.Remove(ref selectedProperties, selectedList [i]);
                        }
                        SaveCurrentType(true, baseTypePopup.SelectedItem);
                        CachePropertiesDrawer(true);
                    }
                }

                if (selectedProperties.Length > 0)
                {
                    if (ColorButton.Draw("Delete All Properties", CommonColor.LightRed, GUILayout.Height(30)))
                    {
                        while (selectedProperties.Length > 0)
                        {
                            ArrayUtility.Clear(ref selectedProperties);
                            SaveCurrentType();
                            CachePropertiesDrawer(true);
                        }
                    }
                }
            }
            else
            {
                GUILayout.Label("NO DATA FOR PREVIEW!");
            }


            GUILayout.EndVertical();
        }
Exemple #2
0
        static public void UpdateCache()
        {
            // Deserialize the cache from the unity resources
            if (eventCache == null)
            {
                eventCache = AssetDatabase.LoadAssetAtPath(CacheAssetFullName, typeof(EventCache)) as EventCache;
                if (eventCache == null || eventCache.cacheVersion != EventCache.CurrentCacheVersion)
                {
                    UnityEngine.Debug.Log("FMOD Studio: Cannot find serialized event cache or cache in old format, creating new instance");
                    eventCache = ScriptableObject.CreateInstance <EventCache>();
                    eventCache.cacheVersion = EventCache.CurrentCacheVersion;

                    AssetDatabase.CreateAsset(eventCache, CacheAssetFullName);
                }
            }

            if (EditorUtils.GetBankDirectory() == null)
            {
                ClearCache();
                return;
            }

            string defaultBankFolder = null;

            if (!Settings.Instance.HasPlatforms)
            {
                defaultBankFolder = EditorUtils.GetBankDirectory();
            }
            else
            {
                FMODPlatform platform = RuntimeUtils.GetEditorFMODPlatform();
                if (platform == FMODPlatform.None)
                {
                    platform = FMODPlatform.PlayInEditor;
                }

                defaultBankFolder = Path.Combine(EditorUtils.GetBankDirectory(), Settings.Instance.GetBankPlatform(platform));
            }

            string[] bankPlatforms = EditorUtils.GetBankPlatforms();
            string[] bankFolders   = new string[bankPlatforms.Length];
            for (int i = 0; i < bankPlatforms.Length; i++)
            {
                bankFolders[i] = Path.Combine(EditorUtils.GetBankDirectory(), bankPlatforms[i]);
            }

            List <String> stringBanks = new List <string>(0);

            try
            {
                var files = Directory.GetFiles(defaultBankFolder, "*." + StringBankExtension);
                stringBanks = new List <string>(files);
            }
            catch
            {
            }

            // Strip out OSX resource-fork files that appear on FAT32
            stringBanks.RemoveAll((x) => Path.GetFileName(x).StartsWith("._"));

            if (stringBanks.Count == 0)
            {
                bool wasValid = eventCache.StringsBankWriteTime != DateTime.MinValue;
                ClearCache();
                if (wasValid)
                {
                    UnityEngine.Debug.LogError(String.Format("FMOD Studio: Directory {0} doesn't contain any banks. Build from the tool or check the path in the settings", defaultBankFolder));
                }
                return;
            }

            // If we have multiple .strings.bank files find the most recent
            stringBanks.Sort((a, b) => File.GetLastWriteTime(b).CompareTo(File.GetLastWriteTime(a)));
            string stringBankPath = stringBanks[0];

            // Use the string bank timestamp as a marker for the most recent build of any bank because it gets exported every time
            if (File.GetLastWriteTime(stringBankPath) == eventCache.StringsBankWriteTime)
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            if (EditorUtils.IsFileOpenByStudio(stringBankPath))
            {
                countdownTimer = CountdownTimerReset;
                return;
            }


            FMOD.Studio.Bank stringBank = null;
            EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));
            if (stringBank == null)
            {
                countdownTimer = CountdownTimerReset;
                return;
            }

            // Iterate every string in the strings bank and look for any that identify banks
            int stringCount;

            stringBank.getStringCount(out stringCount);
            List <string> bankFileNames = new List <string>();

            for (int stringIndex = 0; stringIndex < stringCount; stringIndex++)
            {
                string currentString;
                Guid   currentGuid;
                stringBank.getStringInfo(stringIndex, out currentGuid, out currentString);
                const string BankPrefix       = "bank:/";
                int          BankPrefixLength = BankPrefix.Length;
                if (currentString.StartsWith(BankPrefix))
                {
                    string bankFileName = currentString.Substring(BankPrefixLength) + "." + BankExtension;
                    if (!bankFileName.Contains(StringBankExtension)) // filter out the strings bank
                    {
                        bankFileNames.Add(bankFileName);
                    }
                }
            }

            // Unload the strings bank
            stringBank.unload();

            // Check if any of the files are still being written by studio
            foreach (string bankFileName in bankFileNames)
            {
                string bankPath = Path.Combine(defaultBankFolder, bankFileName);

                if (!File.Exists(bankPath))
                {
                    // TODO: this is meant to catch the case where we're in the middle of a build and a bank is being built
                    // for the first time. But it also stops someone trying to import an incomplete set of banks without any error message.
                    countdownTimer = CountdownTimerReset;
                    return;
                }

                EditorBankRef bankRef = eventCache.EditorBanks.Find((x) => bankPath == x.Path);
                if (bankRef == null)
                {
                    if (EditorUtils.IsFileOpenByStudio(bankPath))
                    {
                        countdownTimer = CountdownTimerReset;
                        return;
                    }
                    continue;
                }

                if (bankRef.LastModified != File.GetLastWriteTime(bankPath))
                {
                    if (EditorUtils.IsFileOpenByStudio(bankPath))
                    {
                        countdownTimer = CountdownTimerReset;
                        return;
                    }
                }
            }

            // Count down the timer in case we catch studio in-between updating two files.
            if (countdownTimer-- > 0)
            {
                return;
            }

            // All files are finished being modified by studio so update the cache

            // Stop editor preview so no stale data being held
            EditorUtils.PreviewStop();

            // Reload the strings bank
            EditorUtils.CheckResult(EditorUtils.System.loadBankFile(stringBankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out stringBank));
            if (stringBank == null)
            {
                ClearCache();
                return;
            }
            FileInfo stringBankFileInfo = new FileInfo(stringBankPath);

            eventCache.StringsBankWriteTime = stringBankFileInfo.LastWriteTime;
            string masterBankFileName = Path.GetFileName(stringBankPath).Replace(StringBankExtension, BankExtension);

            AssetDatabase.StartAssetEditing();

            if (eventCache.StringsBankRef == null)
            {
                eventCache.StringsBankRef           = ScriptableObject.CreateInstance <EditorBankRef>();
                eventCache.StringsBankRef.FileSizes = new List <EditorBankRef.NameValuePair>();
                eventCache.EditorBanks.Add(eventCache.StringsBankRef);
                AssetDatabase.AddObjectToAsset(eventCache.StringsBankRef, eventCache);
                AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(eventCache.StringsBankRef));
            }
            eventCache.StringsBankRef.Path         = stringBankPath;
            eventCache.StringsBankRef.LastModified = eventCache.StringsBankWriteTime;
            eventCache.StringsBankRef.FileSizes.Clear();
            if (Settings.Instance.HasPlatforms)
            {
                for (int i = 0; i < bankPlatforms.Length; i++)
                {
                    eventCache.StringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], stringBankFileInfo.Length));
                }
            }
            else
            {
                eventCache.StringsBankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", stringBankFileInfo.Length));
            }

            eventCache.EditorBanks.ForEach((x) => x.Exists = false);
            eventCache.StringsBankRef.Exists = true;

            string[] folderContents = Directory.GetFiles(defaultBankFolder);

            foreach (string bankFileName in bankFileNames)
            {
                // Get the true file path, can't trust the character case we got from the string bank
                string bankPath = ArrayUtility.Find(folderContents, x => (string.Equals(bankFileName, Path.GetFileName(x), StringComparison.CurrentCultureIgnoreCase)));

                FileInfo      bankFileInfo = new FileInfo(bankPath);
                EditorBankRef bankRef      = eventCache.EditorBanks.Find((x) => bankFileInfo.FullName == x.Path);

                // New bank we've never seen before
                if (bankRef == null)
                {
                    bankRef = ScriptableObject.CreateInstance <EditorBankRef>();
                    AssetDatabase.AddObjectToAsset(bankRef, eventCache);
                    AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(bankRef));
                    bankRef.Path         = bankFileInfo.FullName;
                    bankRef.LastModified = DateTime.MinValue;
                    bankRef.FileSizes    = new List <EditorBankRef.NameValuePair>();
                    eventCache.EditorBanks.Add(bankRef);
                }

                bankRef.Exists = true;

                // Timestamp check - if it doesn't match update events from that bank
                if (bankRef.LastModified != bankFileInfo.LastWriteTime)
                {
                    bankRef.LastModified = bankFileInfo.LastWriteTime;
                    UpdateCacheBank(bankRef);
                }

                // Update file sizes
                bankRef.FileSizes.Clear();
                if (Settings.Instance.HasPlatforms)
                {
                    for (int i = 0; i < bankPlatforms.Length; i++)
                    {
                        string platformBankPath = Path.Combine(bankFolders[i], bankFileName);
                        var    fileInfo         = new FileInfo(platformBankPath);
                        if (fileInfo.Exists)
                        {
                            bankRef.FileSizes.Add(new EditorBankRef.NameValuePair(bankPlatforms[i], fileInfo.Length));
                        }
                    }
                }
                else
                {
                    string platformBankPath = Path.Combine(EditorUtils.GetBankDirectory(), bankFileName);
                    var    fileInfo         = new FileInfo(platformBankPath);
                    if (fileInfo.Exists)
                    {
                        bankRef.FileSizes.Add(new EditorBankRef.NameValuePair("", fileInfo.Length));
                    }
                }

                if (bankFileInfo.Name == masterBankFileName)
                {
                    eventCache.MasterBankRef = bankRef;
                }
            }


            // Unload the strings bank
            stringBank.unload();

            // Remove any stale entries from bank and event lists
            eventCache.EditorBanks.FindAll((x) => !x.Exists).ForEach(RemoveCacheBank);
            eventCache.EditorBanks.RemoveAll((x) => !x.Exists);
            eventCache.EditorEvents.RemoveAll((x) => x.Banks.Count == 0);

            OnCacheChange();
            AssetDatabase.StopAssetEditing();
        }
        /// <summary>
        /// Reads a sequence of bytes from the current stream.
        /// </summary>
        /// <param name="buffer">The buffer that contains decrypted data.</param>
        /// <param name="offset">The offset in buffer at which to begin storing the decrypted data.</param>
        /// <param name="count">The maximum number of bytes to get.</param>
        /// <exception cref="ArgumentOutOfRangeException">Raised when buffer or the internal decryptedBuffer doesn't
        /// contain enough space
        /// </exception>
        /// <exception cref="IOException">Raised when attempting to read from/write to a remote connection which
        /// has been closed</exception>
        /// <returns>The actual number of bytes read into the buffer. Could be less than count</returns>
        public override int Read(byte[] buffer, int offset, int count)
        {
            if (offset > buffer.Length - 1)
            {
                throw new ArgumentOutOfRangeException("offset");
            }

            if (offset + count > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            if (!IsBufferEmpty())
            {
                if (CheckAvailableCount(count))
                {
                    Array.Copy(decryptedBuffer, this.startIndex, buffer, offset, count);
                    this.startIndex += count;

                    return(count);
                }
                else
                {
                    int sizeRead = this.endIndex - this.startIndex;
                    Array.Copy(decryptedBuffer, this.startIndex, buffer, offset, sizeRead);
                    // All data is read, reset indices
                    this.startIndex = 0;
                    this.endIndex   = 0;

                    return(sizeRead);
                }
            }

            byte[] encryptedMsg  = null;
            int    bytesReceived = 0;

            byte[] decryptedMsg = null;

            while (decryptedMsg == null)
            {
                // decryptedMsg being null indicates incomplete data, so we continue reading and decrypting.
                bytesReceived = ReceivePacket();

                // The connection has been closed by remote server
                if (bytesReceived == 0)
                {
                    return(0);
                }

                // There's pooled data, concatenate the buffer together for decryption
                if (this.pooledBuffer != null && this.pooledBuffer.Length > 0)
                {
                    encryptedMsg = new byte[this.pooledBuffer.Length + bytesReceived];
                    Array.Copy(this.pooledBuffer, encryptedMsg, this.pooledBuffer.Length);
                    Array.Copy(recvBuffer, 0, encryptedMsg, this.pooledBuffer.Length, bytesReceived);

                    this.pooledBuffer = null;
                }
                else
                {
                    encryptedMsg = new byte[bytesReceived];
                    Array.Copy(recvBuffer, encryptedMsg, bytesReceived);
                }

                byte[] extraData = null;
                // Do decryption
                SecurityBuffer[] securityBuffers = new SecurityBuffer[]
                {
                    new SecurityBuffer(SecurityBufferType.Data, encryptedMsg),
                    new SecurityBuffer(SecurityBufferType.Empty, null),
                    new SecurityBuffer(SecurityBufferType.Empty, null),
                    new SecurityBuffer(SecurityBufferType.Empty, null)
                };

                context.Decrypt(securityBuffers);
                for (int i = 0; i < securityBuffers.Length; i++)
                {
                    if (securityBuffers[i].BufferType == SecurityBufferType.Data)
                    {
                        decryptedMsg = ArrayUtility.ConcatenateArrays(decryptedMsg, securityBuffers[i].Buffer);
                    }
                    else if (securityBuffers[i].BufferType == SecurityBufferType.Extra)
                    {
                        extraData = ArrayUtility.ConcatenateArrays(extraData, securityBuffers[i].Buffer);
                    }
                }

                if (extraData != null && extraData.Length > 0)
                {
                    this.pooledBuffer = extraData;
                }
            }

            Array.Copy(decryptedMsg, 0, this.decryptedBuffer, this.endIndex, decryptedMsg.Length);
            this.endIndex += decryptedMsg.Length;

            return(Read(buffer, offset, count));
        }
        private void ShowPoint(int index, Vector3 point)
        {
            if (!CanShowPoint(index))
            {
                return;
            }

            Handles.color = ModeColors[(int)m_splineBase.GetControlPointMode(index)];
            if (index % 3 == 0)
            {
                Handles.color = Color.green;
            }

            float size = HandleUtility.GetHandleSize(point);

            Handles.CapFunction dcf = Handles.DotHandleCap;

            if (index == 0)
            {
                size *= 2f;
            }

            if (Handles.Button(point, m_handleRotation, size * HandleSize, size * PickSize, dcf))
            {
                m_selectedIndex = index;

                SplineControlPoint controlPoint = m_splineBase.GetComponentsInChildren <SplineControlPoint>(true).Where(cpt => cpt.Index == index).FirstOrDefault();
                if (controlPoint != null)
                {
                    if (Event.current.control || Event.current.shift)
                    {
                        GameObject[] objects = Selection.gameObjects;
                        Selection.activeGameObject = controlPoint.gameObject;
                        if (!objects.Contains(controlPoint.gameObject))
                        {
                            ArrayUtility.Add(ref objects, controlPoint.gameObject);
                        }
                        else
                        {
                            if (!Event.current.shift)
                            {
                                ArrayUtility.Remove(ref objects, controlPoint.gameObject);
                            }
                        }

                        Selection.objects = objects;
                    }
                    else
                    {
                        Selection.activeGameObject = controlPoint.gameObject;
                    }
                }

                Repaint();
            }

            if (m_selectedIndex == index)
            {
                int curveIndex     = (m_selectedIndex - 1) / 3;
                int prevCurveIndex = curveIndex - 1;
                int nextCurveIndex = curveIndex + 1;
                if (m_splineBase.Loop)
                {
                    if (prevCurveIndex < 0)
                    {
                        prevCurveIndex = m_splineBase.CurveCount - 1;
                    }

                    if (nextCurveIndex > m_splineBase.CurveCount - 1)
                    {
                        nextCurveIndex = 0;
                    }
                }


                GUIStyle style = new GUIStyle();
                style.normal.textColor = Color.green;

                if (prevCurveIndex >= 0)
                {
                    float prevLen = m_splineBase.EvalLength(prevCurveIndex);
                    float prevCur = m_splineBase.EvalCurveLength(prevCurveIndex, GetStepsPerCurve());
                    Handles.Label(m_splineBase.GetPoint(0.5f, prevCurveIndex), string.Format("Len: {0:0.00} m, Cur: {1:0.00} m", prevLen, prevCur), style);
                }
                if (nextCurveIndex < m_splineBase.CurveCount)
                {
                    float nextLen = m_splineBase.EvalLength(nextCurveIndex);
                    float nextCur = m_splineBase.EvalCurveLength(nextCurveIndex, GetStepsPerCurve());
                    Handles.Label(m_splineBase.GetPoint(0.5f, nextCurveIndex), string.Format("Len: {0:0.00} m, Cur: {1:0.00} m", nextLen, nextCur), style);
                }

                float cur = m_splineBase.EvalCurveLength(curveIndex, GetStepsPerCurve());
                float len = m_splineBase.EvalLength(curveIndex);
                Handles.Label(m_splineBase.GetPoint(0.5f, curveIndex), string.Format("Len: {0:0.00} m, Cur: {1:0.00} m", len, cur), style);
            }
        }
Exemple #5
0
        public static Vector3 SnapToWorld(Camera camera, CSGPlane snapPlane, Vector3 unsnappedPosition, Vector3 snappedPosition, ref List <Vector3> snappingEdges, out CSGBrush snappedOnBrush, CSGBrush[] ignoreBrushes = null)
        {
            snappedOnBrush = null;

            test_points[0] = unsnappedPosition;
            test_points[1] = snappedPosition;
            worldIntersections.Clear();

            for (int i = 0; i < test_points.Length; i++)
            {
                var test_point2D = CameraUtility.WorldToGUIPoint(test_points[i]);
                LegacyBrushIntersection intersection;
                if (SceneQueryUtility.FindWorldIntersection(camera, test_point2D, out intersection))
                {
                    if (intersection.brush &&
                        intersection.brush.ControlMesh != null)
                    {
                        intersection.worldIntersection = GeometryUtility.ProjectPointOnPlane(snapPlane, intersection.worldIntersection);

                        worldIntersections.Add(intersection);
                    }
                }
            }

            var     old_difference           = snappedPosition - unsnappedPosition;
            var     old_difference_magnitude = old_difference.magnitude * 1.5f;
            Vector3 newSnappedPoint          = snappedPosition;

            CSGPlane?snappingPlane = snapPlane;

            for (int i = 0; i < worldIntersections.Count; i++)
            {
                if (ignoreBrushes != null &&
                    ArrayUtility.Contains(ignoreBrushes, worldIntersections[i].brush))
                {
                    continue;
                }

                List <Vector3> outEdgePoints;
                Vector3        outPosition;
                if (GridUtility.SnapToVertices(worldIntersections[i].brush,
                                               snappingPlane, unsnappedPosition,
                                               out outEdgePoints,
                                               out outPosition))
                {
                    var new_difference           = outPosition - unsnappedPosition;
                    var new_difference_magnitude = new_difference.magnitude;

                    if (new_difference_magnitude <= old_difference_magnitude + MathConstants.EqualityEpsilon)
                    {
                        old_difference_magnitude = new_difference_magnitude;
                        newSnappedPoint          = outPosition;
                        snappingEdges            = outEdgePoints;
                        snappedOnBrush           = worldIntersections[i].brush;
                    }
                }
                if (GridUtility.SnapToEdge(camera,
                                           worldIntersections[i].brush, snappingPlane ?? worldIntersections[i].worldPlane,
                                           worldIntersections[i].worldIntersection,
                                           out outEdgePoints,
                                           out outPosition))
                {
                    var new_difference           = outPosition - unsnappedPosition;
                    var new_difference_magnitude = new_difference.magnitude * 1.1f;

                    if (new_difference_magnitude <= old_difference_magnitude + MathConstants.EqualityEpsilon)
                    {
                        old_difference_magnitude = new_difference_magnitude;
                        newSnappedPoint          = outPosition;
                        snappingEdges            = outEdgePoints;
                        snappedOnBrush           = worldIntersections[i].brush;
                    }
                }
            }

            //snappingEdges = FindAllEdgesThatTouchPoint(snappedOnBrush, newSnappedPoint);
            return(newSnappedPoint);
        }
Exemple #6
0
        public static void Export(CSGModel model, ExportType exportType, bool exportColliders)
        {
            string typeName;
            string extension;

            switch (exportType)
            {
            case ExportType.FBX: typeName = "FBX"; extension = @"fbx"; break;

            default:
                //case ExportType.UnityMesh:
                typeName = "Mesh"; extension = @"prefab"; exportType = ExportType.UnityMesh; break;
            }
            var newPath = model.exportPath;

            if (exportType != ExportType.UnityMesh)
            {
                newPath = UnityFBXExporter.ExporterMenu.GetNewPath(model.gameObject, typeName, extension, model.exportPath);
                if (string.IsNullOrEmpty(newPath))
                {
                    return;
                }
            }

            model.ShowGeneratedMeshes = false;
            var foundModels = model.GetComponentsInChildren <CSGModel>(true);

            for (var index = 0; index < foundModels.Length; index++)
            {
                if (!foundModels[index].ShowGeneratedMeshes)
                {
                    continue;
                }
                foundModels[index].ShowGeneratedMeshes = false;
                UpdateGeneratedMeshesVisibility(foundModels[index]);
            }

            GameObject tempExportObject;

            if (!string.IsNullOrEmpty(model.exportPath))
            {
                tempExportObject = new GameObject {
                    name = System.IO.Path.GetFileNameWithoutExtension(model.exportPath)
                };
                if (string.IsNullOrEmpty(tempExportObject.name))
                {
                    tempExportObject.name = model.name;
                }
            }
            else
            {
                tempExportObject = new GameObject {
                    name = model.name
                }
            };

            tempExportObject.transform.position   = MathConstants.zeroVector3;
            tempExportObject.transform.rotation   = MathConstants.identityQuaternion;
            tempExportObject.transform.localScale = MathConstants.oneVector3;

            int colliderCounter      = 1;
            int shadowOnlyCounter    = 1;
            var materialMeshCounters = new Dictionary <Material, int>();

            var currentScene        = model.gameObject.scene;
            var foundMeshContainers = SceneQueryUtility.GetAllComponentsInScene <GeneratedMeshes>(currentScene);
            var bounds = new AABB();

            bounds.Reset();
            var foundMeshFilters   = new List <MeshFilter>();
            var foundMeshColliders = new List <MeshCollider>();

            foreach (var meshContainer in foundMeshContainers)
            {
                var owner = meshContainer.owner;
                if (!owner || !ArrayUtility.Contains(foundModels, owner))
                {
                    continue;
                }

                if (!meshContainer || meshContainer.meshInstances == null)
                {
                    continue;
                }

                var instances = meshContainer.meshInstances.Values;
                foreach (var instance in instances)
                {
                    if (!instance)
                    {
                        continue;
                    }

                    Refresh(instance, model, postProcessScene: true);

                    var surfaceType = GetRenderSurfaceType(owner, instance);
                    if (surfaceType != RenderSurfaceType.Normal &&
                        surfaceType != RenderSurfaceType.ShadowOnly &&
                        surfaceType != RenderSurfaceType.Collider)
                    {
                        continue;
                    }

                    int counter = 0;
                    if (instance.RenderMaterial)
                    {
                        if (!materialMeshCounters.TryGetValue(instance.RenderMaterial, out counter))
                        {
                            counter = 1;
                        }
                        else
                        {
                            counter++;
                        }
                    }

                    var mesh = instance.SharedMesh;
                    if (!mesh.isReadable)
                    {
                        //bounds.Extend(mesh.bounds.min);
                        //bounds.Extend(mesh.bounds.max);
                    }
                    else
                    {
                        var vertices = mesh.vertices;
                        for (int v = 0; v < vertices.Length; v++)
                        {
                            bounds.Extend(vertices[v]);
                        }
                    }


                    var subObj = UnityEngine.Object.Instantiate(instance.gameObject, MathConstants.zeroVector3, MathConstants.identityQuaternion) as GameObject;
                    subObj.hideFlags            = HideFlags.None;
                    subObj.transform.position   = owner.transform.position;
                    subObj.transform.rotation   = owner.transform.rotation;
                    subObj.transform.localScale = owner.transform.localScale;
                    subObj.transform.SetParent(tempExportObject.transform, false);

                    var genMeshInstance = subObj.GetComponent <GeneratedMeshInstance>();

                    UnityEngine.Object.DestroyImmediate(genMeshInstance);

                    if (surfaceType == RenderSurfaceType.Collider)
                    {
                        subObj.name = "no-material (" + colliderCounter + ") COLLIDER"; colliderCounter++;
                    }
                    else
                    {
                        if (surfaceType == RenderSurfaceType.ShadowOnly)
                        {
                            subObj.name = "shadow-only (" + shadowOnlyCounter + ")"; shadowOnlyCounter++;
                            var meshRenderer = subObj.GetComponent <MeshRenderer>();
                            if (meshRenderer)
                            {
                                meshRenderer.sharedMaterial = AssetDatabase.GetBuiltinExtraResource <Material>("Default-Diffuse.mat");
                            }
                        }
                        else
                        {
                            subObj.name = instance.RenderMaterial.name + " (" + counter + ")"; counter++;
                            materialMeshCounters[instance.RenderMaterial] = counter;
                        }

                        var meshFilter = subObj.GetComponent <MeshFilter>();
                        if (meshFilter)
                        {
                            foundMeshFilters.Add(meshFilter);
                        }
                    }

                    var meshCollider = subObj.GetComponent <MeshCollider>();
                    if (meshCollider)
                    {
                        foundMeshColliders.Add(meshCollider);
                    }
                }
            }

            Undo.IncrementCurrentGroup();
            var groupIndex = Undo.GetCurrentGroup();

            Undo.SetCurrentGroupName("Exported model");
            try
            {
                Vector3 position = model.transform.position;
                if (float.IsInfinity(position.x) || float.IsNaN(position.x))
                {
                    position.x = 0;
                }
                if (float.IsInfinity(position.y) || float.IsNaN(position.y))
                {
                    position.y = 0;
                }
                if (float.IsInfinity(position.z) || float.IsNaN(position.z))
                {
                    position.z = 0;
                }

                Vector3 center = bounds.Center;
                switch (model.originType)
                {
                default:
                case OriginType.ModelCenter:    center = bounds.Center + position; break;

                case OriginType.ModelPivot:             center = position; break;

                case OriginType.WorldSpace:             center = Vector3.zero; break;
                }
                if (float.IsInfinity(center.x) || float.IsNaN(center.x))
                {
                    center.x = 0;
                }
                if (float.IsInfinity(center.y) || float.IsNaN(center.y))
                {
                    center.y = 0;
                }
                if (float.IsInfinity(center.z) || float.IsNaN(center.z))
                {
                    center.z = 0;
                }

                var modifiedMeshes = new Dictionary <Mesh, Mesh>();
                foreach (var meshFilter in foundMeshFilters)
                {
                    var mesh = meshFilter.sharedMesh;
                    if (!mesh.isReadable)
                    {
                        continue;
                    }

                    Mesh newMesh;
                    if (!modifiedMeshes.TryGetValue(mesh, out newMesh))
                    {
                        newMesh = (Mesh)UnityEngine.Object.Instantiate(mesh);
                        var vertices = mesh.vertices;
                        for (int v = 0; v < vertices.Length; v++)
                        {
                            vertices[v] += position;
                            vertices[v] -= center;
                        }
                        newMesh.vertices     = vertices;
                        modifiedMeshes[mesh] = newMesh;
                    }
                    meshFilter.sharedMesh         = newMesh;
                    meshFilter.transform.position = Vector3.zero;
                }

                foreach (var meshCollider in foundMeshColliders)
                {
                    var mesh = meshCollider.sharedMesh;
                    if (!mesh.isReadable)
                    {
                        continue;
                    }

                    Mesh newMesh;
                    if (!modifiedMeshes.TryGetValue(mesh, out newMesh))
                    {
                        newMesh = (Mesh)UnityEngine.Object.Instantiate(mesh);
                        var vertices = mesh.vertices;
                        for (int v = 0; v < vertices.Length; v++)
                        {
                            vertices[v] += position;
                            vertices[v] -= center;
                        }
                        newMesh.vertices     = vertices;
                        modifiedMeshes[mesh] = newMesh;
                    }
                    meshCollider.sharedMesh         = newMesh;
                    meshCollider.transform.position = Vector3.zero;
                }

                UnityEngine.Object obj;
                GameObject         modelGameObject;
                switch (exportType)
                {
                case ExportType.FBX:
                {
                    if (!UnityFBXExporter.FBXExporter.ExportGameObjToFBX(tempExportObject, newPath, exportColliders: exportColliders))
                    {
                        //InternalCSGModelManager.ClearMeshInstances();
                        EditorUtility.DisplayDialog("Warning", "Failed to export the FBX file.", "Ok");
                        return;
                    }
                    obj = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(newPath);

                    modelGameObject = PrefabUtility.InstantiatePrefab(obj) as GameObject;

                    foreach (var renderer in modelGameObject.GetComponentsInChildren <MeshRenderer>())
                    {
                        var gameObject = renderer.gameObject;
                        if (gameObject.name.EndsWith("COLLIDER"))
                        {
                            var filter       = gameObject.GetComponent <MeshFilter>();
                            var meshCollider = gameObject.AddComponent <MeshCollider>();
                            meshCollider.sharedMesh = filter.sharedMesh;
                            UnityEngine.Object.DestroyImmediate(renderer);
                            UnityEngine.Object.DestroyImmediate(filter);
                        }
                    }
                    model.exportPath = newPath;
                    break;
                }

                default:
                    //case ExportType.UnityMesh:
                {
                    //PrefabUtility.CreatePrefab(newPath, tempExportObject, ReplacePrefabOptions.Default);
                    obj             = tempExportObject;                // AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(newPath);
                    modelGameObject = tempExportObject;

                    foreach (var meshFilter in tempExportObject.GetComponentsInChildren <MeshFilter>())
                    {
                        var mesh = meshFilter.sharedMesh;
                        mesh.name       = tempExportObject.name;
                        meshFilter.mesh = mesh;
                    }
                    break;
                }
                }

                var prefabObj = obj as GameObject;

                model.exportPath = newPath;

                if (exportType == ExportType.FBX && prefabObj)
                {
                    foreach (var meshRenderer in prefabObj.GetComponentsInChildren <MeshRenderer>())
                    {
                        if (meshRenderer.sharedMaterials.Length != 1)
                        {
                            continue;
                        }

                        var gameObject = meshRenderer.gameObject;
                        var nameSplit  = gameObject.name.Split('|');
                        if (nameSplit.Length == 1)
                        {
                            continue;
                        }

                        int instanceId;
                        if (!int.TryParse(nameSplit[1], out instanceId))
                        {
                            continue;
                        }

                        var realMaterial = EditorUtility.InstanceIDToObject(instanceId) as Material;
                        if (!realMaterial)
                        {
                            continue;
                        }

                        meshRenderer.sharedMaterial = realMaterial;
                        gameObject.name             = nameSplit[0];
                    }
                }


                var staticFlags = GameObjectUtility.GetStaticEditorFlags(model.gameObject);
                var modelLayer  = model.gameObject.layer;
                foreach (var transform in modelGameObject.GetComponentsInChildren <Transform>())
                {
                    var gameObject = transform.gameObject;
                    GameObjectUtility.SetStaticEditorFlags(gameObject, staticFlags);
                    gameObject.layer = modelLayer;
                }

                modelGameObject.transform.SetParent(model.transform, true);
                modelGameObject.transform.SetSiblingIndex(0);
                modelGameObject.tag = model.gameObject.tag;

                modelGameObject.transform.localPosition = center - position;


                Undo.RegisterCreatedObjectUndo(modelGameObject, "Instantiated model");


                var exported = model.gameObject.AddComponent <CSGModelExported>();
                exported.containedModel         = null;
                exported.containedExportedModel = modelGameObject;
                exported.disarm = true;
                Undo.RegisterCreatedObjectUndo(exported, "Created CSGModelExported");
                Undo.RegisterCompleteObjectUndo(exported, "Created CSGModelExported");


                var foundBrushes    = model.GetComponentsInChildren <CSGBrush>(true);
                var foundOperations = model.GetComponentsInChildren <CSGOperation>(true);
                var foundContainers = model.GetComponentsInChildren <GeneratedMeshes>(true);

                var foundBehaviours = new HashSet <MonoBehaviour>();

                foreach (var foundBrush         in foundBrushes)
                {
                    foundBehaviours.Add(foundBrush);
                }
                foreach (var foundOperation in foundOperations)
                {
                    foundBehaviours.Add(foundOperation);
                }
                foreach (var foundModel         in foundModels)
                {
                    foundBehaviours.Add(foundModel);
                }
                foreach (var foundContainer in foundContainers)
                {
                    foundBehaviours.Add(foundContainer);
                }


                exported.hiddenComponents = new HiddenComponentData[foundBehaviours.Count];
                var index = 0;
                foreach (var foundBehaviour in foundBehaviours)
                {
                    Undo.RegisterCompleteObjectUndo(foundBehaviour, "Hide component");
                    exported.hiddenComponents[index] = new HiddenComponentData {
                        behaviour = foundBehaviour
                    };
                    index++;
                }

                for (var i = 0; i < exported.hiddenComponents.Length; i++)
                {
                    exported.hiddenComponents[i].hideFlags = exported.hiddenComponents[i].behaviour.hideFlags;
                    exported.hiddenComponents[i].enabled   = exported.hiddenComponents[i].behaviour.enabled;
                }

                for (var i = 0; i < exported.hiddenComponents.Length; i++)
                {
                    exported.hiddenComponents[i].behaviour.hideFlags = exported.hiddenComponents[i].behaviour.hideFlags | ComponentHideFlags;
                    exported.hiddenComponents[i].behaviour.enabled   = false;
                }

                EditorSceneManager.MarkSceneDirty(currentScene);
                Undo.CollapseUndoOperations(groupIndex);
                groupIndex      = 0;
                exported.disarm = false;
            }
            finally
            {
                switch (exportType)
                {
                case ExportType.FBX:
                {
                    UnityEngine.Object.DestroyImmediate(tempExportObject);
                    break;
                }
                }
                if (groupIndex != 0)
                {
                    Undo.CollapseUndoOperations(groupIndex);
                }
            }
        }
Exemple #7
0
        //This is for curves that are tracked slightly differently from regular curves: Active curve and Z-index curve
        private void SetAdditionalCurves(Transform child, MainLineKey[] keys, TimeLine timeLine, AnimationClip clip, float defaultZ)
        {
            var positionChanged = false;
            var kfsZ            = new List <Keyframe> ();
            var changedZ        = false;
            var active          = child.gameObject.activeSelf; //If the sprite or bone isn't present in the mainline,
            var kfsActive       = new List <Keyframe> ();      //Disable the GameObject if it isn't already disabled
            var childPath       = GetPathToChild(child);

            foreach (var key in keys)               //If it is present, enable the GameObject if it isn't already enabled
            {
                var mref = ArrayUtility.Find(key.objectRefs, x => x.timeline == timeLine.id);
                if (mref != null)
                {
                    if (defaultZ == inf)
                    {
                        defaultZ        = mref.z_index;
                        positionChanged = true;
                    }
                    if (!changedZ && mref.z_index != defaultZ)
                    {
                        changedZ = true;
                        if (key.time > 0)
                        {
                            kfsZ.Add(new Keyframe(0f, defaultZ, inf, inf));
                        }
                    }
                    if (changedZ)
                    {
                        kfsZ.Add(new Keyframe(key.time, mref.z_index, inf, inf));
                    }
                    if (!active)
                    {
                        if (kfsActive.Count <= 0 && key.time > 0)
                        {
                            kfsActive.Add(new Keyframe(0f, 0f, inf, inf));
                        }
                        kfsActive.Add(new Keyframe(key.time, 1f, inf, inf));
                        active = true;
                    }
                }
                else if (active)
                {
                    if (kfsActive.Count <= 0 && key.time > 0)
                    {
                        kfsActive.Add(new Keyframe(0f, 1f, inf, inf));
                    }
                    kfsActive.Add(new Keyframe(key.time, 0f, inf, inf));
                    active = false;
                }
            }             //Only add these curves if there is actually a mutation
            if (kfsZ.Count > 0)
            {
                clip.SetCurve(childPath, typeof(Transform), "localPosition.z", new AnimationCurve(kfsZ.ToArray()));
                if (!positionChanged)
                {
                    var info = timeLine.keys [0].info;                     //If these curves don't actually exist, add some empty ones
                    clip.SetCurve(childPath, typeof(Transform), "localPosition.x", new AnimationCurve(new Keyframe(0f, info.x)));
                    clip.SetCurve(childPath, typeof(Transform), "localPosition.y", new AnimationCurve(new Keyframe(0f, info.y)));
                }
            }
            if (kfsActive.Count > 0)
            {
                clip.SetCurve(childPath, typeof(GameObject), "m_IsActive", new AnimationCurve(kfsActive.ToArray()));
            }
        }
        /// <summary>
        /// Insert a number of new points to each edge. Points are evenly spaced out along the edge.
        /// </summary>
        /// <param name="mesh">The source mesh.</param>
        /// <param name="edges">The edges to split with points.</param>
        /// <param name="count">The number of new points to insert. Must be greater than 0.</param>
        /// <returns>The new edges created by inserting points.</returns>
        public static List <Edge> AppendVerticesToEdge(this ProBuilderMesh mesh, IList <Edge> edges, int count)
        {
            if (mesh == null)
            {
                throw new ArgumentNullException("mesh");
            }

            if (edges == null)
            {
                throw new ArgumentNullException("edges");
            }

            if (count < 1 || count > 512)
            {
                Log.Error("New edge vertex count is less than 1 or greater than 512.");
                return(null);
            }

            List <Vertex>         vertices        = new List <Vertex>(mesh.GetVertices());
            Dictionary <int, int> lookup          = mesh.sharedVertexLookup;
            Dictionary <int, int> lookupUV        = mesh.sharedTextureLookup;
            List <int>            indexesToDelete = new List <int>();
            IEnumerable <Edge>    commonEdges     = EdgeUtility.GetSharedVertexHandleEdges(mesh, edges);
            List <Edge>           distinctEdges   = commonEdges.Distinct().ToList();

            Dictionary <Face, FaceRebuildData> modifiedFaces = new Dictionary <Face, FaceRebuildData>();

            int originalSharedIndexesCount = lookup.Count();
            int sharedIndexesCount         = originalSharedIndexesCount;

            foreach (Edge edge in distinctEdges)
            {
                Edge localEdge = EdgeUtility.GetEdgeWithSharedVertexHandles(mesh, edge);

                // Generate the new vertices that will be inserted on this edge
                List <Vertex> verticesToAppend = new List <Vertex>(count);

                for (int i = 0; i < count; i++)
                {
                    verticesToAppend.Add(Vertex.Mix(vertices[localEdge.a], vertices[localEdge.b], (i + 1) / ((float)count + 1)));
                }

                List <SimpleTuple <Face, Edge> > adjacentFaces = ElementSelection.GetNeighborFaces(mesh, localEdge);

                // foreach face attached to common edge, append vertices
                foreach (SimpleTuple <Face, Edge> tup in adjacentFaces)
                {
                    Face face = tup.item1;

                    FaceRebuildData data;

                    if (!modifiedFaces.TryGetValue(face, out data))
                    {
                        data                 = new FaceRebuildData();
                        data.face            = new Face(new int[0], face.submeshIndex, new AutoUnwrapSettings(face.uv), face.smoothingGroup, face.textureGroup, -1, face.manualUV);
                        data.vertices        = new List <Vertex>(ArrayUtility.ValuesWithIndexes(vertices, face.distinctIndexesInternal));
                        data.sharedIndexes   = new List <int>();
                        data.sharedIndexesUV = new List <int>();

                        foreach (int i in face.distinctIndexesInternal)
                        {
                            int shared;

                            if (lookup.TryGetValue(i, out shared))
                            {
                                data.sharedIndexes.Add(shared);
                            }

                            if (lookupUV.TryGetValue(i, out shared))
                            {
                                data.sharedIndexesUV.Add(shared);
                            }
                        }

                        indexesToDelete.AddRange(face.distinctIndexesInternal);

                        modifiedFaces.Add(face, data);
                    }

                    data.vertices.AddRange(verticesToAppend);

                    for (int i = 0; i < count; i++)
                    {
                        data.sharedIndexes.Add(sharedIndexesCount + i);
                        data.sharedIndexesUV.Add(-1);
                    }
                }

                sharedIndexesCount += count;
            }

            // now apply the changes
            List <Face>            dic_face      = modifiedFaces.Keys.ToList();
            List <FaceRebuildData> dic_data      = modifiedFaces.Values.ToList();
            List <EdgeLookup>      appendedEdges = new List <EdgeLookup>();

            for (int i = 0; i < dic_face.Count; i++)
            {
                Face            face = dic_face[i];
                FaceRebuildData data = dic_data[i];

                Vector3   nrm        = Math.Normal(mesh, face);
                Vector2[] projection = Projection.PlanarProject(data.vertices.Select(x => x.position).ToArray(), null, nrm);

                int vertexCount = vertices.Count;

                // triangulate and set new face indexes to end of current vertex list
                List <int> indexes;

                if (Triangulation.SortAndTriangulate(projection, out indexes))
                {
                    data.face.indexesInternal = indexes.ToArray();
                }
                else
                {
                    continue;
                }

                data.face.ShiftIndexes(vertexCount);
                face.CopyFrom(data.face);

                for (int n = 0; n < data.vertices.Count; n++)
                {
                    lookup.Add(vertexCount + n, data.sharedIndexes[n]);
                }

                if (data.sharedIndexesUV.Count == data.vertices.Count)
                {
                    for (int n = 0; n < data.vertices.Count; n++)
                    {
                        lookupUV.Add(vertexCount + n, data.sharedIndexesUV[n]);
                    }
                }

                vertices.AddRange(data.vertices);

                foreach (Edge e in face.edgesInternal)
                {
                    EdgeLookup el = new EdgeLookup(new Edge(lookup[e.a], lookup[e.b]), e);

                    if (el.common.a >= originalSharedIndexesCount || el.common.b >= originalSharedIndexesCount)
                    {
                        appendedEdges.Add(el);
                    }
                }
            }

            indexesToDelete = indexesToDelete.Distinct().ToList();
            int delCount = indexesToDelete.Count;

            var newEdges = appendedEdges.Distinct().Select(x => x.local - delCount).ToList();

            mesh.SetVertices(vertices);
            mesh.SetSharedVertices(lookup);
            mesh.SetSharedTextures(lookupUV);
            mesh.DeleteVertices(indexesToDelete);

            return(newEdges);
        }
Exemple #9
0
    public override void OnInspectorGUI()
    {
        Tapestry_Item i = target as Tapestry_Item;

        if (startup)
        {
            if (!ReferenceEquals(i.data.effect, null))
            {
                if (!ReferenceEquals(i.data.effect.payload, null))
                {
                    pSel = ArrayUtility.IndexOf(Tapestry_Config.GetPayloadTypes().Values.ToArray(), i.data.effect.payload.GetType());
                }
            }
            else
            {
                pSel = 0;
            }
            startup = false;
        }

        string
            displayTooltip      = "What string will display on the player's HUD when looking at this object.",
            prefabTooltip       = "What is the name of the prefab (placed in the Resources/Items folder) that should be instantiated when this object is dropped in world?\n\nGenerally this should be the object's in-world name, rather than its display name.",
            interactableTooltip = "Can the player take this object to their inventory?",
            displayNameTooltip  = "Should the object still show its display name when the player's cursor is hovering over the object?",
            valueTooltip        = "How valuable is this object?";

        GUILayout.BeginVertical("box");

        GUILayout.BeginHorizontal();
        GUILayout.Label(new GUIContent("Display Name", displayTooltip));
        GUILayout.FlexibleSpace();
        i.displayName      = EditorGUILayout.DelayedTextField(i.displayName, GUILayout.Width(270));
        i.data.displayName = i.displayName;
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        GUILayout.Label(new GUIContent("Prefab Name", prefabTooltip));
        GUILayout.FlexibleSpace();
        i.data.prefabName = EditorGUILayout.DelayedTextField(i.data.prefabName, GUILayout.Width(270));
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        i.isInteractable = EditorGUILayout.Toggle(i.isInteractable, GUILayout.Width(12));
        GUILayout.Label(new GUIContent("Takeable?", interactableTooltip));
        GUILayout.Space(20);
        if (!i.isInteractable)
        {
            i.displayNameWhenUnactivatable = EditorGUILayout.Toggle(i.displayNameWhenUnactivatable, GUILayout.Width(12));
            GUILayout.Label(new GUIContent("Display Name Anyway?", displayNameTooltip));
            GUILayout.FlexibleSpace();
        }
        GUILayout.FlexibleSpace();
        GUILayout.Label(new GUIContent("Value", valueTooltip));
        i.data.value = EditorGUILayout.DelayedIntField(i.data.value, GUILayout.Width(50));
        GUILayout.EndHorizontal();

        GUILayout.EndVertical();

        DrawSubTabItemData(i);

        DrawSubTabEffect(i);

        DrawSubTabKeywords(i);
    }
    public override void UpdateCurveWrappers(CinemaClipCurveWrapper clipWrapper)
    {
        CinemaMultiActorCurveClip clipCurve = clipWrapper.Behaviour as CinemaMultiActorCurveClip;

        if (clipCurve == null)
        {
            return;
        }

        for (int i = 0; i < clipCurve.CurveData.Count; i++)
        {
            MemberClipCurveData member = clipCurve.CurveData[i];

            CinemaMemberCurveWrapper memberWrapper = null;
            if (!clipWrapper.TryGetValue(member.PropertyType.ToString(), member.PropertyName, out memberWrapper))
            {
                memberWrapper              = new CinemaMemberCurveWrapper();
                memberWrapper.Type         = member.PropertyType.ToString();
                memberWrapper.PropertyName = member.PropertyName;
                memberWrapper.Texture      = EditorGUIUtility.ObjectContent(null, UnityPropertyTypeInfo.GetUnityType(member.Type)).image;
                ArrayUtility.Add <CinemaMemberCurveWrapper>(ref clipWrapper.MemberCurves, memberWrapper);

                int showingCurves = UnityPropertyTypeInfo.GetCurveCount(member.PropertyType);
                memberWrapper.AnimationCurves = new CinemaAnimationCurveWrapper[showingCurves];

                for (int j = 0; j < showingCurves; j++)
                {
                    memberWrapper.AnimationCurves[j] = new CinemaAnimationCurveWrapper();

                    memberWrapper.AnimationCurves[j].Id    = j;
                    memberWrapper.AnimationCurves[j].Curve = new AnimationCurve(member.GetCurve(j).keys);
                    memberWrapper.AnimationCurves[j].Color = UnityPropertyTypeInfo.GetCurveColor(j);
                    memberWrapper.AnimationCurves[j].Label = UnityPropertyTypeInfo.GetCurveName(member.PropertyType, j);
                }
            }
            else
            {
                int showingCurves = UnityPropertyTypeInfo.GetCurveCount(member.PropertyType);
                for (int j = 0; j < showingCurves; j++)
                {
                    memberWrapper.AnimationCurves[j].Curve = new AnimationCurve(member.GetCurve(j).keys);
                }
            }
        }

        // Remove missing track items
        List <CinemaMemberCurveWrapper> itemRemovals = new List <CinemaMemberCurveWrapper>();

        for (int i = 0; i < clipWrapper.MemberCurves.Length; i++)
        {
            CinemaMemberCurveWrapper cw = clipWrapper.MemberCurves[i];
            bool found = false;
            for (int j = 0; j < clipCurve.CurveData.Count; j++)
            {
                MemberClipCurveData member = clipCurve.CurveData[j];
                if (member.PropertyType.ToString() == cw.Type && member.PropertyName == cw.PropertyName)
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                itemRemovals.Add(cw);
            }
        }
        for (int i = 0; i < itemRemovals.Count; i++)
        {
            ArrayUtility.Remove <CinemaMemberCurveWrapper>(ref clipWrapper.MemberCurves, itemRemovals[i]);
        }
    }
        /// <summary>
        /// Append a new face to the ProBuilderMesh.
        /// </summary>
        /// <param name="mesh">The mesh target.</param>
        /// <param name="positions">The new vertex positions to add.</param>
        /// <param name="colors">The new colors to add (must match positions length).</param>
        /// <param name="uvs">The new uvs to add (must match positions length).</param>
        /// <param name="face">A face with the new triangle indexes. The indexes should be 0 indexed.</param>
        /// <param name="common"></param>
        /// <returns>The new face as referenced on the mesh.</returns>
        internal static Face AppendFace(this ProBuilderMesh mesh, Vector3[] positions, Color[] colors, Vector2[] uvs, Face face, int[] common)
        {
            if (mesh == null)
            {
                throw new ArgumentNullException("mesh");
            }

            if (positions == null)
            {
                throw new ArgumentNullException("positions");
            }

            if (face == null)
            {
                throw new ArgumentNullException("face");
            }

            int faceVertexCount = positions.Length;

            if (common == null)
            {
                common = new int[faceVertexCount];
                for (int i = 0; i < faceVertexCount; i++)
                {
                    common[i] = -1;
                }
            }

            int vertexCount = mesh.vertexCount;

            var mc = mesh.HasArrays(MeshArrays.Color);
            var fc = colors != null;
            var mt = mesh.HasArrays(MeshArrays.Texture0);
            var ft = uvs != null;

            Vector3[] newPositions = new Vector3[vertexCount + faceVertexCount];
            Color[]   newColors    = (mc || fc) ? new Color[vertexCount + faceVertexCount] : null;
            Vector2[] newTextures  = (mt || ft) ? new Vector2[vertexCount + faceVertexCount] : null;

            List <Face> faces = new List <Face>(mesh.facesInternal);

            Array.Copy(mesh.positionsInternal, 0, newPositions, 0, vertexCount);
            Array.Copy(positions, 0, newPositions, vertexCount, faceVertexCount);

            if (mc || fc)
            {
                Array.Copy(mc ? mesh.colorsInternal : ArrayUtility.Fill(Color.white, vertexCount), 0, newColors, 0, vertexCount);
                Array.Copy(fc ? colors : ArrayUtility.Fill(Color.white, faceVertexCount), 0, newColors, vertexCount, colors.Length);
            }

            if (mt || ft)
            {
                Array.Copy(mt ? mesh.texturesInternal : ArrayUtility.Fill(Vector2.zero, vertexCount), 0, newTextures, 0, vertexCount);
                Array.Copy(ft ? uvs : ArrayUtility.Fill(Vector2.zero, faceVertexCount), 0, newTextures, mesh.texturesInternal.Length, faceVertexCount);
            }

            face.ShiftIndexesToZero();
            face.ShiftIndexes(vertexCount);

            faces.Add(face);

            for (int i = 0; i < common.Length; i++)
            {
                if (common[i] < 0)
                {
                    mesh.AddSharedVertex(new SharedVertex(new int[] { i + vertexCount }));
                }
                else
                {
                    mesh.AddToSharedVertex(common[i], i + vertexCount);
                }
            }

            mesh.positions = newPositions;
            mesh.colors    = newColors;
            mesh.textures  = newTextures;
            mesh.faces     = faces;

            return(face);
        }
        public void UpdateMesh(ControlMesh controlMesh, Vector3[] vertices = null)
        {
            if (controlMesh == null ||
                controlMesh.Vertices == null ||
                controlMesh.Edges == null ||
                controlMesh.Polygons == null ||
                PolygonPointIndices == null)
            {
                return;
            }

            if (vertices == null)
            {
                vertices = controlMesh.Vertices;
            }

            if (!BrushTransform)
            {
                return;
            }

            var pointCount = vertices.Length;

            if (WorldPoints.Length != pointCount)
            {
                AllocatePoints(pointCount);
            }

            var edgeCount = controlMesh.Edges.Length;

            if (Edges.Length != edgeCount)
            {
                AllocateEdges(edgeCount);
            }

            var polygonCount = controlMesh.Polygons.Length;

            if (PolygonControlId.Length != polygonCount)
            {
                AllocatePolygons(polygonCount);
            }

            var index = 0;

            for (var e = 0; e < edgeCount; e++)
            {
                if (e >= controlMesh.Edges.Length ||
                    index >= Edges.Length)
                {
                    continue;
                }

                var twin = controlMesh.Edges[e].TwinIndex;
                if (twin < e ||                 // if it's less than e then we've already handled our twin
                    twin >= controlMesh.Edges.Length)
                {
                    continue;
                }

                var polygonIndex = controlMesh.Edges[e].PolygonIndex;
                if (polygonIndex < 0 || polygonIndex >= controlMesh.Polygons.Length)
                {
                    continue;
                }

                var twinPolygonIndex = controlMesh.Edges[twin].PolygonIndex;
                if (twinPolygonIndex < 0 || twinPolygonIndex >= controlMesh.Polygons.Length)
                {
                    continue;
                }

                var vertexIndex1 = controlMesh.Edges[e].VertexIndex;
                var vertexIndex2 = controlMesh.Edges[twin].VertexIndex;

                if (vertexIndex1 < 0 || vertexIndex1 >= Selection.Points.Length ||
                    vertexIndex2 < 0 || vertexIndex2 >= Selection.Points.Length)
                {
                    continue;
                }

                Edges[index]     = vertexIndex1;
                Edges[index + 1] = vertexIndex2;
                EdgeStateToHalfEdge[index / 2] = e;
                HalfEdgeToEdgeStates[e]        = index;
                HalfEdgeToEdgeStates[twin]     = index;
                EdgeSurfaces[index]            = polygonIndex;
                EdgeSurfaces[index + 1]        = twinPolygonIndex;

                /*
                 *              if ((Selection.Points[vertexIndex1] & SelectState.Selected) == SelectState.Selected &&
                 *                      (Selection.Points[vertexIndex2] & SelectState.Selected) == SelectState.Selected)
                 *                      Selection.Edges[index / 2] |= SelectState.Selected;
                 *              else
                 *                      Selection.Edges[index / 2] &= ~SelectState.Selected;
                 */
                //edgeSelectState[index / 2] = SelectState.None;
                index += 2;
            }

            var polygonCountModified = false;

            while (polygonCount > PolygonPointIndices.Length)
            {
                ArrayUtility.Add(ref PolygonPointIndices, null);
                polygonCountModified = true;
            }
            while (polygonCount < PolygonPointIndices.Length)
            {
                ArrayUtility.RemoveAt(ref PolygonPointIndices, PolygonPointIndices.Length - 1);
                polygonCountModified = true;
            }

            if (polygonCountModified)
            {
                for (var i = 0; i < polygonCount; i++)
                {
                    PolygonPointIndices[i] = null;
                }
            }

            UpdatePoints(controlMesh, vertices);
        }
Exemple #13
0
 public void OnPropertyDelete(CustomPropertyInfo property)
 {
     ArrayUtility.Remove <CustomPropertyInfo> (ref selectedProperties, property);
     SaveCurrentType();
     CachePropertiesDrawer();
 }
Exemple #14
0
 static public bool IsViewModelExisted(string name)
 {
     return(ArrayUtility.Contains(types, name));
 }
        private static async Task RegisterAsync(string lastName, string firstName, string username, byte[] password, Role role)
        {
            byte[]           bytes      = Encoding.UTF8.GetBytes("LastName=" + lastName + "&FirstName=" + firstName + "&Username="******"&Password="******"Role error");
            }

            Array.Clear(bytes, 0, bytes.Length);
            Array.Clear(parameters, 0, parameters.Length);
            content.Dispose();

            if (status == 200)
            {
                if (!String.Equals(body, "Success"))
                {
                    if (body.Contains("exists"))
                    {
                        throw new UserExistsException(body);
                    }
                    else
                    {
                        throw new Exception("Message contents could not be parsed.");
                    }
                }
            }
            else if (status == 400)
            {
                throw new Exception(body);
            }
            else if (status == 500)
            {
                throw new ServerException();
            }
            else
            {
                throw new Exception("An error occurred");
            }
        }
Exemple #16
0
        public static bool FindClickWorldIntersection(Vector2 screenPos, out GameObject foundObject)
        {
            var sceneView = SceneView.currentDrawingSceneView ? SceneView.currentDrawingSceneView : SceneView.lastActiveSceneView;
            var camera    = sceneView ? sceneView.camera : Camera.current;

            foundObject = null;
            if (!camera)
            {
                return(false);
            }

            var worldRay  = HandleUtility.GUIPointToWorldRay(screenPos);
            var rayStart  = worldRay.origin;
            var rayVector = (worldRay.direction * (camera.farClipPlane - camera.nearClipPlane));
            var rayEnd    = rayStart + rayVector;

            CSGModel intersectionModel = null;

            if (_prevSceenPos == screenPos && _prevSceneView == sceneView && _deepClickIntersections != null)
            {
                var prevIntersection = (_deepIndex > 0 && _deepIndex < _deepClickIntersections.Length) ? _deepClickIntersections[_deepIndex] : null;
                if (_deepClickIntersections.Length > 1)
                {
                    for (var i = _deepClickIntersections.Length - 1; i >= 0; i--)
                    {
                        if (_deepClickIntersections[i].brush)
                        {
                            continue;
                        }
                        ArrayUtility.RemoveAt(ref _deepClickIntersections, i);
                        if (i <= _deepIndex)
                        {
                            _deepIndex--;
                        }
                    }
                }

                if (_deepClickIntersections.Length <= 1)
                {
                    ResetDeepClick();
                }
                else
                {
                    _deepIndex = (_deepIndex + 1) % _deepClickIntersections.Length;
                    var currentIntersection = (_deepIndex > 0 && _deepIndex < _deepClickIntersections.Length) ? _deepClickIntersections[_deepIndex] : null;
                    if (currentIntersection != prevIntersection &&
                        currentIntersection != null)
                    {
                        foundObject       = currentIntersection.gameObject;
                        _prevSceenPos     = screenPos;
                        _prevSceneView    = sceneView;
                        intersectionModel = currentIntersection.model;
                    }
                    else
                    {
                        ResetDeepClick();
                    }
                }
            }

            if (_prevSceenPos != screenPos)
            {
                var wireframeShown = CSGSettings.IsWireframeShown(sceneView);
                if (FindMultiWorldIntersection(rayStart, rayEnd, out _deepClickIntersections, growDistance: 0, ignoreInvisibleSurfaces: !wireframeShown, ignoreUnrenderables: !wireframeShown))
                {
                    _deepIndex = 0;
                    var intersection = _deepClickIntersections[0];
                    foundObject       = intersection.gameObject;
                    _prevSceenPos     = screenPos;
                    _prevSceneView    = sceneView;
                    intersectionModel = intersection.model;
                }
                else
                {
                    ResetDeepClick();
                }
            }

            GameObject[] modelMeshes = null;
            if (intersectionModel != null)
            {
                modelMeshes = CSGModelManager.GetModelMeshes(intersectionModel);
            }

            if (modelMeshes != null)
            {
                for (var i = 0; i < modelMeshes.Length; i++)
                {
                    modelMeshes[i].hideFlags = HideFlags.None;
                }
            }

            var gameObject = HandleUtility.PickGameObject(screenPos, false);

            if (modelMeshes != null)
            {
                for (var i = 0; i < modelMeshes.Length; i++)
                {
                    var modelMesh = modelMeshes[i];
                    if (!modelMesh)
                    {
                        continue;
                    }

                    if (gameObject == modelMesh)
                    {
                        gameObject = null;
                    }

                    modelMesh.hideFlags = MeshInstanceManager.ComponentHideFlags;
                }
            }

            if (!gameObject ||
                gameObject.GetComponent <CSGModel>() ||
                gameObject.GetComponent <CSGBrush>() ||
                gameObject.GetComponent <CSGOperation>() ||
                gameObject.GetComponent <GeneratedMeshInstance>() ||
                gameObject.GetComponent <GeneratedMeshes>())
            {
                return(foundObject != null);
            }

            foundObject = gameObject;
            return(true);
        }
Exemple #17
0
        /// <summary>
        /// Decode KILE PDUs from received message bytes
        /// </summary>
        /// <param name="endPoint">An endpoint from which the message bytes are received</param>
        /// <param name="receivedBytes">The received bytes to be decoded</param>
        /// <param name="consumedLength">Length of message bytes consumed by decoder</param>
        /// <param name="expectedLength">Length of message bytes the decoder expects to receive</param>
        /// <returns>The decoded KILE PDUs</returns>
        /// <exception cref="System.FormatException">thrown when a kile message type is unsupported</exception>
        internal KilePdu[] DecodePacketCallback(object endPoint,
                                                byte[] receivedBytes,
                                                out int consumedLength,
                                                out int expectedLength)
        {
            // initialize lengths
            consumedLength = 0;
            expectedLength = 0;

            if (null == receivedBytes || 0 == receivedBytes.Length)
            {
                return(null);
            }
            if (!isClientRole)
            {
                serverContext = null;

                if (serverContextList != null)
                {
                    KileConnection kileConnection = new KileConnection((IPEndPoint)endPoint);

                    if (!serverContextList.ContainsKey(kileConnection))
                    {
                        serverContext = new KileServerContext();
                        serverContext.TransportType = connectionType;
                        serverContextList.Add(kileConnection, serverContext);
                    }
                    else
                    {
                        serverContext = serverContextList[kileConnection];
                    }
                }
                if (serverContext == null)
                {
                    throw new InvalidOperationException("The kileConnection related context does not exist.");
                }
            }

            // TCP has a 4 bytes length header, while UDP has not
            byte[] pduBytes = receivedBytes;

            if ((isClientRole && clientContext.TransportType == KileConnectionType.TCP) ||
                (!isClientRole && serverContext.TransportType == KileConnectionType.TCP))
            {
                // insufficient data, needs to receive more
                if (receivedBytes.Length < sizeof(int))
                {
                    return(null);
                }

                // get pdu data length
                byte[] lengthBytes = ArrayUtility.SubArray(receivedBytes, 0, sizeof(int));
                Array.Reverse(lengthBytes);
                int pduLength = BitConverter.ToInt32(lengthBytes, 0);

                // insufficient data, needs to receive more
                expectedLength = sizeof(int) + pduLength;
                if (receivedBytes.Length < expectedLength)
                {
                    return(null);
                }

                // check if it is a krb zero message
                if (pduLength == 0 && receivedBytes.Length == sizeof(int))
                {
                    consumedLength = sizeof(int);
                    KrbZero krbZeroPdu = new KrbZero(clientContext);
                    return(new KilePdu[] { krbZeroPdu });
                }

                // remove length header from pdu bytes
                pduBytes = ArrayUtility.SubArray <byte>(receivedBytes, sizeof(int), pduLength);
            }
            else
            {
                // UDP has no length header
                expectedLength = pduBytes.Length;
            }

            // get message type
            // (the lower 5 bits indicates its kile message type)
            MsgType kileMessageType = (MsgType)(pduBytes[0] & 0x1f);

            // decode according to message type
            consumedLength = expectedLength;
            KilePdu pdu = null;

            switch (kileMessageType)
            {
            case MsgType.KRB_AS_REQ:
                pdu = new KileAsRequest(serverContext);
                break;

            case MsgType.KRB_AS_RESP:
                pdu = new KileAsResponse(clientContext);
                break;

            case MsgType.KRB_TGS_REQ:
                pdu = new KileTgsRequest(serverContext);
                break;

            case MsgType.KRB_TGS_RESP:
                pdu = new KileTgsResponse(clientContext);
                break;

            case MsgType.KRB_ERROR:
                pdu = new KileKrbError();
                break;

            default:
                throw new FormatException(
                          "Unsupported Message Type: " + kileMessageType.ToString());
            }
            pdu.FromBytes(pduBytes);

            // update context
            if (isClientRole)
            {
                clientContext.UpdateContext(pdu);
            }
            else
            {
                serverContext.UpdateContext(pdu);
            }

            return(new KilePdu[] { pdu });
        }
 internal static bool IsFormatRequireCompressionSetting(TextureImporterFormat format)
 {
     return(ArrayUtility.Contains <TextureImporterFormat>(TexturePlatformSettingsModal.kFormatsWithCompressionSettings, format));
 }
Exemple #19
0
    /* if (!Application.isPlaying)
     * El OnInspectorGUI y OnSceneGUI usan esta condicion porque hay ciertas
     * cosas del PlatformController que se inicializan en el Start, por lo que
     * si se pretende cambiar algo en el inspector o desde la escena mientras
     * esta en modo juego no va a funcionar bien.
     */

    public override void OnInspectorGUI()
    {
        #region     VELOCIDAD DE LA PLATAFORMA
        EditorGUI.BeginChangeCheck();

        float speed = m_PlatformController.m_speed;
        speed = EditorGUILayout.FloatField("Velocidad", speed);

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

        if (EditorGUI.EndChangeCheck())
        {
            Undo.RecordObject(target, "changed speed");
            m_PlatformController.m_speed = speed;
        }
        #endregion

        if (!Application.isPlaying)
        {
            #region     EN QUE NODO EMPIEZA
            EditorGUI.BeginChangeCheck();

            int begin = m_PlatformController.m_button;
            begin = EditorGUILayout.IntField("Empieza en", begin);

            if (begin > (m_PlatformController.localNodes.Length - 1))
            {
                begin = m_PlatformController.localNodes.Length - 1;
            }
            else if (begin < 0)
            {
                begin = 0;
            }

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(target, "changed where it begins");
                m_PlatformController.m_button = begin;
                for (int i = 0; i < m_PlatformController.localNodes.Length; ++i)
                {
                    if (i != begin)
                    {
                        m_PlatformController.localNodes[i] -= m_PlatformController.localNodes[begin];
                    }
                }
                m_PlatformController.transform.position = m_PlatformController.transform.TransformPoint(m_PlatformController.localNodes[begin]);
                m_PlatformController.localNodes[begin]  = Vector3.zero;
            }
            #endregion

            #region     NODOS
            if (GUILayout.Button("Add Node"))                                                                                   // Crea el boton 'Add Node'
            {
                Undo.RecordObject(target, "added node");                                                                        // Guarda los cambios que se realicen a continuacion
                Vector3 position = m_PlatformController.localNodes[m_PlatformController.localNodes.Length - 1] + Vector3.right; // posicion del ultimo nodo
                ArrayUtility.Add(ref m_PlatformController.localNodes, position);                                                // Anyade un nuevo nodo al array en la posicion 'position'
            }

            EditorGUIUtility.labelWidth = 64;
            int delete = -1;                                          // Muestra y modifica la posicion de los nodos
            for (int i = 0; i < m_PlatformController.localNodes.Length; ++i)
            {
                EditorGUI.BeginChangeCheck();

                EditorGUILayout.BeginHorizontal();          // HORIZONTAL

                int size = 64;
                EditorGUILayout.BeginVertical(GUILayout.Width(size));                // Crea menu desplegable?
                EditorGUILayout.LabelField("Node " + i, GUILayout.Width(size));      // Enumeracion de los nodos
                if ((i != 0) && (GUILayout.Button("Delete", GUILayout.Width(size)))) // Boton para eliminar un nodo (excepto el primero)
                {                                                                    // !BOTON! No implementa aqui la eliminacion
                    delete = i;
                }
                EditorGUILayout.EndVertical();

                EditorGUILayout.BeginVertical();            // Muestra la posicion (x,y) de cada nuevo nodo
                Vector2 newPosition;                        // (excepto el primero que esta fijo)
                newPosition = EditorGUILayout.Vector2Field("Position",
                                                           m_PlatformController.transform.TransformPoint(m_PlatformController.localNodes[i]));
                EditorGUILayout.EndVertical();

                EditorGUILayout.EndHorizontal();        // HORIZONTAL: todo esto se escribe en una sola linea

                if (EditorGUI.EndChangeCheck())
                {
                    Undo.RecordObject(target, "changed position");
                    m_PlatformController.localNodes[i] = m_PlatformController.transform.InverseTransformPoint(newPosition);       // Guarda la nueva posicion asignada
                }
            }
            EditorGUIUtility.labelWidth = 0;

            if (delete != -1)
            {
                Undo.RecordObject(target, "Removed node");              // Elimina un nodo
                ArrayUtility.RemoveAt(ref m_PlatformController.localNodes, delete);
            }
            #endregion
        }
    }
        public override void OnGUI(Rect pos, SerializedProperty prop, GUIContent label)
        {
            if (!attributeScanned)
            {
                attributeScanned = true;

                // check for EventTargetVariable Attribute
                object[] _evenTargets = this.fieldInfo.GetCustomAttributes(typeof(EventTargetVariable), true);

                if (_evenTargets.Length > 0)
                {
                    string variableName = (_evenTargets[0] as EventTargetVariable).variable;
                    eventTargetVariable = prop.serializedObject.FindProperty(variableName);
                }

                /// check for the ShowOptions attribute
                object[] _showOptions = this.fieldInfo.GetCustomAttributes(typeof(ShowOptions), true);

                if (_showOptions.Length > 0)
                {
                    showOptions = true;
                }
            }

            if (eventTargetVariable != null)
            {
                eventTarget     = eventTargetVariable.FindPropertyRelative("eventTarget");
                includeChildren = eventTargetVariable.FindPropertyRelative("includeChildren");
                gameObject      = eventTargetVariable.FindPropertyRelative("gameObject");
                fsmComponent    = eventTargetVariable.FindPropertyRelative("fsmComponent");
            }

            eventName = prop.FindPropertyRelative("eventName");
            string _eventName = eventName.stringValue;

            allowLocalEvents = prop.FindPropertyRelative("allowLocalEvents");
            bool _allowEvent = allowLocalEvents.boolValue;

            defaultEventName      = prop.FindPropertyRelative("defaultEventName");
            defaultEventNameValue = defaultEventName.stringValue;

            CacheOwnerGameObject(prop.serializedObject);

            int row = 0;

            string[] _eventList = new string[0];

            bool isEventImplemented = false;


            // Get the list of events
            if (eventTarget == null || eventTarget.enumValueIndex == 2)         // Undefined || broadcastAll
            {
                _eventList = PlayMakerInspectorUtils.GetGlobalEvents(true);
            }
            else if (eventTarget.enumValueIndex == 0 || eventTarget.enumValueIndex == 1)          // Owner || GameObject
            {
                _eventList         = PlayMakerInspectorUtils.GetGlobalEvents(true);
                isEventImplemented = PlayMakerInspectorUtils.DoesTargetImplementsEvent((GameObject)gameObject.objectReferenceValue, _eventName, true);
            }
            else if (eventTarget.enumValueIndex == 3)              // FsmComponent
            {
                PlayMakerFSM _fsm = (PlayMakerFSM)fsmComponent.objectReferenceValue;
                _eventList = PlayMakerInspectorUtils.GetImplementedGlobalEvents(_fsm, true);

                isEventImplemented = PlayMakerInspectorUtils.DoesTargetImplementsEvent(_fsm, _eventName);
            }

            // find the index of the serialized event name in the list of events
            int selected = 0;

            if (!string.IsNullOrEmpty(_eventName))
            {
                selected = ArrayUtility.IndexOf <string>(_eventList, _eventName);
            }

            Rect _rect = GetRectforRow(pos, ++row - 1);

            if (showOptions)
            {
                _rect.width -= 18;
            }

            string _popupLabel = label.text;

            if (selected != 0 && eventTarget.enumValueIndex != 2)        // not none and not broadcasting
            {
                if ((selected > 0 && !isEventImplemented) || selected == -1)
                {
                    //_popup = GUI.skin.GetStyle("ErrorLabel");
                    GUIStyle labelStyle = GUI.skin.GetStyle("controlLabel");
                    labelStyle.richText = true;

                    _popupLabel = "<color=red>" + _popupLabel + "</color>";
                }
            }

            // Event Popup
            Rect _contentRect = EditorGUI.PrefixLabel(_rect, label);

            //_contentRect.width -= 0;
            if (GUI.Button(
                    _contentRect,
                    string.IsNullOrEmpty(_eventName)?"none":_eventName,
                    EditorStyles.popup))
            {
                GenericMenu menu = GenerateEventMenu(_eventList, _eventName);
                menu.DropDown(_rect);
            }

            /*
             * _rect.x =_rect.xMax-10;
             * _rect.width = 10;
             *
             * if (GUI.Button(_rect,"?","label"))
             * {
             *      //buttonRect.x += FsmEditor.Window.position.x + FsmEditor.Window.position.width - FsmEditor.InspectorPanelWidth;
             *      //buttonRect.y += FsmEditor.Window.position.y + StateInspector.ActionsPanelRect.y + 3 - FsmEditor.StateInspector.scrollPosition.y;
             *      //var newVariableWindow = PlayMakerEditor.  NewEventWindow.CreateDropdown("New Global Event", _contentRect, eventName);
             *      //newVariableWindow.EditCommited += DoNewGlobalEvent;
             * }
             */
            _rect.x     = _rect.xMax + 2;
            _rect.width = 18;

            if (showOptions)
            {
                if (GUI.Button(_rect, FsmEditorContent.SettingsButton, "label"))
                {
                    GenericMenu menu = new GenericMenu();

                    if (eventTarget != null && eventTarget.enumValueIndex != 2)                    // not a broadcast call
                    {
                        menu.AddItem(new GUIContent("Show All global Events"), false, ShowAllEvents);
                        menu.AddItem(new GUIContent("Show local Event"), false, ShowImplementedEvents);

                        menu.AddSeparator("");
                    }

                    menu.AddItem(new GUIContent("Reset"), false, ResetToDefault);

                    menu.ShowAsContext();
                }
            }

            // feedback
            if (selected == -1)
            {
                EditorGUI.LabelField(
                    GetRectforRow(pos, ++row - 1),
                    "<color=red>missing event</color>",
                    "<color=red>" + _eventName + "</color>"
                    );
            }

            if (selected != 0 && eventTarget.enumValueIndex != 2)        // not none and not broadcasting
            {
                if (selected > 0 && !isEventImplemented)
                {
                    EditorGUI.LabelField(
                        GetRectforRow(pos, ++row - 1),
                        " ",
                        "<color=red>Not implemented on target</color>"
                        );
                }
            }



            // attempt to refresh UI and avoid glitch
            if (row != rowCount)
            {
                prop.serializedObject.ApplyModifiedProperties();
                prop.serializedObject.Update();
            }
            rowCount = row;
        }
Exemple #21
0
        public void Build(Animation animation, IDictionary <int, TimeLine> timeLines)
        {
            var clip = new AnimationClip();

            clip.name = animation.name;
            var pendingTransforms = new Dictionary <string, Transform> (Transforms);            //This Dictionary will shrink in size for every transform

            foreach (var key in animation.mainlineKeys)                                         //that is considered "used"
            {
                var parentTimelines = new Dictionary <int, List <TimeLineKey> > ();
                var brefs           = new Queue <Ref> (key.boneRefs ?? new Ref [0]);
                while (brefs.Count > 0)
                {
                    var bref = brefs.Dequeue();
                    if (bref.parent < 0 || parentTimelines.ContainsKey(bref.parent))
                    {
                        var timeLine = timeLines [bref.timeline];
                        parentTimelines [bref.id] = new List <TimeLineKey> (timeLine.keys);
                        Transform bone;
                        if (pendingTransforms.TryGetValue(timeLine.name, out bone))                            //Skip it if it's already "used"
                        {
                            List <TimeLineKey> parentTimeline;
                            parentTimelines.TryGetValue(bref.parent, out parentTimeline);
                            SetCurves(bone, DefaultBones [timeLine.name], parentTimeline, timeLine, clip, animation);
                            pendingTransforms.Remove(timeLine.name);
                        }
                    }
                    else
                    {
                        brefs.Enqueue(bref);
                    }
                }
                foreach (var sref in key.objectRefs)
                {
                    var       timeLine = timeLines [sref.timeline];
                    Transform sprite;
                    if (pendingTransforms.TryGetValue(timeLine.name, out sprite))
                    {
                        var defaultZ = sref.z_index;
                        List <TimeLineKey> parentTimeline;
                        parentTimelines.TryGetValue(sref.parent, out parentTimeline);
                        SetCurves(sprite, DefaultSprites [timeLine.name], parentTimeline, timeLine, clip, animation, ref defaultZ);
                        SetAdditionalCurves(sprite, animation.mainlineKeys, timeLine, clip, defaultZ);
                        pendingTransforms.Remove(timeLine.name);
                    }
                }
                foreach (var kvPair in pendingTransforms)                   //Disable the remaining tansforms if they are sprites and not already disabled
                {
                    if (DefaultSprites.ContainsKey(kvPair.Key) && kvPair.Value.gameObject.activeSelf)
                    {
                        var curve = new AnimationCurve(new Keyframe(0f, 0f, inf, inf));
                        clip.SetCurve(GetPathToChild(kvPair.Value), typeof(GameObject), "m_IsActive", curve);
                    }
                }
            }
            var settings = AnimationUtility.GetAnimationClipSettings(clip);

            settings.stopTime = animation.length;             //Set the animation's length and other settings
            if (animation.looping)
            {
                clip.wrapMode     = WrapMode.Loop;
                settings.loopTime = true;
            }
            else
            {
                clip.wrapMode = WrapMode.ClampForever;
            }
            AnimationUtility.SetAnimationClipSettings(clip, settings);
            if (OriginalClips.ContainsKey(animation.name))                //If the clip already exists, copy this clip into the old one
            {
                var oldClip      = OriginalClips [animation.name];
                var cachedEvents = oldClip.events;
                EditorUtility.CopySerialized(clip, oldClip);
                clip = oldClip;
                AnimationUtility.SetAnimationEvents(clip, cachedEvents);
                ProcessingInfo.ModifiedAnims.Add(clip);
            }
            else
            {
                switch (S2USettings.ImportStyle)
                {
                case AnimationImportOption.NestedInPrefab:
                    AssetDatabase.AddObjectToAsset(clip, PrefabPath);                      //Otherwise create a new one
                    break;

                case AnimationImportOption.SeparateFolder:
                    if (!AssetDatabase.IsValidFolder(AnimationsPath))
                    {
                        var splitIndex = AnimationsPath.LastIndexOf('/');
                        var path       = AnimationsPath.Substring(0, splitIndex);
                        var newFolder  = AnimationsPath.Substring(splitIndex + 1);
                        AssetDatabase.CreateFolder(path, newFolder);
                    }
                    AssetDatabase.CreateAsset(clip, string.Format("{0}/{1}.anim", AnimationsPath, clip.name));
                    break;
                }
                ProcessingInfo.NewAnims.Add(clip);
            }
            if (!ArrayUtility.Contains(Controller.animationClips, clip))        //Don't add the clip if it's already there
            {
                var state = GetStateFromController(clip.name);                  //Find a state of the same name
                if (state != null)
                {
                    state.motion = clip;                                //If it exists, replace it
                }
                else
                {
                    Controller.AddMotion(clip);                   //Otherwise add it as a new state
                }
                if (!ModdedController)
                {
                    if (!ProcessingInfo.NewControllers.Contains(Controller) && !ProcessingInfo.ModifiedControllers.Contains(Controller))
                    {
                        ProcessingInfo.ModifiedControllers.Add(Controller);
                    }
                    ModdedController = true;
                }
            }
        }
        private bool m_displayAutocompleteBtn = false; // fix gui warning when button appears
        public void Display(Object target, uint[] aTileData, int[] tileIdxMap, int gridWidth, int gridHeight, Vector2 visualTileSize, int[] symbolIdxMap)
        {
            GUI.changed      = m_hasChanged;
            m_hasChanged     = false;
            m_target         = target;
            m_aBrushTileData = aTileData;
            Event e = Event.current;
            bool  isRightMouseReleased = e.type == EventType.MouseUp && e.button == 0;

            if (isRightMouseReleased && !m_tileSelectionRect.Contains(e.mousePosition))
            {
                m_selectedTileIdx = -1;
            }

            GUILayout.BeginHorizontal();

            // Draw Autotile Combination Control
            GUI.backgroundColor = Tileset.BackgroundColor;
            GUILayout.BeginScrollView(Vector2.zero, (GUIStyle)"Button", GUILayout.Width(visualTileSize.x * gridWidth), GUILayout.Height(visualTileSize.y * gridHeight + 1f));
            GUI.backgroundColor = Color.white;
            for (int i = 0; i < gridWidth * gridHeight; ++i)
            {
                int  gx          = i % gridWidth;
                int  gy          = i / gridWidth;
                int  tileIdx     = tileIdxMap[i];
                Rect rVisualTile = new Rect(gx * visualTileSize.x, gy * visualTileSize.y, visualTileSize.x, visualTileSize.y);

                int tileId = (int)(m_aBrushTileData[tileIdx] & Tileset.k_TileDataMask_TileId);
                if (tileId != Tileset.k_TileId_Empty)
                {
                    //Rect tileUV = Tileset.Tiles[tileId].uv;
                    //GUI.DrawTextureWithTexCoords(rVisualTile, Tileset.AtlasTexture, tileUV, true);
                    TilesetEditor.DoGUIDrawTileFromTileData(rVisualTile, m_aBrushTileData[tileIdx], Tileset);
                }
                else if (symbolIdxMap != null)
                {
                    GUI.DrawTexture(rVisualTile, GetTileSymbolTexture((byte)symbolIdxMap[i]), ScaleMode.ScaleToFit, true);
                }

                Color bgColor = new Color(1f - Tileset.BackgroundColor.r, 1f - Tileset.BackgroundColor.g, 1f - Tileset.BackgroundColor.b, Tileset.BackgroundColor.a);
                HandlesEx.DrawRectWithOutline(rVisualTile, m_selectedTileIdx == tileIdx ? new Color(0f, 0f, 0f, 0.1f) : new Color(), m_selectedTileIdx == tileIdx ? new Color(1f, 1f, 0f, 1f) : bgColor);

                if (isRightMouseReleased && rVisualTile.Contains(e.mousePosition))
                {
                    m_selectedTileIdx = tileIdx;
                    EditorWindow wnd = EditorWindow.focusedWindow;
                    TileSelectionWindow.Show(Tileset);
                    TileSelectionWindow.Instance.Ping();
                    wnd.Focus();
                    GUI.FocusControl("");
                }
            }
            GUILayout.EndScrollView();

            uint brushTileData = m_selectedTileIdx >= 0 ? m_aBrushTileData[m_selectedTileIdx] : Tileset.k_TileData_Empty;

            brushTileData = DoTileDataPropertiesLayout(brushTileData, Tileset);
            if (m_selectedTileIdx >= 0)
            {
                m_aBrushTileData[m_selectedTileIdx] = brushTileData;
            }

            GUILayout.EndHorizontal();
            if (e.type == EventType.Repaint)
            {
                m_tileSelectionRect = GUILayoutUtility.GetLastRect();
            }

            bool hasEmptyTiles = ArrayUtility.Contains <uint>(m_aBrushTileData, Tileset.k_TileData_Empty);

            m_displayAutocompleteBtn = e.type == EventType.Layout ? !hasEmptyTiles && m_tileIdOff != 0 : m_displayAutocompleteBtn;
            if (m_displayAutocompleteBtn && GUILayout.Button("Autocomplete relative to last change"))
            {
                Undo.RecordObject(m_target, "MultipleTileChanged");
                for (int i = 0; i < tileIdxMap.Length; ++i)
                {
                    int tileIdx = tileIdxMap[i];
                    if (tileIdx != m_tileIdOffSkipIdx)
                    {
                        int brushTileId = (int)(m_aBrushTileData[tileIdx] & Tileset.k_TileDataMask_TileId);
                        brushTileId += m_tileIdOff;
                        if (brushTileId < 0 || brushTileId >= m_tileset.Tiles.Count)
                        {
                            m_aBrushTileData[tileIdx] = Tileset.k_TileData_Empty;
                        }
                        else
                        {
                            m_aBrushTileData[tileIdx] &= ~Tileset.k_TileDataMask_TileId;
                            m_aBrushTileData[tileIdx] |= (uint)(brushTileId & Tileset.k_TileDataMask_TileId);
                        }
                    }
                }
                m_tileIdOff = 0;
                EditorUtility.SetDirty(m_target);
            }
            if (Tileset.TileSelection != null && Tileset.TileSelection.selectionData.Count == gridWidth * gridHeight && Tileset.TileSelection.rowLength == gridWidth)
            {
                if (GUILayout.Button("Autocomplete from selection"))
                {
                    Undo.RecordObject(m_target, "MultipleTileChanged");
                    for (int i = 0; i < tileIdxMap.Length; ++i)
                    {
                        int tileIdx      = tileIdxMap[i];
                        int selectionIdx = (i % gridWidth) + (gridHeight - 1 - i / gridWidth) * gridWidth;
                        int brushTileId  = (int)(Tileset.TileSelection.selectionData[selectionIdx] & Tileset.k_TileDataMask_TileId);
                        m_aBrushTileData[tileIdx] = (uint)(brushTileId & Tileset.k_TileDataMask_TileId);
                    }
                    m_tileIdOff = 0;
                    EditorUtility.SetDirty(m_target);
                }
            }

            if (ShowHelpBox)
            {
                EditorGUILayout.HelpBox("Select  a tile from the grid, then select a tile from Tile Selection Window to change the tile.\nOr select a group of tiles and press Autocomplete from selection.", MessageType.Info);
            }
        }
Exemple #23
0
        internal static GameObject PickNodeOrGameObject(Camera camera, Vector2 pickposition, int layers, ref GameObject[] ignore, ref GameObject[] filter, out ChiselModel model, out ChiselNode node, out CSGTreeBrushIntersection intersection)
        {
TryNextSelection:
            intersection = new CSGTreeBrushIntersection {
                surfaceID = -1, brushUserID = -1
            };

            model = null;
            node  = null;
            Material sharedMaterial;
            var      gameObject = PickModel(camera, pickposition, layers, ref ignore, ref filter, out model, out sharedMaterial);

            if (object.Equals(gameObject, null))
            {
                return(null);
            }

            if (model)
            {
                int filterLayerParameter0 = (sharedMaterial) ? sharedMaterial.GetInstanceID() : 0;
                {
                    var worldRay       = camera.ScreenPointToRay(pickposition);
                    var worldRayStart  = worldRay.origin;
                    var worldRayVector = (worldRay.direction * (camera.farClipPlane - camera.nearClipPlane));
                    var worldRayEnd    = worldRayStart + worldRayVector;

                    CSGTreeBrushIntersection tempIntersection;
                    if (ChiselSceneQuery.FindFirstWorldIntersection(model, worldRayStart, worldRayEnd, filterLayerParameter0, layers, ignore, filter, out tempIntersection))
                    {
                        var clickedBrush = tempIntersection.brush;
                        node = ChiselNodeHierarchyManager.FindChiselNodeByInstanceID(clickedBrush.UserID);
                        if (node)
                        {
                            if (ignore != null &&
                                ignore.Contains(node.gameObject))
                            {
                                node = null;
                                return(null);
                            }
                            intersection = tempIntersection;
                            return(node.gameObject);
                        }
                        else
                        {
                            node = null;
                        }
                    }
                }

                if (ignore == null)
                {
                    return(null);
                }

                ArrayUtility.Add(ref ignore, gameObject);
                goto TryNextSelection;
            }

            if (object.Equals(gameObject, null))
            {
                return(null);
            }

            if (ignore != null &&
                ignore.Contains(gameObject))
            {
                return(null);
            }

            return(gameObject);
        }
        private void ShowList(SerializedProperty list)
        {
            EditorGUI.indentLevel++;

            // remove the keywords already assigned from the registered list
            var handler           = (SpeechInputHandler)target;
            var availableKeywords = new string[0];

            if (handler.Keywords != null)
            {
                availableKeywords = registeredKeywords.Except(handler.Keywords.Select(keywordAndResponse => keywordAndResponse.Keyword)).ToArray();
            }

            // keyword rows
            for (int index = 0; index < list.arraySize; index++)
            {
                // the element
                SerializedProperty speechCommandProperty = list.GetArrayElementAtIndex(index);
                EditorGUILayout.BeginHorizontal();
                bool elementExpanded = EditorGUILayout.PropertyField(speechCommandProperty);
                GUILayout.FlexibleSpace();
                // the remove element button
                bool elementRemoved = GUILayout.Button(RemoveButtonContent, EditorStyles.miniButton, MiniButtonWidth);

                if (elementRemoved)
                {
                    list.DeleteArrayElementAtIndex(index);
                }

                EditorGUILayout.EndHorizontal();

                SerializedProperty keywordProperty = speechCommandProperty.FindPropertyRelative("keyword");

                bool invalidKeyword = true;
                foreach (string keyword in registeredKeywords)
                {
                    if (keyword == keywordProperty.stringValue)
                    {
                        invalidKeyword = false;
                        break;
                    }
                }

                if (invalidKeyword)
                {
                    EditorGUILayout.HelpBox("Registered keyword is not recognized in the speech command profile!", MessageType.Error);
                }

                if (!elementRemoved && elementExpanded)
                {
                    string[] keywords          = availableKeywords.Concat(new[] { keywordProperty.stringValue }).OrderBy(keyword => keyword).ToArray();
                    int      previousSelection = ArrayUtility.IndexOf(keywords, keywordProperty.stringValue);
                    int      currentSelection  = EditorGUILayout.Popup("Keyword", previousSelection, keywords);

                    if (currentSelection != previousSelection)
                    {
                        keywordProperty.stringValue = keywords[currentSelection];
                    }

                    SerializedProperty responseProperty = speechCommandProperty.FindPropertyRelative("response");
                    EditorGUILayout.PropertyField(responseProperty, true);
                }
            }

            // add button row
            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();

            // the add element button
            if (GUILayout.Button(AddButtonContent, EditorStyles.miniButton, MiniButtonWidth))
            {
                var index = list.arraySize;
                list.InsertArrayElementAtIndex(index);
                var elementProperty = list.GetArrayElementAtIndex(index);
                SerializedProperty keywordProperty = elementProperty.FindPropertyRelative("keyword");
                keywordProperty.stringValue = string.Empty;
            }

            EditorGUILayout.EndHorizontal();
            EditorGUI.indentLevel--;
        }
Exemple #25
0
    public override void OnInspectorGUI()
    {
        EditorGUILayout.BeginVertical();

        var oldSize = map.mapSize;

        map.mapSize = EditorGUILayout.Vector2Field("Map Size:", map.mapSize);
        if (map.mapSize != oldSize)
        {
            UpdateCalculations();
        }

        var oldTexture = map.texture2D;

        map.texture2D = (Texture2D)EditorGUILayout.ObjectField("Texture2D:", map.texture2D, typeof(Texture2D), false);

        if (oldTexture != map.texture2D)
        {
            UpdateCalculations();
            map.tileID = 1;
            CreateBrush();
        }


        if (map.texture2D == null)
        {
            EditorGUILayout.HelpBox("You have not selected a texture 2D yet.", MessageType.Warning);
        }
        else
        {
            EditorGUILayout.LabelField("Tile Size:", map.tileSize.x + "x" + map.tileSize.y);
            map.tilePadding = EditorGUILayout.Vector2Field("Tile Padding", map.tilePadding);
            EditorGUILayout.LabelField("Grid Size In Units:", map.gridSize.x + "x" + map.gridSize.y);
            EditorGUILayout.LabelField("Pixels To Units:", map.pixelsToUnits.ToString());
            solidFlag    = EditorGUILayout.Toggle("Solid", solidFlag);
            sortingOrder = EditorGUILayout.IntField("Order in Layer", sortingOrder);

            var layerNames = getLayerNames();
            var index      = ArrayUtility.IndexOf(layerNames, layerName);
            index = EditorGUILayout.Popup("Layer Name", index, layerNames);

            if (index > -1)
            {
                layerName = layerNames[index];
                if (GUILayout.Button("Clear Layer"))
                {
                    layerName = null;
                }
            }

            UpdateBrush(map.currentTileBrush);

            if (GUILayout.Button("Clear Tiles"))
            {
                if (EditorUtility.DisplayDialog("Clear map's tiles?", "Are you sure?", "Clear", "Do not clear"))
                {
                    ClearMap();
                }
            }
        }

        EditorGUILayout.EndVertical();
    }
        private void TryBuild(Entity entity, GameObject prefab, GameObject instance, string directory, string prefabPath, IDictionary <int, IDictionary <int, Sprite> > folders)
        {
            var controllerPath = string.Format("{0}/{1}.controller", directory, entity.name);
            var animator       = instance.GetComponent <Animator> ();      //Fetches the prefab's Animator

            if (animator == null)
            {
                animator = instance.AddComponent <Animator> ();                              //Or creates one if it doesn't exist
            }
            AnimatorController controller = null;

            if (animator.runtimeAnimatorController != null)                              //The controller we use is hopefully the controller attached to the animator
            {
                controller = animator.runtimeAnimatorController as AnimatorController ?? //Or the one that's referenced by an OverrideController
                             (AnimatorController)((AnimatorOverrideController)animator.runtimeAnimatorController).runtimeAnimatorController;
            }
            if (controller == null)               //Otherwise we have to check the AssetDatabase for our controller
            {
                controller = (AnimatorController)AssetDatabase.LoadAssetAtPath(controllerPath, typeof(AnimatorController));
                if (controller == null)
                {
                    controller = AnimatorController.CreateAnimatorControllerAtPath(controllerPath);                      //Or create a new one if it doesn't exist.
                    ProcessingInfo.NewControllers.Add(controller);
                }
                animator.runtimeAnimatorController = controller;
            }
            var transforms = new Dictionary <string, Transform> ();       //All of the bones and sprites, identified by TimeLine.name, because those are truly unique

            transforms ["rootTransform"] = instance.transform;            //The root GameObject needs to be part of this hierarchy as well
            var defaultBones   = new Dictionary <string, SpatialInfo> (); //These are basically the object states on the first frame of the first animation
            var defaultSprites = new Dictionary <string, SpriteInfo> ();  //They are used as control values in determining whether something has changed
            var animBuilder    = new AnimationBuilder(ProcessingInfo, folders, transforms, defaultBones, defaultSprites, prefabPath, controller);
            var firstAnim      = true;                                    //The prefab's graphic will be determined by the first frame of the first animation

            foreach (var animation in entity.animations)
            {
                var timeLines = new Dictionary <int, TimeLine> ();
                foreach (var timeLine in animation.timelines)                 //TimeLines hold all the critical data such as positioning and graphics used
                {
                    timeLines [timeLine.id] = timeLine;
                }
                foreach (var key in animation.mainlineKeys)
                {
                    var parents = new Dictionary <int, string> ();      //Parents are referenced by different IDs V_V
                    parents [-1] = "rootTransform";                     //This is where "-1 == no parent" comes in handy
                    var boneRefs = new Queue <Ref> (key.boneRefs ?? new Ref[0]);
                    while (boneRefs.Count > 0)
                    {
                        var bone     = boneRefs.Dequeue();
                        var timeLine = timeLines [bone.timeline];
                        parents [bone.id] = timeLine.name;
                        if (!transforms.ContainsKey(timeLine.name))                            //We only need to go through this once, so ignore it if it's already in the dict
                        {
                            if (parents.ContainsKey(bone.parent))                              //If the parent cannot be found, it will probably be found later, so save it
                            {
                                var parentID = parents [bone.parent];
                                var parent   = transforms [parentID];
                                var child    = parent.Find(timeLine.name);           //Try to find the child transform if it exists
                                if (child == null)                                   //Or create a new one
                                {
                                    child = new GameObject(timeLine.name).transform;
                                    child.SetParent(parent);
                                }
                                transforms [timeLine.name] = child;
                                var spatialInfo = defaultBones [timeLine.name] = ArrayUtility.Find(timeLine.keys, x => x.id == bone.key).info;
                                if (!spatialInfo.processed)
                                {
                                    SpatialInfo parentInfo;
                                    defaultBones.TryGetValue(parentID, out parentInfo);
                                    spatialInfo.Process(parentInfo);
                                }
                                child.localPosition = new Vector3(spatialInfo.x, spatialInfo.y, 0f);
                                child.localRotation = spatialInfo.rotation;
                                child.localScale    = new Vector3(spatialInfo.scale_x, spatialInfo.scale_y, 1f);
                            }
                            else
                            {
                                boneRefs.Enqueue(bone);
                            }
                        }
                    }
                    foreach (var oref in key.objectRefs)
                    {
                        var timeLine = timeLines [oref.timeline];
                        if (!transforms.ContainsKey(timeLine.name))                            //Same as above
                        {
                            var parentID = parents [oref.parent];
                            var parent   = transforms [parentID];
                            var child    = parent.Find(timeLine.name);
                            if (child == null)
                            {
                                child = new GameObject(timeLine.name).transform;
                                child.SetParent(parent);
                            }
                            transforms [timeLine.name] = child;
                            var swapper = child.GetComponent <TextureController> ();                            //Destroy the Sprite Swapper, we'll make a new one later
                            if (swapper != null)
                            {
                                DestroyImmediate(swapper);
                            }
                            var renderer = child.GetComponent <SpriteRenderer> ();                            //Get or create a Sprite Renderer
                            if (renderer == null)
                            {
                                renderer = child.gameObject.AddComponent <SpriteRenderer> ();
                            }
                            var spriteInfo = defaultSprites [timeLine.name] = (SpriteInfo)ArrayUtility.Find(timeLine.keys, x => x.id == 0).info;
                            renderer.sprite = folders [spriteInfo.folder] [spriteInfo.file];
                            if (!spriteInfo.processed)
                            {
                                SpatialInfo parentInfo;
                                defaultBones.TryGetValue(parentID, out parentInfo);
                                spriteInfo.Process(parentInfo);
                            }
                            child.localPosition    = new Vector3(spriteInfo.x, spriteInfo.y, oref.z_index);                           //Z-index helps determine draw order
                            child.localEulerAngles = new Vector3(0f, 0f, spriteInfo.angle);                                           //The reason I don't use layers or layer orders is because
                            child.localScale       = new Vector3(spriteInfo.scale_x, spriteInfo.scale_y, 1f);                         //There tend to be a LOT of body parts, it's better to treat
                            var color = renderer.color;                                                                               //The entity as a single sprite for layer sorting purposes.
                            color.a        = spriteInfo.a;
                            renderer.color = color;
                            if (!firstAnim)
                            {
                                child.gameObject.SetActive(false);                                          //Disable the GameObject if this isn't the first frame of the first animation
                            }
                        }
                    }
                    if (firstAnim)
                    {
                        firstAnim = false;
                    }
                }
                try {
                    animBuilder.Build(animation, timeLines);                      //Builds the currently processed AnimationClip, see AnimationBuilder for more info
                }
                catch (Exception e) {
                    Debug.LogErrorFormat("Unable to build animation '{0}' for '{1}', reason: {2}", animation.name, entity.name, e);
                }
            }
            if (instance.GetComponent <EntityRenderer> () == null)
            {
                instance.AddComponent <EntityRenderer> ();                                                              //Adds an EntityRenderer if one is not already present
            }
            PrefabUtility.ReplacePrefab(instance, prefab, ReplacePrefabOptions.ConnectToPrefab);
            DestroyImmediate(instance);              //Apply the instance's changes to the prefab, then destroy the instance.
        }
Exemple #27
0
    public static UnityEngine.Object[] GetSceneCustomActionDependencies()
    {
        UnityEngine.Object[] list = new UnityEngine.Object[0];

        FsmEditor.RebuildFsmList();

        List <PlayMakerFSM> fsms = FsmEditor.FsmComponentList;

//		List<System.Type> PlayMakerActions = FsmEditorUtility.Actionslist;

        foreach (PlayMakerFSM fsm in fsms)
        {
            //Debug.Log(FsmEditorUtility.GetFullFsmLabel(fsm));

            //if (fsm.FsmStates != null) fsm.FsmStates.Initialize();

            for (int s = 0; s < fsm.FsmStates.Length; ++s)
            {
                fsm.FsmStates[s].LoadActions();

                Debug.Log(fsm.FsmStates[s].Name + " is loaded:" + fsm.FsmStates[s].ActionsLoaded);

                // Show SendEvent and SendMessage as we find them
                foreach (FsmStateAction action in fsm.FsmStates[s].Actions)
                {
                                                #if PLAYMAKER_1_8_OR_NEWER
                    UnityEngine.Object _asset = ActionScripts.GetAsset(action);
                                                #else
                    UnityEngine.Object _asset = FsmEditorUtility.GetActionScriptAsset(action);
                                                #endif

                    string _name = action.Name;
                    if (String.IsNullOrEmpty(_name))
                    {
                        if (_asset != null)
                        {
                            _name = _asset.name;
                        }
                        else
                        {
                                                                #if PLAYMAKER_1_8_OR_NEWER
                            _name = Labels.GetActionLabel(action) + "[WARNING: FILE NOT FOUND]";
                                                                #else
                            _name = FsmEditorUtility.GetActionLabel(action) + "[WARNING: FILE NOT FOUND]";
                                                                #endif
                        }
                    }

                    if (Enum.IsDefined(typeof(WikiPages), _name))
                    {
                        //	Debug.Log(_name+" : official action");
                    }
                    else
                    {
                        //	Debug.Log(_name+" : custom action");

                        if (_asset != null)
                        {
                            ArrayUtility.Add <UnityEngine.Object>(ref list, _asset);
                        }
                    }
                }
            }
        }

        return(list);
    }    // GetSceneCustomActionDependencies
        public static void PreferenceWindow()
        {
            if (constants == null)
            {
                constants = new LocalStyles();
            }
            if (keyArray == null)
            {
                keyArray = GetKeys();
                ReadKeys();
            }

            int id = GUIUtility.GetControlID(s_KeysControlHash, FocusType.Keyboard);

            KeyPref prevKey          = null;
            KeyPref nextKey          = null;
            bool    foundSelectedKey = false;


            var width = Mathf.Min(Mathf.Max(170f, EditorGUIUtility.currentViewWidth - 600), 400);

            GUILayout.BeginHorizontal();
            GUILayout.BeginVertical(GUILayout.MaxWidth(width));
            GUILayout.Label("Actions", constants.settingsBoxTitle, GUILayout.ExpandWidth(true));
            Rect selectedRect = default(Rect);

            keyNamesScrollPos = GUILayout.BeginScrollView(keyNamesScrollPos);            //, constants.settingsBox);
            {
                for (int i = 0; i < keyArray.Length; i++)
                {
                    var keyPref = keyArray[i];
                    if (!foundSelectedKey)
                    {
                        if (keyPref == m_SelectedKey)
                        {
                            foundSelectedKey = true;
                        }
                        else
                        {
                            prevKey = keyPref;
                        }
                    }
                    else
                    {
                        if (nextKey == null)
                        {
                            nextKey = keyPref;
                        }
                    }

                    EditorGUI.BeginChangeCheck();
                    if (GUILayout.Toggle(keyPref == m_SelectedKey, keyPref.name, constants.keysElement))
                    {
                        if (m_SelectedKey != keyPref)
                        {
                            checkBounds = true;
                        }
                        m_SelectedKeyIndex = i;
                        m_SelectedKey      = keyPref;
                        newKey             = new KeyCodeWithModifier();
                        if (Event.current.type == EventType.Repaint)
                        {
                            selectedRect = GUILayoutUtility.GetLastRect();
                        }
                    }
                    if (EditorGUI.EndChangeCheck())
                    {
                        GUIUtility.keyboardControl = id;
                    }
                }
            }
            GUILayout.EndScrollView();
            GUILayout.EndVertical();
            if (Event.current.type == EventType.Repaint && checkBounds)
            {
                checkBounds = false;
                Rect scrollViewRect = GUILayoutUtility.GetLastRect();
                scrollViewRect.position  = Vector2.zero;
                scrollViewRect.position += keyNamesScrollPos;
                scrollViewRect.yMax     -= 34;

                if (selectedRect.yMax > scrollViewRect.yMax)
                {
                    keyNamesScrollPos.y = selectedRect.yMax - scrollViewRect.height;
                    HandleUtility.Repaint();
                }
                if (selectedRect.yMin < scrollViewRect.yMin)
                {
                    keyNamesScrollPos.y = selectedRect.yMin;
                    HandleUtility.Repaint();
                }
                if (keyNamesScrollPos.y < 0)
                {
                    keyNamesScrollPos.y = 0;
                }
            }

            GUILayout.Space(10.0f);

            GUILayout.BeginVertical();
            keySettingsScrollPos = GUILayout.BeginScrollView(keySettingsScrollPos);

            if (m_SelectedKey != null)
            {
                GUI.changed = false;

                var allKeys = m_SelectedKey.keyEvent.keys;

                for (int i = 0; i < allKeys.Length; i++)
                {
                    PreferenceKey(ref allKeys, i);
                }

                PreferenceKeyItem(ref newKey);
                if (newKey.keyCode != KeyCode.None)
                {
                    ArrayUtility.Add(ref allKeys, newKey);
                }

                m_SelectedKey.keyEvent.keys = allKeys;


                if (GUI.changed)
                {
                    StoreKeys();
                }
                else
                {
                    if (GUIUtility.keyboardControl == id && Event.current.type == EventType.KeyDown)
                    {
                        switch (Event.current.keyCode)
                        {
                        case KeyCode.UpArrow:
                            if (prevKey != null && prevKey != m_SelectedKey)
                            {
                                m_SelectedKey = prevKey;
                                checkBounds   = true;
                                //m_ValidKeyChange = true;
                            }
                            Event.current.Use();
                            break;

                        case KeyCode.DownArrow:
                            if (nextKey != null && nextKey != m_SelectedKey)
                            {
                                m_SelectedKey = nextKey;
                                checkBounds   = true;
                                //m_ValidKeyChange = true;
                            }
                            Event.current.Use();
                            break;
                        }
                    }
                }
            }

            GUILayout.EndScrollView();
            GUILayout.EndVertical();
            GUILayout.Space(10f);

            GUILayout.EndHorizontal();
            GUILayout.Space(5f);

            if (GUILayout.Button("Use Defaults", GUILayout.Width(120)))
            {
                RevertKeys();
                StoreKeys();
            }
        }
Exemple #29
0
        /// <summary>
        /// update context on receiving RPCE CO Bind PDU.
        /// </summary>
        /// <param name="bindPdu">Bind PDU to receive.</param>
        internal void UpdateContextOnReceivingBindPdu(RpceCoBindPdu bindPdu)
        {
            this.MaxTransmitFragmentSize = bindPdu.max_xmit_frag;
            this.MaxReceiveFragmentSize  = bindPdu.max_recv_frag;

            if (bindPdu.assoc_group_id != 0)
            {
                this.AssociateGroupId = bindPdu.assoc_group_id;
            }
            else
            {
                if (this.associateGroupIdList.Count == 0)
                {
                    this.AssociateGroupId = bindPdu.assoc_group_id + 1;
                }
                else
                {
                    this.associateGroupIdList.Sort();
                    this.AssociateGroupId = this.associateGroupIdList[this.associateGroupIdList.Count - 1] + 1;
                }
            }

            associateGroupIdList.Add(this.AssociateGroupId);

            if (bindPdu.p_context_elem.p_cont_elem != null &&
                bindPdu.p_context_elem.p_cont_elem.Length > 0)
            {
                this.InterfaceId
                    = bindPdu.p_context_elem.p_cont_elem[0].abstract_syntax.if_uuid;
                this.InterfaceMajorVersion
                    = bindPdu.p_context_elem.p_cont_elem[0].abstract_syntax.if_vers_major;
                this.InterfaceMinorVersion
                    = bindPdu.p_context_elem.p_cont_elem[0].abstract_syntax.if_vers_minor;

                this.NdrVersion = RpceNdrVersion.None;
                this.PresentationContextsTable.Clear();
                for (int i = 0; i < bindPdu.p_context_elem.p_cont_elem.Length; i++)
                {
                    p_cont_elem_t p_cont_elem = bindPdu.p_context_elem.p_cont_elem[i];

                    if (p_cont_elem.transfer_syntaxes == null)
                    {
                        continue;
                    }
                    for (int j = 0; j < p_cont_elem.transfer_syntaxes.Length; j++)
                    {
                        p_syntax_id_t transfer_syntax = p_cont_elem.transfer_syntaxes[j];

                        if (transfer_syntax.if_uuid == RpceUtility.NDR_INTERFACE_UUID
                            &&
                            transfer_syntax.if_vers_major == RpceUtility.NDR_INTERFACE_MAJOR_VERSION
                            &&
                            transfer_syntax.if_vers_minor == RpceUtility.NDR_INTERFACE_MINOR_VERSION)
                        {
                            this.NdrVersion |= RpceNdrVersion.NDR;
                            this.PresentationContextsTable.Add(p_cont_elem.p_cont_id, RpceNdrVersion.NDR);
                        }
                        else if (transfer_syntax.if_uuid == RpceUtility.NDR64_INTERFACE_UUID
                                 &&
                                 transfer_syntax.if_vers_major == RpceUtility.NDR64_INTERFACE_MAJOR_VERSION
                                 &&
                                 transfer_syntax.if_vers_minor == RpceUtility.NDR64_INTERFACE_MINOR_VERSION)
                        {
                            this.NdrVersion |= RpceNdrVersion.NDR64;
                            this.PresentationContextsTable.Add(p_cont_elem.p_cont_id, RpceNdrVersion.NDR64);
                        }
                        else
                        {
                            byte[] uuid = transfer_syntax.if_uuid.ToByteArray();
                            if (ArrayUtility.CompareArrays(
                                    ArrayUtility.SubArray(
                                        uuid,
                                        0,
                                        RpceUtility.BIND_TIME_FEATURE_NEGOTIATION_BITMASK_PREFIX_LENGTH),
                                    ArrayUtility.SubArray(
                                        RpceUtility.BIND_TIME_FEATURE_NEGOTIATION_BITMASK_GUID_BYTES,
                                        0,
                                        RpceUtility.BIND_TIME_FEATURE_NEGOTIATION_BITMASK_PREFIX_LENGTH))
                                &&
                                transfer_syntax.if_vers_major == 1
                                &&
                                transfer_syntax.if_vers_minor == 0)
                            {
                                this.BindTimeFeatureNegotiationBitmask = (RpceBindTimeFeatureNegotiationBitmask)
                                                                         uuid[RpceUtility.BIND_TIME_FEATURE_NEGOTIATION_BITMASK_PREFIX_LENGTH];
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// GUI Player Settingsの描画を行います
        /// </summary>
        public void DrawGUI_PlayerSettings()
        {
            var currentParams = P.GetCurrentParams();

            int  opt = currentParams.platformOption;
            bool fold;


            using (new GUILayout.VerticalScope(Styles.helpBox)) {
                using (new GUILayout.HorizontalScope()) {
                    EditorGUI.BeginChangeCheck();

                    fold = HEditorGUILayout.Foldout(E.i.fold.Has(E.FoldPlatform), "Player Settings");
                    E.i.fold.Toggle(E.FoldPlatform, fold);
                    if (EditorGUI.EndChangeCheck())
                    {
                        s_changed = true;
                    }

                    GUILayout.FlexibleSpace();

                    var r = EditorHelper.GetLayout(Styles.iconSettings, HEditorStyles.iconButton);

                    if (HEditorGUI.IconButton(r, Styles.iconSettings, 1))
                    {
                        if (PB.i.enableOldStyleProjectSettings)
                        {
                            Selection.activeObject = AssetDatabase.LoadAssetAtPath <UnityObject>(AssetDatabase.GUIDToAssetPath("00000000000000004000000000000000"));
                            EditorUtils.InspectorWindow().Focus();
                        }
                        else
                        {
                            UnityEditorMenu.Edit_Project_Settings();
                        }
                    }
                }

                EditorGUI.BeginChangeCheck();
                if (fold)
                {
                    EditorGUI.indentLevel++;

                    if (P.i.selectBuildTargetGroup == BuildTargetGroup.Standalone ||
                        P.i.selectBuildTargetGroup == BuildTargetGroup.Android)
                    {
                        currentParams.scriptingBackend = (ScriptingImplementation)EditorGUILayout.Popup(S._ScriptingBackend, (int)currentParams.scriptingBackend, B.kScriptingBackendNames);
                    }

                    bool backend = false;
                    if (P.i.selectBuildTargetGroup == BuildTargetGroup.WebGL)
                    {
                    }
                    else if (currentParams.scriptingBackend == ScriptingImplementation.Mono2x)
                    {
                        backend = true;
                    }
                    using (new EditorGUI.DisabledGroupScope(backend)) {
                        currentParams.il2CppCompilerConfiguration = (Il2CppCompilerConfiguration)EditorGUILayout.EnumPopup(S._C__CompilerConfiguration, currentParams.il2CppCompilerConfiguration);
                    }
                    EditorGUILayout.LabelField($"{S._ScriptingDefineSymbols} ({S._Applybuildonly})");


                    using (new GUILayout.HorizontalScope()) {
                        currentParams.scriptingDefineSymbols = EditorGUILayout.TextField(currentParams.scriptingDefineSymbols);
                        var mm = R.Method("GetSymbolList", "Hananoki.SymbolSettings.SettingsProject", "Hananoki.SymbolSettings.Editor");
                        if (mm != null)
                        {
                            var tc = GUILayoutUtility.GetRect(EditorHelper.TempContent(Styles.iconPlus), HEditorStyles.iconButton, GUILayout.Width(16), GUILayout.Height(16));

                            if (HEditorGUI.IconButton(tc, Styles.iconPlus, 3))
                            {
                                GUI.FocusControl("");
                                void add(object obj)
                                {
                                    var s  = obj as string;
                                    var ss = currentParams.scriptingDefineSymbols.Split(';');

                                    ArrayUtility.Add(ref ss, s);
                                    currentParams.scriptingDefineSymbols = string.Join(";", ss.Where(x => !x.IsEmpty()).Distinct().ToArray());
                                }

                                var hoge = (ValueTuple <string[], string[]>)mm.Invoke(null, null);
                                var lst  = new List <string>();
                                var m    = new GenericMenu();
                                foreach (var s in hoge.Item1)
                                {
                                    m.AddItem("Project/" + s, false, add, s);
                                }
                                foreach (var s in hoge.Item2)
                                {
                                    m.AddItem("Editor/" + s, false, add, s);
                                }
                                m.DropDown(tc);
                            }
                        }
                    }
                    EditorGUILayout.LabelField($"{S._ScriptingDefineSymbols} ({S._Current})");
                    EditorGUI.BeginDisabledGroup(true);
                    EditorGUILayout.TextField(B.scriptingDefineSymbols);
                    EditorGUI.EndDisabledGroup();

                    EditorGUI.indentLevel--;
                    GUILayout.Space(4);
                }
                if (EditorGUI.EndChangeCheck())
                {
                    currentParams.platformOption = opt;
                    s_changed = true;
                }
            }
        }