private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; Debug.Log("Unity v" + Application.unityVersion + ", " + "Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " + "OVRPlugin v" + OVRPlugin.version + ", " + "SDK v" + OVRPlugin.nativeSDKVersion + "."); #if !UNITY_EDITOR if (IsUnityAlphaOrBetaVersion()) { Debug.LogWarning(UnityAlphaOrBetaVersionWarningMessage); } #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN var supportedTypes = UnityEngine.Rendering.GraphicsDeviceType.Direct3D11.ToString() + ", " + UnityEngine.Rendering.GraphicsDeviceType.Direct3D12.ToString(); if (!supportedTypes.Contains(SystemInfo.graphicsDeviceType.ToString())) { Debug.LogWarning("VR rendering requires one of the following device types: (" + supportedTypes + "). Your graphics device: " + SystemInfo.graphicsDeviceType.ToString()); } #endif // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; if (currPlatform == RuntimePlatform.Android || // currPlatform == RuntimePlatform.LinuxPlayer || currPlatform == RuntimePlatform.OSXEditor || currPlatform == RuntimePlatform.OSXPlayer || currPlatform == RuntimePlatform.WindowsEditor || currPlatform == RuntimePlatform.WindowsPlayer) { isSupportedPlatform = true; } else { isSupportedPlatform = false; } if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if UNITY_ANDROID && !UNITY_EDITOR // Turn off chromatic aberration by default to save texture bandwidth. chromatic = false; #endif #if UNITY_STANDALONE_WIN && !UNITY_EDITOR enableMixedReality = false; // we should never start the standalone game in MxR mode, unless the command-line parameter is provided #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN bool loadMrcConfig = LoadMixedRealityCaptureConfigurationFileFromCmd(); bool createMrcConfig = CreateMixedRealityCaptureConfigurationFileFromCmd(); if (loadMrcConfig || createMrcConfig) { OVRMixedRealityCaptureSettings mrcSettings = ScriptableObject.CreateInstance <OVRMixedRealityCaptureSettings>(); mrcSettings.ReadFrom(this); if (loadMrcConfig) { mrcSettings.CombineWithConfigurationFile(); mrcSettings.ApplyTo(this); } if (createMrcConfig) { mrcSettings.WriteToConfigurationFile(); } ScriptableObject.Destroy(mrcSettings); } if (MixedRealityEnabledFromCmd()) { enableMixedReality = true; } if (enableMixedReality) { Debug.Log("OVR: Mixed Reality mode enabled"); if (UseDirectCompositionFromCmd()) { compositionMethod = CompositionMethod.Direct; } if (UseExternalCompositionFromCmd()) { compositionMethod = CompositionMethod.External; } Debug.Log("OVR: CompositionMethod : " + compositionMethod); } #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN if (enableAdaptiveResolution && !OVRManager.IsAdaptiveResSupportedByEngine()) { enableAdaptiveResolution = false; UnityEngine.Debug.LogError("Your current Unity Engine " + Application.unityVersion + " might have issues to support adaptive resolution, please disable it under OVRManager"); } #endif Initialize(); if (resetTrackerOnLoad) { display.RecenterPose(); } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN // Force OcculusionMesh on all the time, you can change the value to false if you really need it be off for some reasons, // be aware there are performance drops if you don't use occlusionMesh. OVRPlugin.occlusionMesh = true; #endif }
public void loadAction(GameObject disk) { RunAction(disk, ScriptableObject.CreateInstance <CCFlyAction>()); }
public Builder() { Object = ScriptableObject.CreateInstance<TObj>(); }
private static IEnumerable ReactionTestData() { var a = ScriptableObject.CreateInstance <Reagent>(); a.Name = nameof(a); var b = ScriptableObject.CreateInstance <Reagent>(); b.Name = nameof(b); var c = ScriptableObject.CreateInstance <Reagent>(); c.Name = nameof(c); var simpleReaction = ScriptableObject.CreateInstance <Reaction>(); simpleReaction.ingredients = new SerializableDictionary <Reagent, int> { [a] = 1, [b] = 1 }; simpleReaction.catalysts = new SerializableDictionary <Reagent, int> { }; simpleReaction.inhibitors = new SerializableDictionary <Reagent, int> { }; simpleReaction.results = new SerializableDictionary <Reagent, int> { [c] = 1 }; simpleReaction.effects = new global::Chemistry.Effect[0]; var tempReaction = ScriptableObject.CreateInstance <Reaction>(); tempReaction.ingredients = new SerializableDictionary <Reagent, int> { [a] = 1, [b] = 1 }; tempReaction.catalysts = new SerializableDictionary <Reagent, int> { }; tempReaction.inhibitors = new SerializableDictionary <Reagent, int> { }; tempReaction.results = new SerializableDictionary <Reagent, int> { [c] = 1 }; tempReaction.effects = new global::Chemistry.Effect[0]; tempReaction.hasMinTemp = true; tempReaction.serializableTempMin = 200; tempReaction.hasMaxTemp = true; tempReaction.serializableTempMax = 300; // Non temperature dependant reaction, should always occur yield return(new object[] { new ReagentMix(new SerializableDictionary <Reagent, float> { [a] = 1, [b] = 1 }), simpleReaction, new ReagentMix(new SerializableDictionary <Reagent, float> { [c] = 1 }), }); yield return(new object[] { new ReagentMix(new SerializableDictionary <Reagent, float> { [a] = 1, [b] = 1 }, 100), simpleReaction, new ReagentMix(new SerializableDictionary <Reagent, float> { [c] = 1 }, 100), }); yield return(new object[] { new ReagentMix(new SerializableDictionary <Reagent, float> { [a] = 1, [b] = 1 }, 300), simpleReaction, new ReagentMix(new SerializableDictionary <Reagent, float> { [c] = 1 }, 300), }); // Temperature dependant reaction, should only occur in the right temperature window yield return(new object[] { new ReagentMix(new SerializableDictionary <Reagent, float> { [a] = 1, [b] = 1 }), tempReaction, new ReagentMix(new SerializableDictionary <Reagent, float> { [c] = 1 }), }); yield return(new object[] { new ReagentMix(new SerializableDictionary <Reagent, float> { [a] = 1, [b] = 1 }, 100), tempReaction, new ReagentMix(new SerializableDictionary <Reagent, float> { [a] = 1, [b] = 1 }, 100), }); yield return(new object[] { new ReagentMix(new SerializableDictionary <Reagent, float> { [a] = 1, [b] = 1 }, 300), tempReaction, new ReagentMix(new SerializableDictionary <Reagent, float> { [a] = 1, [b] = 1 }, 300), }); }
void OnEnable() { var controllerSettings = ScriptableObject.CreateInstance <RecorderControllerSettings>(); m_RecorderController = new RecorderController(controllerSettings); var animationOutputFolder = Application.dataPath + "/SampleRecordings"; var mediaOutputFolder = Application.dataPath + "../SampleRecordings"; //var outputFolder = Application.dataPath + "/SampleRecordings"; // Video var videoRecorder = ScriptableObject.CreateInstance <MovieRecorderSettings>(); videoRecorder.name = "My Video Recorder"; videoRecorder.enabled = true; videoRecorder.outputFormat = VideoRecorderOutputFormat.MP4; videoRecorder.videoBitRateMode = VideoBitrateMode.Low; videoRecorder.imageInputSettings = new GameViewInputSettings { outputWidth = 1920, outputHeight = 1080 }; videoRecorder.audioInputSettings.preserveAudio = true; videoRecorder.outputFile = mediaOutputFolder + "/video_" + DefaultWildcard.Take; // Animation var animationRecorder = ScriptableObject.CreateInstance <AnimationRecorderSettings>(); animationRecorder.name = "My Animation Recorder"; animationRecorder.enabled = true; var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); animationRecorder.animationInputSettings = new AnimationInputSettings { gameObject = sphere, recursive = true, }; animationRecorder.animationInputSettings.AddComponentToRecord(typeof(Transform)); animationRecorder.outputFile = animationOutputFolder + "/animation_" + DefaultWildcard.GeneratePattern("GameObject") + "_" + DefaultWildcard.Take; // Image Sequence var imageRecorder = ScriptableObject.CreateInstance <ImageRecorderSettings>(); imageRecorder.name = "My Image Recorder"; imageRecorder.enabled = true; imageRecorder.outputFormat = ImageRecorderOutputFormat.PNG; imageRecorder.captureAlpha = true; imageRecorder.outputFile = mediaOutputFolder + "/image_" + DefaultWildcard.Frame + "_" + DefaultWildcard.Take; imageRecorder.imageInputSettings = new CameraInputSettings { source = ImageSource.MainCamera, outputWidth = 1920, outputHeight = 1080, captureUI = true }; // Setup Recording controllerSettings.AddRecorderSettings(videoRecorder); controllerSettings.AddRecorderSettings(animationRecorder); controllerSettings.AddRecorderSettings(imageRecorder); controllerSettings.SetRecordModeToManual(); controllerSettings.frameRate = 60.0f; Options.verboseMode = false; m_RecorderController.StartRecording(); }
public void AddGameObjectModifier() { var layer = _abstractMap.VectorData.GetFeatureSubLayerAtIndex(0); layer.BehaviorModifiers.AddGameObjectModifier(ScriptableObject.CreateInstance <ColliderModifier>()); }
// Use this for initialization void Awake() { List <List <string> > clipList = readFabula(); foreach (List <string> clipItem in clipList) { Debug.Log("Clip:"); foreach (string item in clipItem) { Debug.Log(item); } } timeline = (TimelineAsset)ScriptableObject.CreateInstance("TimelineAsset"); PlayableDirector director = GetComponent <PlayableDirector>(); TrackAsset ctrack = timeline.CreateTrack <ControlTrack>(null, "control_track"); PlayableTrack ntrack = timeline.CreateTrack <PlayableTrack>(null, "nav_track"); foreach (List <string> clipitem_list in clipList) { string name = clipitem_list[0]; string type = clipitem_list[1]; if (type.Equals("animate")) { float start = float.Parse(clipitem_list[2]); float dur = float.Parse(clipitem_list[3]); string anim_location = clipitem_list[4]; string animation_obj = clipitem_list[5]; start_pos = GameObject.Find(anim_location).transform; var lerp_clip = ntrack.CreateClip <LerpMoveObjectAsset>(); var lerpclip = lerp_clip.asset as LerpMoveObjectAsset; var clip = ctrack.CreateDefaultClip(); clip.start = start; clip.duration = dur; clip.displayName = name; animTimeline = GameObject.Find(animation_obj); var controlAnim = clip.asset as ControlPlayableAsset; anim_transform = animTimeline.transform; anim_loc = anim_transform.position; anim_rot = anim_transform.rotation; setClipOffset(animTimeline, anim_loc, anim_rot); //List<TimelineClip> lerp_clips = target_lerp_track.GetClips().ToList(); lerpclip.ObjectToMove.exposedName = UnityEditor.GUID.Generate().ToString(); lerpclip.LerpMoveTo.exposedName = UnityEditor.GUID.Generate().ToString(); //director.SetReferenceValue(lerpclip.ObjectToMove.exposedName, movingObj); director.SetReferenceValue(lerpclip.LerpMoveTo.exposedName, start_pos); // Set control clip to be on fabula timeline controlAnim.sourceGameObject.exposedName = UnityEditor.GUID.Generate().ToString(); director.SetReferenceValue(controlAnim.sourceGameObject.exposedName, animTimeline); } else if (type.Equals("navigate")) { float start = float.Parse(clipitem_list[2]); float dur = float.Parse(clipitem_list[3]); string start_location = clipitem_list[4]; string end_location = clipitem_list[5]; string agent = clipitem_list[6]; float speed = float.Parse(clipitem_list[7]); //ntrack ////var clip = ctrack.CreateDefaultClip(); var lerp_clip = ntrack.CreateClip <LerpMoveObjectAsset>(); var clip = ntrack.CreateClip <SetAgentTargetAsset>(); //var navclip = clip.asset as SetAgentTargetAsset; lerp_clip.start = start; lerp_clip.duration = .05f; lerp_clip.displayName = "lerp"; clip.start = start + .05f; clip.duration = dur - .05f; clip.displayName = name; GameObject movingObj = GameObject.Find(agent); NavMeshAgent navigatingAgent = movingObj.GetComponent <NavMeshAgent>(); start_pos = GameObject.Find(start_location).transform; Transform end_pos = GameObject.Find(end_location).transform; var navclip = clip.asset as SetAgentTargetAsset; var lerpclip = lerp_clip.asset as LerpMoveObjectAsset; navclip.AgentSpeed = speed; //navclip.Agent = navigatingAgent as NavMeshAgent; navclip.Target.exposedName = UnityEditor.GUID.Generate().ToString(); navclip.Agent.exposedName = UnityEditor.GUID.Generate().ToString(); director.SetReferenceValue(navclip.Agent.exposedName, navigatingAgent); director.SetReferenceValue(navclip.Target.exposedName, end_pos); lerpclip.ObjectToMove.exposedName = UnityEditor.GUID.Generate().ToString(); lerpclip.LerpMoveTo.exposedName = UnityEditor.GUID.Generate().ToString(); director.SetReferenceValue(lerpclip.ObjectToMove.exposedName, movingObj); director.SetReferenceValue(lerpclip.LerpMoveTo.exposedName, start_pos); } else { Debug.Log("incorrect clip type"); } } director.Play(timeline); }
public static BakedLightmapData CreateAssetForActiveScene(string folder) { var scene = SceneManager.GetActiveScene().name; string file = EditorUtility.SaveFilePanelInProject("Save Baked Lightmap", scene, "asset", "Save Asset", folder); if (string.IsNullOrEmpty(file)) { return(null); } folder = Path.GetDirectoryName(file); var fname = Path.GetFileName(file); if (StringUtil.EndWithIgnoreCase(fname, ".asset")) { fname = fname.Substring(0, fname.Length - 6); } BakedLightmapData data = ScriptableObject.CreateInstance <BakedLightmapData>(); if (File.Exists(file)) { AssetDatabase.DeleteAsset(file); } AssetDatabase.CreateAsset(data, file); var lightmaps = LightmapSettings.lightmaps; int len = lightmaps == null ? 0 : lightmaps.Length; data.m_Lightmaps = new LightmapInfo[len]; var ptitle = "Copy Lightmap Datas"; var plen = (float)len * 3; for (int i = 0; i < len; i++) { LightmapInfo info; var color = lightmaps[i].lightmapColor == null ? null : AssetDatabase.GetAssetPath(lightmaps[i].lightmapColor); var dir = lightmaps[i].lightmapDir == null ? null : AssetDatabase.GetAssetPath(lightmaps[i].lightmapDir); var mask = lightmaps[i].shadowMask == null ? null : AssetDatabase.GetAssetPath(lightmaps[i].shadowMask); var color2 = color == null ? null : string.Format("{0}/{1}_{2}_light.png", folder, fname, i); var dir2 = dir == null ? null : string.Format("{0}/{1}_{2}_dir.png", folder, fname, i); var mask2 = mask == null ? null : string.Format("{0}/{1}_{2}_shadowmask.png", folder, fname, i); EditorUtility.DisplayProgressBar(ptitle, string.Format("Copy light colors[{0}]...", i), (float)(i * 3) / plen); if (color2 != null && File.Exists(color2)) { AssetDatabase.DeleteAsset(color2); } if (color2 != null && AssetDatabase.CopyAsset(color, color2)) { info.lightColor = AssetDatabase.LoadAssetAtPath <Texture2D>(color2); } else { info.lightColor = null; } EditorUtility.DisplayProgressBar(ptitle, string.Format("Copy light dirs[{0}]...", i), (float)(i * 3 + 1) / plen); if (dir2 != null && File.Exists(dir2)) { AssetDatabase.DeleteAsset(dir2); } if (dir2 != null && AssetDatabase.CopyAsset(dir, dir2)) { info.lightDir = AssetDatabase.LoadAssetAtPath <Texture2D>(dir2); } else { info.lightDir = null; } EditorUtility.DisplayProgressBar(ptitle, string.Format("Copy shadow masks[{0}]...", i), (float)(i * 3 + 2) / plen); if (mask2 != null && File.Exists(mask2)) { AssetDatabase.DeleteAsset(mask2); } if (mask2 != null && AssetDatabase.CopyAsset(mask, mask2)) { info.shadowMask = AssetDatabase.LoadAssetAtPath <Texture2D>(mask2); } else { info.shadowMask = null; } data.m_Lightmaps[i] = info; } AssetDatabase.Refresh(); EditorUtility.ClearProgressBar(); return(data); }
public AudioOptionDrawer() { dummy = ScriptableObject.CreateInstance <AudioOptionDrawerDummy>(); dummy.hideFlags = HideFlags.DontSave; dummySerialized = new SerializedObject(dummy); }
void OnGUI() { GUI.skin = exampleSkin; if (eventList == null) { GUILayout.Label("Select EventList asset in Project view, or create a new EventList", EditorStyles.wordWrappedLabel); path = EditorGUILayout.TextField("File path:", path, GUILayout.ExpandWidth(true)); if (path == "") { EditorGUILayout.HelpBox("File path required to create new asset", MessageType.Warning); } EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Open Selected List")) { eventList = Selection.activeObject as DUUGEventList; } if (GUILayout.Button("Create New List") && path != "") { eventList = ScriptableObject.CreateInstance <DUUGEventList>(); AssetDatabase.CreateAsset(eventList as Object, path + ".asset"); Debug.Log(AssetDatabase.GetAssetPath(eventList)); } EditorGUILayout.EndHorizontal(); } else { EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Save Current List")) { EditorUtility.SetDirty(eventList); AssetDatabase.SaveAssets(); } if (GUILayout.Button("Open Selected List")) { eventList = Selection.activeObject as DUUGEventList; } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); GUILayout.TextField("Events:", EditorStyles.boldLabel); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); for (int i = 0; i < eventList.events.Count; i++) { DUUGEvent duugEvent = eventList.events[i]; SerializedObject serializedEvent = new SerializedObject(duugEvent); EditorGUILayout.BeginVertical(EditorStyles.textArea); duugEvent.expand = EditorGUILayout.Foldout(duugEvent.expand, "Event " + (i + 1) + ":"); if (duugEvent.expand) { duugEvent.venue = EditorGUILayout.TextField("Venue:", duugEvent.venue); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Date:", GUILayout.Width(60)); EditorGUILayout.Space(); duugEvent.day = EditorGUILayout.IntField(duugEvent.day, GUILayout.Width(20)); duugEvent.month = EditorGUILayout.IntField(duugEvent.month, GUILayout.Width(20)); duugEvent.year = EditorGUILayout.IntField(duugEvent.year, GUILayout.Width(40)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); SerializedProperty presenterProperty = serializedEvent.FindProperty("presenters"); int presenterCount = presenterProperty.arraySize; presenterProperty.Next(true); presenterProperty.Next(true); GUILayout.Label("Presenters:"); if (GUILayout.Button("Add presenter")) { duugEvent.presenters.Add(new DUUGPresenter()); } for (int j = 0; j < presenterCount; j++) { presenterProperty.Next(false); EditorGUILayout.PropertyField(presenterProperty); if (GUILayout.Button("Remove presenter")) { duugEvent.presenters.Remove(duugEvent.presenters[i]); break; } } presenterProperty.serializedObject.ApplyModifiedProperties(); } if (GUILayout.Button("Delete event")) { eventList.events.Remove(eventList.events[i]); break; } EditorGUILayout.Space(); EditorGUILayout.EndVertical(); } EditorGUILayout.EndScrollView(); if (GUILayout.Button("Add Event")) { eventList.events.Add(ScriptableObject.CreateInstance <DUUGEvent>()); } } }
// Adds any missing platforms: // * From the template collection // * From the legacy settings public void AddMissingPlatforms() { var newPlatforms = new List <Platform>(); foreach (Settings.PlatformTemplate template in Settings.PlatformTemplates) { if (!RuntimeSettings.PlatformExists(template.Identifier)) { newPlatforms.Add(template.CreateInstance()); } } // Ensure that the default platform exists if (!RuntimeSettings.DefaultPlatform) { RuntimeSettings.DefaultPlatform = ScriptableObject.CreateInstance <PlatformDefault>(); newPlatforms.Add(RuntimeSettings.DefaultPlatform); } // Ensure that the Play In Editor platform exists if (!RuntimeSettings.PlayInEditorPlatform) { RuntimeSettings.PlayInEditorPlatform = ScriptableObject.CreateInstance <PlatformPlayInEditor>(); newPlatforms.Add(RuntimeSettings.PlayInEditorPlatform); } // Ensure that the default and Play In Editor platforms have properties AffirmPlatformProperties(RuntimeSettings.DefaultPlatform); AffirmPlatformProperties(RuntimeSettings.PlayInEditorPlatform); // Migrate plugins if necessary var PluginsProperty = Platform.PropertyAccessors.Plugins; if (!RuntimeSettings.MigratedPlatforms.Contains(RuntimeSettings.DefaultPlatform.LegacyIdentifier)) { PluginsProperty.Set(RuntimeSettings.DefaultPlatform, RuntimeSettings.Plugins); } else if (!PluginsProperty.HasValue(RuntimeSettings.DefaultPlatform)) { PluginsProperty.Set(RuntimeSettings.DefaultPlatform, new List <string>()); } // Migrate LiveUpdatePort if (!Platform.PropertyAccessors.LiveUpdatePort.HasValue(RuntimeSettings.DefaultPlatform)) { Platform.PropertyAccessors.LiveUpdatePort.Set(RuntimeSettings.DefaultPlatform, RuntimeSettings.LiveUpdatePort); } // Create a map for migrating legacy settings var platformMap = new Dictionary <Legacy.Platform, Platform>(); foreach (Platform platform in RuntimeSettings.Platforms.Concat(newPlatforms)) { if (platform.LegacyIdentifier != Legacy.Platform.None) { platformMap.Add(platform.LegacyIdentifier, platform); } } Func <Legacy.Platform, Platform> AffirmPlatform = null; // Ensures that all of the platform's ancestors exist. Action <Platform> AffirmAncestors = (platform) => { Legacy.Platform legacyParent = Legacy.Parent(platform.LegacyIdentifier); if (legacyParent != Legacy.Platform.None) { platform.ParentIdentifier = AffirmPlatform(legacyParent).Identifier; } }; // Gets the platform corresponding to legacyPlatform (or creates it if it is a group), // and ensures that it has properties and all of its ancestors exist. // Returns null if legacyPlatform is unknown. AffirmPlatform = (legacyPlatform) => { Platform platform; if (platformMap.TryGetValue(legacyPlatform, out platform)) { platform.AffirmProperties(); } else if (Legacy.IsGroup(legacyPlatform)) { PlatformGroup group = PlatformGroup.Create(Legacy.DisplayName(legacyPlatform), legacyPlatform); platformMap.Add(legacyPlatform, group); newPlatforms.Add(group); platform = group; } else { // This is an unknown platform return(null); } AffirmAncestors(platform); return(platform); }; // Gets the target plaform to use when migrating settings from legacyPlatform. // Returns null if legacyPlatform is unknown or has already been migrated. Func <Legacy.Platform, Platform> getMigrationTarget = (legacyPlatform) => { if (RuntimeSettings.MigratedPlatforms.Contains(legacyPlatform)) { // Already migrated return(null); } return(AffirmPlatform(legacyPlatform)); }; var speakerModeSettings = RuntimeSettings.SpeakerModeSettings.ConvertAll( setting => new Legacy.PlatformSetting <FMOD.SPEAKERMODE>() { Value = (FMOD.SPEAKERMODE)setting.Value, Platform = setting.Platform } ); // Migrate all the legacy settings, creating platforms as we need them via AffirmPlatform MigrateLegacyPlatforms(speakerModeSettings, Platform.PropertyAccessors.SpeakerMode, getMigrationTarget); MigrateLegacyPlatforms(RuntimeSettings.SampleRateSettings, Platform.PropertyAccessors.SampleRate, getMigrationTarget); MigrateLegacyPlatforms(RuntimeSettings.LiveUpdateSettings, Platform.PropertyAccessors.LiveUpdate, getMigrationTarget); MigrateLegacyPlatforms(RuntimeSettings.OverlaySettings, Platform.PropertyAccessors.Overlay, getMigrationTarget); MigrateLegacyPlatforms(RuntimeSettings.BankDirectorySettings, Platform.PropertyAccessors.BuildDirectory, getMigrationTarget); MigrateLegacyPlatforms(RuntimeSettings.VirtualChannelSettings, Platform.PropertyAccessors.VirtualChannelCount, getMigrationTarget); MigrateLegacyPlatforms(RuntimeSettings.RealChannelSettings, Platform.PropertyAccessors.RealChannelCount, getMigrationTarget); // Now we ensure that if a legacy group has settings, all of its descendants exist // and inherit from it (even if they have no settings of their own), so that the // inheritance structure matches the old system. // We look at all groups (not just newly created ones), because a newly created platform // may need to inherit from a preexisting group. var groupsToProcess = new Queue <Platform>(platformMap.Values.Where( platform => platform is PlatformGroup && platform.LegacyIdentifier != Legacy.Platform.None && platform.HasAnyOverriddenProperties)); while (groupsToProcess.Count > 0) { Platform group = groupsToProcess.Dequeue(); // Ensure that all descendants exist foreach (var child in platformMap.Values) { if (child.Active) { // Don't overwrite existing settings continue; } var legacyPlatform = child.LegacyIdentifier; if (legacyPlatform == Legacy.Platform.iOS || legacyPlatform == Legacy.Platform.Android) { // These platforms were overridden by MobileHigh and MobileLow in the old system continue; } if (RuntimeSettings.MigratedPlatforms.Contains(legacyPlatform)) { // The user may have deleted this platform since migration, so don't mess with it continue; } if (Legacy.Parent(legacyPlatform) == group.LegacyIdentifier) { child.AffirmProperties(); child.ParentIdentifier = group.Identifier; if (child is PlatformGroup) { groupsToProcess.Enqueue(child as PlatformGroup); } } } } // Add all of the new platforms to the set of known platforms foreach (Platform platform in newPlatforms) { RuntimeSettings.AddPlatform(platform); } RuntimeSettings.ForEachPlatform(UpdateMigratedPlatform); }
public static void Init() { GameObject characterPrefab = Resources.Load <GameObject>("Prefabs/CharacterBodies/JellyfishBody"); ItemDisplayRuleSet itemDisplayRuleSet = ScriptableObject.CreateInstance <ItemDisplayRuleSet>(); List <ItemDisplayRuleSet.NamedRuleGroup> list = new List <ItemDisplayRuleSet.NamedRuleGroup>(); List <ItemDisplayRuleSet.NamedRuleGroup> list2 = new List <ItemDisplayRuleSet.NamedRuleGroup>(); ItemDisplayRuleSet original = characterPrefab.GetComponentInChildren <CharacterModel>().itemDisplayRuleSet; list2.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "AffixRed", displayRuleGroup = original.FindEquipmentDisplayRuleGroup("AffixRed") }); list2.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "AffixBlue", displayRuleGroup = original.FindEquipmentDisplayRuleGroup("AffixBlue") }); list2.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "AffixWhite", displayRuleGroup = original.FindEquipmentDisplayRuleGroup("AffixWhite") }); list2.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "AffixPoison", displayRuleGroup = original.FindEquipmentDisplayRuleGroup("AffixPoison") }); list2.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "AffixHaunted", displayRuleGroup = original.FindEquipmentDisplayRuleGroup("AffixHaunted") }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "CritGlasses", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayGlasses"), childName = "Hull2", localPos = new Vector3(0, 1.1f, 0), localAngles = new Vector3(270, 90, 0), localScale = new Vector3(2.8f, 3, 3), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "Crowbar", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayCrowbar"), childName = "Hull2", localPos = new Vector3(1, 0, 0), localAngles = new Vector3(0, 0, 0), localScale = new Vector3(2, 2, 2), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "Behemoth", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayBehemoth"), childName = "Hull2", localPos = new Vector3(0, 0.6f, 1.5f), localAngles = new Vector3(0, 0, 0), localScale = new Vector3(0.3f, 0.3f, 0.3f), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "NearbyDamageBonus", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayDiamond"), childName = "Hull2", localPos = new Vector3(0, 0, 0), localAngles = new Vector3(0, 0, 0), localScale = new Vector3(1.5f, 1.5f, 1.5f), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "FireRing", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayFireRing"), childName = "Hull2", localPos = new Vector3(0, 0, 0), localAngles = new Vector3(90, 0, 0), localScale = new Vector3(11, 11, 11), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "IceRing", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayIceRing"), childName = "Hull2", localPos = new Vector3(0, 0.5f, 0), localAngles = new Vector3(90, 0, 0), localScale = new Vector3(11, 11, 11), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "ArmorPlate", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayRepulsionArmorPlate"), childName = "Hull2", localPos = new Vector3(-0.3f, 0, 0.65f), localAngles = new Vector3(270, 0, 0), localScale = new Vector3(3, 2, 2), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "Bear", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayBear"), childName = "Hull2", localPos = new Vector3(0.7f, 0, -0.7f), localAngles = new Vector3(0, 135, 0), localScale = new Vector3(2, 2, 2), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "Medkit", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayMedkit"), childName = "Hull2", localPos = new Vector3(-1.25f, 0, 0), localAngles = new Vector3(270, 270, 0), localScale = new Vector3(4, 4, 4), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "Dagger", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayDagger"), childName = "Hull2", localPos = new Vector3(0, 0.75f, 0.75f), localAngles = new Vector3(270, 0, 0), localScale = new Vector3(5, 5, 5), limbMask = LimbFlags.None } } } }); /*list.Add(new ItemDisplayRuleSet.NamedRuleGroup * { * name = "ChainLightning", * displayRuleGroup = new DisplayRuleGroup * { * rules = new ItemDisplayRule[] * { * new ItemDisplayRule * { * ruleType = ItemDisplayRuleType.ParentedPrefab, * followerPrefab = ItemDisplays.LoadDisplay("DisplayUkulele"), * childName = "Hull2", * localPos = new Vector3(0.4f, 0, -1.75f), * localAngles = new Vector3(0, 85, 90), * localScale = new Vector3(0.8f, 0.8f, 0.8f), * limbMask = LimbFlags.None * } * } * } * });*/ list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "Syringe", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplaySyringeCluster"), childName = "Hull2", localPos = new Vector3(0.5f, 0, 0.5f), localAngles = new Vector3(0, 315, 270), localScale = new Vector3(1, 1, 1), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "UtilitySkillMagazine", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayAfterburnerShoulderRing"), childName = "Hull2", localPos = new Vector3(0, 0.6f, 0), localAngles = new Vector3(0, 0, 0), localScale = new Vector3(4, 4, 4), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "Hoof", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayHoof"), childName = "Hull2", localPos = new Vector3(0, -1, 0), localAngles = new Vector3(270, 270, 0), localScale = new Vector3(0.25f, 0.25f, 0.25f), limbMask = LimbFlags.None } } } }); list.Add(new ItemDisplayRuleSet.NamedRuleGroup { name = "SprintOutOfCombat", displayRuleGroup = new DisplayRuleGroup { rules = new ItemDisplayRule[] { new ItemDisplayRule { ruleType = ItemDisplayRuleType.ParentedPrefab, followerPrefab = ItemDisplays.LoadDisplay("DisplayWhip"), childName = "Hull2 ", localPos = new Vector3(0, 0, 0), localAngles = new Vector3(0, 0, 90), localScale = new Vector3(3, 3, 3), limbMask = LimbFlags.None } } } }); //apply displays here BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; ItemDisplayRuleSet.NamedRuleGroup[] value = list.ToArray(); ItemDisplayRuleSet.NamedRuleGroup[] value2 = list2.ToArray(); typeof(ItemDisplayRuleSet).GetField("namedItemRuleGroups", bindingAttr).SetValue(itemDisplayRuleSet, value); typeof(ItemDisplayRuleSet).GetField("namedEquipmentRuleGroups", bindingAttr).SetValue(itemDisplayRuleSet, value2); characterPrefab.GetComponentInChildren <CharacterModel>().itemDisplayRuleSet = itemDisplayRuleSet; }
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (string asset in importedAssets) { if (!filePath.Equals(asset)) { continue; } Format data = (Format)AssetDatabase.LoadAssetAtPath(exportPath, typeof(Format)); if (data == null) { data = ScriptableObject.CreateInstance <Format> (); AssetDatabase.CreateAsset((ScriptableObject)data, exportPath); data.hideFlags = HideFlags.NotEditable; } data.sheets.Clear(); using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { IWorkbook book = null; if (Path.GetExtension(filePath) == ".xls") { book = new HSSFWorkbook(stream); } else { book = new XSSFWorkbook(stream); } foreach (string sheetName in sheetNames) { ISheet sheet = book.GetSheet(sheetName); if (sheet == null) { Debug.LogError("[QuestData] sheet not found:" + sheetName); continue; } Format.Sheet s = new Format.Sheet(); s.name = sheetName; for (int i = 1; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); ICell cell = null; Format.Param p = new Format.Param(); cell = row.GetCell(0); p.num_quest = (int)(cell == null ? 0 : cell.NumericCellValue); cell = row.GetCell(1); p.content = (cell == null ? "" : cell.StringCellValue); cell = row.GetCell(2); p.num_button = (int)(cell == null ? 0 : cell.NumericCellValue); s.list.Add(p); } data.sheets.Add(s); } } ScriptableObject obj = AssetDatabase.LoadAssetAtPath(exportPath, typeof(ScriptableObject)) as ScriptableObject; EditorUtility.SetDirty(obj); } }
private void OnEnable() { Color backColor = GUI.backgroundColor; Color contentColor = GUI.contentColor; float line = EditorGUIUtility.singleLineHeight; SerializedProperty property = serializedObject.FindProperty("services"); services = new ReorderableList(serializedObject, property); services.showDefaultBackground = true; services.elementHeight = line + 6; services.drawHeaderCallback = (rect) => { EditorGUI.LabelField(rect, "Core Framework Services"); }; services.drawElementCallback = (Rect rect, int index, bool active, bool focused) => { float width = rect.width - 22; SerializedProperty element = services.serializedProperty.GetArrayElementAtIndex(index); if (GUI.Button(new Rect(rect.x + rect.width - 20, rect.y + 4, 18, line), EditorGUIUtility.IconContent("_Popup").image, GUIStyle.none)) { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("Edit"), false, delegate() { Selection.activeObject = element.objectReferenceValue; }); menu.AddItem(new GUIContent("Remove"), false, delegate() { if (!gameConfiguration.services[index]) { gameConfiguration.services.RemoveAt(index); EditorUtility.SetDirty(gameConfiguration); } else if (EditorUtility.DisplayDialog("Remove " + ObjectNames.NicifyVariableName(gameConfiguration.services[index].name) + "?", "Are you sure you want to remove this service? This will delete the ScriptableObject and can't be undone.", "Yes", "No")) { AssetDatabase.DeleteAsset(AssetDatabase.GetAssetOrScenePath(element.objectReferenceValue)); gameConfiguration.services.RemoveAt(index); EditorUtility.SetDirty(gameConfiguration); } }); menu.ShowAsContext(); } EditorGUI.PropertyField(new Rect(rect.x, rect.y + 2, width, line), element, GUIContent.none); }; services.onAddCallback = (list) => { Type[] allServiceTypes = GetAllServiceTypes(); GenericMenu servicesMenu = new GenericMenu(); foreach (var serviceType in allServiceTypes) { servicesMenu.AddItem(new GUIContent(ObjectNames.NicifyVariableName(serviceType.Name)), false, delegate(object service) { Type styp = service as Type; foreach (var assy in AppDomain.CurrentDomain.GetAssemblies()) { foreach (var typ in assy.GetTypes()) { if (typ.Name == styp.Name + "Config" || typ.Name == styp.Name + "Configuration") { serializedObject.ApplyModifiedProperties(); object thing = ScriptableObject.CreateInstance(typ); if (thing == null || (thing as ServiceConfiguration) == null) { return; } serializedObject.ApplyModifiedProperties(); string path = AssetDatabase.GetAssetOrScenePath(serializedObject.targetObject); path = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + styp.Name + ".asset"; AssetDatabase.CreateAsset(thing as ServiceConfiguration, path); if (thing != null) { gameConfiguration.services.Add(thing as ServiceConfiguration); EditorUtility.SetDirty(gameConfiguration); } return; } } } }, serviceType); } servicesMenu.ShowAsContext(); }; }
protected override PresetScriptableObject GetPresetScriptableObjectInstance() { return(ScriptableObject.CreateInstance <StaticForcePanelPresetScriptableObject>()); }
public static void NewRndTile() { string path = EditorUtility.SaveFilePanelInProject("Create RndTile", "RndTile", "asset", "Create RndTile"); AssetDatabase.CreateAsset(ScriptableObject.CreateInstance <RndTile>(), path); }
void OnGUI() { TextAnchor oldAlignment = GUI.skin.window.alignment; GUI.skin.window.alignment = TextAnchor.UpperLeft; // check if windows need to be recreated if (Event.current.type == EventType.Repaint && filePopupSelectedIndex >= 0 && selectedEntry != null) createWindows(); GUILayout.BeginHorizontal(); GUILayout.BeginVertical(GUILayout.Width(200)); GUILayout.Space(5); GUILayout.BeginHorizontal(); int t = filePopupSelectedIndex; filePopupSelectedIndex = EditorGUILayout.Popup(filePopupSelectedIndex, filePopupList); if (t != filePopupSelectedIndex) { } // the selected index has changed, load the correct dialogue file // create new dialogue file if (GUILayout.Button("+")) { saveUndo("creating dialogue file"); // create new dialogueFile DialogueFile file = ScriptableObject.CreateInstance<DialogueFile>(); AssetDatabase.CreateAsset(file, AssetDatabase.GenerateUniqueAssetPath("Assets/Script.asset")); AssetDatabase.SaveAssets(); files.Add(file); buildFilePopupArray(); } GUILayout.EndHorizontal(); // import export buttons GUILayout.BeginHorizontal(); if (filePopupSelectedIndex < 0) GUI.enabled = false; if (GUILayout.Button("Import")) { string filename = EditorUtility.OpenFilePanel("Import dialogue", ".", "xml"); DialogueFile importedFile = deserializeFromXML(filename); // import the various entries and lines // check if the existing file already has the same entries bool foundSameEntryName = false; string sameEntryName = ""; foreach (DialogueFile.DialogueEntry entry in importedFile.entries) { foreach (DialogueFile.DialogueEntry oldEntry in files[filePopupSelectedIndex].entries) { if (entry.id == oldEntry.id) { // found same entry foundSameEntryName = true; sameEntryName = entry.id; break; } } } bool continueImport = true; if (foundSameEntryName) { continueImport = EditorUtility.DisplayDialog("Same dialogue entry found", "The existing dialogue already has an entry named " + sameEntryName + ". If you continue, existing dialogues will be overwritten. Do you want to continue?", "Continue", "Cancel"); } if (continueImport) { saveUndo("Importing dialogue"); // add the entries and lines foreach (DialogueFile.DialogueEntry entry in importedFile.entries) { // check if it already exists bool dialogueExists = false; foreach (DialogueFile.DialogueEntry oldEntry in files[filePopupSelectedIndex].entries) { if (entry.id == oldEntry.id) { dialogueExists = true; // clear out existing lines files[filePopupSelectedIndex].lines.RemoveAll((item) => item.dialogueEntry == entry.id); } } if (!dialogueExists) files[filePopupSelectedIndex].entries.Add(entry); // add entry if it does not exists } // add the lines in one go files[filePopupSelectedIndex].lines.AddRange(importedFile.lines); EditorUtility.SetDirty(files[filePopupSelectedIndex]); } } if (GUILayout.Button("Export")) { // test serialization string filename = EditorUtility.SaveFilePanelInProject("Export dialogue", "dialogue", "xml", ""); serializeToXML(filename, files[filePopupSelectedIndex]); AssetDatabase.Refresh(); } if (filePopupSelectedIndex < 0) GUI.enabled = true; GUILayout.EndHorizontal(); // draw the dialogues dialogueListScroll = GUILayout.BeginScrollView(dialogueListScroll, (GUIStyle)"box"); if (filePopupSelectedIndex >= 0) { foreach (DialogueFile.DialogueEntry entry in files[filePopupSelectedIndex].entries) { if (entry == selectedEntry) { GUILayout.Label(entry.id, (GUIStyle)"boldLabel"); } else { if (GUILayout.Button(entry.id, (GUIStyle)"label")) { selectedEntry = entry; // build windows createWindows(); } } } } GUILayout.EndScrollView(); GUILayout.BeginHorizontal(); if (filePopupSelectedIndex < 0) GUI.enabled = false; if (GUILayout.Button("+")) { saveUndo("creating dialogue"); // create new dialogue entry DialogueFile.DialogueEntry newEntry = new DialogueFile.DialogueEntry(createUniqueDialogueName()); DialogueFile.DialogueLine beginLine = new DialogueFile.DialogueLine(); beginLine.dialogueEntry = newEntry.id; beginLine.id = 0; beginLine.position = new Vector2(10, 10); files[filePopupSelectedIndex].entries.Add(newEntry); files[filePopupSelectedIndex].lines.Add(beginLine); EditorUtility.SetDirty(files[filePopupSelectedIndex]); } if (GUILayout.Button("-")) { saveUndo("deleting dialogue"); // delete all the lines corresponding to this entry files[filePopupSelectedIndex].lines.RemoveAll((item) => item.dialogueEntry == selectedEntry.id); // delete the entry files[filePopupSelectedIndex].entries.Remove(selectedEntry); selectedEntry = null; windows.Clear(); EditorUtility.SetDirty(files[filePopupSelectedIndex]); } if (filePopupSelectedIndex < 0) GUI.enabled = true; GUILayout.EndHorizontal(); GUILayout.Space(5); GUILayout.EndVertical(); GUILayout.BeginVertical(); // show selected dialogueinfo GUILayout.BeginHorizontal(); // display name if (selectedEntry != null) GUILayout.Label("Name: " + selectedEntry.id); else GUILayout.Label("Name: "); GUILayout.FlexibleSpace(); if (selectedEntry == null) GUI.enabled = false; // rename button if (GUILayout.Button("Rename")) { // open rename dialog RenameDialogue dialog = GetWindow<RenameDialogue>(true); dialog.oldName = dialog.newName = selectedEntry.id; dialog.file = files[filePopupSelectedIndex]; } if (GUILayout.Button("Edit Speakers")) { // open rename dialog EditSpeakers dialog = GetWindow<EditSpeakers>(true); dialog.Init(files[filePopupSelectedIndex], selectedEntry.id); } if (selectedEntry == null) GUI.enabled = true; GUILayout.EndHorizontal(); // get rect for scrollview GUIStyle style = new GUIStyle(); style.stretchHeight = true; style.stretchWidth = true; style.margin = new RectOffset(4, 4, 4, 4); Rect rc = GUILayoutUtility.GetRect(new GUIContent(), style); GUI.Box(rc, ""); Rect bounds = getBoundingRect(new Rect(25, 25, rc.width - 50, rc.height - 50)); bounds.x -= 25; bounds.y -= 25; bounds.width += 50; bounds.height += 50; dialogueTreeScroll = GUI.BeginScrollView(rc, dialogueTreeScroll, bounds); BeginWindows(); int index = 0; bool createWindow = false; bool createLink = false; bool breakLink = false; bool deleteWindow = false; foreach (DialogueWindow window in windows) { string title = ""; if (window.line.id == 0) { title = "BEGIN"; } else { if (window.line != null) title = window.line.dialogue; } // draw output lines if (window.line != null) { foreach (int outputId in window.line.output) { // find connecting line foreach (DialogueFile.DialogueLine outputLine in files[filePopupSelectedIndex].lines) { if (outputLine.dialogueEntry == selectedEntry.id && outputLine.id == outputId) { Color color = Color.black; if (lastFocusWindow >= 0 && windows.Count > lastFocusWindow && windows[lastFocusWindow].line.id == outputId) color = Color.green; else if (lastFocusWindow >= 0 && windows.Count > lastFocusWindow && windows[lastFocusWindow].line == window.line) color = Color.red; Vector2 startPos = window.line.position + new Vector2(100, 25); Vector2 endPos = outputLine.position + new Vector2(0, 25); Vector2 midPos = (endPos - startPos).normalized; // found correct line float diffY = Mathf.Abs(startPos.y - endPos.y) / 4; float diffX = Mathf.Abs(startPos.x - endPos.x) / 4; Vector2 tPos = new Vector2(startPos.x + Mathf.Min(25, diffX), (startPos.y < endPos.y) ? startPos.y + Mathf.Min(25, diffY) : startPos.y - Mathf.Min(25, diffY)); Vector2 tPos2 = new Vector2(endPos.x - Mathf.Min(25, diffX), (startPos.y < endPos.y) ? endPos.y - Mathf.Min(25, diffY) : endPos.y + Mathf.Min(25, diffY)); Handles.DrawBezier(startPos, tPos, startPos + new Vector2(10, 0), tPos + midPos * -20, color, linetexture, 2); Handles.DrawBezier(tPos, tPos2, tPos + midPos * 20, tPos2 + midPos * -20, color, linetexture, 2); Handles.DrawBezier(tPos2, endPos, tPos2 + midPos * 20, endPos + new Vector2(-10, 0), color, linetexture, 2); break; } } } } window.rect = GUI.Window(index, window.rect, doWindow, title); if (window.line != null) window.line.position = new Vector2(window.rect.x, window.rect.y); //if (FocusedWindow < 0) GUI.FocusWindow(lastFocusWindow); GUI.FocusWindow(FocusedWindow); if (index == FocusedWindow) { // show extra buttons if (GUI.Button(new Rect(window.rect.xMax, window.rect.y + 10, 20, 20), "+", windowButtonStyle)) { createWindow = true; } if (GUI.Button(new Rect(window.rect.xMax, window.rect.y + 30, 20, 20), "->", windowButtonStyle)) { createLink = true; } if (GUI.Button(new Rect(window.rect.x - 20, window.rect.y + 10, 20, 20), "X", windowButtonStyle)) { breakLink = true; } if (index != 0) { if (GUI.Button(new Rect(window.rect.x + 80, window.rect.y - 15, 15, 15), "x", windowButtonStyle)) { deleteWindow = true; } } } lastFocusWindow = FocusedWindow; index++; } if (createdWindow >= 0) { GUI.BringWindowToFront(createdWindow); createdWindow = -1; } if (createWindow) { saveUndo("creating node"); // create new line and window DialogueFile.DialogueLine line = new DialogueFile.DialogueLine(); line.dialogue = ""; line.dialogueEntry = selectedEntry.id; line.id = selectedEntry.maxLineId++; // set line's position Rect windowRc = windows[lastFocusWindow].rect; line.position = new Vector2(windowRc.xMax + 50, windowRc.y); files[filePopupSelectedIndex].lines.Add(line); if (windows[lastFocusWindow].line != null) windows[lastFocusWindow].line.output.Add(line.id); int w = addWindow(line); GUI.FocusWindow(w); createdWindow = w; EditorUtility.SetDirty(files[filePopupSelectedIndex]); } if (createLink) { linkDragging = true; linkDragStartWindow = windows[lastFocusWindow]; wantsMouseMove = true; } if (breakLink) { linkDragging = true; this.breakLink = true; linkDragStartWindow = windows[lastFocusWindow]; wantsMouseMove = true; } if (linkDragging) { if (Event.current.type == EventType.MouseMove) { mousePos = Event.current.mousePosition; Repaint(); } if (this.breakLink) { // draw bezier curve from start window to cursor Vector2 pos1 = linkDragStartWindow.line.position + new Vector2(0, 25); Vector2 pos2 = mousePos; Handles.DrawBezier(pos1, pos2, pos1, pos2, Color.red, linetexture, 2); } else { // draw bezier curve from start window to cursor Vector2 pos1 = linkDragStartWindow.line.position + new Vector2(100, 25); Vector2 pos2 = mousePos; Handles.DrawBezier(pos1, pos2, pos1, pos2, Color.green, linetexture, 2); } } if (deleteWindow) { saveUndo("deleting node"); // find lines that link to this one foreach (DialogueFile.DialogueLine line in files[filePopupSelectedIndex].lines) { if (line.dialogueEntry == windows[lastFocusWindow].line.dialogueEntry) { if (line.output.Contains(windows[lastFocusWindow].line.id)) line.output.Remove(windows[lastFocusWindow].line.id); } } // remove currently selected window files[filePopupSelectedIndex].lines.Remove(windows[lastFocusWindow].line); windows.RemoveAt(lastFocusWindow); GUI.FocusWindow(0); lastFocusWindow = 0; EditorUtility.SetDirty(files[filePopupSelectedIndex]); } EndWindows(); // dialogue line text area GUI.EndScrollView(); if (lastFocusWindow > 0 && windows.Count > lastFocusWindow) windows[lastFocusWindow].line.dialogue = GUILayout.TextArea(windows[lastFocusWindow].line.dialogue, GUILayout.Height(GUI.skin.textArea.lineHeight * 3.1f)); else GUILayout.TextArea("", GUILayout.Height(GUI.skin.textArea.lineHeight * 3.1f)); GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUI.skin.window.alignment = oldAlignment; }
/// <summary> /// Set up imported objects with colliders, register them to be used accross the network, and set properties from the data received and the setup flags from AssetImportSetupSettings /// </summary> /// <param name="menuButtonIndex"> index of Menu Button. </param> /// <param name="modelData"> custom data received by the network</param> /// <param name="loadedObject"> our loaded object</param> /// <param name="setupFlags"> setup instructions</param> /// <returns></returns> public static GameObject SetUpGameObject(int menuButtonIndex, ModelDataTemplate.ModelImportData modelData, GameObject loadedObject, ModelImportSettings setupFlags = null) { const float defaultFitToScale = 2; const bool defaultDoSetUpColliders = true; const bool defaultIsNetworked = true; const float defaultModelSpawnHeight = 0.0f; if (loadedObject == null) { throw new System.Exception("Failed to import an model at runtime because the loaded object was null. Please ensure your custom runtime importer properly returns a valid GameObject."); } if (setupFlags == null) { setupFlags = ScriptableObject.CreateInstance <ModelImportSettings>(); setupFlags.fitToScale = defaultFitToScale; setupFlags.doSetUpColliders = defaultDoSetUpColliders; setupFlags.isNetworked = defaultIsNetworked; setupFlags.spawnHeight = defaultModelSpawnHeight; } //parent of model in list Transform newParent = new GameObject(menuButtonIndex.ToString()).transform; NetworkedGameObject nRGO = default; if (setupFlags.isNetworked) { //set up reference to use with network nRGO = NetworkedObjectsManager.Instance.CreateNetworkedGameObject(newParent.gameObject, menuButtonIndex, modelData.id); } //provide appropriate tag to enable it to be grabbed newParent.gameObject.gameObject.tag = TagList.interactable; newParent.gameObject.SetActive(false); Bounds bounds = new Bounds(); if (setupFlags.doSetUpColliders) { SetUpColliders(loadedObject, bounds, newParent, modelData, setupFlags, menuButtonIndex); //turn off whole colliders for non-whole objects if (!modelData.isWholeObject) { SetUpSubObjects(newParent, loadedObject, menuButtonIndex); } SetUpAnimation(newParent, loadedObject, modelData.isWholeObject); AdjustHeight(newParent, setupFlags); AdjustScale(newParent, bounds, setupFlags); } AdjustPose(newParent, modelData, bounds); //Initialize fields for ECS ConvertObjectsToEntities(nRGO, newParent, menuButtonIndex); newParent.gameObject.SetActive(false); return(newParent.gameObject); }
protected T GetGenericTemplate <T>() where T : SerializableKeyValueTemplate <K, V> { return(ScriptableObject.CreateInstance <T>()); }
public static void CreateMetaTile() { MetaTile tile = ScriptableObject.CreateInstance <MetaTile>(); TileBuilder.CreateAsset(tile, "MetaTile"); }
private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serializedObject, Editor editor, bool reuseIMGUIContainer) { if ((mode & (Mode.IMGUICustom | Mode.IMGUIDefault)) == 0) { return(null); } if ((mode & Mode.IMGUICustom) > 0 && (mode & Mode.IMGUIDefault) == 0 && editor is GenericInspector) { return(null); } if ((mode & Mode.IMGUICustom) == 0 && (mode & Mode.IMGUIDefault) > 0 && !(editor is GenericInspector)) { editor = ScriptableObject.CreateInstance <GenericInspector>(); editor.hideFlags = HideFlags.HideAndDontSave; editor.InternalSetTargets(new[] { serializedObject.targetObject }); } if (editor is GenericInspector) { AddToClassList(iMGUIDefaultVariantUssClassName); if ((mode & Mode.DebugMod) > 0) { AddToClassList(debugVariantUssClassName); editor.inspectorMode = InspectorMode.Debug; } else if ((mode & Mode.DebugInternalMod) > 0) { AddToClassList(debugInternalVariantUssClassName); editor.inspectorMode = InspectorMode.DebugInternal; } } else { AddToClassList(iMGUICustomVariantUssClassName); } IMGUIContainer inspector; // Reusing the existing IMGUIContainer allows us to re-use the existing gui state, when we are drawing the same inspector this will let us keep the same control ids if (reuseIMGUIContainer && m_IMGUIContainer != null) { inspector = m_IMGUIContainer; } else { inspector = new IMGUIContainer(); } m_IgnoreOnInspectorGUIErrors = false; inspector.onGUIHandler = () => { // It's possible to run 2-3 frames after the tracker of this inspector window has // been recreated, and with it the Editor and its SerializedObject. One example of // when this happens is when the Preview window is detached from a *second* instance // of an InspectorWindow and re-attached. // // This is only a problem for the *second* (or third, forth, etc) instance of // the InspectorWindow because only the first instance can use the // ActiveEditorTracker.sharedTracker in InspectorWindow.CreateTracker(). The // other instances have to create a new tracker...each time. // // Not an ideal solution, but basically we temporarily hold the printing to console // for errors for which GUIUtility.ShouldRethrowException(e) returns false. // The errors that may occur during this brief "bad state" are SerializedProperty // errors. If the custom Editor created and remembered references to some // SerializedProperties during its OnEnable(), those references will be invalid // when the tracker is refreshed, until this GUIHandler is reassigned. This fix // just ignores those errors. // // We don't simply early return here because that can break some tests that // rely heavily on yields and timing of UI redraws. Yes.. // // case 1119612 if (editor.m_SerializedObject == null) { editor.Repaint(); m_IgnoreOnInspectorGUIErrors = true; } if ((editor.target == null && !GenericInspector.ObjectIsMonoBehaviourOrScriptableObject(editor.target)) || !editor.serializedObject.isValid) { return; } EditorGUIUtility.ResetGUIState(); using (new EditorGUI.DisabledScope(!editor.IsEnabled())) { var genericEditor = editor as GenericInspector; if (genericEditor != null) { switch (mode) { case Mode.Normal: genericEditor.inspectorMode = InspectorMode.Normal; break; case Mode.Default: genericEditor.inspectorMode = InspectorMode.Debug; break; case Mode.Custom: genericEditor.inspectorMode = InspectorMode.DebugInternal; break; case Mode.IMGUI: break; } } //set the current PropertyHandlerCache to the current editor ScriptAttributeUtility.propertyHandlerCache = editor.propertyHandlerCache; var originalWideMode = EditorGUIUtility.wideMode; var originalHierarchyMode = EditorGUIUtility.hierarchyMode; EditorGUIUtility.hierarchyMode = true; var inspectorWidth = inspector.layout.width; // the inspector's width can be NaN if this is our first layout check. // If that's the case we'll set wideMode to true to avoid computing too tall an inspector on the first layout calculation if (!float.IsNaN(inspectorWidth)) { EditorGUIUtility.wideMode = inspectorWidth > Editor.k_WideModeMinWidth; } else { EditorGUIUtility.wideMode = true; } GUIStyle editorWrapper = (editor.UseDefaultMargins() ? EditorStyles.inspectorDefaultMargins : GUIStyle.none); try { GUI.changed = false; using (new InspectorWindowUtils.LayoutGroupChecker()) { EditorGUILayout.BeginVertical(editorWrapper); { try { var rebuildOptimizedGUIBlocks = GetRebuildOptimizedGUIBlocks(editor.target); rebuildOptimizedGUIBlocks |= editor.isInspectorDirty; float height; if (editor.GetOptimizedGUIBlock(rebuildOptimizedGUIBlocks, visible, out height)) { var contentRect = GUILayoutUtility.GetRect(0, visible ? height : 0); // Layout events are ignored in the optimized code path // The exception is when we are drawing a GenericInspector, they always use the optimized path and must therefore run at least one layout calculation in it if (Event.current.type == EventType.Layout && !(editor is GenericInspector)) { return; } InspectorWindowUtils.DrawAddedComponentBackground(contentRect, editor.targets); // Draw content if (visible) { GUI.changed = false; editor.OnOptimizedInspectorGUI(contentRect); } } else { InspectorWindowUtils.DrawAddedComponentBackground(contentRect, editor.targets); editor.OnInspectorGUI(); } } catch (Exception e) { if (GUIUtility.ShouldRethrowException(e)) { throw; } if (!m_IgnoreOnInspectorGUIErrors) { Debug.LogException(e); } } } EditorGUILayout.EndVertical(); } } finally { EditorGUIUtility.wideMode = originalWideMode; EditorGUIUtility.hierarchyMode = originalHierarchyMode; } } }; inspector.style.overflow = Overflow.Visible; m_IMGUIContainer = inspector; if (!(editor is GenericInspector)) { inspector.AddToClassList(customInspectorUssClassName); } inspector.AddToClassList(iMGUIContainerUssClassName); AddToClassList(iMGUIInspectorVariantUssClassName); return(inspector); }
void InitializeCustomPostProcessesLists() { var ppVolumeTypeInjectionPoints = new Dictionary <Type, CustomPostProcessInjectionPoint>(); var ppVolumeTypes = TypeCache.GetTypesDerivedFrom <CustomPostProcessVolumeComponent>(); foreach (var ppVolumeType in ppVolumeTypes.Where(t => !t.IsAbstract)) { var comp = ScriptableObject.CreateInstance(ppVolumeType) as CustomPostProcessVolumeComponent; ppVolumeTypeInjectionPoints[ppVolumeType] = comp.injectionPoint; CoreUtils.Destroy(comp); } var globalSettings = serializedObject.targetObject as HDRenderPipelineGlobalSettings; InitList(ref uiBeforeTransparentCustomPostProcesses, globalSettings.beforeTransparentCustomPostProcesses, "After Opaque And Sky", CustomPostProcessInjectionPoint.AfterOpaqueAndSky); InitList(ref uiBeforePostProcessCustomPostProcesses, globalSettings.beforePostProcessCustomPostProcesses, "Before Post Process", CustomPostProcessInjectionPoint.BeforePostProcess); InitList(ref uiAfterPostProcessCustomPostProcesses, globalSettings.afterPostProcessCustomPostProcesses, "After Post Process", CustomPostProcessInjectionPoint.AfterPostProcess); InitList(ref uiBeforeTAACustomPostProcesses, globalSettings.beforeTAACustomPostProcesses, "Before TAA", CustomPostProcessInjectionPoint.BeforeTAA); void InitList(ref ReorderableList reorderableList, List <string> customPostProcessTypes, string headerName, CustomPostProcessInjectionPoint injectionPoint) { // Sanitize the list customPostProcessTypes.RemoveAll(s => Type.GetType(s) == null); reorderableList = new ReorderableList(customPostProcessTypes, typeof(string)); reorderableList.drawHeaderCallback = (rect) => EditorGUI.LabelField(rect, headerName, EditorStyles.label); reorderableList.drawElementCallback = (rect, index, isActive, isFocused) => { rect.height = EditorGUIUtility.singleLineHeight; var elemType = Type.GetType(customPostProcessTypes[index]); EditorGUI.LabelField(rect, elemType.ToString(), EditorStyles.boldLabel); }; reorderableList.onAddCallback = (list) => { var menu = new GenericMenu(); foreach (var kp in ppVolumeTypeInjectionPoints) { if (kp.Value == injectionPoint && !customPostProcessTypes.Contains(kp.Key.AssemblyQualifiedName)) { menu.AddItem(new GUIContent(kp.Key.ToString()), false, () => { Undo.RegisterCompleteObjectUndo(serializedObject.targetObject, $"Added {kp.Key.ToString()} Custom Post Process"); customPostProcessTypes.Add(kp.Key.AssemblyQualifiedName); }); } } if (menu.GetItemCount() == 0) { menu.AddDisabledItem(new GUIContent("No Custom Post Process Available")); } menu.ShowAsContext(); EditorUtility.SetDirty(serializedObject.targetObject); }; reorderableList.onRemoveCallback = (list) => { Undo.RegisterCompleteObjectUndo(serializedObject.targetObject, $"Removed {list.list[list.index].ToString()} Custom Post Process"); customPostProcessTypes.RemoveAt(list.index); EditorUtility.SetDirty(serializedObject.targetObject); }; reorderableList.elementHeightCallback = _ => EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; reorderableList.onReorderCallback = (list) => { EditorUtility.SetDirty(serializedObject.targetObject); }; } }
public void SetUp() { UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.DefaultGameObjects); otherGlobalSettings = ScriptableObject.CreateInstance <UniversalRenderPipelineGlobalSettings>(); }
public override void OnImportAsset(AssetImportContext ctx) { var oldShader = AssetDatabase.LoadAssetAtPath <Shader>(ctx.assetPath); if (oldShader != null) { ShaderUtil.ClearShaderMessages(oldShader); } List <PropertyCollector.TextureInfo> configuredTextures; string path = ctx.assetPath; AssetCollection assetCollection = new AssetCollection(); MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection); var textGraph = File.ReadAllText(path, Encoding.UTF8); var graph = new GraphData { messageManager = new MessageManager(), assetGuid = AssetDatabase.AssetPathToGUID(path) }; MultiJson.Deserialize(graph, textGraph); graph.OnEnable(); graph.ValidateGraph(); Shader shader = null; #if VFX_GRAPH_10_0_0_OR_NEWER if (!graph.isOnlyVFXTarget) #endif { // build the shader text // this will also add Target dependencies into the asset collection var text = GetShaderText(path, out configuredTextures, assetCollection, graph); #if UNITY_2021_1_OR_NEWER // 2021.1 or later is guaranteed to have the new version of this function shader = ShaderUtil.CreateShaderAsset(ctx, text, false); #else // earlier builds of Unity may or may not have it // here we try to invoke the new version via reflection var createShaderAssetMethod = typeof(ShaderUtil).GetMethod( "CreateShaderAsset", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.ExactBinding, null, new Type[] { typeof(AssetImportContext), typeof(string), typeof(bool) }, null); if (createShaderAssetMethod != null) { shader = createShaderAssetMethod.Invoke(null, new Object[] { ctx, text, false }) as Shader; } else { // method doesn't exist in this version of Unity, call old version // this doesn't create dependencies properly, but is the best that we can do shader = ShaderUtil.CreateShaderAsset(text, false); } #endif ReportErrors(graph, shader, path); EditorMaterialUtility.SetShaderDefaults( shader, configuredTextures.Where(x => x.modifiable).Select(x => x.name).ToArray(), configuredTextures.Where(x => x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray()); EditorMaterialUtility.SetShaderNonModifiableDefaults( shader, configuredTextures.Where(x => !x.modifiable).Select(x => x.name).ToArray(), configuredTextures.Where(x => !x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray()); } UnityEngine.Object mainObject = shader; #if VFX_GRAPH_10_0_0_OR_NEWER ShaderGraphVfxAsset vfxAsset = null; if (graph.hasVFXTarget) { vfxAsset = GenerateVfxShaderGraphAsset(graph); if (mainObject == null) { mainObject = vfxAsset; } else { //Correct main object if we have a shader and ShaderGraphVfxAsset : save as sub asset vfxAsset.name = Path.GetFileNameWithoutExtension(path); ctx.AddObjectToAsset("VFXShaderGraph", vfxAsset); } } #endif Texture2D texture = Resources.Load <Texture2D>("Icons/sg_graph_icon"); ctx.AddObjectToAsset("MainAsset", mainObject, texture); ctx.SetMainObject(mainObject); foreach (var target in graph.activeTargets) { if (target is IHasMetadata iHasMetadata) { var metadata = iHasMetadata.GetMetadataObject(); if (metadata == null) { continue; } metadata.hideFlags = HideFlags.HideInHierarchy; ctx.AddObjectToAsset($"{iHasMetadata.identifier}:Metadata", metadata); } } var sgMetadata = ScriptableObject.CreateInstance <ShaderGraphMetadata>(); sgMetadata.hideFlags = HideFlags.HideInHierarchy; sgMetadata.assetDependencies = new List <UnityEngine.Object>(); foreach (var asset in assetCollection.assets) { if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage)) { // this sucks that we have to fully load these assets just to set the reference, // which then gets serialized as the GUID that we already have here. :P var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key); if (!string.IsNullOrEmpty(dependencyPath)) { sgMetadata.assetDependencies.Add( AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object))); } } } ctx.AddObjectToAsset("SGInternal:Metadata", sgMetadata); // declare dependencies foreach (var asset in assetCollection.assets) { if (asset.Value.HasFlag(AssetCollection.Flags.SourceDependency)) { ctx.DependsOnSourceAsset(asset.Key); // I'm not sure if this warning below is actually used or not, keeping it to be safe var assetPath = AssetDatabase.GUIDToAssetPath(asset.Key); // Ensure that dependency path is relative to project if (!string.IsNullOrEmpty(assetPath) && !assetPath.StartsWith("Packages/") && !assetPath.StartsWith("Assets/")) { Debug.LogWarning($"Invalid dependency path: {assetPath}", mainObject); } } // NOTE: dependencies declared by GatherDependenciesFromSourceFile are automatically registered as artifact dependencies // HOWEVER: that path ONLY grabs dependencies via MinimalGraphData, and will fail to register dependencies // on GUIDs that don't exist in the project. For both of those reasons, we re-declare the dependencies here. if (asset.Value.HasFlag(AssetCollection.Flags.ArtifactDependency)) { ctx.DependsOnArtifact(asset.Key); } } }
private void CreateEditorAndComponent(Type volumeComponentType, ref VolumeComponent component, ref VolumeComponentEditor editor) { component = (VolumeComponent)ScriptableObject.CreateInstance(volumeComponentType); editor = (VolumeComponentEditor)Editor.CreateEditor(component); editor.Invoke("Init"); }
// TODO: Fix this static ShaderGraphVfxAsset GenerateVfxShaderGraphAsset(GraphData graph) { var target = graph.activeTargets.FirstOrDefault(x => x is VFXTarget) as VFXTarget; if (target == null) { return(null); } // we need to override graph.isSubgraph, so save old state to restore it // (this is not great, but whole VFX pipeline is rather hacky at the moment) // use try/finally to ensure it always gets restored bool oldIsSubGraph = graph.isSubGraph; try { // override to generate as a subgraph, as that is what VFX is using it as graph.isSubGraph = true; var nl = Environment.NewLine; var indent = new string(' ', 4); var asset = ScriptableObject.CreateInstance <ShaderGraphVfxAsset>(); var result = asset.compilationResult = new GraphCompilationResult(); var mode = GenerationMode.ForReals; asset.lit = target.lit; asset.alphaClipping = target.alphaTest; var assetGuid = graph.assetGuid; var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid); var hlslName = NodeUtils.GetHLSLSafeName(Path.GetFileNameWithoutExtension(assetPath)); var ports = new List <MaterialSlot>(); var nodes = new List <AbstractMaterialNode>(); foreach (var vertexBlock in graph.vertexContext.blocks) { vertexBlock.value.GetInputSlots(ports); NodeUtils.DepthFirstCollectNodesFromNode(nodes, vertexBlock); } foreach (var fragmentBlock in graph.fragmentContext.blocks) { fragmentBlock.value.GetInputSlots(ports); NodeUtils.DepthFirstCollectNodesFromNode(nodes, fragmentBlock); } //Remove inactive blocks from generation { var tmpCtx = new TargetActiveBlockContext(new List <BlockFieldDescriptor>(), null); target.GetActiveBlocks(ref tmpCtx); ports.RemoveAll(materialSlot => { return(!tmpCtx.activeBlocks.Any(o => materialSlot.RawDisplayName() == o.displayName)); }); } var bodySb = new ShaderStringBuilder(1); var graphIncludes = new IncludeCollection(); var registry = new FunctionRegistry(new ShaderStringBuilder(), graphIncludes, true); foreach (var properties in graph.properties) { properties.SetupConcretePrecision(graph.graphDefaultConcretePrecision); } foreach (var node in nodes) { if (node is IGeneratesBodyCode bodyGenerator) { bodySb.currentNode = node; bodyGenerator.GenerateNodeCode(bodySb, mode); bodySb.ReplaceInCurrentMapping(PrecisionUtil.Token, node.concretePrecision.ToShaderString()); } if (node is IGeneratesFunction generatesFunction) { registry.builder.currentNode = node; generatesFunction.GenerateNodeFunction(registry, mode); } } bodySb.currentNode = null; var portNodeSets = new HashSet <AbstractMaterialNode> [ports.Count]; for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var port = ports[portIndex]; var nodeSet = new HashSet <AbstractMaterialNode>(); NodeUtils.CollectNodeSet(nodeSet, port); portNodeSets[portIndex] = nodeSet; } var portPropertySets = new HashSet <string> [ports.Count]; for (var portIndex = 0; portIndex < ports.Count; portIndex++) { portPropertySets[portIndex] = new HashSet <string>(); } foreach (var node in nodes) { if (!(node is PropertyNode propertyNode)) { continue; } for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var portNodeSet = portNodeSets[portIndex]; if (portNodeSet.Contains(node)) { portPropertySets[portIndex].Add(propertyNode.property.objectId); } } } var shaderProperties = new PropertyCollector(); foreach (var node in nodes) { node.CollectShaderProperties(shaderProperties, GenerationMode.ForReals); } asset.SetTextureInfos(shaderProperties.GetConfiguredTexutres()); var codeSnippets = new List <string>(); var portCodeIndices = new List <int> [ports.Count]; var sharedCodeIndices = new List <int>(); for (var i = 0; i < portCodeIndices.Length; i++) { portCodeIndices[i] = new List <int>(); } sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"#include \"Packages/com.unity.shadergraph/ShaderGraphLibrary/Functions.hlsl\"{nl}"); foreach (var include in graphIncludes) { sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add(include.value + nl); } for (var registryIndex = 0; registryIndex < registry.names.Count; registryIndex++) { var name = registry.names[registryIndex]; var source = registry.sources[name]; var precision = source.nodes.First().concretePrecision; var hasPrecisionMismatch = false; var nodeNames = new HashSet <string>(); foreach (var node in source.nodes) { nodeNames.Add(node.name); if (node.concretePrecision != precision) { hasPrecisionMismatch = true; break; } } if (hasPrecisionMismatch) { var message = new StringBuilder($"Precision mismatch for function {name}:"); foreach (var node in source.nodes) { message.AppendLine($"{node.name} ({node.objectId}): {node.concretePrecision}"); } throw new InvalidOperationException(message.ToString()); } var code = source.code.Replace(PrecisionUtil.Token, precision.ToShaderString()); code = $"// Node: {string.Join(", ", nodeNames)}{nl}{code}"; var codeIndex = codeSnippets.Count; codeSnippets.Add(code + nl); for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var portNodeSet = portNodeSets[portIndex]; foreach (var node in source.nodes) { if (portNodeSet.Contains(node)) { portCodeIndices[portIndex].Add(codeIndex); break; } } } } foreach (var property in graph.properties) { if (property.isExposed) { continue; } for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var portPropertySet = portPropertySets[portIndex]; if (portPropertySet.Contains(property.objectId)) { portCodeIndices[portIndex].Add(codeSnippets.Count); } } ShaderStringBuilder builder = new ShaderStringBuilder(); property.ForeachHLSLProperty(h => h.AppendTo(builder)); codeSnippets.Add($"// Property: {property.displayName}{nl}{builder.ToCodeBlock()}{nl}{nl}"); } var inputStructName = $"SG_Input_{assetGuid}"; var outputStructName = $"SG_Output_{assetGuid}"; var evaluationFunctionName = $"SG_Evaluate_{assetGuid}"; #region Input Struct sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"struct {inputStructName}{nl}{{{nl}"); #region Requirements var portRequirements = new ShaderGraphRequirements[ports.Count]; for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var requirementsNodes = portNodeSets[portIndex].ToList(); requirementsNodes.Add(ports[portIndex].owner); portRequirements[portIndex] = ShaderGraphRequirements.FromNodes(requirementsNodes, ports[portIndex].stageCapability); } var portIndices = new List <int>(); portIndices.Capacity = ports.Count; void AddRequirementsSnippet(Func <ShaderGraphRequirements, bool> predicate, string snippet) { portIndices.Clear(); for (var portIndex = 0; portIndex < ports.Count; portIndex++) { if (predicate(portRequirements[portIndex])) { portIndices.Add(portIndex); } } if (portIndices.Count > 0) { foreach (var portIndex in portIndices) { portCodeIndices[portIndex].Add(codeSnippets.Count); } codeSnippets.Add($"{indent}{snippet};{nl}"); } } void AddCoordinateSpaceSnippets(InterpolatorType interpolatorType, Func <ShaderGraphRequirements, NeededCoordinateSpace> selector) { foreach (var space in EnumInfo <CoordinateSpace> .values) { var neededSpace = space.ToNeededCoordinateSpace(); AddRequirementsSnippet(r => (selector(r) & neededSpace) > 0, $"float3 {space.ToVariableName(interpolatorType)}"); } } // TODO: Rework requirements system to make this better AddCoordinateSpaceSnippets(InterpolatorType.Normal, r => r.requiresNormal); AddCoordinateSpaceSnippets(InterpolatorType.Tangent, r => r.requiresTangent); AddCoordinateSpaceSnippets(InterpolatorType.BiTangent, r => r.requiresBitangent); AddCoordinateSpaceSnippets(InterpolatorType.ViewDirection, r => r.requiresViewDir); AddCoordinateSpaceSnippets(InterpolatorType.Position, r => r.requiresPosition); AddRequirementsSnippet(r => r.requiresVertexColor, $"float4 {ShaderGeneratorNames.VertexColor}"); AddRequirementsSnippet(r => r.requiresScreenPosition, $"float4 {ShaderGeneratorNames.ScreenPosition}"); AddRequirementsSnippet(r => r.requiresFaceSign, $"float4 {ShaderGeneratorNames.FaceSign}"); foreach (var uvChannel in EnumInfo <UVChannel> .values) { AddRequirementsSnippet(r => r.requiresMeshUVs.Contains(uvChannel), $"half4 {uvChannel.GetUVName()}"); } AddRequirementsSnippet(r => r.requiresTime, $"float3 {ShaderGeneratorNames.TimeParameters}"); #endregion sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"}};{nl}{nl}"); #endregion // VFX Code heavily relies on the slotId from the original MasterNodes // Since we keep these around for upgrades anyway, for now it is simpler to use them // Therefore we remap the output blocks back to the original Ids here var originialPortIds = new int[ports.Count]; for (int i = 0; i < originialPortIds.Length; i++) { if (!VFXTarget.s_BlockMap.TryGetValue((ports[i].owner as BlockNode).descriptor, out var originalId)) { continue; } // In Master Nodes we had a different BaseColor/Color slot id between Unlit/Lit // In the stack we use BaseColor for both cases. Catch this here. if (asset.lit && originalId == ShaderGraphVfxAsset.ColorSlotId) { originalId = ShaderGraphVfxAsset.BaseColorSlotId; } originialPortIds[i] = originalId; } #region Output Struct sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"struct {outputStructName}{nl}{{"); for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var port = ports[portIndex]; portCodeIndices[portIndex].Add(codeSnippets.Count); codeSnippets.Add($"{nl}{indent}{port.concreteValueType.ToShaderString(graph.graphDefaultConcretePrecision)} {port.shaderOutputName}_{originialPortIds[portIndex]};"); } sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"{nl}}};{nl}{nl}"); #endregion #region Graph Function sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"{outputStructName} {evaluationFunctionName}({nl}{indent}{inputStructName} IN"); var inputProperties = new List <AbstractShaderProperty>(); var portPropertyIndices = new List <int> [ports.Count]; for (var portIndex = 0; portIndex < ports.Count; portIndex++) { portPropertyIndices[portIndex] = new List <int>(); } foreach (var property in graph.properties) { if (!property.isExposed) { continue; } var propertyIndex = inputProperties.Count; var codeIndex = codeSnippets.Count; for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var portPropertySet = portPropertySets[portIndex]; if (portPropertySet.Contains(property.objectId)) { portCodeIndices[portIndex].Add(codeIndex); portPropertyIndices[portIndex].Add(propertyIndex); } } inputProperties.Add(property); codeSnippets.Add($",{nl}{indent}/* Property: {property.displayName} */ {property.GetPropertyAsArgumentString(property.concretePrecision.ToShaderString())}"); } sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"){nl}{{"); #region Node Code for (var mappingIndex = 0; mappingIndex < bodySb.mappings.Count; mappingIndex++) { var mapping = bodySb.mappings[mappingIndex]; var code = bodySb.ToString(mapping.startIndex, mapping.count); if (string.IsNullOrWhiteSpace(code)) { continue; } code = $"{nl}{indent}// Node: {mapping.node.name}{nl}{code}"; var codeIndex = codeSnippets.Count; codeSnippets.Add(code); for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var portNodeSet = portNodeSets[portIndex]; if (portNodeSet.Contains(mapping.node)) { portCodeIndices[portIndex].Add(codeIndex); } } } #endregion #region Output Mapping sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"{nl}{indent}// VFXMasterNode{nl}{indent}{outputStructName} OUT;{nl}"); // Output mapping for (var portIndex = 0; portIndex < ports.Count; portIndex++) { var port = ports[portIndex]; portCodeIndices[portIndex].Add(codeSnippets.Count); codeSnippets.Add($"{indent}OUT.{port.shaderOutputName}_{originialPortIds[portIndex]} = {port.owner.GetSlotValue(port.id, GenerationMode.ForReals, graph.graphDefaultConcretePrecision)};{nl}"); } #endregion // Function end sharedCodeIndices.Add(codeSnippets.Count); codeSnippets.Add($"{indent}return OUT;{nl}}}{nl}"); #endregion result.codeSnippets = codeSnippets.ToArray(); result.sharedCodeIndices = sharedCodeIndices.ToArray(); result.outputCodeIndices = new IntArray[ports.Count]; for (var i = 0; i < ports.Count; i++) { result.outputCodeIndices[i] = portCodeIndices[i].ToArray(); } var outputMetadatas = new OutputMetadata[ports.Count]; for (int portIndex = 0; portIndex < outputMetadatas.Length; portIndex++) { outputMetadatas[portIndex] = new OutputMetadata(portIndex, ports[portIndex].shaderOutputName, originialPortIds[portIndex]); } asset.SetOutputs(outputMetadatas); asset.evaluationFunctionName = evaluationFunctionName; asset.inputStructName = inputStructName; asset.outputStructName = outputStructName; asset.portRequirements = portRequirements; asset.concretePrecision = graph.graphDefaultConcretePrecision; asset.SetProperties(inputProperties); asset.outputPropertyIndices = new IntArray[ports.Count]; for (var portIndex = 0; portIndex < ports.Count; portIndex++) { asset.outputPropertyIndices[portIndex] = portPropertyIndices[portIndex].ToArray(); } return(asset); } finally { graph.isSubGraph = oldIsSubGraph; } }
public override void OnInspectorGUI() { serializedObject.Update(); base.OnInspectorGUI(); GUILayout.Space(5); controller = target as ColorsController; controller.itemMaterial = DrawMaterialAndColorEditor("Item", controller.itemMaterial); GUILayout.Space(8); controller.obstacleMaterial = DrawMaterialAndColorEditor("Obstacle", controller.obstacleMaterial); GUILayout.Space(8); controller.groundMaterial = DrawMaterialAndColorEditor("Ground", controller.groundMaterial); GUILayout.Space(8); controller.bordersMaterial = DrawMaterialAndColorEditor("Borders", controller.bordersMaterial); GUILayout.Space(8); controller.backSeaMaterial = DrawMaterialAndColorEditor("Back Sea", controller.backSeaMaterial); GUILayout.Space(10); GUILayout.Label("Developement", boldSyle); if (!presetCreation) { EditorGUILayout.BeginHorizontal(); controller.currentPresetEditor = (ColorsPreset)EditorGUILayout.ObjectField("Current Preset: ", controller.currentPresetEditor, typeof(ColorsPreset), true); if (GUILayout.Button("New")) { presetCreation = true; } GUILayout.EndHorizontal(); //if (hasUnsavedChanges) //{ // GUILayout.Space(10); // EditorGUILayout.HelpBox("There is unsaved changes", MessageType.Warning); //} GUILayout.Space(10); if (EditorApplication.isPlaying) { GUILayout.BeginHorizontal(); if (GUILayout.Button("◀", GUILayout.Height(20))) { if (hasUnsavedChanges) { if (EditorUtility.DisplayDialog("There is unsaved changes", "All changes will be lost", "Discard changes", "Cancel")) { hasUnsavedChanges = false; ColorsController.EditorSetRandomPresetInverse(); } } else { ColorsController.EditorSetRandomPresetInverse(); } } if (GUILayout.Button("▶", GUILayout.Height(20))) { if (hasUnsavedChanges) { if (EditorUtility.DisplayDialog("There is unsaved changes", "All changes will be lost", "Discard changes", "Cancel")) { hasUnsavedChanges = false; ColorsController.SetRandomPreset(); } } else { ColorsController.SetRandomPreset(); } } GUILayout.EndHorizontal(); } GUILayout.BeginHorizontal(); if (GUILayout.Button("Load current", GUILayout.Height(30), GUILayout.Width(EditorGUIUtility.currentViewWidth * 0.463f))) { LoadCurrent(controller); } if (GUILayout.Button((hasUnsavedChanges ? "*" : "") + "Save to current", GUILayout.Height(30), GUILayout.Width(EditorGUIUtility.currentViewWidth * 0.463f))) { SaveToCurrent(controller); } GUILayout.EndHorizontal(); } else { newPresetName = EditorGUILayout.TextField("Preset Name: ", newPresetName); GUILayout.Space(10); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Cancel", GUILayout.Height(30))) { presetCreation = false; newPresetName = string.Empty; } if (GUILayout.Button("Create", GUILayout.Height(30))) { controller.currentPresetEditor = ScriptableObject.CreateInstance <ColorsPreset>(); AssetDatabase.CreateAsset(controller.currentPresetEditor, PRESETS_PATH + (newPresetName == string.Empty ? "NewPreset" : newPresetName) + ".asset"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); presetCreation = false; } GUILayout.EndHorizontal(); } serializedObject.ApplyModifiedProperties(); }
void ShowAssetChooser(FileType type) { BaseFileOpenDialog fileDialog = null; switch (type) { case FileType.PATH: fileDialog = ScriptableObject.CreateInstance <PathFileOpenDialog>(); break; case FileType.SCENE_BACKGROUND: case FileType.SCENE_FOREGROUND: case FileType.EXIT_ICON: case FileType.FRAME_IMAGE: case FileType.ITEM_ICON: case FileType.ITEM_IMAGE: case FileType.ITEM_IMAGE_OVER: case FileType.SET_ITEM_IMAGE: case FileType.BOOK_IMAGE_PARAGRAPH: case FileType.BOOK_ARROW_LEFT_NORMAL: case FileType.BOOK_ARROW_LEFT_OVER: case FileType.BOOK_ARROW_RIGHT_NORMAL: case FileType.BOOK_ARROW_RIGHT_OVER: case FileType.CURSOR: case FileType.BUTTON: case FileType.BUTTON_OVER: fileDialog = ScriptableObject.CreateInstance <ImageFileOpenDialog>(); break; case FileType.SCENE_MUSIC: case FileType.CUTSCENE_MUSIC: case FileType.EXIT_MUSIC: case FileType.FRAME_MUSIC: case FileType.NPC_DESCRIPTION_NAME_SOUND: case FileType.NPC_DESCRIPTION_DETAILED_SOUND: case FileType.NPC_DESCRIPTION_BRIEF_SOUND: case FileType.ITEM_DESCRIPTION_NAME_SOUND: case FileType.ITEM_DESCRIPTION_DETAILED_SOUND: case FileType.ITEM_DESCRIPTION_BRIEF_SOUND: case FileType.PLAY_SOUND_EFFECT: case FileType.BUTTON_SOUND: fileDialog = ScriptableObject.CreateInstance <MusicFileOpenDialog>(); break; case FileType.PLAY_ANIMATION_EFFECT: case FileType.CHARACTER_ANIM: case FileType.CUTSCENE_SLIDES: fileDialog = ScriptableObject.CreateInstance <AnimationFileOpenDialog>(); break; case FileType.CUTSCENE_VIDEO: fileDialog = ScriptableObject.CreateInstance <VideoFileOpenDialog>(); break; } if (fileDialog) { fileDialog.Init(this, type); } else { Debug.LogError("No window popup for filetype: " + type); } }
public static void CreateNewTimeline() { var icon = EditorGUIUtility.IconContent("TimelineAsset Icon").image as Texture2D; ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance <DoCreateTimeline>(), "New Timeline.playable", icon, null); }
public static void Import() { string path = string.Format("{0}/Localization/Localization_Example.csv", Application.dataPath); string[] lines = System.IO.File.ReadAllLines(path); Debug.LogFormat("Lines:{0}", lines.Length); // Determino le lingue da importare string[] firstCols = lines[0].Split(','); LanguageData[] languages = new LanguageData[firstCols.Length - 3]; for (int i = 3; i < firstCols.Length; i++) { //prelevo il codice lingua string languageCode = firstCols[i]; // creo il languageData per la lingua, lo inizializzo e lo salvo string languagePath = string.Format("Assets/Localization/{0}.asset", languageCode); LanguageData language; language = AssetDatabase.LoadAssetAtPath <LanguageData>(languagePath); // se non esiste lo creo if (language == null) { language = ScriptableObject.CreateInstance <LanguageData>(); Debug.LogFormat("Creating language file:{0}", languagePath); AssetDatabase.CreateAsset(language, languagePath); } language.languageCode = languageCode; language.values = new string[lines.Length - 1]; language.keys = new string[lines.Length - 1]; // lo salvo in un array così posso referenziarlo dopo languages[i - 3] = language; } // per tutte le linee for (int i = 1; i < lines.Length; i++) { // prendo le colonne string[] cols = lines[i].Split(','); // per ogni lingua for (int langIndex = 3; langIndex < cols.Length; langIndex++) { try { // salvo il corrispondente di quella chiave languages[langIndex - 3].values[i - 1] = cols[langIndex]; languages[langIndex - 3].keys[i - 1] = cols[0]; EditorUtility.SetDirty(languages[langIndex - 3]); } catch (System.Exception e) { Debug.LogErrorFormat("Error importing row {0} col {1}", i, langIndex); Debug.LogException(e); } } } AssetDatabase.Refresh(); CheckConsistency(languages); BuildCharacterCollection(languages); }