void LoadGenerator (Vector2 pos) { string path= UnityEditor.EditorUtility.OpenFilePanel( "Load Node", "Assets", "asset"); if (path==null || path.Length==0) return; path = path.Replace(Application.dataPath, "Assets"); GeneratorsAsset loadedGens = (GeneratorsAsset)AssetDatabase.LoadAssetAtPath(path, typeof(GeneratorsAsset)); for (int i=loadedGens.list.Length-1; i>=0; i--) { //cloning //loadedGens.list[i] = loadedGens.list[i].ReflectionCopy(); Generator gen = loadedGens.list[i]; //offset gen.guiRect.position += pos; //ignoring already existing outputs if (gen is IOutput && MapMagic.instance.gens.GetGenerator(gen.GetType())!=null) { Debug.Log ("MapMagic: tried to load Output which already exists (" + gen + "). Skipping."); loadedGens.UnlinkGenerator(gen); ArrayUtility.RemoveAt(ref loadedGens.list, i); } } ArrayUtility.AddRange(ref MapMagic.instance.gens.list, loadedGens.list); MapMagic.instance.gens.ChangeGenerator(null); repaint=true; Repaint(); }
static void CreateMapMagic () { if (FindObjectOfType<MapMagic>() != null) { Debug.LogError("Could not create new Map Magic instance, it already exists in scene."); return; } GameObject go = new GameObject(); go.name = "Map Magic"; MapMagic.instance = go.AddComponent<MapMagic>(); //new terrains MapMagic.instance.chunks = new ChunkGrid<Chunk>(); MapMagic.instance.seed=12345; MapMagic.instance.terrainSize=1000; MapMagic.instance.terrainHeight=300; MapMagic.instance.resolution=512; MapMagic.instance.chunks.Create(new Coord(0,0), MapMagic.instance, pin:true); //MapMagic.instance.terrains.maxCount = 5; //creating initial generators MapMagic.instance.gens = GeneratorsAsset.Default(); //MapMagic.instance.guiGens = MapMagic.instance.gens; //registering undo MapMagic.instance.gens.OnBeforeSerialize(); Undo.RegisterCreatedObjectUndo (go, "MapMagic Create"); EditorUtility.SetDirty(MapMagic.instance); MapMagicWindow.Show(MapMagic.instance.gens, MapMagic.instance, forceOpen:false, asBiome:false); /*HeightOutput heightOut = new HeightOutput(); heightOut.guiRect = new Rect(43,76,200,20); MapMagic.instance.generators.array[1] = heightOut; heightOut.input.Link(noiseGen.output, noiseGen);*/ }
public static void ShowEditor () { //GeneratorsAsset gens = FindObjectOfType<GeneratorsAsset>(); MapMagic mm = FindObjectOfType<MapMagic>(); GeneratorsAsset gens = mm!=null? mm.gens : null; MapMagicWindow.Show(gens, mm, forceOpen:true); }
//public static virtual void Process (Chunk chunk) //gui public void DrawHeader(IMapMagic mapMagic, GeneratorsAsset gens, bool debug = false) { //drawing header background layout.Icon("MapMagic_Window_Header", new Rect(layout.field.x, layout.field.y, layout.field.width, 16)); //drawing eye icon layout.Par(14); layout.Inset(2); Rect eyeRect = layout.Inset(18); GeneratorMenuAttribute attribute = System.Attribute.GetCustomAttribute(GetType(), typeof(GeneratorMenuAttribute)) as GeneratorMenuAttribute; if (attribute != null && attribute.disengageable) { layout.Toggle(ref enabled, rect: eyeRect, onIcon: "MapMagic_GeneratorEnabled", offIcon: "MapMagic_GeneratorDisabled"); } else { layout.Icon("MapMagic_GeneratorAlwaysOn", eyeRect, Layout.IconAligment.center, Layout.IconAligment.center); } //drawing label string genName = ""; if (mapMagic != null && debug) { int num = -1; for (int n = 0; n < gens.list.Length; n++) { if (gens.list[n] == this) { num = n; } } genName += num + ". "; } genName += attribute == null? "Unknown" : attribute.name; if (mapMagic != null && debug && !mapMagic.IsGeneratorReady(this)) { genName += "*"; } Rect labelRect = layout.Inset(layout.field.width - 18 - 22); labelRect.height = 25; labelRect.y -= (1f - layout.zoom) * 6 + 2; layout.Label(genName, labelRect, fontStyle: FontStyle.Bold, fontSize: 19 - layout.zoom * 8); //drawing help link Rect helpRect = layout.Inset(22); if (attribute != null && attribute.helpLink != null && attribute.helpLink.Length != 0) { layout.Label("", helpRect, url: attribute.helpLink, icon: "MapMagic_Help"); //if (layout.Button("", helpRect, icon:"MapMagic_Help")) Application.OpenURL(attribute.helpLink); //UnityEditor.EditorGUIUtility.AddCursorRect (layout.ToDisplay(helpRect), UnityEditor.MouseCursor.Link); } layout.Par(4); }
public void Update () { //checking if instance already exists and disabling if it is another mm if (instance != null && instance != this) { Debug.LogError("MapMagic object already present in scene. Disabling duplicate"); this.enabled = false; return; } //loading old non-asset data if (gens == null) { if (serializer != null && serializer.entities != null && serializer.entities.Count != 0) { Debug.Log("MapMagic: Loading outdated scene format. Please check node consistency and re-save the scene."); LoadOldNonAssetData(); serializer = null; } else Debug.Log("MapMagic: Could not find the proper graph data. Please assign it manually."); } //checking gens asset if (gens == null) gens = ScriptableObject.CreateInstance<GeneratorsAsset>(); //finding camera positions Vector3[] camPoses = GetCamPoses(); if (camPoses.Length==0) return; //displaying debug range if (guiDebug && !isEditor) for (int c=0; c<camPoses.Length; c++) transform.TransformPoint(camPoses[c]).DrawDebug(generateRange, Color.green); //deploying terrain matrix if (!isEditor && generateInfinite) terrains.Deploy(camPoses, allowMove:true); //enabling/disabling, switching lods, starting threads terrains.SwitchState(camPoses); //transforming cam poses to coords Coord[] camCoords = GetCamCoords(); if (camCoords.Length==0) return; //calculating number of running threads and checking a need to prepare generators runningThreadsCount = 0; bool prepareGenerators = false; foreach (Chunk tw in terrains.Objects()) { if (tw.running) runningThreadsCount++; if (tw.start) prepareGenerators = true; //if any of chunks started this frame } //preparing generators if (prepareGenerators) { foreach (TextureInput tin in gens.GeneratorsOfType<TextureInput>()) tin.CheckLoadTexture(); } //updating chunks foreach (Chunk tw in terrains.ObjectsFromCoords(camCoords)) tw.Update(); }
//get static actions using instance //public override Action<CoordRect, Chunk.Results, GeneratorsAsset, Chunk.Size, Func<float,bool>> GetProces () { return null; } //public override System.Func<CoordRect, Terrain, object, Func<float,bool>, IEnumerator> GetApply () { return null; } //public override System.Action<CoordRect, Terrain> GetPurge () { return null; } public override void OnGUI(GeneratorsAsset gens) { layout.Par(20); mask.DrawIcon(layout, "Mask"); layout.Par(5); layout.fieldSize = 0.7f; data = layout.ScriptableAssetField(data, construct: null); //drawing "Edit" button in mmwindow }
public void LoadOldNonAssetData () { serializer.ClearLinks(); GeneratorsList generators = new GeneratorsList(); generators = (GeneratorsList)serializer.Retrieve(0); serializer.ClearLinks(); gens = ScriptableObject.CreateInstance<GeneratorsAsset>(); gens.list = generators.list; //gens.outputs = generators.outputs; }
public void Populate(GeneratorsAsset gens) { generators.Clear(); for (int i = 0; i < gens.list.Length; i++) { Generator gen = gens.list[i]; if (layout.field.Contains(gen.layout.field)) { generators.Add(gen); } } }
public GeneratorsAsset ReleaseAsset() { #if UNITY_EDITOR UnityEditor.Undo.RecordObject(MapMagic.instance, "MapMagic Release Data"); MapMagic.instance.setDirty = !MapMagic.instance.setDirty; GeneratorsAsset newData = ScriptableObject.CreateInstance <GeneratorsAsset>(); newData.list = (Generator[])CustomSerialization.DeepCopy(list); return(newData); //UnityEditor.EditorUtility.SetDirty(MapMagic.instance); #else return(null); #endif }
void SaveGenerator (Generator gen, Vector2 pos) { string path= UnityEditor.EditorUtility.SaveFilePanel( "Save Node as Unity Asset", "Assets", "MapMagicNode.asset", "asset"); if (path==null || path.Length==0) return; path = path.Replace(Application.dataPath, "Assets"); GeneratorsAsset saveGens = SmartCopyGenerator(gen); if (gen != null) for (int i=0; i<saveGens.list.Length; i++) saveGens.list[i].guiRect.position -= gen.guiRect.position; AssetDatabase.CreateAsset(saveGens, path); AssetDatabase.SaveAssets(); }
public override void OnGUI(GeneratorsAsset gens) { #if VOXELAND //voxeland = MapMagic.instance.GetComponent("Voxeland"); //refreshing voxeland blocks information if (voxeland == null) { voxeland = GameObject.FindObjectOfType <Voxeland5.Voxeland>(); } //creating layers if (voxeland != null) { int layersCount = voxeland.grassTypes.array.Length; if (layersCount != layers.Length) { for (int i = layersCount; i < layers.Length; i++) { layers[i].input.Unlink(); } ArrayTools.Resize(ref layers, layersCount); } for (int i = 0; i < layers.Length; i++) { if (layers[i] == null) { layers[i] = new Layer(); } } } if (layers.Length == 0) { layout.Par(32); layout.Label("Voxeland terrain has no Grass Block types", rect: layout.Inset(), helpbox: true); } //drawing layers layout.Par(1); layout.Label("Temp", rect: layout.Inset()); //needed to reset label bold style layout.margin = 10; layout.rightMargin = 10; for (int i = layers.Length - 1; i >= 0; i--) { layout.DrawLayer(OnLayerGUI, ref selected, i); } #endif }
private GeneratorsAsset SmartCopyGenerator (Generator gen) { GeneratorsAsset copyGens = ScriptableObject.CreateInstance<GeneratorsAsset>(); //saving all gens if clicked to background if (gen == null) { copyGens.list = (Generator[])Serializer.DeepCopy(MapMagic.instance.gens.list); } //saving group else if (gen is Group) { Group copyGroup = (Group)Serializer.DeepCopy(gen); copyGens.UnlinkGenerator(copyGroup, unlinkGroup: true); Generator[] copyAllGens= (Generator[])Serializer.DeepCopy(MapMagic.instance.gens.list); copyGens.list = new Generator[] { copyGroup }; for (int i=0; i<copyAllGens.Length; i++) { if (!copyGroup.guiRect.Contains(copyAllGens[i].guiRect)) continue; //un-linking copy gens foreach (Generator.Input input in copyAllGens[i].Inputs()) { if (input.link == null) continue; if (!copyGroup.guiRect.Contains(input.linkGen.guiRect)) input.Unlink(); } ArrayUtility.Add(ref copyGens.list, copyAllGens[i]); } } //saving single generator else { Generator copyGen = (Generator)Serializer.DeepCopy(gen); copyGens.UnlinkGenerator(copyGen); copyGens.list = new Generator[] { copyGen }; } return copyGens; }
public override void OnGUI(GeneratorsAsset gens) { #if VOXELAND //voxeland = MapMagic.instance.GetComponent("Voxeland"); //refreshing voxeland blocks information if (voxeland == null) { voxeland = GameObject.FindObjectOfType <Voxeland5.Voxeland>(); } //gathering block names if (voxeland != null) { int namesCount = voxeland.landTypes.array.Length + 2; if (blockNames == null || blockNames.Length != namesCount) { blockNames = new string[namesCount]; } for (int i = 0; i < voxeland.landTypes.array.Length; i++) { blockNames[i] = voxeland.landTypes.array[i].name; } blockNames[namesCount - 1] = "Empty"; } //drawing layers layout.Par(1); layout.Label("Temp", rect: layout.Inset()); //needed to reset label bold style layout.margin = 10; layout.rightMargin = 10; for (int i = layers.Length - 1; i >= 0; i--) { layout.DrawLayer(OnLayerGUI, ref selected, i); } layout.Par(3); layout.Par(); layout.DrawArrayAdd(ref layers, ref selected, layout.Inset(0.15f), reverse: true, createElement: () => new Layer()); layout.DrawArrayRemove(ref layers, ref selected, layout.Inset(0.15f), reverse: true); layout.DrawArrayDown(ref layers, ref selected, layout.Inset(0.15f), dispUp: true); layout.DrawArrayUp(ref layers, ref selected, layout.Inset(0.15f), dispDown: true); layout.Par(5); #endif }
public void TryLoadOldNonAssetData () { if (serializer != null && serializer.entities != null && serializer.entities.Count != 0) { Debug.Log("MapMagic: Loading outdated scene format. Please check node consistency and re-save the scene."); serializer.ClearLinks(); GeneratorsList generators = new GeneratorsList(); generators = (GeneratorsList)serializer.Retrieve(0); serializer.ClearLinks(); gens = ScriptableObject.CreateInstance<GeneratorsAsset>(); gens.list = generators.list; //gens.outputs = generators.outputs; serializer = null; } else { Debug.Log("MapMagic: Could not find the proper graph data. It the data file was changed externally reload the scene, otherwise create the new one in the General Settings tab."); return; } }
public void UnlinkInActiveGens() { //TODO20: each generator should have a link to gens object activeGensBoxed = Extensions.CallStaticMethodFrom("Assembly-CSharp-Editor", "MapMagic.MapMagicWindow", "GetGens", null); if (activeGensBoxed == null) { return; } GeneratorsAsset activeGens = activeGensBoxed as GeneratorsAsset; Input connectedInput = GetConnectedInput(activeGens.list); if (connectedInput != null) { connectedInput.Link(null, null); } }
public override void OnGUI() { layout.Par(20); mask.DrawIcon(layout, "Mask"); layout.Par(5); layout.fieldSize = 0.7f; layout.margin = 3; layout.Field(ref data, "Data"); layout.Par(20); if (data == null) { if (layout.Button("Create", rect: layout.Inset(0.5f))) { data = ScriptableObject.CreateInstance <GeneratorsAsset>(); } } else { if (layout.Button("Edit", rect: layout.Inset(0.5f))) { MapMagic.instance.guiGens = data; } } #if UNITY_EDITOR if (data == null || !UnityEditor.AssetDatabase.Contains(data)) { if (layout.Button("Save", rect: layout.Inset(0.5f), disabled: data == null)) { data.SaveAsset(); } } else { if (layout.Button("Release", rect: layout.Inset(0.5f))) { data = data.ReleaseAsset(); } } #endif }
public static GeneratorsAsset Default() { GeneratorsAsset gens = ScriptableObject.CreateInstance <GeneratorsAsset>(); //creating initial generators NoiseGenerator1 noiseGen = (NoiseGenerator1)gens.CreateGenerator(typeof(NoiseGenerator1), new Vector2(50, 50)); noiseGen.intensity = 0.75f; CurveGenerator curveGen = (CurveGenerator)gens.CreateGenerator(typeof(CurveGenerator), new Vector2(250, 50)); curveGen.curve = new AnimationCurve(new Keyframe[] { new Keyframe(0, 0, 0, 0), new Keyframe(1, 1, 2.5f, 1) }); HeightOutput heightOut = (HeightOutput)gens.CreateGenerator(typeof(HeightOutput), new Vector2(450, 50)); curveGen.input.Link(noiseGen.output, noiseGen); heightOut.input.Link(curveGen.output, curveGen); return(gens); }
public static void Show (GeneratorsAsset gens, IMapMagic mapMagic, bool forceOpen=true, bool asBiome=false) { //opening if force open if (forceOpen) instance = (MapMagicWindow)EditorWindow.GetWindow (typeof (MapMagicWindow)); //finding instance if (instance == null) { MapMagicWindow[] windows = Resources.FindObjectsOfTypeAll<MapMagicWindow>(); if (windows.Length==0) return; instance = windows[0]; } instance.mapMagic = mapMagic; if (!asBiome) instance.gensBiomeHierarchy.Clear(); instance.gensBiomeHierarchy.Add(gens); instance.Show(); instance.Repaint(); }
public override void OnInspectorGUI() { GeneratorsAsset gens = (GeneratorsAsset)target; if (layout == null) { layout = new Layout(); } layout.margin = 0; layout.field = Layout.GetInspectorRect(); layout.cursor = new Rect(); layout.undoObject = gens; layout.undoName = "MapMagic Generator change"; layout.Par(24); if (layout.Button("Show Editor", rect: layout.Inset(), icon: "MapMagic_EditorIcon")) { MapMagicWindow.Show(gens, null, forceOpen: true, asBiome: false); } Layout.SetInspectorRect(layout.field); }
public override void OnGUI(GeneratorsAsset gens) { //initializing layout layout.cursor = new Rect(); layout.change = false; //drawing background layout.Element("MapMagic_Group", layout.field, new RectOffset(16, 16, 16, 16), new RectOffset(0, 0, 0, 0)); //lock sign /*Rect lockRect = new Rect(guiRect.x+guiRect.width-14-6, field.y+6, 14, 12); * layout.Icon(locked? "MapMagic_LockLocked":"MapMagic_LockUnlocked", lockRect, verticalAlign:Layout.IconAligment.center); * bool wasLocked = locked; #if UNITY_EDITOR * locked = UnityEditor.EditorGUI.Toggle(layout.ToDisplay(lockRect.Extend(3)), locked, GUIStyle.none); #endif * if (locked && !wasLocked) LockContents(); * if (!locked && wasLocked) UnlockContents();*/ //name and comment layout.margin = 5; layout.CheckStyles(); float nameWidth = layout.boldLabelStyle.CalcSize(new GUIContent(name)).x * 1.1f / layout.zoom + 10f; float commentWidth = layout.labelStyle.CalcSize(new GUIContent(comment)).x / layout.zoom + 10; nameWidth = Mathf.Min(nameWidth, guiRect.width - 5); commentWidth = Mathf.Min(commentWidth, guiRect.width - 5); if (!locked) { layout.fontSize = 13; layout.Par(22); name = layout.Field(name, rect: layout.Inset(nameWidth), useEvent: true, style: layout.boldLabelStyle); layout.fontSize = 11; layout.Par(18); comment = layout.Field(comment, rect: layout.Inset(commentWidth), useEvent: true, style: layout.labelStyle); } else { layout.fontSize = 13; layout.Par(22); layout.Label(name, rect: layout.Inset(nameWidth), fontStyle: FontStyle.Bold); layout.fontSize = 11; layout.Par(18); layout.Label(comment, rect: layout.Inset(commentWidth)); } }
public void DrawPortalSelector (Portal exit, Generator.InoutType type) { if (MapMagic.instance.guiGens == null) MapMagic.instance.guiGens = MapMagic.instance.gens; GeneratorsAsset gens = MapMagic.instance.guiGens; //if (MapMagic.instance.guiGens != null) gens = MapMagic.instance.guiGens; int entersNum = 0; for (int g=0; g<gens.list.Length; g++) { Portal portal = gens.list[g] as Portal; if (portal == null) continue; if (portal.form == Portal.PortalForm.Out) continue; if (portal.type != type) continue; entersNum++; } PopupMenu.MenuItem[] popupItems = new PopupMenu.MenuItem[entersNum]; int counter = 0; for (int g=0; g<gens.list.Length; g++) { Portal enter = gens.list[g] as Portal; if (enter == null) continue; if (enter.form == Portal.PortalForm.Out) continue; if (enter.type != type) continue; popupItems[counter] = new PopupMenu.MenuItem( enter.name, delegate () { if (enter.IsDependentFrom(exit)) { Debug.LogError("MapMagic: Linking portals this way will create dependency loop."); return; } exit.input.Link(enter.output, enter); gens.ChangeGenerator(exit); } ); counter++; } PopupMenu.DrawPopup(popupItems, Event.current.mousePosition, closeAllOther:true); }
void DuplicateGenerator (Generator gen) { GeneratorsAsset copyGens = SmartCopyGenerator(gen); //ignoring already existing outputs for (int i=copyGens.list.Length-1; i>=0; i--) { Generator copyGen = copyGens.list[i]; if (copyGen is IOutput && MapMagic.instance.gens.GetGenerator(gen.GetType())!=null) { Debug.Log ("MapMagic: tried to copy Output which already exists (" + copyGen + "). Skipping."); copyGens.UnlinkGenerator(copyGen); ArrayUtility.RemoveAt(ref copyGens.list, i); } copyGen.guiRect.position += new Vector2(0, gen.guiRect.height + 10); } ArrayUtility.AddRange(ref MapMagic.instance.gens.list, copyGens.list); MapMagic.instance.gens.ChangeGenerator(null); repaint=true; Repaint(); }
public override void OnGUI(GeneratorsAsset gens) { if (min < 0) { min = 0; } if (max < 0) { max = MapMagic.instance.terrainHeight; } //inouts layout.Par(20); input.DrawIcon(layout, "Input"); output.DrawIcon(layout, "Output"); layout.Par(20); maskIn.DrawIcon(layout, "Mask"); layout.Par(5); layout.Field(ref unitClamp, "Unit Clamp"); layout.margin = 20; layout.Label("Range:"); //layout.Par(); layout.Label("Min:", rect:layout.Inset(0.999f)); layout.Label("Max:", rect:layout.Inset(1f)); layout.Field(ref min, "Lower", min: 0, max: MapMagic.instance.terrainHeight); layout.Field(ref max, "Upper", min: 0, max: MapMagic.instance.terrainHeight); }
public static void Process(CoordRect rect, Chunk.Results results, GeneratorsAsset gens, Chunk.Size terrainSize, Func <float, bool> stop = null) { #if VOXELAND if (stop != null && stop(0)) { return; } if (voxeland == null) { return; } //finding area by rect offset Coord areaCoord = Coord.PickCell(rect.offset.x, rect.offset.z, voxeland.data.areaSize); Voxeland5.Data.Area area = voxeland.data.areas[areaCoord.x, areaCoord.z]; //clearing grass area.ClearGrass(); //preparing random //Noise noise = new Noise(12345); //to switch grass depending on it's opacity //processing foreach (VoxelandGrassOutput gen in gens.GeneratorsOfType <VoxelandGrassOutput>(onlyEnabled:true, checkBiomes:true)) { //reading output directly if (stop != null && stop(0)) { return; //checking stop before reading output } //loading biome matrix Matrix biomeMask = null; if (gen.biome != null) { object biomeMaskObj = gen.biome.mask.GetObject(results); if (biomeMaskObj == null) { continue; //adding nothing if biome has no mask } biomeMask = (Matrix)biomeMaskObj; if (biomeMask == null) { continue; } if (biomeMask.IsEmpty()) { continue; //optimizing empty biomes } } //iterating layers for (int l = 0; l < gen.layers.Length; l++) { Layer layer = gen.layers[l]; //loading inputs Matrix src = (Matrix)layer.input.GetObject(results); if (src == null) { continue; } //multiplying with biome mask - in SetGrassLayer //apply //area.SetGrassLayer(src, (byte)l, layer.density, noise:noise, layerNum:l, mask:biomeMask); area.SetGrassLayer(src.rect.offset.x, src.rect.offset.z, src.rect.size.x, src.array, (byte)l, layer.density, l, biomeMask == null? null : biomeMask.array); } } //pushing to apply if (stop != null && stop(0)) { return; } results.apply.CheckAdd(typeof(VoxelandOutput), null, replace: true); #endif }
public override void OnGUI(GeneratorsAsset gens) { layout.margin = 18; layout.rightMargin = 15; layout.Par(17); if (form == PortalForm.In) { input.DrawIcon(layout); if (drawConnections) { output.DrawIcon(layout); } else { output.guiRect = new Rect(guiRect.x + guiRect.width, guiRect.y + 25, 0, 0); } } if (form == PortalForm.Out) { if (drawConnections) { input.DrawIcon(layout); } else { input.guiRect = new Rect(guiRect.x, guiRect.y + 25, 0, 0); } output.DrawIcon(layout); } layout.Field(ref type, rect: layout.Inset(0.39f)); if (type != input.type) { input.Unlink(); input.type = type; output.type = type; } if (layout.lastChange) { foreach (Portal portal in MapMagic.instance.gens.GeneratorsOfType <Portal>()) { if (portal.input.linkGen == this) { portal.input.Unlink(); } } //TODO: can't change type without MM instance } layout.Field(ref form, rect: layout.Inset(0.30f)); layout.CheckButton(ref drawConnections, label: "", rect: layout.Inset(20), monitorChange: false, icon: "MapMagic_ShowConnections", tooltip: "Show portal connections"); if (layout.Button("", layout.Inset(20), monitorChange: false, icon: "MapMagic_Focus_Small", disabled: form == PortalForm.In, tooltip: "Focus on input portal") && input.linkGen != null && MapMagic.instance != null) { MapMagic.instance.layout.Focus(input.linkGen.guiRect.center); } //select input/button layout.Par(20); if (form == PortalForm.In) { name = layout.Field(name, rect: layout.Inset()); } if (form == PortalForm.Out) { string buttonLabel = "Select"; if (input.linkGen != null) { if (!(input.linkGen is Portal)) { input.Link(null, null); //in case connected input portal was changet to output } else { buttonLabel = ((Portal)input.linkGen).name; } } Rect buttonRect = layout.Inset(); buttonRect.height -= 3; if (layout.Button(buttonLabel, rect: buttonRect) && OnChooseEnter != null) { OnChooseEnter(this, type); } } }
public abstract void OnGUI(GeneratorsAsset gens);
private void OnGUI() { DrawWindow(); if (repaint) DrawWindow(); repaint = false; } //drawing window, or doing it twice if repaint is needed private void DrawWindow() { if (gens == null) return; //un-selecting field on drag #if !UNITY_EDITOR_LINUX if (Event.current.button != 0 && UnityEngine.GUI.GetNameOfFocusedControl() != "Temp") RemoveFocusOnControl(); #endif //startingscript.layout if (gens.layout==null) { gens.layout = new Layout(); gens.layout.scroll = gens.guiScroll; gens.layout.zoom = gens.guiZoom; gens.layout.maxZoom = 1f; } gens.layout.Zoom(); gens.layout.Scroll(); //scrolling and zooming if (gens.layout.zoom < 0.0001f) gens.layout.zoom = 1; gens.layout.field = this.position; //zoomning with keyboard if (Event.current.type == EventType.KeyDown) { if (Event.current.keyCode==KeyCode.Equals && Event.current.alt) { gens.layout.zoom += gens.layout.zoomStep; if (gens.layout.zoom>1) gens.layout.zoom=1; Event.current.Use(); } if (Event.current.keyCode==KeyCode.Minus && Event.current.alt) { gens.layout.zoom -= gens.layout.zoomStep; Event.current.Use(); } } //unity 5.4 beta if (Event.current.type == EventType.Layout) return; if (Event.current.type == EventType.MouseDrag) //skip all mouse drags (except when dragging text selection cursor in field) { if (!UnityEditor.EditorGUIUtility.editingTextField) return; if (UnityEngine.GUI.GetNameOfFocusedControl() == "Temp") return; } //using middle mouse click events if (Event.current.button == 2) Event.current.Use(); //undo Undo.undoRedoPerformed -= PerformUndo; Undo.undoRedoPerformed += PerformUndo; //setting title content titleContent = new GUIContent("Map Magic"); titleContent.image =gens.layout.GetIcon("MapMagic_WindowIcon"); //drawing background Vector2 windowZeroPos =gens.layout.ToInternal(Vector2.zero); windowZeroPos.x = ((int)(windowZeroPos.x/64f)) * 64; windowZeroPos.y = ((int)(windowZeroPos.y/64f)) * 64; Texture2D backTex = gens.layout.GetIcon("MapMagic_Background"); Rect backRect = new Rect(windowZeroPos - new Vector2(64,64), position.size + new Vector2(127,127)); UnityEditor.EditorGUI.DrawPreviewTexture(new Rect(0,0,position.width,position.height), backTex, null, ScaleMode.ScaleAndCrop); gens.layout.Icon(backTex, backRect, tile:true); //drawing test center //script.layout.Button("Zero", new Rect(-10,-10,20,20)); //calculating visible area Rect visibleArea = gens.layout.ToInternal( new Rect(0,0,position.size.x,position.size.y) ); if (forceAll) { visibleArea = new Rect(-200000,-200000,400000,400000); forceAll = false; } //visibleArea = new Rect(visibleArea.x+100, visibleArea.y+100, visibleArea.width-200, visibleArea.height-200); //layout.Label("Area", helpBox:true, rect:visibleArea); //checking if all generators are loaded, and none of them is null for (int i=gens.list.Length-1; i>=0; i--) { if (gens.list[i] == null) { ArrayTools.RemoveAt(ref gens.list, i); continue; } foreach (Generator.Input input in gens.list[i].Inputs()) { if (input == null) continue; if (input.linkGen == null) input.Link(null, null); } } #region Drawing groups for(int i=0; i<gens.list.Length; i++) { if (!(gens.list[i] is Group)) continue; Group group = gens.list[i] as Group; //checking if this is withinscript.layout field if (group.guiRect.x > visibleArea.x+visibleArea.width || group.guiRect.y > visibleArea.y+visibleArea.height || group.guiRect.x+group.guiRect.width < visibleArea.x || group.guiRect.y+group.guiRect.height < visibleArea.y) if (group.guiRect.width > 0.001f && gens.layout.dragState != Layout.DragState.Drag) continue; //if guiRect initialized and not dragging //settingscript.layout data group.layout.field = group.guiRect; group.layout.scroll = gens.layout.scroll; group.layout.zoom = gens.layout.zoom; group.OnGUI(gens); group.guiRect = group.layout.field; } #endregion #region Drawing connections (before generators to make them display under nodes) foreach(Generator gen in gens.list) { foreach (Generator.Input input in gen.Inputs()) { if (input==null || input.link == null) continue; //input could be null in layered generators if (gen is Portal) { Portal portal = (Portal)gen; if (!portal.drawInputConnection) continue; } gens.layout.Spline(input.link.guiConnectionPos, input.guiConnectionPos, color:GeneratorsAsset.CanConnect(input.link,input)? input.guiColor : Color.red); } } #endregion #region creating connections (after generators to make clicking in inout work) int dragIdCounter = gens.list.Length+1; foreach (Generator gen in gens.list) foreach (Generator.IGuiInout inout in gen.Inouts()) { if (inout == null) continue; if (gens.layout.DragDrop(inout.guiRect, dragIdCounter)) { //finding target Generator.IGuiInout target = null; foreach (Generator gen2 in gens.list) foreach (Generator.IGuiInout inout2 in gen2.Inouts()) if (inout2.guiRect.Contains(gens.layout.dragPos)) target = inout2; //converting inout to Input (or Output) and target to Output (or Input) Generator.Input input = inout as Generator.Input; if (input==null) input = target as Generator.Input; Generator.Output output = inout as Generator.Output; if (output==null) output = target as Generator.Output; //connection validity test bool canConnect = input!=null && output!=null && GeneratorsAsset.CanConnect(output,input); //infinite loop test if (canConnect) { Generator outputGen = output.GetGenerator(gens.list); Generator inputGen = input.GetGenerator(gens.list); if (inputGen == outputGen || gens.CheckDependence(inputGen,outputGen)) canConnect = false; } //drag //if (script.layout.dragState==Layout.DragState.Drag) //commented out because will not be displayed on repaint otherwise //{ if (input == null)gens.layout.Spline(output.guiConnectionPos,gens.layout.dragPos, color:Color.red); else if (output == null)gens.layout.Spline(gens.layout.dragPos, input.guiConnectionPos, color:Color.red); else gens.layout.Spline(output.guiConnectionPos, input.guiConnectionPos, color:canConnect? input.guiColor : Color.red); //} //release if (gens.layout.dragState==Layout.DragState.Released && input!=null) //on release. Do nothing if input not defined { Undo.RecordObject (gens, "MapMagic Connection"); gens.setDirty = !gens.setDirty; input.Unlink(); if (canConnect) input.Link(output, output.GetGenerator(gens.list)); if (mapMagic!=null) { mapMagic.ClearResults(gen); mapMagic.Generate(); } EditorUtility.SetDirty(gens); } } dragIdCounter++; } #endregion #region Drawing generators for(int i=0; i<gens.list.Length; i++) { Generator gen = gens.list[i]; if (gen is Group) continue; //skipping groups //checking if this generator is withinscript.layout field if (gen.guiRect.x > visibleArea.x+visibleArea.width || gen.guiRect.y > visibleArea.y+visibleArea.height || gen.guiRect.x+gen.guiRect.width < visibleArea.x || gen.guiRect.y+gen.guiRect.height < visibleArea.y) if (gen.guiRect.width > 0.001f && gens.layout.dragState != Layout.DragState.Drag) continue; //if guiRect initialized and not dragging if (gen.layout == null) gen.layout = new Layout(); gen.layout.field = gen.guiRect; gen.layout.field.width = 160; //MapMagic.instance.guiGeneratorWidth; //gen.layout.OnBeforeChange -= RecordGeneratorUndo; //gen.layout.OnBeforeChange += RecordGeneratorUndo; gen.layout.undoObject = gens; gen.layout.undoName = "MapMagic Generators Change"; gen.layout.dragChange = true; gen.layout.disabled = changeLock; //copyscript.layout params gen.layout.scroll = gens.layout.scroll; gen.layout.zoom = gens.layout.zoom; //drawing background gen.layout.Element("MapMagic_Window", gen.layout.field, new RectOffset(34,34,34,34), new RectOffset(33,33,33,33)); //resetting layout gen.layout.field.height = 0; gen.layout.field.width =160; gen.layout.cursor = new Rect(); gen.layout.change = false; gen.layout.margin = 1; gen.layout.rightMargin = 1; gen.layout.fieldSize = 0.4f; //drawing header gen.DrawHeader (mapMagic, gens); if (gen is OutputGenerator && gen.layout.change && gen.enabled == false) //if just disabled output gensBiomeHierarchy[0].OnDisableGenerator(gen); //drawing parameters #if WDEBUG gen.OnGUI(gens); #else try { gen.OnGUI(gens); } catch (UnityException e) { Debug.LogError("Error drawing generator " + GetType() + "\n" + e);} //should be system.exception but it causes ExitGUIException on opening curve/color/texture fields //it's so unity... //if something goes wrong but no error is displayed - you know where to find it #endif gen.layout.Par(3); //drawing debug generate time #if WDEBUG if (mapMagic!=null) { Rect timerRect = new Rect(gen.layout.field.x, gen.layout.field.y+gen.layout.field.height, 200, 20); string timeLabel = "g:" + gen.guiGenerateTime + "ms "; if (gen is OutputGenerator) { if (Generator.guiProcessTime.ContainsKey(gen.GetType())) timeLabel += " p:" + Generator.guiProcessTime[gen.GetType()] + "ms "; if (Generator.guiApplyTime.ContainsKey(gen.GetType())) timeLabel += " a:" + Generator.guiApplyTime[gen.GetType()] + "ms "; } gen.layout.Label(timeLabel, timerRect); } #endif //instant generate on params change if (gen.layout.change) { if (mapMagic!=null) { mapMagic.ClearResults(gen); mapMagic.Generate(); } repaint=true; Repaint(); EditorUtility.SetDirty(gens); } //drawing biome "edit" button. Rather hacky, but we have to call editor method when pressing "Edit" if (gen is Biome) { Biome biome = (Biome)gen; if (gen.layout.Button("Edit", disabled:biome.data==null)) { MapMagicWindow.Show(biome.data, mapMagic, forceOpen:true,asBiome: true); Repaint(); return; //cancel drawing this graph if biome was opened } gen.layout.Par(10); } //changing all of the output generators of the same type (in case this one was disabled to make refresh) if (gen.layout.change && !gen.enabled && gen is OutputGenerator) { foreach (GeneratorsAsset ga in gensBiomeHierarchy) foreach (OutputGenerator sameOut in ga.GeneratorsOfType<OutputGenerator>(onlyEnabled:true, checkBiomes:true)) if (sameOut.GetType() == gen.GetType()) { mapMagic.ClearResults(sameOut); mapMagic.Generate(); } } if (gen.guiRect.width<1 && gen.guiRect.height<1) { repaint=true; Repaint(); } //repainting if some of the generators rect is 0 gen.guiRect = gen.layout.field; } #endregion #region Toolbar if (toolbarLayout==null) toolbarLayout = new Layout(); toolbarLayout.margin = 0; toolbarLayout.rightMargin = 0; toolbarLayout.field.width = this.position.width; toolbarLayout.field.height = 18; toolbarLayout.cursor = new Rect(); //toolbarLayout.window = this; toolbarLayout.Par(18, padding:0); EditorGUI.LabelField(toolbarLayout.field, "", EditorStyles.toolbarButton); if (mapMagic!=null && mapMagic.ToString()!="null" && !ReferenceEquals(mapMagic.gameObject,null)) //check game object in case it was deleted //mapMagic.ToString()!="null" - the only efficient delete check. Nor Equals neither ReferenceEquals are reliable. I <3 Unity! { //drawing state icon toolbarLayout.Inset(25); if (ThreadWorker.IsWorking("MapMagic")) { toolbarLayout.Icon("MapMagic_Loading", new Rect(5,0,16,16), animationFrames:12); Repaint(); } else toolbarLayout.Icon("MapMagic_Success", new Rect(5,0,16,16)); //TODO: changed sign //mapmagic name Rect nameLabelRect = toolbarLayout.Inset(100); nameLabelRect.y+=1; //nameLabelRect.height-=4; EditorGUI.LabelField(nameLabelRect, mapMagic.gameObject.name, EditorStyles.miniLabel); //generate buttons if (GUI.Button(toolbarLayout.Inset(110,padding:0), "Generate Changed", EditorStyles.toolbarButton)) mapMagic.Generate(force:true); if (GUI.Button(toolbarLayout.Inset(110,padding:0), "Force Generate All", EditorStyles.toolbarButton)) { mapMagic.ClearResults(); if (MapMagic.instance != null) foreach (Chunk chunk in MapMagic.instance.chunks.All()) if (chunk.terrain != null) chunk.terrain.transform.RemoveChildren(); mapMagic.Generate(force:true); } //seed field toolbarLayout.Inset(10); Rect seedLabelRect = toolbarLayout.Inset(34); seedLabelRect.y+=1; seedLabelRect.height-=4; Rect seedFieldRect = toolbarLayout.Inset(64); seedFieldRect.y+=2; seedFieldRect.height-=4; } else { Rect nameLabelRect = toolbarLayout.Inset(300); nameLabelRect.y+=1; //nameLabelRect.height-=4; EditorGUI.LabelField(nameLabelRect, "External data '" + AssetDatabase.GetAssetPath(gens) + "'", EditorStyles.miniLabel); } //right part toolbarLayout.Inset(toolbarLayout.field.width - toolbarLayout.cursor.x - 150 - 22,padding:0); //drawing exit biome button Rect biomeRect = toolbarLayout.Inset(80, padding:0); if (gensBiomeHierarchy.Count>1) { if (toolbarLayout.Button("", biomeRect, icon:"MapMagic_ExitBiome", style:EditorStyles.toolbarButton)) { gensBiomeHierarchy.RemoveAt(gensBiomeHierarchy.Count-1); Repaint(); return; } toolbarLayout.Label("Exit Biome", new Rect(toolbarLayout.cursor.x-60, toolbarLayout.cursor.y+3, 60, toolbarLayout.cursor.height), fontSize:9); } //focus button // if (GUI.Button(script.toolbarLayout.Inset(100,padding:0), "Focus", EditorStyles.toolbarButton)) FocusOnGenerators(); if (toolbarLayout.Button("", toolbarLayout.Inset(23,padding:0), icon:"MapMagic_Focus", style:EditorStyles.toolbarButton)) FocusOnGenerators(); if (toolbarLayout.Button("", toolbarLayout.Inset(47,padding:0), icon:"MapMagic_Zoom", style:EditorStyles.toolbarButton)) gens.layout.zoom=1; toolbarLayout.Label((int)(gens.layout.zoom*100)+"%", new Rect(toolbarLayout.cursor.x-28, toolbarLayout.cursor.y+3, 28, toolbarLayout.cursor.height), fontSize:8); toolbarLayout.Inset(3, margin:0); toolbarLayout.Label("", toolbarLayout.Inset(22, margin:0), url:"https://gitlab.com/denispahunov/mapmagic/wikis/Editor%20Window", icon:"MapMagic_Help"); #endregion #region Draging //dragging generators for(int i=gens.list.Length-1; i>=0; i--) { Generator gen = gens.list[i]; if (gen is Group) continue; gen.layout.field = gen.guiRect; //dragging if (gens.layout.DragDrop(gen.layout.field, i)) { if (gens.layout.dragState == Layout.DragState.Pressed) { Undo.RecordObject (gens, "MapMagic Generators Drag"); gens.setDirty = !gens.setDirty; } if (gens.layout.dragState == Layout.DragState.Drag || gens.layout.dragState == Layout.DragState.Released) { //gen.Move(gens.layout.dragDelta,true); gen.layout.field.position += gens.layout.dragDelta; gen.guiRect = gens.layout.field; //moving inouts to remove lag foreach (Generator.IGuiInout inout in gen.Inouts()) inout.guiRect = new Rect(inout.guiRect.position+gens.layout.dragDelta, inout.guiRect.size); //moving group if (gen is Group) { Group group = gen as Group; for (int g=0; g<group.generators.Count; g++) //group.generators[g].Move(delta,false); { group.generators[g].layout.field.position += gens.layout.dragDelta; group.generators[g].guiRect = gens.layout.field; foreach (Generator.IGuiInout inout in group.generators[g].Inouts()) //moving inouts to remove lag inout.guiRect = new Rect(inout.guiRect.position+gens.layout.dragDelta, inout.guiRect.size); } } repaint=true; Repaint(); EditorUtility.SetDirty(gens); } } //saving all generator rects gen.guiRect = gen.layout.field; } //dragging groups for (int i=gens.list.Length-1; i>=0; i--) { //Generator gen = gens.list[i]; Group group = gens.list[i] as Group; if (group == null) continue; group.layout.field = group.guiRect; //resizing group.layout.field =gens.layout.ResizeRect(group.layout.field, i+20000); //dragging if (gens.layout.DragDrop(group.layout.field, i)) { if (gens.layout.dragState == Layout.DragState.Pressed) { Undo.RecordObject (gens, "MapMagic Group Drag"); gens.setDirty = !gens.setDirty; group.Populate(gens); } if (gens.layout.dragState == Layout.DragState.Drag || gens.layout.dragState == Layout.DragState.Released) { //group.Move(gens.layout.dragDelta,true); group.layout.field.position += gens.layout.dragDelta; group.guiRect = gens.layout.field; for (int g=0; g<group.generators.Count; g++) //group.generators[g].Move(delta,false); { group.generators[g].layout.field.position += gens.layout.dragDelta; group.generators[g].guiRect.position += gens.layout.dragDelta; // = gens.layout.field; // foreach (Generator.IGuiInout inout in group.generators[g].Inouts()) //moving inouts to remove lag // inout.guiRect = new Rect(inout.guiRect.position+gens.layout.dragDelta, inout.guiRect.size); } repaint=true; Repaint(); EditorUtility.SetDirty(gens); } if (gens.layout.dragState == Layout.DragState.Released && group != null) gens.SortGroups(); } //saving all group rects group.guiRect = group.layout.field; } #endregion //right-click menus if (Event.current.type == EventType.ContextClick || (Event.current.type == EventType.MouseDown && Event.current.control)) DrawPopup(); //debug center //EditorGUI.HelpBox(script.layout.ToLocal(new Rect(-25,-10,50,20)), "Zero", MessageType.None); //assigning portal popup action Portal.OnChooseEnter -= DrawPortalSelector; Portal.OnChooseEnter += DrawPortalSelector; //saving scroll and zoom gens.guiScroll = gens.layout.scroll; gens.guiZoom = gens.layout.zoom; DrawDemoLock(); }
public override void OnInspectorGUI () { script = (MapMagic)target; if (MapMagic.instance == null) MapMagic.instance = script; script.terrains.CheckEmpty(); if (layout == null) layout = new Layout(); layout.margin = 0; layout.field = Layout.GetInspectorRect(); layout.cursor = new Rect(); layout.undoObject = script; layout.undoName = "MapMagic settings change"; layout.Par(20); bool modeNailing = layout.CheckButton(selectionMode == SelectionMode.nailing, "Pin Terrain", rect:layout.Inset(0.5f), icon:"MapMagic_PinIcon"); if (layout.lastChange && modeNailing) selectionMode = SelectionMode.nailing; if (layout.lastChange && !modeNailing) selectionMode = SelectionMode.none; bool modeLocking = layout.CheckButton(selectionMode == SelectionMode.locking, "Lock Terrain", rect:layout.Inset(0.5f), icon:"MapMagic_LockIcon"); if (layout.lastChange && modeLocking) selectionMode = SelectionMode.locking; if (layout.lastChange && !modeLocking) selectionMode = SelectionMode.none; layout.Par(4); layout.Par(24); if (layout.Button("Show Editor", rect:layout.Inset(), icon:"MapMagic_EditorIcon")) { MapMagicWindow window = (MapMagicWindow)EditorWindow.GetWindow (typeof (MapMagicWindow)); //SceneMagicWindow window = EditorWindow.GetWindow<VoxelandCreate>(); //window.script = script; window.Show(); // window.FocusOnOutput(); } // layout.ComplexField(ref MapMagic.instance.seed, "Seed"); // layout.ComplexSlider(script.terrains.terrainSize, "Terrain Size", max:2048, quadratic:true); // layout.ComplexSlider(ref script.terrainHeight, "Terrain Height", max:2048, quadratic:true); // layout.Par(); // layout.Par(); if (layout.Button("Generate")) { MapMagic.instance.terrains.start = true; script.ProcessThreads(); } // layout.Par(); if (layout.Button("Clear")) MapMagic.instance.generators.ClearGenerators(); // Undo.RecordObject (script, "MapMagic settings change"); layout.margin =10; layout.fieldSize = 0.4f; layout.Par(5); layout.Foldout(ref script.guiSettings, "General Settings"); if (script.guiSettings) { MapMagic.instance.resolution = (int)layout.Field((Pots)MapMagic.instance.resolution, "Resolution"); if (layout.lastChange && MapMagic.instance.instantGenerate) MapMagic.instance.ForceGenerate(); layout.Field(ref MapMagic.instance.terrainSize, "Terrain Size"); if (layout.lastChange) MapMagic.instance.terrains.Reset(); layout.Field(ref MapMagic.instance.terrainHeight, "Terrain Height"); if (layout.lastChange) MapMagic.instance.terrains.Reset(); layout.Par(5); layout.Field(ref MapMagic.instance.generateInfinite, "Generate Infinite Terrain"); if (MapMagic.instance.generateInfinite) { layout.Field(ref MapMagic.instance.generateRange, "Generate Range"); layout.Field(ref MapMagic.instance.removeRange, "Remove Range", min:MapMagic.instance.generateRange); layout.Field(ref MapMagic.instance.enableRange, "Enable Range"); //layout.Field(ref MapMagic.instance.terrains.enableRange, "Low Detail Range"); //layout.Field(ref MapMagic.instance.terrains.detailRange, "Full Detail Range"); } layout.Par(5); layout.Field(ref script.multiThreaded, "Multithreaded"); if (script.multiThreaded) layout.Field(ref script.maxThreads, "Max Threads"); layout.Field(ref script.instantGenerate, "Instant Generate"); layout.Field(ref script.saveIntermediate, "Save Intermediate Results"); layout.Par(5); layout.Field(ref script.heightWeldMargins, "Height Weld Margins", max:100); layout.Field(ref script.splatsWeldMargins, "Splats Weld Margins", max:100); //layout.ComplexField(ref script.hideWireframe, "Hide Wireframe"); layout.Par(5); layout.Toggle(ref script.hideFarTerrains, "Hide Out-of-Range Terrains"); //layout.Toggle(ref script.useAllCameras, "Generate around All Cameras"); layout.Toggle(ref script.copyLayersTags, "Copy Layers and Tags to Terrains"); layout.Toggle(ref script.copyComponents, "Copy Components to Terrains"); layout.Par(5); layout.Label("Generate Terrain Markers:"); layout.Field(ref script.genAroundMainCam, "Around Main Camera"); layout.Par(); layout.Field(ref script.genAroundObjsTag, "Around Objects Tagged", rect:layout.Inset()); int tagFieldWidth = (int)(layout.field.width*layout.fieldSize - 25); layout.cursor.x -= tagFieldWidth; script.genAroundTag = EditorGUI.TagField(layout.Inset(tagFieldWidth), script.genAroundTag); layout.Par(10); layout.Par(); layout.Label("Data", layout.Inset(0.2f)); GeneratorsAsset newGens = layout.Field<GeneratorsAsset>(script.gens, rect:layout.Inset(0.5f)); if (newGens != script.gens) { script.gens = newGens; script.guiGens = newGens; } if (layout.lastChange) script.gens.OnAfterDeserialize(); if (script.gens == null) { if (layout.Button("Create", layout.Inset(0.3f))) { MapMagic.instance.gens = GeneratorsAsset.Default(); MapMagic.instance.guiGens = MapMagic.instance.gens; EditorUtility.SetDirty(MapMagic.instance); } } else if (!AssetDatabase.Contains(script.gens)) { if (layout.Button("Save", layout.Inset(0.3f))) { MapMagic.instance.gens.SaveAsset(); EditorUtility.SetDirty(MapMagic.instance); } } else { if (layout.Button("Release", layout.Inset(0.3f))) { MapMagic.instance.gens = MapMagic.instance.gens.ReleaseAsset(); MapMagic.instance.guiGens = MapMagic.instance.gens; EditorUtility.SetDirty(MapMagic.instance); } } layout.Par(5); //layout.Field(ref script.guiGeneratorWidth, "Node Width"); layout.Toggle(ref script.guiDebug, "Debug"); } layout.fieldSize = 0.5f; layout.sliderSize = 0.6f; layout.Par(5); layout.Foldout(ref script.guiTerrainSettings, "Terrain Settings"); if (script.guiTerrainSettings) { layout.Field(ref script.pixelError, "Pixel Error", min:0, max:200, slider:true); layout.Field(ref script.baseMapDist, "Base Map Dist.", min:0, max:2000, slider:true); layout.Field(ref script.castShadows, "Cast Shadows"); layout.Field(ref script.terrainMaterialType, "Material Type", disabled:script.previewGenerator!=null); layout.Field(ref script.customTerrainMaterial, "Custom Material", disabled:script.terrainMaterialType!=MapMagic.TerrainMaterialType.Custom); if (script.previewGenerator!=null) layout.Label("Terrain Material is disabled in preview mode", helpbox: true); } layout.Par(5); layout.Foldout(ref script.guiTreesGrassSettings, "Trees, Details and Grass Settings"); if (script.guiTreesGrassSettings) { layout.Field(ref script.detailDraw, "Draw"); layout.Field(ref script.detailDistance, "Detail Distance", min:0, max:250, slider:true); layout.Field(ref script.detailDensity, "Detail Density", min:0, max:1, slider:true); layout.Field(ref script.treeDistance, "Tree Distance", min:0, max:5000, slider:true); layout.Field(ref script.treeBillboardStart, "Billboard Start", min:0, max:2000, slider:true); layout.Field(ref script.treeFadeLength, "Fade Length", min:0, max:200, slider:true); layout.Field(ref script.treeFullLod, "Max Full LOD Trees", min:0, max:10000, slider:true); layout.Par(5); layout.Field(ref script.windSpeed, "Wind Amount", min:0, max:1, slider:true); layout.Field(ref script.windSize, "Wind Bending", min:0, max:1, slider:true); layout.Field(ref script.windBending, "Wind Speed", min:0, max:1, slider:true); //there's no mistake here. Variable names are swapped in unity layout.Field(ref script.grassTint, "Grass Tint"); } if (layout.change) foreach (Chunk tw in MapMagic.instance.terrains.Objects()) tw.SetSettings(); #region About layout.Par(5); layout.Foldout(ref script.guiAbout, "About"); if (script.guiAbout) { Rect savedCursor = layout.cursor; layout.Par(100, padding:0); layout.Icon("MapMagicAbout", layout.Inset(100,padding:0)); layout.cursor = savedCursor; layout.margin = 115; layout.Label("MapMagic " + (int)(MapMagic.version/10f) + "." + (MapMagic.version - (int)(MapMagic.version/10f)*10)); layout.Label("by Denis Pahunov"); layout.Par(10); layout.Label(" - Online Documentation", url:"https://docs.google.com/document/d/1OX7zYOrPz9qOFNAfO0qawhB7T3M6tLG9VgZSEntRJTA/edit?usp=sharing"); layout.Label(" - Video Tutorials", url:"https://www.youtube.com/playlist?list=PL8fjbXLqBxvZb5yqXwp_bn4keyzyg5e0R"); layout.Label(" - Forum Thread", url:"http://forum.unity3d.com/threads/map-magic-a-node-based-procedural-and-infinite-map-generator-for-asset-store.344440/"); //layout.Par(10); //layout.Par(); layout.Label("Review or rating vote on"); //layout.Par(); layout.Label("Asset Store", url:"--"); //layout.Par(); layout.Label("would be appreciated."); layout.Par(10); layout.Label("On any issues related"); layout.Label("with plugin functioning "); layout.Label("you can contact the"); layout.Label("author by mail:"); layout.Label("*****@*****.**", url:"mailto:[email protected]"); } #endregion Layout.SetInspectorRect(layout.field); }
public override void OnGUI(GeneratorsAsset gens) { #if RTP if (rtp == null) { rtp = MapMagic.instance.GetComponent <ReliefTerrain>(); } if (renderer == null) { renderer = MapMagic.instance.GetComponent <MeshRenderer>(); } //wrong material and settings warnings if (MapMagic.instance.copyComponents) { layout.Par(42); layout.Label("Copy Component should be turned off to prevent copying RTP to chunks.", rect: layout.Inset(0.8f), helpbox: true); if (layout.Button("Fix", rect: layout.Inset(0.2f))) { MapMagic.instance.copyComponents = false; } } if (rtp == null) { layout.Par(42); layout.Label("Could not find Relief Terrain component on MapMagic object.", rect: layout.Inset(0.8f), helpbox: true); if (layout.Button("Fix", rect: layout.Inset(0.2f))) { renderer = MapMagic.instance.gameObject.GetComponent <MeshRenderer>(); if (renderer == null) { renderer = MapMagic.instance.gameObject.AddComponent <MeshRenderer>(); } renderer.enabled = false; rtp = MapMagic.instance.gameObject.AddComponent <ReliefTerrain>(); //if (MapMagic.instance.gameObject.GetComponent<InstantUpdater>()==null) MapMagic.instance.gameObject.AddComponent<InstantUpdater>(); //filling empty splats Texture2D emptyTex = Extensions.ColorTexture(4, 4, new Color(0.5f, 0.5f, 0.5f, 1f)); emptyTex.name = "Empty"; rtp.globalSettingsHolder.splats = new Texture2D[] { emptyTex, emptyTex, emptyTex, emptyTex }; } } if (MapMagic.instance.terrainMaterialType != Terrain.MaterialType.Custom) { layout.Par(30); layout.Label("Material Type is not switched to Custom.", rect: layout.Inset(0.8f), helpbox: true); if (layout.Button("Fix", rect: layout.Inset(0.2f))) { MapMagic.instance.terrainMaterialType = Terrain.MaterialType.Custom; foreach (Chunk tw in MapMagic.instance.chunks.All()) { tw.SetSettings(); } } } if (MapMagic.instance.assignCustomTerrainMaterial) { layout.Par(30); layout.Label("Assign Custom Material is turned on.", rect: layout.Inset(0.8f), helpbox: true); if (layout.Button("Fix", rect: layout.Inset(0.2f))) { MapMagic.instance.assignCustomTerrainMaterial = false; } } if (MapMagic.instance.GetComponent <InstantUpdater>() == null) { layout.Par(52); layout.Label("Use Instant Updater component to apply RTP changes to all the terrains.", rect: layout.Inset(0.8f), helpbox: true); if (layout.Button("Fix", rect: layout.Inset(0.2f))) { MapMagic.instance.gameObject.AddComponent <InstantUpdater>(); } } /*if (!MapMagic.instance.materialTemplateMode) * { * layout.Par(30); * layout.Label("Material Template Mode is off.", rect:layout.Inset(0.8f), helpbox:true); * if (layout.Button("Fix",rect:layout.Inset(0.2f))) MapMagic.instance.materialTemplateMode = true; * }*/ /*if ((renderer != null) && * (renderer.sharedMaterial == null || !renderer.sharedMaterial.shader.name.Contains("ReliefTerrain"))) * { * layout.Par(50); * layout.Label("No Relief Terrain material is assigned as Custom Material in Terrain Settings.", rect:layout.Inset(0.8f), helpbox:true); * if (layout.Button("Fix",rect:layout.Inset(0.2f))) * { * //if (renderer.sharedMaterial == null) * //{ * Shader shader = Shader.Find("Relief Pack/ReliefTerrain-FirstPass"); * if (shader != null) renderer.sharedMaterial = new Material(shader); * else Debug.Log ("MapMagic: Could not find Relief Pack/ReliefTerrain-FirstPass shader. Make sure RTP is installed or switch material type to Standard."); * //} * MapMagic.instance.customTerrainMaterial = renderer.sharedMaterial; * foreach (Chunk tw in MapMagic.instance.chunks.All()) tw.SetSettings(); * } * }*/ if (rtp == null) { return; } bool doubleLayer = false; for (int i = 0; i < baseLayers.Length; i++) { for (int j = 0; j < baseLayers.Length; j++) { if (i == j) { continue; } if (baseLayers[i].index == baseLayers[j].index) { doubleLayer = true; } } } if (doubleLayer) { layout.Par(30); layout.Label("Seems that multiple layers use the same splat index.", rect: layout.Inset(0.8f), helpbox: true); if (layout.Button("Fix", rect: layout.Inset(0.2f))) { ResetLayers(baseLayers.Length); } } //refreshing layers from rtp Texture2D[] splats = rtp.globalSettingsHolder.splats; if (baseLayers.Length != splats.Length) { ResetLayers(splats.Length); } //drawing layers layout.margin = 20; layout.rightMargin = 20; layout.fieldSize = 1f; for (int i = baseLayers.Length - 1; i >= 0; i--) { //if (baseLayers[i] == null) //baseLayers[i] = new Layer(); if (layout.DrawWithBackground(OnLayerGUI, active:i == selected, num:i, frameDisabled:false)) { selected = i; } } layout.Par(3); layout.Par(); //layout.DrawArrayAdd(ref baseLayers, ref selected, layout.Inset(0.25f)); //layout.DrawArrayRemove(ref baseLayers, ref selected, layout.Inset(0.25f)); layout.DrawArrayUp(ref baseLayers, ref selected, layout.Inset(0.25f), reverseOrder: true); layout.DrawArrayDown(ref baseLayers, ref selected, layout.Inset(0.25f), reverseOrder: true); layout.margin = 3; layout.rightMargin = 3; layout.Par(64); layout.Label("Use Relief Terrain component to set layer properties. \"Refresh All\" in RTP settings might be required.", rect: layout.Inset(), helpbox: true); #else layout.margin = 5; layout.rightMargin = 5; layout.Par(45); layout.Label("Cannot find Relief Terrain plugin. Restart Unity if you have just installed it.", rect: layout.Inset(), helpbox: true); #endif }
public static void Process(CoordRect rect, Chunk.Results results, GeneratorsAsset gens, Chunk.Size terrainSize, Func <float, bool> stop = null) { #if RTP if (stop != null && stop(0)) { return; } //finding number of layers int layersCount = 0; foreach (RTPOutput gen in MapMagic.instance.gens.GeneratorsOfType <RTPOutput>(onlyEnabled:true, checkBiomes:true)) { layersCount = gen.baseLayers.Length; break; } //creating color arrays RTPTuple result = new RTPTuple(); result.colorsA = new Color[MapMagic.instance.resolution * MapMagic.instance.resolution]; if (layersCount > 4) { result.colorsB = new Color[MapMagic.instance.resolution * MapMagic.instance.resolution]; } //filling color arrays foreach (RTPOutput gen in MapMagic.instance.gens.GeneratorsOfType <RTPOutput>(onlyEnabled:true, checkBiomes:true)) { //loading biome matrix Matrix biomeMask = null; if (gen.biome != null) { object biomeMaskObj = gen.biome.mask.GetObject(results); if (biomeMaskObj == null) { continue; //adding nothing if biome has no mask } biomeMask = (Matrix)biomeMaskObj; if (biomeMask == null) { continue; } if (biomeMask.IsEmpty()) { continue; //optimizing empty biomes } } for (int i = 0; i < gen.baseLayers.Length; i++) { //reading output directly Output output = gen.baseLayers[i].output; if (stop != null && stop(0)) { return; //checking stop before reading output } if (!results.results.ContainsKey(output)) { continue; } Matrix matrix = (Matrix)results.results[output]; if (matrix.IsEmpty()) { continue; } for (int x = 0; x < rect.size.x; x++) { for (int z = 0; z < rect.size.z; z++) { int pos = matrix.rect.GetPos(x + matrix.rect.offset.x, z + matrix.rect.offset.z); //pos should be the same for colors array and matrix array //get value and adjust with biome mask float val = matrix.array[pos]; float biomeVal = biomeMask != null? biomeMask.array[pos] : 1; val *= biomeVal; //save value to colors array switch (gen.baseLayers[i].index) { case 0: result.colorsA[pos].r += val; break; case 1: result.colorsA[pos].g += val; break; case 2: result.colorsA[pos].b += val; break; case 3: result.colorsA[pos].a += val; break; case 4: result.colorsB[pos].r += val; break; case 5: result.colorsB[pos].g += val; break; case 6: result.colorsB[pos].b += val; break; case 7: result.colorsB[pos].a += val; break; } } } if (stop != null && stop(0)) { return; } } } //TODO: normalizing color arrays (if needed) //pushing to apply if (stop != null && stop(0)) { return; } results.apply.CheckAdd(typeof(RTPOutput), result, replace: true); #endif }