void UpdateRTP()
    {
        switch (EnviroSkyMgr.instance.Seasons.currentSeasons)
        {
        case EnviroSeasons.Seasons.Spring:
            rtp.InterpolatePresets(currentPreset.PresetID, springPreset.PresetID, 0.1f);
            currentPreset = springPreset;
            break;

        case EnviroSeasons.Seasons.Summer:
            rtp.InterpolatePresets(currentPreset.PresetID, summerPreset.PresetID, 0.1f);
            currentPreset = summerPreset;
            break;

        case EnviroSeasons.Seasons.Autumn:
            rtp.InterpolatePresets(currentPreset.PresetID, autumnPreset.PresetID, 0.1f);
            currentPreset = autumnPreset;
            break;

        case EnviroSeasons.Seasons.Winter:
            rtp.InterpolatePresets(currentPreset.PresetID, winterPreset.PresetID, 0.1f);
            currentPreset = winterPreset;
            break;
        }
        rtp.globalSettingsHolder.Refresh();
    }
Beispiel #2
0
    public bool InterpolatePresets(string PresetID1, string PresetID2, float t)
    {
        ReliefTerrainPresetHolder presetByID  = this.GetPresetByID(PresetID1);
        ReliefTerrainPresetHolder presetByID2 = this.GetPresetByID(PresetID2);

        if (presetByID == null || presetByID2 == null || presetByID.Spec == null || presetByID2.Spec == null || presetByID.Spec.Length != presetByID2.Spec.Length)
        {
            return(false);
        }
        this.globalSettingsHolder.InterpolatePresets(presetByID, presetByID2, t);
        return(true);
    }
 public void RestorePreset(ReliefTerrainPresetHolder holder)
 {
     this.controlA = holder.controlA;
     this.controlB = holder.controlB;
     this.controlC = holder.controlC;
     this.SetCustomControlMaps();
     this.ColorGlobal                = holder.ColorGlobal;
     this.NormalGlobal               = holder.NormalGlobal;
     this.TreesGlobal                = holder.TreesGlobal;
     this.AmbientEmissiveMap         = holder.AmbientEmissiveMap;
     this.BumpGlobalCombined         = holder.BumpGlobalCombined;
     this.globalColorModifed_flag    = holder.globalColorModifed_flag;
     this.globalCombinedModifed_flag = holder.globalCombinedModifed_flag;
     this.RefreshTextures(null, false);
     this.globalSettingsHolder.RestorePreset(holder);
 }
    // Use this for initialization
    void Start()
    {
        if (terrain == null)
        {
            terrain = GetComponent <Terrain> ();
        }



        if (ChangePresets)
        {
            springPreset = rtp.GetPresetByName(RTPSpringPresetName);
            summerPreset = rtp.GetPresetByName(RTPSummerPresetName);
            autumnPreset = rtp.GetPresetByName(RTPAutumnPresetName);
            winterPreset = rtp.GetPresetByName(RTPWinterPresetName);

            switch (EnviroSkyMgr.instance.Seasons.currentSeasons)
            {
            case EnviroSeasons.Seasons.Spring:
                currentPreset = rtp.GetPresetByName(RTPSpringPresetName);
                break;

            case EnviroSeasons.Seasons.Summer:
                currentPreset = rtp.GetPresetByName(RTPSpringPresetName);
                break;

            case EnviroSeasons.Seasons.Autumn:
                currentPreset = rtp.GetPresetByName(RTPSpringPresetName);
                break;

            case EnviroSeasons.Seasons.Winter:
                currentPreset = rtp.GetPresetByName(RTPSpringPresetName);
                break;
            }
        }

        UpdateSeason();

        EnviroSkyMgr.instance.OnSeasonChanged += (EnviroSeasons.Seasons season) =>
        {
            UpdateSeason();
        };
    }
	public override void OnInspectorGUI () {
		ReliefTerrain _targetRT=(ReliefTerrain)target;
		ReliefTerrainGlobalSettingsHolder _target=_targetRT.globalSettingsHolder;
		if (_target==null) {
			_targetRT.RefreshTextures();
			_target=_targetRT.globalSettingsHolder;
		}
		dirtyFlag=false;
		
		RTP_LODmanager _RTP_LODmanagerScript = _target.Get_RTP_LODmanagerScript();
		if (_RTP_LODmanagerScript!=null) {
			if (_RTP_LODmanagerScript.gameObject.GetComponent(typeof(RTPFogUpdate))==null) {
				_RTP_LODmanagerScript.gameObject.AddComponent(typeof(RTPFogUpdate));
			}
		}

		Terrain terrainComp = (Terrain)_targetRT.GetComponent(typeof(Terrain));
		if (terrainComp) {
			if (_target.numLayers!=terrainComp.terrainData.splatPrototypes.Length) {
				// a layer removed or added
				_target.ReInit(terrainComp);
				ReliefTerrain[] script_objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
				for(int s=0; s<script_objs.Length; s++) {
					script_objs[s].splat_layer_seq=new int[12] {0,1,2,3,4,5,6,7,8,9,10,11};
				}				
			}
			if (!_target.useTerrainMaterial && _target.numTiles>1) {
				// U3 - multiple terrains or U4 w/o material - multiple terrains
				if (_target.numLayers!=4 && _target.numLayers!=8) {
					EditorGUILayout.HelpBox("RTP on multiple terrains w/o materials (available in U4) works only if we have 4 or 8 layers only !", MessageType.Error, true);
					return;
				}
			}
		}
		if (_target.splats==null || _target.numLayers!=_target.splats.Length) {
			EditorGUILayout.HelpBox("Problem with number of layers, try to reassign ReliefTerrain component script on this terrain...", MessageType.Error, true);
			return;
		}
		int sw=512;
		for(int i=0; i<_target.numLayers; i++) {
			if (_target.splats[i]) {
				sw=_target.splats[i].width;
				break;
			}
		}
		for(int i=0; i<_target.numLayers; i++) {
			if (_target.splats[i]==null) {
				Debug.LogError("Splat (detail) texture "+i+" was empty ! Assigning null texture");
				_target.splats[i]=new Texture2D(sw, sw, TextureFormat.ARGB32, true, QualitySettings.activeColorSpace==ColorSpace.Linear);
			}
		}		
		
		// >RTP3.1		
		// update-set to default
		if (_target.gloss_baked==null || _target.gloss_baked.Length==0) {
			_target.gloss_baked=new RTPGlossBaked[12];
		}
		
		if (_target.CheckAndUpdate(ref _target.RTP_gloss2mask, 0.5f, _target.numLayers)) {
			for(int k=0; k<_target.numLayers; k++) {
				_target.Spec[k]=1; // zresetuj od razu mnożnik glossa (RTP3.1 - zmienna ma inne znaczenie)
			}
		}
		_target.CheckAndUpdate(ref _target.RTP_gloss_mult, 1f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.RTP_gloss_shaping, 0.5f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.RTP_Fresnel, 0, _target.numLayers);
		_target.CheckAndUpdate(ref _target.RTP_FresnelAtten, 0, _target.numLayers);
		_target.CheckAndUpdate(ref _target.RTP_DiffFresnel, 0, _target.numLayers);
		_target.CheckAndUpdate(ref _target.RTP_IBL_bump_smoothness, 0.7f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.RTP_IBL_DiffuseStrength, 0.5f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.RTP_IBL_SpecStrength, 0.5f, _target.numLayers);
		
		_target.CheckAndUpdate(ref _target.TERRAIN_WaterSpecularity, 0.5f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.TERRAIN_WaterGloss, 0.1f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.TERRAIN_WaterGlossDamper, 0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.TERRAIN_WetSpecularity, 0.2f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.TERRAIN_WetGloss, 0.05f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.TERRAIN_WetFlow, 0.05f, _target.numLayers);
		
		_target.CheckAndUpdate(ref _target.MixBrightness, 2.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.MixReplace, 0.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.LayerBrightness, 1.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.LayerBrightness2Spec, 0.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.LayerAlbedo2SpecColor, 0.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.LayerSaturation, 1.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.FarSpecCorrection, 0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.LayerEmission, 0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.LayerEmissionColor, Color.black, _target.numLayers);
		_target.CheckAndUpdate(ref _target.LayerEmissionRefractStrength, 0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.LayerEmissionRefractHBedge, 0f, _target.numLayers);
		
		_target.CheckAndUpdate(ref _target.GlobalColorBottom, 0.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.GlobalColorTop, 1.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.GlobalColorColormapLoSat, 1.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.GlobalColorColormapHiSat, 1.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.GlobalColorLayerLoSat, 1.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.GlobalColorLayerHiSat, 1.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.GlobalColorLoBlend, 1.0f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.GlobalColorHiBlend, 1.0f, _target.numLayers);
		
		_target.CheckAndUpdate(ref _target.TERRAIN_WaterIBL_SpecWetStrength, 0.1f, _target.numLayers);
		_target.CheckAndUpdate(ref _target.TERRAIN_WaterIBL_SpecWaterStrength, 0.5f, _target.numLayers);
		
		// update (RTP3.1)
		if (_target.splat_atlases.Length==2) {
			Texture2D _atA=_target.splat_atlases[0];
			Texture2D _atB=_target.splat_atlases[1];
			_target.splat_atlases=new Texture2D[3];
			_target.splat_atlases[0]=_atA;
			_target.splat_atlases[1]=_atB;
		}
		
		bool atlasA_needed=false;
		bool atlasB_needed=false;
		bool atlasC_needed=false;
		
		bool _4LAYERS_SHADER_USED=false;
		if (_RTP_LODmanagerScript) {
			_target._4LAYERS_SHADER_USED=_4LAYERS_SHADER_USED=_RTP_LODmanagerScript.RTP_4LAYERS_MODE;
		}
		if (_RTP_LODmanagerScript) _RTP_LODmanagerScript.numLayers=_target.numLayers;
		
		if (_RTP_LODmanagerScript) {
			if (_target.numLayers<=4 && !_RTP_LODmanagerScript.RTP_4LAYERS_MODE) {
				EditorGUILayout.HelpBox("Shaders are set to 8 layers mode while number of layers is less than 5. Add layers or recompile shaders in RTP_LODmanager to not use 8 layers in first pass.", MessageType.Error, true);
			}
			atlasA_needed=!_4LAYERS_SHADER_USED || _RTP_LODmanagerScript.RTP_USE_COLOR_ATLAS_FIRST;
			atlasB_needed=(!_4LAYERS_SHADER_USED || _RTP_LODmanagerScript.RTP_USE_COLOR_ATLAS_ADD) && (_target.numLayers>4);
			atlasC_needed=(!_4LAYERS_SHADER_USED && _RTP_LODmanagerScript.RTP_USE_COLOR_ATLAS_ADD) && (_target.numLayers>8);
			
			bool atlas_made=false;
			if (atlasA_needed) {
				if (_target.splat_atlases[0]==null) {
					PrepareAtlases(0);
					_target.atlas_glossBaked[0]=null;
					for(int k=0; k<((_target.numLayers<4) ? _target.numLayers : 4); k++) {
						_target.gloss_baked[k]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked;
						_target.splats_glossBaked[k]=null;
					}
					atlas_made=true;
				}
			} else {
				_target.splat_atlases[0]=null;
				_target.atlas_glossBaked[0]=null;
			}
			if (atlasB_needed) {
				if (_target.splat_atlases[1]==null) {
					PrepareAtlases(1);
					_target.atlas_glossBaked[1]=null;
					for(int k=4; k<((_target.numLayers<8) ? _target.numLayers : 8); k++) {
						_target.gloss_baked[k]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked;
						_target.splats_glossBaked[k]=null;
					}
					atlas_made=true;
				}
			} else {
				_target.splat_atlases[1]=null;
				_target.atlas_glossBaked[1]=null;
			}
			if (atlasC_needed) {
				if (_target.splat_atlases[2]==null) {
					PrepareAtlases(2);
					_target.atlas_glossBaked[2]=null;
					for(int k=12; k<((_target.numLayers<12) ? _target.numLayers : 12); k++) {
						_target.gloss_baked[k]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked;
						_target.splats_glossBaked[k]=null;
					}
					atlas_made=true;
				}
			} else {
				_target.splat_atlases[2]=null;
				_target.atlas_glossBaked[2]=null;
			}
			if (atlas_made) {
				_target.Refresh(null, _targetRT);
			}
		}
		
		bool ADV_COLOR_MAP_BLENDING_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.ADV_COLOR_MAP_BLENDING_FIRST;
		bool ADV_COLOR_MAP_BLENDING_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.ADV_COLOR_MAP_BLENDING_ADD;
		
		bool UV_BLEND_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_UV_BLEND_FIRST;
		bool UV_BLEND_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_UV_BLEND_ADD;
		int[] UV_BLEND_ROUTE_NUM_FIRST;
		int[] UV_BLEND_ROUTE_NUM_ADD;
		if (_RTP_LODmanagerScript) {
			UV_BLEND_ROUTE_NUM_FIRST=_RTP_LODmanagerScript.UV_BLEND_ROUTE_NUM_FIRST;
			UV_BLEND_ROUTE_NUM_ADD=_RTP_LODmanagerScript.UV_BLEND_ROUTE_NUM_ADD;
		} else {
			UV_BLEND_ROUTE_NUM_FIRST=new int[8]{0,1,2,3,4,5,6,7};
			UV_BLEND_ROUTE_NUM_ADD=new int[8]{0,1,2,3,4,5,6,7};
		}
		
		bool RTP_INDEPENDENT_TILING = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_INDEPENDENT_TILING;
		
		bool RTP_CUT_HOLES = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_CUT_HOLES;
		bool RTP_PBL_FRESNEL = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_PBL_FRESNEL;
		
		bool RTP_USE_EXTRUDE_REDUCTION_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_USE_EXTRUDE_REDUCTION_FIRST;
		bool RTP_USE_EXTRUDE_REDUCTION_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_USE_EXTRUDE_REDUCTION_ADD;
		
		bool RTP_VERTICAL_TEXTURE_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_FIRST;
		bool RTP_VERTICAL_TEXTURE_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_ADD;
		
		bool RTP_NORMALGLOBAL = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_NORMALGLOBAL;
		bool RTP_TREESGLOBAL = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_TREESGLOBAL;
		bool RTP_AMBIENT_EMISSIVE_MAP = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_AMBIENT_EMISSIVE_MAP;

		bool RTP_TESSELLATION = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_TESSELLATION;
		bool RTP_TESSELLATION_SAMPLE_TEXTURE = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_TESSELLATION_SAMPLE_TEXTURE;
		bool RTP_HEIGHTMAP_SAMPLE_BICUBIC = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_HEIGHTMAP_SAMPLE_BICUBIC;

		bool RTP_SUPER_SIMPLE = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_SIMPLE;
		bool RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_SIMPLE  && _RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST;
		bool RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD = _target.numLayers>4 && _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_SIMPLE  && _RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD;
		bool RTP_USE_PERLIN_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_USE_PERLIN_FIRST;
		bool RTP_USE_PERLIN_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_USE_PERLIN_ADD;
		
		bool SUPER_DETAIL_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_DETAIL_FIRST;
		bool SUPER_DETAIL_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_DETAIL_ADD;
		bool SUPER_DETAIL_MULTS_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_FIRST;
		bool SUPER_DETAIL_MULTS_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_ADD;
		
		bool SNOW_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SNOW_FIRST;
		bool SNOW_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SNOW_ADD;
		
		bool REFLECTION_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_REFLECTION_FIRST;
		bool REFLECTION_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_REFLECTION_ADD;
		bool REFLECTION_ROTATION_ENABLED = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_ROTATE_REFLECTION;
		
		bool RTP_HEIGHTBLEND_AO_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_HEIGHTBLEND_AO_FIRST;
		bool RTP_HEIGHTBLEND_AO_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_HEIGHTBLEND_AO_ADD;
		
		bool RTP_EMISSION_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_EMISSION_FIRST;
		bool RTP_EMISSION_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_EMISSION_ADD;

		bool RTP_HOTAIR_EMISSION_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_HOTAIR_EMISSION_FIRST;
		bool RTP_HOTAIR_EMISSION_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_HOTAIR_EMISSION_ADD;
		
		bool RTP_COMPLEMENTARY_LIGHTS = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_COMPLEMENTARY_LIGHTS;
		bool RTP_SPEC_COMPLEMENTARY_LIGHTS = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SPEC_COMPLEMENTARY_LIGHTS;
		
		bool RTP_SKYSHOP_SYNC = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SKYSHOP_SYNC;
		bool RTP_IBL_DIFFUSE_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_IBL_DIFFUSE_FIRST;
		bool RTP_IBL_DIFFUSE_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_IBL_DIFFUSE_ADD;
		bool RTP_IBL_SPEC_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_IBL_SPEC_FIRST;
		bool RTP_IBL_SPEC_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_IBL_SPEC_ADD;
		
		bool WATER_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_WETNESS_FIRST;
		bool WATER_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_WETNESS_ADD;
		bool RIPPLEMAP_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_FIRST;
		bool RIPPLEMAP_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_ADD;
		
		bool CAUSTICS_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_CAUSTICS_FIRST;
		bool CAUSTICS_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_CAUSTICS_ADD;
		
		bool RTP_VERTALPHA_CAUSTICS = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_VERTALPHA_CAUSTICS && (RTP_VERTICAL_TEXTURE_FIRST || RTP_VERTICAL_TEXTURE_ADD);
		
		string[] toolbarStrings;
		GUIContent[] toolbarIcons = new GUIContent[4]{ new GUIContent("Layers", icoLayers), new GUIContent("Coverage", icoCoverage), new GUIContent("Combined\ntexures", icoCombinedTexutres), new GUIContent("Settings", icoSettings) };
		GUILayout.Space(10);			
		EditorGUILayout.BeginHorizontal();
		GUILayout.FlexibleSpace();
		_target.submenu=(ReliefTerrainMenuItems)(GUILayout.Toolbar((int)_target.submenu, toolbarIcons, EditorStyles.miniButton, GUILayout.MaxWidth(370)));
		GUILayout.FlexibleSpace();
		EditorGUILayout.EndHorizontal();
		GUILayout.Space(10);			
		
		_target.show_details = _target.submenu==ReliefTerrainMenuItems.Details;
		_target.show_controlmaps = _target.submenu==ReliefTerrainMenuItems.Control;
		_target.show_derivedmaps = _target.submenu==ReliefTerrainMenuItems.CombinedTextures;
		_target.show_settings = _target.submenu==ReliefTerrainMenuItems.GeneralSettings;
		
		if (_target.show_active_layer>=_target.numLayers) {
			_target.show_active_layer=_target.numLayers-1;
		}			
		//Debug.Log (_target.show_active_layer+","+_target.numLayers);
		
		if (_target.show_details) {
			#region Detail maps unfold
			
			if (_target.numLayers>0) {
				#region Detail maps unfold	- layers
				
				if (!terrainComp) {
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.BeginHorizontal();
					EditorGUI.BeginDisabledGroup(_target.numLayers==8);
					if (GUILayout.Button("Add layer")) {
						_target.numLayers++;
						int j=_target.numLayers-1;
						
						ReliefTerrain[] script_objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
						for(int s=0; s<script_objs.Length; s++) {
							script_objs[s].splat_layer_seq[j]=j;
							script_objs[s].splat_layer_boost[j]=1;
							script_objs[s].splat_layer_calc[j]=true;
							script_objs[s].splat_layer_masked[j]=false;
							script_objs[s].source_controls_invert[j]=false;
							script_objs[s].source_controls_mask_invert[j]=false;
						}
						
						_target.Bumps[j]=null;
						_target.Heights[j]=null;
						#if !UNITY_WEBGL || UNITY_EDITOR
						_target.Substances[j]=null;						
						#endif						
						_target.ReturnToDefaults("layer", j);
						
						Texture2D[] splats_new=new Texture2D[_target.numLayers];
						for(int i=0; i<_target.splats.Length; i++) splats_new[i]=_target.splats[i];
						_target.splats=splats_new;
						_target.splats[_target.numLayers-1]=_target.splats[((_target.numLayers-2) >=0) ? (_target.numLayers-2) : 0];
					}
					EditorGUI.EndDisabledGroup();
					EditorGUI.BeginDisabledGroup(_target.numLayers==1);
					if (GUILayout.Button("Remove layer")) {
						_target.numLayers--;
						Texture2D[] splats_new=new Texture2D[_target.numLayers];
						for(int i=0; i<splats_new.Length; i++) splats_new[i]=_target.splats[i];
						_target.splats=splats_new;
						ReliefTerrain[] script_objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
						for(int s=0; s<script_objs.Length; s++) {
							script_objs[s].splat_layer_seq=new int[12] {0,1,2,3,4,5,6,7,8,9,10,11};
						}
						if (_target.show_active_layer>=_target.numLayers) {
							_target.show_active_layer=_target.numLayers-1;
						}								
					}
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
				}
				
				#if !UNITY_WEBGL || UNITY_EDITOR
				bool handle_substances=false;
				#if UNITY_4_1 || UNITY_4_2 || UNITY_4_3  || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6
				handle_substances=true;
				#else
				if (PlayerSettings.advancedLicense) {
					handle_substances=true;
				}
				#endif
				#endif

				EditorGUILayout.BeginVertical("Box");
				Color skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Choose layer", EditorStyles.boldLabel);
				GUI.color=skin_color;
				EditorGUILayout.HelpBox("Hint: to quickly select a layer - focus on scene view (by click) and press L holding cursor over the layer that should be selected.", MessageType.Info, true);
				
				GUISkin gs=EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);
				RectOffset ro1=gs.label.padding;
				RectOffset ro2=gs.label.margin;
				gs.label.padding=new  RectOffset(0, 0, 0, 0);
				gs.label.margin=new  RectOffset(3, 3, 3, 3);
				int thumb_size=50;
				int per_row=Mathf.Max( 4, (Screen.width)/thumb_size - 1 );
				thumb_size=(Screen.width-50-2*per_row)/per_row;
				Color ccol=GUI.contentColor;
				for(int n=0; n<_target.numLayers; n++) {
					if ((n%per_row)==0) EditorGUILayout.BeginHorizontal();
					Color bcol=GUI.backgroundColor;
					if (n==_target.show_active_layer) {
						GUI.contentColor=new Color(1,1,1,1);
						GUI.backgroundColor=new Color(1,1,0,1);
						EditorGUILayout.BeginHorizontal("Box");
						if (_target.splats[n]) {
							#if !UNITY_3_5
							GUILayout.Label((Texture2D)AssetPreview.GetAssetPreview(_target.splats[n]), GUILayout.Width(thumb_size-8), GUILayout.Height(thumb_size-8));
							#else
							GUILayout.Label((Texture2D)EditorUtility.GetAssetPreview(_target.splats[n]), GUILayout.Width(thumb_size-8), GUILayout.Height(thumb_size-8));
							#endif
						} else {
							GUILayout.Label(" ", GUILayout.Width(thumb_size-8), GUILayout.Height(thumb_size-8));
						}
					} else {
						GUI.contentColor=new Color(1,1,1,0.5f);
						if (_target.splats[n]) {
							#if !UNITY_3_5
							if (GUILayout.Button((Texture2D)AssetPreview.GetAssetPreview(_target.splats[n]), "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
								#else
								if (GUILayout.Button((Texture2D)EditorUtility.GetAssetPreview(_target.splats[n]), "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
									#endif
									_target.show_active_layer=n;
								}
							} else {
								if (GUILayout.Button(" ", "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
									_target.show_active_layer=n;
								}
							}
						}
						if (n==_target.show_active_layer) {
							EditorGUILayout.EndHorizontal();
							GUI.backgroundColor=bcol;
						}
						if ((n%per_row)==(per_row-1) || n==_target.numLayers-1) EditorGUILayout.EndHorizontal();
					}
					GUI.contentColor=ccol;
					gs.label.padding=ro1;
					gs.label.margin=ro2;					
					EditorGUILayout.EndVertical();
					
					EditorGUILayout.Space();
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Layer properties", EditorStyles.boldLabel);
					GUI.color=skin_color;
					EditorGUILayout.HelpBox("All layers should share THE SAME size for given texture type\n(i.e. all detail textures should have the same size and so on). ", MessageType.Info, true);
					EditorGUILayout.Space();
					{
						int thW=(Screen.width-60)/3;
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Detail", EditorStyles.boldLabel, GUILayout.Width(thW));
						EditorGUILayout.LabelField("Normal", EditorStyles.boldLabel, GUILayout.Width(thW));
						EditorGUILayout.LabelField("Height (A)", EditorStyles.boldLabel, GUILayout.Width(thW));
						EditorGUILayout.EndHorizontal();
					}
					
					{
						int n=_target.show_active_layer;
						EditorGUILayout.BeginHorizontal();
						
						int thW=(Screen.width-60)/3;
						//Debug.Log (_target.splats.Length+"  "+_target.numLayers);
						Texture2D tex=_target.splats[n];
						Texture2D ntex=tex;
						checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.splats[n], typeof(Texture2D), false, GUILayout.Width(thW), GUILayout.Height(thW)));
						if (ntex!=tex && ntex) {
							_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked; // nie mamy inf. o zmodyfikowanym roughness dla tej tekstury
							_target.splats_glossBaked[n]=null; // nie mamy też tekstury ze zmodyfikowanymi MIP levelami (będa używane splats[i])
							_target.atlas_glossBaked[n/4]=null; // używany atlas jest nieważny
							_target.splats[n]=ntex;
							int prep_atlas=-1;
							if (n<4) {
								if (atlasA_needed) {
									prep_atlas=0;
								}
							} else if (n<8) {
								if (atlasB_needed) {
									prep_atlas=1;
								}
							} else if (n<12) {
								if (atlasC_needed) {
									prep_atlas=2;
								}
							}
							if (prep_atlas>=0) {
								if (EditorUtility.DisplayDialog("RTP Notification", "You have to recalc atlas to see changes.", "OK, do it now", "Thanks, I'll do it later")) {
									_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked; // nie mamy inf. o zmodyfikowanym roughness dla tej tekstury
									_target.splats_glossBaked[n]=null; // nie mamy też tekstury ze zmodyfikowanymi MIP levelami (będa używane splats[i])
									_target.atlas_glossBaked[n/4]=null; // używany atlas jest nieważny
									PrepareAtlases(prep_atlas);
								}
							}
							_target.Refresh(null, _targetRT);
						}
						
						tex=_target.Bumps[n];
						ntex=tex;
						checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.Bumps[n], typeof(Texture2D), false, GUILayout.Width(thW), GUILayout.Height(thW)));
						if (ntex!=tex) {
							_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked; // nie mamy inf. o zmodyfikowanym roughness dla tej tekstury
							_target.splats_glossBaked[n]=null; // nie mamy też tekstury ze zmodyfikowanymi MIP levelami (będa używane splats[i])
							_target.atlas_glossBaked[n/4]=null; // używany atlas jest nieważny
							Texture2D tex_prev=_target.Bumps[n];
							_target.Bumps[n]=ntex;
							AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								bool changed=false;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Normal texture "+n+" ("+ntex.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									changed=true;
								}
								if (!tex_importer.normalmap) {
									Debug.LogWarning("Normal texture "+n+" ("+ntex.name+") has been reimported as normal map type.");
									tex_importer.normalmap=true;
									changed=true;
								}
								if (changed) {
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
								}
							}							
							if (!_target.PrepareNormals()) _target.Bumps[n]=tex_prev;
							_target.Refresh(null, _targetRT);
						}
						
						tex=_target.Heights[n];
						ntex=tex;
						checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.Heights[n], typeof(Texture2D), false, GUILayout.Width(thW), GUILayout.Height(thW)));
						if (ntex!=tex) {
							Texture2D tex_prev=_target.Heights[n];
							_target.Heights[n]=ntex;
							AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								bool changed=false;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Height texture "+n+" ("+ntex.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									changed=true;
								}
								if (!tex_importer.linearTexture) {
									Debug.LogWarning("Height texture "+n+" ("+ntex.name+") has been reimported as linear.");
									tex_importer.linearTexture=true;
									changed=true;
								}
								if (changed) {
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
								}
							}
							if (!PrepareHeights(n)) _target.Heights[n]=tex_prev;
							_target.Refresh(null, _targetRT);
						}
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						int thW2=(Screen.width-60)/3;
						// refresh detail (atlas)
						{
							int prep_atlas=-1;
							if (n<4 && atlasA_needed) {
								prep_atlas=0;
							} else if (n>=4 && n<8 && atlasB_needed) {
								prep_atlas=1;
							} else if (n>=8 && n<12 && atlasC_needed) {
								prep_atlas=2;
							}
							EditorGUI.BeginDisabledGroup(prep_atlas==-1);
							if (GUILayout.Button("Refresh",GUILayout.Width(thW2))) {
								_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked; // nie mamy inf. o zmodyfikowanym roughness dla tej tekstury
								_target.splats_glossBaked[n]=null; // nie mamy też tekstury ze zmodyfikowanymi MIP levelami (będa używane splats[i])
								_target.atlas_glossBaked[n/4]=null; // używany atlas jest nieważny
								PrepareAtlases(prep_atlas);
								_target.Refresh(null, _targetRT);
							}
							EditorGUI.EndDisabledGroup();
						}
						// refresh normal combined
						if (GUILayout.Button("Refresh",GUILayout.Width(thW2))) {
							_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked; // nie mamy inf. o zmodyfikowanym roughness dla tej tekstury
							_target.splats_glossBaked[n]=null; // nie mamy też tekstury ze zmodyfikowanymi MIP levelami (będa używane splats[i])
							_target.atlas_glossBaked[n/4]=null; // używany atlas jest nieważny
							_target.PrepareNormals();
							_target.Refresh(null, _targetRT);
						}
						// refresh height combined
						if (GUILayout.Button("Refresh",GUILayout.Width(thW2))) {
							PrepareHeights(n);
							_target.Refresh(null, _targetRT);
						}
						
						EditorGUILayout.EndHorizontal();
						#if !UNITY_WEBGL || UNITY_EDITOR
						if (handle_substances) {
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("Substance", EditorStyles.boldLabel, GUILayout.MaxWidth(75));
							
							ProceduralMaterial subs=_target.Substances[n];
							ProceduralMaterial nsubs=subs;
							checkChange(ref nsubs, (ProceduralMaterial)EditorGUILayout.ObjectField(_target.Substances[n], typeof(ProceduralMaterial), false));
							if (nsubs!=subs) {
								_target.Substances[n]=nsubs;
								#if UNITY_4_1 || UNITY_4_2 || UNITY_4_3  || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6									
								if (nsubs) {
									_target.Substances[n].isReadable=true;
									_target.Substances[n].RebuildTexturesImmediately();
									SubstanceImporter s_importer=(SubstanceImporter)SubstanceImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.Substances[n]));
									if (_target.Substances[n].shader.name!="Parallax Specular") {
										_target.Substances[n].shader=Shader.Find("Parallax Specular");
										s_importer.OnShaderModified(_target.Substances[n]);
									}
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.Substances[n]),  ImportAssetOptions.ForceUpdate);
									//GetSubstanceTex("_Diffuse","_MainTex", n);		
									//GetSubstanceTex("_Normal","_BumpMap", n, true);	
									//GetSubstanceTex("_Height","_ParallaxMap", n);
									
								}
								#endif
							}
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.HelpBox("Before you proceed with Get textures button below, make sure your substance material format is set to RAW. If substance resists to give proper output try getting texture again.", MessageType.Warning, true);
							EditorGUI.BeginDisabledGroup(_target.Substances[n]==null || _target.Substances[n].isProcessing);
							if (GUILayout.Button("Get textures")) {
								
								#if UNITY_4_1 || UNITY_4_2 || UNITY_4_3  || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6									
								_target.Substances[n].isReadable=true;
								#endif
								SubstanceImporter s_importer=(SubstanceImporter)SubstanceImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.Substances[n]));
								if (_target.Substances[n].shader.name!="Parallax Specular") {
									_target.Substances[n].shader=Shader.Find("Parallax Specular");
									s_importer.OnShaderModified(_target.Substances[n]);
								}
								_target.Substances[n].RebuildTexturesImmediately();
								
								AssetImporter _importer;
								string orig_path;
								string path="";
								bool override_flag;
								byte[] bytes;
								int option;
								
								_importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.splats[n]));
								if (_importer) {
									orig_path=AssetDatabase.GetAssetPath(_target.splats[n]);
									orig_path=orig_path.Substring(0,orig_path.LastIndexOf("/")+1);
								} else {
									orig_path=System.IO.Directory.GetParent(AssetDatabase.GetAssetPath(_target.Substances[n]))+"/";
								}
								
								//
								// diffuse								
								//
								ntex=GetSubstanceTex("_Diffuse","_MainTex", n);		
								
								path=orig_path+_target.Substances[n].name+"_diffuse_spec"+".png";
								override_flag=AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null;
								if (override_flag) {
									option=EditorUtility.DisplayDialogComplex("RTP Notification", "Override color/diffuse texture ?", "OK", "Make copy", "Skip texture");
								} else {
									option=0;
								}
								if (option==1) {
									do {
										int suffix_pos=path.LastIndexOf(".");
										path=path.Substring(0,suffix_pos)+"_copy"+path.Substring(suffix_pos);
									} while(AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null);
								}
								if (option<2) {									
									bytes = ntex.EncodeToPNG();
									DestroyImmediate(ntex);
									ntex=null;
									System.IO.File.WriteAllBytes(path, bytes);
									AssetDatabase.Refresh();
									_importer=AssetImporter.GetAtPath(path);
									if (_importer) {
										TextureImporter tex_importer=(TextureImporter)_importer;
										tex_importer.isReadable=true;
										tex_importer.maxTextureSize=_target.splats[n].width;
										AssetDatabase.ImportAsset(path,  ImportAssetOptions.ForceUpdate);
										ntex=(Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
										_target.splats[n]=ntex;
										int prep_atlas=-1;
										if (n<4) {
											if (atlasA_needed) {
												prep_atlas=0;
											}
										} else if (n<8) {
											if (atlasB_needed) {
												prep_atlas=1;
											}
										} else if (n<12) {
											if (atlasC_needed) {
												prep_atlas=2;
											}
										}
										if (prep_atlas>=0) {
											if (EditorUtility.DisplayDialog("RTP Notification", "You have to recalc atlas to see changes.", "OK, do it now", "Thanks, I'll do it later")) {
												PrepareAtlases(prep_atlas);
											}
										}
										_target.Refresh(null, _targetRT);
									}				
								}
								
								//
								// normal						
								//
								ntex=GetSubstanceTex("_Normal","_BumpMap", n, true);	
								int nwidth=ntex.width;
								path=orig_path+_target.Substances[n].name+"_normal"+".png";
								override_flag=AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null;
								if (override_flag) {
									option=EditorUtility.DisplayDialogComplex("RTP Notification", "Override normal texture ?", "OK", "Make copy", "Skip texture");
								} else {
									option=0;
								}
								if (option==1) {
									do {
										int suffix_pos=path.LastIndexOf(".");
										path=path.Substring(0,suffix_pos)+"_copy"+path.Substring(suffix_pos);
									} while(AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null);
								}
								if (option<2) {
									bytes = ntex.EncodeToPNG();
									DestroyImmediate(ntex);
									ntex=null;
									System.IO.File.WriteAllBytes(path, bytes);
									AssetDatabase.Refresh();
									_importer=AssetImporter.GetAtPath(path);
									if (_importer) {
										Texture2D tex_prev=_target.Bumps[n];
										TextureImporter tex_importer=(TextureImporter)_importer;
										tex_importer.isReadable=true;
										int compare_n;
										if ((n&1)==0) {
											if ((n+1)<_target.numLayers) {
												compare_n=n+1;
											} else {
												compare_n=-1;
											}
										} else {
											compare_n=n-1;
										}
										if (compare_n>=0 && _target.Bumps[compare_n]!=null) {
											if (nwidth<_target.Bumps[compare_n].width) {
												TextureImporter tex_importer_tmp=(TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.Bumps[compare_n].width));
												tex_importer_tmp.maxTextureSize=nwidth;
												Debug.LogWarning("Normal texture "+compare_n+" ("+_target.splats[compare_n].name+") has been reimported with "+tex_importer_tmp.maxTextureSize+" size.");
												AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.Bumps[compare_n].width),  ImportAssetOptions.ForceUpdate);
											} else if (nwidth>_target.Bumps[compare_n].width) {
												tex_importer.maxTextureSize=_target.Bumps[compare_n].width;
												Debug.LogWarning("Normal texture "+n+" ("+_target.splats[n].name+") has been imported with "+tex_importer.maxTextureSize+" size.");
											}
										}
										tex_importer.textureType=TextureImporterType.Bump;
										AssetDatabase.ImportAsset(path,  ImportAssetOptions.ForceUpdate);
										ntex=(Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
										_target.Bumps[n]=ntex;
										if (!_target.PrepareNormals()) _target.Bumps[n]=tex_prev;
										_target.Refresh(null, _targetRT);
									}
								}
								
								//
								// height				
								//
								ntex=GetSubstanceTex("_Height","_ParallaxMap", n);
								
								path=orig_path+_target.Substances[n].name+"_height"+".png";
								override_flag=AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null;
								if (override_flag) {
									option=EditorUtility.DisplayDialogComplex("RTP Notification", "Override height texture ?", "OK", "Make copy", "Skip texture");
								} else {
									option=0;
								}
								if (option==1) {
									do {
										int suffix_pos=path.LastIndexOf(".");
										path=path.Substring(0,suffix_pos)+"_copy"+path.Substring(suffix_pos);
									} while(AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null);
								}
								if (option<2) {
									bytes = ntex.EncodeToPNG();
									DestroyImmediate(ntex);
									ntex=null;
									System.IO.File.WriteAllBytes(path, bytes);
									AssetDatabase.Refresh();
									_importer=AssetImporter.GetAtPath(path);
									if (_importer) {
										Texture2D tex_prev=_target.Heights[n];
										TextureImporter tex_importer=(TextureImporter)_importer;
										tex_importer.isReadable=true;
										tex_importer.linearTexture=true;
										tex_importer.textureFormat=TextureImporterFormat.Alpha8;
										AssetDatabase.ImportAsset(path,  ImportAssetOptions.ForceUpdate);
										ntex=(Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
										_target.Heights[n]=ntex;
										if (!PrepareHeights(n)) _target.Heights[n]=tex_prev;
										_target.Refresh(null, _targetRT);
									}						
								}
								
							}
							
							EditorGUI.EndDisabledGroup();
						} // handle substances
						#endif // WebGL substances off

						GUILayout.Space(10);
						
						bool AddPass_flag=(_4LAYERS_SHADER_USED && n>=4) || (n>=8);
						
						EditorGUILayout.BeginVertical("Box");
						EditorGUILayout.LabelField("PBL / IBL properties", EditorStyles.boldLabel);
						EditorGUILayout.HelpBox("Detail texture A channel defines gloss (how smooth or rough is the surface), not specularity (named spec here which defines brightness of specular reflection). Current gloss value is commonly named Shininess in Unity built-in shaders. Fresnel for direct lighting works when enabled and in forward ONLY.", MessageType.None, true);
						EditorGUILayout.BeginVertical("Box");
						float nval;
						nval=_target.Spec[n];
						checkChange(ref nval, EditorGUILayout.Slider("Layer "+n+" spec multiplier", _target.Spec[n], 0f, 4f, GUILayout.ExpandWidth(true)));
						_target.Spec[n]=nval;
						EditorGUI.BeginDisabledGroup(_target.gloss_baked[n]!=null && _target.gloss_baked[n].baked);
							nval=_target.RTP_gloss_mult[n];
							checkChange(ref nval, EditorGUILayout.Slider("   gloss multiplier", _target.RTP_gloss_mult[n], 0f, 4f, GUILayout.ExpandWidth(true)));
							_target.RTP_gloss_mult[n]=nval;
						EditorGUI.EndDisabledGroup();
						nval=_target.RTP_gloss2mask[n];
						checkChange(ref nval, EditorGUILayout.Slider("   spec mask from gloss", _target.RTP_gloss2mask[n], 0f, 1f, GUILayout.ExpandWidth(true)));
						_target.RTP_gloss2mask[n]=nval;
						nval=_target.LayerBrightness2Spec[n];
						checkChange(ref nval, EditorGUILayout.Slider("   spec mask from albedo", _target.LayerBrightness2Spec[n], 0f, 1f, GUILayout.ExpandWidth(true)));
						_target.LayerBrightness2Spec[n]=nval;
						EditorGUI.BeginDisabledGroup(_target.gloss_baked[n]!=null && _target.gloss_baked[n].baked);
							nval=_target.RTP_gloss_shaping[n];
							checkChange(ref nval, EditorGUILayout.Slider("   gloss shaping", _target.RTP_gloss_shaping[n]*2-1, -1f, 1f, GUILayout.ExpandWidth(true))*0.5f+0.5f);
							_target.RTP_gloss_shaping[n]=nval;
						EditorGUI.EndDisabledGroup();
						if (!RTP_SUPER_SIMPLE) {
							nval=_target.FarSpecCorrection[n];
							checkChange(ref nval, EditorGUILayout.Slider("   far spec correction", _target.FarSpecCorrection[n], -1f, 1f, GUILayout.ExpandWidth(true)));
							_target.FarSpecCorrection[n]=nval;
							if ( (!AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) || (AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) || RTP_PBL_FRESNEL) {
								nval=_target.RTP_Fresnel[n];
								checkChange(ref nval, EditorGUILayout.Slider("   fresnel", _target.RTP_Fresnel[n], 0f, 1f, GUILayout.ExpandWidth(true)));
								_target.RTP_Fresnel[n]=nval;
								EditorGUI.BeginDisabledGroup(_target.RTP_Fresnel[n]==0);
								nval=_target.RTP_FresnelAtten[n];
								checkChange(ref nval, EditorGUILayout.Slider("      attenuate by gloss", _target.RTP_FresnelAtten[n], 0f, 1f, GUILayout.ExpandWidth(true)));
								_target.RTP_FresnelAtten[n]=nval;
								EditorGUI.EndDisabledGroup();
							}
							nval=_target.RTP_DiffFresnel[n];
							checkChange(ref nval, EditorGUILayout.Slider("   diffuse scattering", _target.RTP_DiffFresnel[n], 0f, 2f, GUILayout.ExpandWidth(true)));
							_target.RTP_DiffFresnel[n]=nval;
							
							nval=_target.RTP_IBL_bump_smoothness[n];
							checkChange(ref nval, EditorGUILayout.Slider("IBL / Refl bump smooth", _target.RTP_IBL_bump_smoothness[n], 0f, 1f));
							_target.RTP_IBL_bump_smoothness[n]=nval;		
							
							if ( (!AddPass_flag && RTP_IBL_DIFFUSE_FIRST) || (AddPass_flag && RTP_IBL_SPEC_ADD) ) {
								nval=_target.RTP_IBL_DiffuseStrength[n];
								checkChange(ref nval, EditorGUILayout.Slider("IBL diffuse exposure", _target.RTP_IBL_DiffuseStrength[n], 0f, 8f));
								_target.RTP_IBL_DiffuseStrength[n]=nval;
							}						
							
							EditorGUILayout.BeginHorizontal();
							if (GUILayout.Button(new GUIContent(icoReflection, "Reflection settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
								_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
								_target.submenu_settings=ReliefTerrainSettingsItems.Reflections;
							}
							
							EditorGUI.BeginDisabledGroup( !( (!AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) || (AddPass_flag && (REFLECTION_ENABLED_ADD || RTP_IBL_SPEC_ADD)) ) );
							nval=_target.RTP_IBL_SpecStrength[n];
							EditorGUILayout.LabelField("IBL spec / Refl exposure", GUILayout.Width(150));
							checkChange(ref nval, EditorGUILayout.Slider(_target.RTP_IBL_SpecStrength[n], 0f, 8f));
							_target.RTP_IBL_SpecStrength[n]=nval;							
							EditorGUI.EndDisabledGroup();
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("     color from albedo (metal tint)", GUILayout.Width(200));
							nval=_target.LayerAlbedo2SpecColor[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.LayerAlbedo2SpecColor[n], 0f, 1f, GUILayout.ExpandWidth(true)));
							_target.LayerAlbedo2SpecColor[n]=nval;
							EditorGUILayout.EndHorizontal();	
							if (AddPass_flag) {
								EditorGUILayout.BeginHorizontal();
									EditorGUILayout.LabelField("Specmask for deferred AddPass", GUILayout.MinWidth(190), GUILayout.MaxWidth(190));
									checkChange(ref _target._DeferredSpecDampAddPass[n], EditorGUILayout.Slider(_target._DeferredSpecDampAddPass[n],0,1));
								EditorGUILayout.EndHorizontal();
							}
						}
						EditorGUILayout.EndVertical();	
						GUILayout.Space(8);
												
						//
						// gloss baking section
						//
						if (!RTP_SUPER_SIMPLE) {
							EditorGUILayout.LabelField("PBL - gloss by normal variance baking utility", EditorStyles.boldLabel);
							EditorGUILayout.HelpBox("Gloss baking makes sense only when using PBR high dynamic range (in forward and in deferred using Lux). You can consider baking esp. when your surface is very gossy with gloss (Detail A channel) or normalmap contain high frequency details. Baking removes specular spot pixels jittering when using higher texture MIP levels.", MessageType.Warning, true);
							EditorGUILayout.BeginVertical("Box");
							
							int prep_atlas=-1;
							if (n<4 && atlasA_needed) {
								prep_atlas=0;
							} else if (n>=4 && n<8 && atlasB_needed) {
								prep_atlas=1;
							} else if (n>=8 && n<12 && atlasC_needed) {
								prep_atlas=2;
							}
														
							EditorGUILayout.BeginHorizontal();
							if (prep_atlas==-1) {
								if (_target.gloss_baked[n] && _target.gloss_baked[n].baked && _target.gloss_baked[n].used_in_atlas) {
									// był zbake'owany, ale dla atlasa - usuń
									_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked;
									_target.splats_glossBaked[n]=null;
								}
								EditorGUILayout.ObjectField(_target.splats_glossBaked[n], typeof(Texture2D), false, GUILayout.Width(80), GUILayout.Height(80));
							} else {
								if (_target.gloss_baked[n] && _target.gloss_baked[n].baked && !_target.gloss_baked[n].used_in_atlas) {
									// był zbake'owany, ale dla pojedynczej tekstury - usuń
									_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked;
									_target.splats_glossBaked[n]=null;
									_target.atlas_glossBaked[prep_atlas]=null;
								}
								EditorGUILayout.ObjectField(_target.atlas_glossBaked[prep_atlas], typeof(Texture2D), false, GUILayout.Width(80), GUILayout.Height(80));
							}
							EditorGUILayout.BeginVertical();
							if (GUILayout.Button("Bake MIP gloss data")) {
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.splats[n]));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Texture ("+_target.splats[n].name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.splats[n]),  ImportAssetOptions.ForceUpdate);
									}
								}								
								_importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.Bumps[n]));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Texture ("+_target.Bumps[n].name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.Bumps[n]),  ImportAssetOptions.ForceUpdate);
									}
								}
								_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked;
								_target.gloss_baked[n].Init(_target.splats[n].width);
								if (prep_atlas==-1) {
									if (_importer) {
										TextureImporter tex_importer=(TextureImporter)_importer;
										if (!tex_importer.isReadable) {
											Debug.LogWarning("Texture ("+_target.splats[n].name+") has been reimported as readable.");
											tex_importer.isReadable=true;
											AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.splats[n]),  ImportAssetOptions.ForceUpdate);
										}
									}								
									_target.gloss_baked[n].PrepareMIPGlossMap(_target.splats[n], _target.Bumps[n], _target.RTP_gloss_mult[n], _target.RTP_gloss_shaping[n]);
								} else {
									if (_target.splat_atlases[prep_atlas]!=null) {
										Texture2D atlasTileTex=new Texture2D(_target.splat_atlases[prep_atlas].width/2, _target.splat_atlases[prep_atlas].height/2, TextureFormat.ARGB32, false);
										int bx=(n%2)*atlasTileTex.width;
										int by=((n%4)<2) ? 0 : atlasTileTex.height;
										_importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.splat_atlases[prep_atlas]));
										if (_importer) {
											TextureImporter tex_importer=(TextureImporter)_importer;
											if (!tex_importer.isReadable) {
												Debug.LogWarning("Atlas texture ("+_target.splat_atlases[prep_atlas].name+") has been reimported as readable.");
												tex_importer.isReadable=true;
												AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.splat_atlases[prep_atlas]),  ImportAssetOptions.ForceUpdate);
											}
										}
										atlasTileTex.SetPixels( _target.splat_atlases[prep_atlas].GetPixels( bx, by, atlasTileTex.width, atlasTileTex.height) );
										atlasTileTex.Apply(false, false);
										Texture2D paddedBumpTex=null;
										if (_target.Bumps[n]) {
											paddedBumpTex=new Texture2D(_target.Bumps[n].width, _target.Bumps[n].height, TextureFormat.ARGB32, false);
											paddedBumpTex.SetPixels32(_target.Bumps[n].GetPixels32(0), 0);
											paddedBumpTex.Apply(false, false);
											paddedBumpTex=PadTex(paddedBumpTex, Mathf.FloorToInt(16.0f*paddedBumpTex.width/_target.Bumps[n].width), false);
											paddedBumpTex.name=_target.Bumps[n].name;
										}
										_target.gloss_baked[n].PrepareMIPGlossMap(atlasTileTex, paddedBumpTex, _target.RTP_gloss_mult[n], _target.RTP_gloss_shaping[n], n);
										_target.gloss_baked[n].used_in_atlas=true;
									}
								}
								string fname=AssetDatabase.GetAssetPath(_target.splats[n]);
								if (fname=="") {
									fname="GlossBakedData";
								} else {
									fname=Path.GetFileNameWithoutExtension(fname)+"_MIPGlossData";
								}
								fname += (prep_atlas==-1) ? "" : "(atlased_tile)";
								_target.gloss_baked[n].name=fname;
								_target.Refresh(null, _targetRT);
							}
							GUI.color=new Color(1,0.4f,0.2f,1);
							EditorGUI.BeginDisabledGroup(_target.gloss_baked[n]==null || !_target.gloss_baked[n].baked);
							if (GUILayout.Button("Clear MIP gloss data")) {
								_target.gloss_baked[n]=ScriptableObject.CreateInstance(typeof(RTPGlossBaked)) as RTPGlossBaked;
								_target.splats_glossBaked[n]=null;
								_target.atlas_glossBaked[n/4]=null;
								_target.Refresh(null, _targetRT);
							}
							EditorGUI.EndDisabledGroup();
							GUI.color=new Color(0.5f, 1, 0.5f, 1);
							EditorGUI.BeginDisabledGroup(_target.gloss_baked[n]==null || !_target.gloss_baked[n].baked);
							if (GUILayout.Button("Save MIP gloss data to file")) {
								string fname=AssetDatabase.GetAssetPath(_target.splats[n]);
								string fpath="Assets";
								if (fname=="") {
									fname="GlossBakedData";
								} else {
									fpath=Path.GetDirectoryName(fname);
									fname=Path.GetFileNameWithoutExtension(fname)+"_MIPGlossData";
								}
								fname += (prep_atlas==-1) ? "" : "(atlased_tile)";
								string path = EditorUtility.SaveFilePanel("Save baked MIP gloss data", fpath, fname, "asset");
								if (path!="") {	
									int idx=path.IndexOf("/Assets/")+1;
									if (idx>0) {
										path=path.Substring(idx);
										RTPGlossBaked savedGlossData=UnityEngine.Object.Instantiate(_target.gloss_baked[n]) as RTPGlossBaked;
										Debug.Log("GlossBaked data saved at "+path);
										if (AssetDatabase.LoadAssetAtPath(path, typeof(RTPGlossBaked))!=null) AssetDatabase.DeleteAsset(path);
										AssetDatabase.CreateAsset(savedGlossData, path);
										_target.gloss_baked[n]=savedGlossData;
									} else {
										Debug.Log ("Nothing saved...");
									}
								}
							}
							EditorGUI.EndDisabledGroup();
							GUI.color=skin_color;							
							RTPGlossBaked ngb=(RTPGlossBaked)EditorGUILayout.ObjectField(_target.gloss_baked[n], typeof(RTPGlossBaked), false);
							if (ngb!=_target.gloss_baked[n]) {
								if (ngb && ngb.baked && _target.splats[n]!=null) {
									if (_target.splats[n].width!=ngb.size) {
										EditorUtility.DisplayDialog("Error","Can't apply - gloss baked data size ("+ngb.size+") doesn't fit layer detail texture size ("+_target.splats[n].width+")", "OK");
									} else if ( ngb.used_in_atlas && (prep_atlas==-1) ) {
										EditorUtility.DisplayDialog("Error","Can't apply - gloss baked data was prepared for using in atlases only.", "OK");
									} else if ( !ngb.used_in_atlas && (prep_atlas!=-1) ) {
										EditorUtility.DisplayDialog("Error","Can't apply - gloss baked data was prepared for non atlased layer only.", "OK");
									} else {
										_target.gloss_baked[n]=ngb;
										_target.splats_glossBaked[n]=null;
										_target.atlas_glossBaked[n/4]=null;
										_target.Refresh(null, _targetRT);
									}
								}
							}
							EditorGUILayout.EndVertical();
							EditorGUILayout.EndHorizontal();		
							EditorGUILayout.EndVertical();
						}
						// EOF gloss baking section
						GUILayout.Space(8);
						
						if (!RTP_SUPER_SIMPLE) {						
							EditorGUILayout.LabelField("Layer adjustement", EditorStyles.boldLabel);
							EditorGUILayout.HelpBox("Setting brightness to 0 allows for finetuning / debuging specular term alone.", MessageType.None, true);
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("Layer Brightness", GUILayout.Width(127));
							nval=_target.LayerBrightness[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.LayerBrightness[n], 0f, 4f, GUILayout.ExpandWidth(true)));
							_target.LayerBrightness[n]=nval;
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("Layer Saturation", GUILayout.Width(127));
							nval=_target.LayerSaturation[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.LayerSaturation[n], 0f, 2f, GUILayout.ExpandWidth(true)));
							_target.LayerSaturation[n]=nval;
							EditorGUILayout.EndHorizontal();	
							EditorGUI.BeginDisabledGroup( !(AddPass_flag ? RTP_USE_EXTRUDE_REDUCTION_ADD : RTP_USE_EXTRUDE_REDUCTION_FIRST) );
							nval=_target.PER_LAYER_HEIGHT_MODIFIER[n];
							checkChange(ref nval, EditorGUILayout.Slider("Extrude reduction", _target.PER_LAYER_HEIGHT_MODIFIER[n], 0.0f, 1f, GUILayout.ExpandWidth(true)));
							_target.PER_LAYER_HEIGHT_MODIFIER[n]=nval;
							EditorGUI.EndDisabledGroup();
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("Far filtering", GUILayout.Width(127));
							nval=_target.MIPmult[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.MIPmult[n], 0f, 7f, GUILayout.ExpandWidth(true)));
							_target.MIPmult[n]=nval;
							EditorGUILayout.EndHorizontal();	
							if ( (!AddPass_flag && RTP_HEIGHTBLEND_AO_FIRST) || (AddPass_flag && RTP_HEIGHTBLEND_AO_ADD) ) {
								EditorGUILayout.BeginHorizontal();	
									EditorGUILayout.LabelField("Heightblend AO", GUILayout.Width(127));
									nval=_target.AO_strength[n];
									checkChange(ref nval, EditorGUILayout.Slider(_target.AO_strength[n], 0f, 1f, GUILayout.ExpandWidth(true)));
									_target.AO_strength[n]=nval;
								EditorGUILayout.EndHorizontal();	
							}							
							if ( (!AddPass_flag && RTP_EMISSION_FIRST) || (AddPass_flag && RTP_EMISSION_ADD) ) {
								EditorGUILayout.HelpBox("Layer emission is controlled by below slider && gloss output. For high emission values layer specularity is cancelled.", MessageType.None, true);
								EditorGUILayout.BeginHorizontal();	
									EditorGUILayout.LabelField("Layer emission", GUILayout.Width(125));
									nval=_target.LayerEmission[n];
									checkChange(ref nval, EditorGUILayout.Slider(_target.LayerEmission[n], 0f, 1f, GUILayout.ExpandWidth(true)));
									_target.LayerEmission[n]=nval;
								EditorGUILayout.EndHorizontal();	
								EditorGUILayout.BeginHorizontal();	
									EditorGUILayout.LabelField("Emission glow color", GUILayout.Width(125));
									checkChange(ref _target.LayerEmissionColor[n], EditorGUILayout.ColorField(_target.LayerEmissionColor[n]));
								EditorGUILayout.EndHorizontal();
								if ( (!AddPass_flag && RTP_EMISSION_FIRST && RTP_HOTAIR_EMISSION_FIRST) || (AddPass_flag && RTP_EMISSION_ADD && RTP_HOTAIR_EMISSION_ADD) ) {
									EditorGUILayout.HelpBox("For emissive layers you can adjust simple hot air refraction effect.", MessageType.None, true);
									EditorGUILayout.BeginHorizontal();	
									EditorGUILayout.LabelField("Hot air refraction strength", GUILayout.Width(160));
									nval=_target.LayerEmissionRefractStrength[n];
									checkChange(ref nval, EditorGUILayout.Slider(_target.LayerEmissionRefractStrength[n], 0f, 0.02f, GUILayout.ExpandWidth(true)));
									_target.LayerEmissionRefractStrength[n]=nval;
									EditorGUILayout.EndHorizontal();	
									EditorGUILayout.BeginHorizontal();	
									EditorGUILayout.LabelField("        on layer edges only", GUILayout.Width(160));
									nval=_target.LayerEmissionRefractHBedge[n];
									checkChange(ref nval, EditorGUILayout.Slider(_target.LayerEmissionRefractHBedge[n], 0f, 1f, GUILayout.ExpandWidth(true)));
									_target.LayerEmissionRefractHBedge[n]=nval;
									EditorGUILayout.EndHorizontal();	
								}
							}
						} // EOF !super-simple
						
						EditorGUILayout.EndVertical();
						
						EditorGUILayout.BeginVertical("Box");
						EditorGUILayout.BeginHorizontal();	
						if (GUILayout.Button(new GUIContent(icoGlobalcolor, "Global maps settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
							_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
							_target.submenu_settings=ReliefTerrainSettingsItems.GlobalColor;
						}
						EditorGUILayout.LabelField("Global colormap", GUILayout.Width(130));
						nval=_target.GlobalColorPerLayer[n];
						checkChange(ref nval, EditorGUILayout.Slider(_target.GlobalColorPerLayer[n], 0f, 1f, GUILayout.ExpandWidth(true)));
						_target.GlobalColorPerLayer[n]=nval;
						EditorGUILayout.EndHorizontal();	
						if (!RTP_SUPER_SIMPLE && (AddPass_flag ? ADV_COLOR_MAP_BLENDING_ENABLED_ADD : ADV_COLOR_MAP_BLENDING_ENABLED_FIRST) ) {
							EditorGUILayout.BeginVertical("Box");
							EditorGUILayout.LabelField("Advanced blending settings", EditorStyles.boldLabel);
							EditorGUILayout.HelpBox("Below options are based on detail heightmaps. You can separately set blending for low & hi parts.", MessageType.None, true);
							
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("Height levels", GUILayout.Width(145));
							float valMin=_target.GlobalColorBottom[n];
							float valMax=_target.GlobalColorTop[n];
							float nvalMin=_target.GlobalColorBottom[n];
							float nvalMax=_target.GlobalColorTop[n];
							EditorGUILayout.MinMaxSlider(ref valMin, ref valMax, 0f, 1f, GUILayout.ExpandWidth(true));
							if (checkChange(ref nvalMin, valMin, ref nvalMax, valMax)) {
								if (Mathf.Abs(nvalMin-nvalMax)<0.04f) {
									nvalMin-=0.02f;
									if (nvalMin<0) nvalMin=0;
									nvalMax+=0.02f;
									if (nvalMax>1) nvalMax=1;
								}
							}
							_target.GlobalColorBottom[n] = nvalMin;
							_target.GlobalColorTop[n] = nvalMax;
							EditorGUILayout.EndHorizontal();	
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("  colormap saturation LO", GUILayout.Width(145));
							nval=_target.GlobalColorColormapLoSat[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.GlobalColorColormapLoSat[n], 0f, 2f, GUILayout.ExpandWidth(true)));
							_target.GlobalColorColormapLoSat[n]=nval;
							EditorGUILayout.EndHorizontal();	
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("  colormap saturation HI", GUILayout.Width(145));
							nval=_target.GlobalColorColormapHiSat[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.GlobalColorColormapHiSat[n], 0f, 2f, GUILayout.ExpandWidth(true)));
							_target.GlobalColorColormapHiSat[n]=nval;
							EditorGUILayout.EndHorizontal();	
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("  layer saturation LO", GUILayout.Width(145));
							nval=_target.GlobalColorLayerLoSat[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.GlobalColorLayerLoSat[n], 0f, 2f, GUILayout.ExpandWidth(true)));
							_target.GlobalColorLayerLoSat[n]=nval;
							EditorGUILayout.EndHorizontal();	
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("  layer saturation HI", GUILayout.Width(145));
							nval=_target.GlobalColorLayerHiSat[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.GlobalColorLayerHiSat[n], 0f, 2f, GUILayout.ExpandWidth(true)));
							_target.GlobalColorLayerHiSat[n]=nval;
							EditorGUILayout.EndHorizontal();	
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("Blending for LO", GUILayout.Width(145));
							nval=_target.GlobalColorLoBlend[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.GlobalColorLoBlend[n], 0f, 1f, GUILayout.ExpandWidth(true)));
							_target.GlobalColorLoBlend[n]=nval;
							EditorGUILayout.EndHorizontal();	
							EditorGUILayout.BeginHorizontal();	
							EditorGUILayout.LabelField("Blending for HI", GUILayout.Width(145));
							nval=_target.GlobalColorHiBlend[n];
							checkChange(ref nval, EditorGUILayout.Slider(_target.GlobalColorHiBlend[n], 0f, 1f, GUILayout.ExpandWidth(true)));
							_target.GlobalColorHiBlend[n]=nval;
							EditorGUILayout.EndHorizontal();	
							
							EditorGUILayout.EndVertical();
						}
						EditorGUILayout.EndVertical();
						
						if (!RTP_SUPER_SIMPLE) {							
							EditorGUILayout.BeginVertical("Box");
							if( (AddPass_flag ? UV_BLEND_ENABLED_ADD : UV_BLEND_ENABLED_FIRST) ) {
								EditorGUI.BeginDisabledGroup( !(AddPass_flag ? UV_BLEND_ENABLED_ADD : UV_BLEND_ENABLED_FIRST) );
								EditorGUILayout.BeginHorizontal();
								if (GUILayout.Button(new GUIContent(icoUVBlend, "UV blend settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
									_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
									_target.submenu_settings=ReliefTerrainSettingsItems.UVblend;
								}
								int firstAddPassLayer = AddPass_flag ? ( (_target.numLayers>8)?8:4) : 0;
								int routed_n=AddPass_flag ? UV_BLEND_ROUTE_NUM_ADD[n-firstAddPassLayer] : UV_BLEND_ROUTE_NUM_FIRST[n];
								if (routed_n>_target.MixScale.Length-1) routed_n=n; // at init
								nval=_target.MixScale[routed_n+firstAddPassLayer];
								EditorGUILayout.LabelField("UV blend scale"+((routed_n!=n-firstAddPassLayer) ? " (from "+routed_n+")":""), GUILayout.Width(130+((routed_n!=n-firstAddPassLayer) ? 10:0)));
								EditorGUILayout.BeginHorizontal();
								checkChange(ref nval, EditorGUILayout.Slider(_target.MixScale[routed_n+firstAddPassLayer], 0.01f, 0.5f));
//								if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
//									float ratio=Mathf.Round(_target.ReliefTransform.x*nval);
//									nval=ratio/_target.ReliefTransform.x;
//									_target.RefreshAll();
//								}
								EditorGUILayout.EndHorizontal();						
								_target.MixScale[routed_n+firstAddPassLayer]=nval;
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();
								nval=_target.MixBlend[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("UV blend val", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target.MixBlend[n], 0, 0.9f));
								_target.MixBlend[n]=nval;
								EditorGUILayout.EndHorizontal();
								
								EditorGUILayout.BeginHorizontal();
								nval=_target.MixSaturation[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("              saturation", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target.MixSaturation[n], 0, 1.0f));
								_target.MixSaturation[n]=nval;
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();
								nval=_target.MixBrightness[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("              brightness", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target.MixBrightness[n], 0, 4.0f));
								_target.MixBrightness[n]=nval;
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();
								nval=_target.MixReplace[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("Far blend replace", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target.MixReplace[n], 0, 1.0f));
								_target.MixReplace[n]=nval;
								EditorGUILayout.EndHorizontal();
							} else {
								EditorGUILayout.BeginHorizontal();
								if (GUILayout.Button(new GUIContent(icoUVBlend, "UV blend settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
									_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
									_target.submenu_settings=ReliefTerrainSettingsItems.UVblend;
								}
								EditorGUI.BeginDisabledGroup( true );
								EditorGUILayout.LabelField("UV blend (disabled)");
								EditorGUI.EndDisabledGroup();
								EditorGUILayout.EndHorizontal();
							}							
							EditorGUILayout.EndVertical();
						}
						if (!RTP_SUPER_SIMPLE || (AddPass_flag ? RTP_USE_PERLIN_ADD : RTP_USE_PERLIN_FIRST)) {
							EditorGUILayout.BeginVertical("Box");
							EditorGUILayout.BeginHorizontal();
							if (GUILayout.Button(new GUIContent(icoPerlinNormal, "Perlin normal settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
								_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
								_target.submenu_settings=ReliefTerrainSettingsItems.GlobalNormal;
							}
							nval=_target._BumpMapGlobalStrength[n];
							EditorGUILayout.LabelField("Perlin normal", GUILayout.Width(130));
							checkChange(ref nval, EditorGUILayout.Slider(_target._BumpMapGlobalStrength[n], 0.02f, 2f));
							_target._BumpMapGlobalStrength[n]=nval;		
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.EndVertical();
						}			
									
						if (!RTP_SUPER_SIMPLE) {
							EditorGUILayout.BeginVertical("Box");
							
							EditorGUILayout.BeginHorizontal();
							if (GUILayout.Button(new GUIContent(icoSuperdetail, "Superdetail settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
								_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
								_target.submenu_settings=ReliefTerrainSettingsItems.Superdetail;
							}
							if (AddPass_flag ? SUPER_DETAIL_ENABLED_ADD : SUPER_DETAIL_ENABLED_FIRST) {
								nval=_target._SuperDetailStrengthNormal[n];
								EditorGUILayout.LabelField("Superdetail normal", GUILayout.Width(130));
								if (checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthNormal[n], 0f, 1f))) {
									_target._SuperDetailStrengthNormal[n]=nval;	
								}
							} else {
								EditorGUI.BeginDisabledGroup( true );
								EditorGUILayout.LabelField("Superdetail (disabled)", GUILayout.Width(130));
								EditorGUI.EndDisabledGroup();
							}
							EditorGUILayout.EndHorizontal();
							
							if ( (AddPass_flag ? SUPER_DETAIL_ENABLED_ADD : SUPER_DETAIL_ENABLED_FIRST) && (AddPass_flag ? SUPER_DETAIL_MULTS_ENABLED_ADD : SUPER_DETAIL_MULTS_ENABLED_FIRST) ) {
								EditorGUILayout.BeginHorizontal();							
								_target._SuperDetailStrengthNormal[n]=nval;							
								nval=_target._SuperDetailStrengthMultA[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("Superdetail mult A", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultA[n], 0f, 1f));
								_target._SuperDetailStrengthMultA[n]=nval;	
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();							
								nval=_target._SuperDetailStrengthMultASelfMaskNear[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("  SelfMask near", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultASelfMaskNear[n], 0f, 1f));
								_target._SuperDetailStrengthMultASelfMaskNear[n]=nval;	
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();							
								nval=_target._SuperDetailStrengthMultASelfMaskFar[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("  SelfMask far", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultASelfMaskFar[n], 0f, 1f));
								_target._SuperDetailStrengthMultASelfMaskFar[n]=nval;
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();							
								nval=_target._SuperDetailStrengthMultB[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("Superdetail mult B", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultB[n], 0f, 1f));
								_target._SuperDetailStrengthMultB[n]=nval;							
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();							
								nval=_target._SuperDetailStrengthMultBSelfMaskNear[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("  SelfMask near", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultBSelfMaskNear[n], 0f, 1f));
								_target._SuperDetailStrengthMultBSelfMaskNear[n]=nval;	
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();							
								nval=_target._SuperDetailStrengthMultBSelfMaskFar[n];
								EditorGUILayout.LabelField(" ", GUILayout.Width(16));
								EditorGUILayout.LabelField("  SelfMask far", GUILayout.Width(130));
								checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultBSelfMaskFar[n], 0f, 1f));
								_target._SuperDetailStrengthMultBSelfMaskFar[n]=nval;	
								EditorGUILayout.EndHorizontal();
							}
							
							EditorGUILayout.EndVertical();
							
							EditorGUILayout.BeginVertical("Box");
							EditorGUILayout.BeginHorizontal();
							if (GUILayout.Button(new GUIContent(icoVerticalTexture, "Vertical map settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
								_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
								_target.submenu_settings=ReliefTerrainSettingsItems.VerticalTex;
							}
							if (AddPass_flag ? RTP_VERTICAL_TEXTURE_ADD : RTP_VERTICAL_TEXTURE_FIRST) {
								EditorGUI.BeginDisabledGroup( !(AddPass_flag ? RTP_VERTICAL_TEXTURE_ADD : RTP_VERTICAL_TEXTURE_FIRST) );
								nval=_target.VerticalTextureStrength[n];
								checkChange(ref nval, EditorGUILayout.Slider("Vertical map strength", _target.VerticalTextureStrength[n], 0f, 1f));
								_target.VerticalTextureStrength[n]=nval;							
								EditorGUI.EndDisabledGroup();
							} else {
								EditorGUI.BeginDisabledGroup( true);
								EditorGUILayout.LabelField("Vertical map (disabled)");
								EditorGUI.EndDisabledGroup();
							}
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.EndVertical();
							
							EditorGUILayout.BeginVertical("Box");
							EditorGUILayout.BeginHorizontal();
							if (GUILayout.Button(new GUIContent(icoSnow, "Snow settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
								_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
								_target.submenu_settings=ReliefTerrainSettingsItems.Snow;
							}
							if (AddPass_flag ? SNOW_ENABLED_ADD : SNOW_ENABLED_FIRST) {
								nval=_target._snow_strength_per_layer[n];
								checkChange(ref nval, EditorGUILayout.Slider("Snow strength", _target._snow_strength_per_layer[n], 0f, 1f));
								_target._snow_strength_per_layer[n]=nval;							
							} else {
								EditorGUI.BeginDisabledGroup( true);
								EditorGUILayout.LabelField("Snow (disabled)");
								EditorGUI.EndDisabledGroup();
							}
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.EndVertical();
							
							EditorGUILayout.BeginVertical("Box");
							EditorGUILayout.BeginHorizontal();
							if (GUILayout.Button(new GUIContent(icoWater, "Water settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
								_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
								_target.submenu_settings=ReliefTerrainSettingsItems.Water;
							}
							if (AddPass_flag ? WATER_ENABLED_ADD : WATER_ENABLED_FIRST) {
								nval=_target.TERRAIN_LayerWetStrength[n];
								checkChange(ref nval, EditorGUILayout.Slider("Layer wetness", _target.TERRAIN_LayerWetStrength[n], 0f, 1f));
								_target.TERRAIN_LayerWetStrength[n]=nval;							
								EditorGUILayout.EndHorizontal();
								
								EditorGUILayout.HelpBox("Accumulated water color (below water level).\nRealised multiplicative (unless you set high water opacity).\nColor alpha controls water Fresnel effect.",MessageType.None, true);
								checkChange(ref _target.TERRAIN_WaterColor[n], EditorGUILayout.ColorField("Water color", _target.TERRAIN_WaterColor[n]));
								nval=_target.TERRAIN_WaterOpacity[n];
								checkChange(ref nval, EditorGUILayout.Slider("Water opacity", _target.TERRAIN_WaterOpacity[n], 0f, 1f));
								_target.TERRAIN_WaterOpacity[n]=nval;		
								if ( (!AddPass_flag && RTP_EMISSION_FIRST) || (AddPass_flag && RTP_EMISSION_ADD) ) {
									nval=_target.TERRAIN_WaterEmission[n];
									checkChange(ref nval, EditorGUILayout.Slider("Water emission", _target.TERRAIN_WaterEmission[n], 0f, 1f, GUILayout.ExpandWidth(true)));
									_target.TERRAIN_WaterEmission[n]=nval;
								}
								
								GUILayout.Space(4);
								
								nval=_target.TERRAIN_WaterLevel[n];
								checkChange(ref nval, EditorGUILayout.Slider("Water level", _target.TERRAIN_WaterLevel[n]/2f, 0f, 1f)*2f);
								_target.TERRAIN_WaterLevel[n]=nval;		
								
								nval=_target.TERRAIN_WaterLevelSlopeDamp[n];
								checkChange(ref nval, EditorGUILayout.Slider("Water level slope damp", _target.TERRAIN_WaterLevelSlopeDamp[n], 0.1f, 2));
								_target.TERRAIN_WaterLevelSlopeDamp[n]=nval;		
								
								nval=_target.TERRAIN_WaterEdge[n];
								checkChange(ref nval, Mathf.Pow(2, EditorGUILayout.Slider("Water level sharpness", Mathf.Log(_target.TERRAIN_WaterEdge[n])/Mathf.Log(2)/2, 0, 1)*2));
								_target.TERRAIN_WaterEdge[n]=nval;		
								
								GUILayout.Space(4);
								
								nval=_target.TERRAIN_WaterSpecularity[n];
								checkChange(ref nval, EditorGUILayout.Slider("Water spec boost", _target.TERRAIN_WaterSpecularity[n], -1f, 1f));
								_target.TERRAIN_WaterSpecularity[n]=nval;		
								
								nval=_target.TERRAIN_WaterGloss[n];
								checkChange(ref nval, EditorGUILayout.Slider("Water gloss boost", _target.TERRAIN_WaterGloss[n], -1f, 1f));
								_target.TERRAIN_WaterGloss[n]=nval;		
								
								nval=_target.TERRAIN_Flow[n];
								checkChange(ref nval, EditorGUILayout.Slider("Water flow", _target.TERRAIN_Flow[n], 0f, 1f));
								_target.TERRAIN_Flow[n]=nval;		
								nval=_target.TERRAIN_Refraction[n];
								checkChange(ref nval, EditorGUILayout.Slider("Water refraction", _target.TERRAIN_Refraction[n], 0f, 0.04f));
								_target.TERRAIN_Refraction[n]=nval;		
								
								if ( (!AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) || (AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) ) {
									GUILayout.Space(4);
									nval=_target.TERRAIN_WaterIBL_SpecWaterStrength[n];
									checkChange(ref nval, EditorGUILayout.Slider("IBL spec / Refl - water", _target.TERRAIN_WaterIBL_SpecWaterStrength[n], 0f, 8f));
									_target.TERRAIN_WaterIBL_SpecWaterStrength[n]=nval;
								}
								
								GUILayout.Space(4);
								EditorGUILayout.HelpBox("Wet means layer surface covered by thin water layer, but above water level",MessageType.None,true);							
								nval=_target.TERRAIN_WetSpecularity[n];
								checkChange(ref nval, EditorGUILayout.Slider("Wet spec boost", _target.TERRAIN_WetSpecularity[n], -1f, 1f));
								_target.TERRAIN_WetSpecularity[n]=nval;		
								
								nval=_target.TERRAIN_WetGloss[n];
								checkChange(ref nval, EditorGUILayout.Slider("Wet gloss boost", _target.TERRAIN_WetGloss[n], -1f, 1f));
								_target.TERRAIN_WetGloss[n]=nval;		
								
								nval=_target.TERRAIN_WetFlow[n];
								checkChange(ref nval, EditorGUILayout.Slider("Wet flow", _target.TERRAIN_WetFlow[n], 0f, 1f));
								_target.TERRAIN_WetFlow[n]=nval;		
								
								//					nval=_target.TERRAIN_WetReflection[n];
								//					checkChange(ref nval, EditorGUILayout.Slider("Wet reflection", _target.TERRAIN_WetReflection[n]/2f, 0f, 1f)*2f);
								//					_target.TERRAIN_WetReflection[n]=nval;		
								
								nval=_target.TERRAIN_WetRefraction[n];
								checkChange(ref nval, EditorGUILayout.Slider("Wet refraction factor", _target.TERRAIN_WetRefraction[n], 0f, 1f));
								_target.TERRAIN_WetRefraction[n]=nval;		
								
								if ( (!AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) || (AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) ) {
									nval=_target.TERRAIN_WaterIBL_SpecWetStrength[n];
									checkChange(ref nval, EditorGUILayout.Slider("IBL spec / Refl - wet", _target.TERRAIN_WaterIBL_SpecWetStrength[n], 0f, 8f));
									_target.TERRAIN_WaterIBL_SpecWetStrength[n]=nval;
								}
								GUILayout.Space(4);
								
								EditorGUILayout.BeginHorizontal();
								EditorGUILayout.LabelField("Hi-freq / distance gloss damper", GUILayout.MinWidth(190), GUILayout.MaxWidth(190));
								nval=_target.TERRAIN_WaterGlossDamper[n];
								checkChange(ref nval, EditorGUILayout.Slider(_target.TERRAIN_WaterGlossDamper[n], 0f, 1f));
								_target.TERRAIN_WaterGlossDamper[n]=nval;		
								EditorGUILayout.EndHorizontal();
								
								GUILayout.Space(6);
								
								string[] options=new string[_target.numLayers];
								options[0]="Choose layer to copy water params from";
								for(int k=0; k<_target.numLayers; k++) {
									if (k<=n) {
										if (k<_target.numLayers-1) options[k+1]="layer "+k;
									} else {
										options[k]="layer "+k;
									}
								}
								int idx=EditorGUILayout.Popup(0, options);
								if (idx>0) {
									if (idx-1<n) {
										idx--;
									}
									#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
									Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
									#else
									Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
									#endif
									_target.CopyWaterParams(idx, n);
									EditorUtility.SetDirty(_targetRT);
									_target.Refresh(null, _targetRT);						
								}
								
							} else {
								EditorGUI.BeginDisabledGroup( true);
								EditorGUILayout.LabelField("Water (disabled)");
								EditorGUI.EndDisabledGroup();
								EditorGUILayout.EndHorizontal();
							}
							EditorGUILayout.EndVertical();
							
						}
						EditorGUILayout.EndVertical();
						EditorGUILayout.Space();
					} // EOF !super-simple
					
					GUILayout.Space(8);							
					if (GUILayout.Button("Reset layer numeric params to default")) {
						#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
						Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
						#else
						Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
						#endif
						_target.ReturnToDefaults("layer");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh(null, _targetRT);
					}	
					
					#endregion Detail maps unfold	- layers
				}
				
				
				#endregion Detail maps unfold
			}	
			
			//bool nshow_controlmaps=EditorGUILayout.Foldout(_target.show_controlmaps, "Control (alpha) maps");
			//if (nshow_controlmaps) {
			if (_target.show_controlmaps) {
				#region Control maps
				Color skin_color;
				toolbarStrings = new string[3]{"Compose", "Acquire", "Control maps"};
				GUILayout.Space(6);
				EditorGUILayout.BeginHorizontal();
				GUILayout.FlexibleSpace();
				_target.submenu_control_textures=(ReliefTerrainControlTexturesItems )(GUILayout.Toolbar((int)_target.submenu_control_textures, toolbarStrings, EditorStyles.miniButton, GUILayout.MaxWidth(370)));
				GUILayout.FlexibleSpace();
				EditorGUILayout.EndHorizontal();
				
				switch(_target.submenu_control_textures) {
				case ReliefTerrainControlTexturesItems.Compose:
					#region Control maps - compose maps
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Compose splats", EditorStyles.boldLabel);
					GUI.color=skin_color;
					EditorGUILayout.HelpBox("Here you can manipulate alpha maps that control layers coverage,\n1. Source splat is coverage texture and you can choose its channel,\n2. Value taken from coverage texture (can be inverted) is multiplied by given factor,\n3. Result is normalized,\n4. Blank source splats are considered 1 (white),\n5. In case you unset \"active\", input value is taken from current control map.",MessageType.None, true);				
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Layer", EditorStyles.boldLabel, GUILayout.MaxWidth(100));
					EditorGUILayout.LabelField("Source splats", EditorStyles.boldLabel, GUILayout.MaxWidth(100));
					EditorGUILayout.EndHorizontal();		
					
					for(int i=0; i<_target.numLayers; i++) {
						int n=_targetRT.splat_layer_seq[i];
						Texture2D tex=_targetRT.source_controls[n];
						Texture2D ntex=tex;
						EditorGUILayout.BeginHorizontal();
						#if !UNITY_3_5
						GUILayout.Label((Texture2D)AssetPreview.GetAssetPreview(_target.splats[n]), GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
						#else
						GUILayout.Label((Texture2D)EditorUtility.GetAssetPreview(_target.splats[n]), GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
						#endif						
						if (_targetRT.splat_layer_calc[n]) {
							if (_targetRT.source_controls[n]) {
								checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_targetRT.source_controls[n], typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
							} else {
								if (!blank_white_tex) {
									blank_white_tex=new Texture2D(4,4,TextureFormat.ARGB32,false);
									Color[] cols=new Color[16];
									for(int k=0; k<16; k++) cols[k]=Color.white;
									blank_white_tex.SetPixels(cols);
									blank_white_tex.Apply(false, true);
								}
								if (!blank_black_tex) {
									blank_black_tex=new Texture2D(4,4,TextureFormat.ARGB32,false);
									Color[] cols=new Color[16];
									for(int k=0; k<16; k++) cols[k]=Color.black;
									blank_black_tex.SetPixels(cols);
									blank_black_tex.Apply(false, true);
								}
								if (_targetRT.source_controls_invert[n]) {
									ntex=tex=blank_black_tex;
								} else {
									ntex=tex=blank_white_tex;
								}
								checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(tex, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
								if (ntex==null) {
									_targetRT.source_controls[n]=tex=null;
								}
							}
							if (_targetRT.source_controls[n]==blank_white_tex || ntex==blank_white_tex || _targetRT.source_controls[n]==blank_black_tex || ntex==blank_black_tex || ntex==null) _targetRT.source_controls[n]=ntex=tex=null;
							if (ntex!=tex) {
								int wdth=1024;
								if (_targetRT.controlA!=null) {
									wdth=_targetRT.controlA.width;
									for(int j=0; j<_targetRT.source_controls.Length; j++) {
										Color[] cols=new Color[wdth*wdth];
										bool cols_inited=false;
										if (_targetRT.source_controls[j]) {
											if (_targetRT.source_controls[j].width!=wdth) {
												if (!cols_inited) {
													cols_inited=true;
													for(int u=0; u<cols.Length; u++) cols[u]=Color.white;
												}
												_targetRT.source_controls[j]=new Texture2D(wdth,wdth);
												_targetRT.source_controls[j].SetPixels(cols);
												_targetRT.source_controls[j].Apply(true);
											}
										}
									}
								} else {
									for(int j=0; j<_targetRT.source_controls.Length; j++) {
										if (_targetRT.source_controls[j]) {
											wdth=_targetRT.source_controls[j].width;
											break;
										}
									}
								}
								if (ntex && ntex.width==wdth) {
									_targetRT.source_controls[n]=ntex;
									AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
									if (_importer) {
										TextureImporter tex_importer=(TextureImporter)_importer;
										if (!tex_importer.isReadable) {
											Debug.LogWarning("Source splat texture "+n+" ("+ntex.name+") has been reimported as readable.");
											tex_importer.isReadable=true;
											AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
										}
									}
									if ( _targetRT.source_controls_invert[n] ) {
										Color[] cols=_targetRT.source_controls[n].GetPixels();
										_target.InvertChannel(cols, -1);
										int w=_targetRT.source_controls[n].width;
										_targetRT.source_controls[n]=new Texture2D(w,w);
										_targetRT.source_controls[n].SetPixels(cols);
										_targetRT.source_controls[n].Apply();
									}									
								} else {
									if (_targetRT.controlA) {
										EditorUtility.DisplayDialog("Error", "Source control alpha maps should have "+wdth+" size.","OK");
									} else {
										///////////////////
										if (EditorUtility.DisplayDialog("Error", "Should I reset all source control alpha maps to "+ntex.width+" size?","Yes, please","No, thanks")) {
											wdth=ntex.width;
											Color[] cols=new Color[wdth*wdth];
											for(int u=0; u<cols.Length; u++) cols[u]=Color.white;
											for(int j=0; j<_targetRT.source_controls.Length; j++) {
												if (j!=n) {
													if (_targetRT.source_controls[j].width!=wdth) {
														_targetRT.source_controls[j]=new Texture2D(wdth,wdth);
														_targetRT.source_controls[j].SetPixels(cols);
														_targetRT.source_controls[j].Apply(true);
													}
												} else {
													_targetRT.source_controls[n]=ntex;
												}
											}
										}
										/////////////////										
									}
								}
							}
						} else {
							GUILayout.Label((Texture2D)null, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
						}
						EditorGUILayout.BeginVertical(); // layer props
						EditorGUILayout.BeginHorizontal();
						checkChange(ref _targetRT.splat_layer_calc[n], EditorGUILayout.Toggle(_targetRT.splat_layer_calc[n], GUILayout.MinWidth(10), GUILayout.MaxWidth(10)));
						EditorGUILayout.LabelField("active", GUILayout.MinWidth(40), GUILayout.MaxWidth(40));
						EditorGUILayout.EndHorizontal();
						if (_targetRT.splat_layer_calc[n]) {
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							checkChange(ref _targetRT.source_controls_channels[n], (RTPColorChannels)EditorGUILayout.EnumPopup(_targetRT.source_controls_channels[n]));
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("multiplier", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							checkChange(ref _targetRT.splat_layer_boost[n], EditorGUILayout.FloatField(_targetRT.splat_layer_boost[n]));
							EditorGUILayout.EndHorizontal();
							
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("masked", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							checkChange(ref _targetRT.splat_layer_masked[n], EditorGUILayout.Toggle(_targetRT.splat_layer_masked[n], GUILayout.MinWidth(10), GUILayout.MaxWidth(10)));
							//									if (_targetRT.splat_layer_masked[n] && !_targetRT.source_controls[n]) {
							//										_targetRT.splat_layer_masked[n]=false;
							//										EditorUtility.DisplayDialog("Error", "Blank input can not be masked.","OK");
							//									}
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("invert", GUILayout.MinWidth(40), GUILayout.MaxWidth(40));
							bool nval=_targetRT.source_controls_invert[n];
							checkChange(ref nval, EditorGUILayout.Toggle(_targetRT.source_controls_invert[n], GUILayout.MinWidth(10), GUILayout.MaxWidth(10)));
							if ( (_targetRT.source_controls_invert[n]!=nval)  && (_targetRT.source_controls[n])) {
								Color[] cols=_targetRT.source_controls[n].GetPixels();
								_target.InvertChannel(cols, -1);
								int w=_targetRT.source_controls[n].width;
								_targetRT.source_controls[n]=new Texture2D(w,w);
								_targetRT.source_controls[n].SetPixels(cols);
								_targetRT.source_controls[n].Apply();
							}
							_targetRT.source_controls_invert[n]=nval;								
							//									if (_targetRT.source_controls_invert[n] && !_targetRT.source_controls[n]) {
							//										_targetRT.source_controls_invert[n]=false;
							//										EditorUtility.DisplayDialog("Error", "Blank input can not be inverted.","OK");
							//									}
							EditorGUILayout.EndHorizontal();						
							EditorGUILayout.EndHorizontal();
						}
						
						EditorGUILayout.BeginHorizontal(); // move up/down
						if (GUILayout.Button("Move up")) {
							if (i>0) {
								int tmp=_targetRT.splat_layer_seq[i];
								_targetRT.splat_layer_seq[i]=_targetRT.splat_layer_seq[i-1];
								_targetRT.splat_layer_seq[i-1]=tmp;
							}
							//_targetRT.splat_layer_seq=new int[8]{0,1,2,3,4,5,6,7};
						}
						if (GUILayout.Button("Move down")) {
							if (i<_target.numLayers-1) {
								int tmp=_targetRT.splat_layer_seq[i];
								_targetRT.splat_layer_seq[i]=_targetRT.splat_layer_seq[i+1];
								_targetRT.splat_layer_seq[i+1]=tmp;
							}
						}
						EditorGUILayout.EndHorizontal(); // move up/down
						EditorGUILayout.EndVertical(); // layer props
						
						EditorGUILayout.EndHorizontal();
						// optional mask
						if (	_targetRT.splat_layer_masked[n] && _targetRT.splat_layer_calc[n]) {
							EditorGUILayout.BeginHorizontal();
							GUILayout.Label("Source splat\nmask >", GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
							tex=ntex=_targetRT.source_controls_mask[n];
							checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(tex, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
							if (ntex!=tex) {
								int wdth=1024;
								if (_targetRT.controlA!=null) {
									wdth=_targetRT.controlA.width;
								} else {
									for(int j=0; j<_targetRT.source_controls.Length; j++) {
										if (_targetRT.source_controls[j]) {
											wdth=_targetRT.source_controls[j].width;
											break;
										}
									}
								}
								if (ntex && ntex.width==wdth) {							
									_targetRT.source_controls_mask[n]=ntex;
									AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
									if (_importer) {
										TextureImporter tex_importer=(TextureImporter)_importer;
										if (!tex_importer.isReadable) {
											Debug.LogWarning("Mask texture "+n+" ("+ntex.name+") has been reimported as readable.");
											tex_importer.isReadable=true;
											AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
										}
									}
									if ( _targetRT.source_controls_mask_invert[n] ) {
										Color[] cols=_targetRT.source_controls_mask[n].GetPixels();
										_target.InvertChannel(cols, -1);
										int w=_targetRT.source_controls_mask[n].width;
										_targetRT.source_controls_mask[n]=new Texture2D(w,w);
										_targetRT.source_controls_mask[n].SetPixels(cols);
										_targetRT.source_controls_mask[n].Apply();
									}									
								} else if (ntex) {
									EditorUtility.DisplayDialog("Error", "Mask texture should have "+_targetRT.controlA.width+" size.","OK");
								} else {
									_targetRT.source_controls_mask[n]=ntex; // null
									_targetRT.splat_layer_masked[n]=false;
								}
							}
							EditorGUILayout.BeginVertical(); // mask props
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							checkChange(ref _targetRT.source_controls_mask_channels[n], (RTPColorChannels)EditorGUILayout.EnumPopup(_targetRT.source_controls_mask_channels[n]));
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("invert", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							bool nval=_targetRT.source_controls_mask_invert[n];
							checkChange(ref nval, EditorGUILayout.Toggle(_targetRT.source_controls_mask_invert[n]));
							if ( (_targetRT.source_controls_mask_invert[n]!=nval)  && (_targetRT.source_controls_mask[n])) {
								Color[] cols=_targetRT.source_controls_mask[n].GetPixels();
								_target.InvertChannel(cols, -1);
								int w=_targetRT.source_controls_mask[n].width;
								_targetRT.source_controls_mask[n]=new Texture2D(w,w);
								_targetRT.source_controls_mask[n].SetPixels(cols);
								_targetRT.source_controls_mask[n].Apply();
							}
							_targetRT.source_controls_mask_invert[n]=nval;									
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.EndVertical(); // mask props						
							
							EditorGUILayout.EndHorizontal();
						}
						
					}
					EditorGUILayout.BeginHorizontal();
					if (GUILayout.Button("Set all \"active\" flags")) {
						for(int j=0; j<_target.numLayers; j++) {
							_targetRT.splat_layer_calc[j]=true;
						}
					}				
					if (GUILayout.Button("Clear all \"active\" flags")) {
						for(int j=0; j<_target.numLayers; j++) {
							_targetRT.splat_layer_calc[j]=false;
						}
					}
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.HelpBox("In layered mode highest (bottom) layer \"wins\". In unlayered mode order doesn't matter.",MessageType.None, true);
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Layered mode", EditorStyles.boldLabel, GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _targetRT.splat_layer_ordered_mode, EditorGUILayout.Toggle(_targetRT.splat_layer_ordered_mode));
					EditorGUILayout.EndHorizontal();
					if (GUILayout.Button("Render Control maps from source splats")) {
						if (EditorUtility.DisplayDialog("Warning", "This will overwrite current splat controlmaps\n(you may backup them using save feature in \"Splatmaps...\" unfold below). Are you sure ?","Yes","Cancel")) {
							if (terrainComp) {
								_targetRT.RecalcControlMaps();
							} else {
								_targetRT.RecalcControlMapsForMesh();
							}
						}
					}
					
					EditorGUILayout.EndVertical();
					#endregion Control maps - compose maps
					break;
				case ReliefTerrainControlTexturesItems.Acquire:
					#region Control maps - acquire mask textures
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Acquire mask textures", EditorStyles.boldLabel);
					GUI.color=skin_color;
					if (terrainComp) {
						EditorGUILayout.HelpBox("Here you can get coverage textures taken from height, steepness or normal direction (relative to reference object's Z axis and Y component of compared direction vectors may be optionally skipped, if not - resultant texture might be considered lightmap when using light as ref direction object).\n\nProduced textures are esp. useful for users that don't use external terrain tools, but only heightmap as base for their work. Textures taken here may serve as splat sources (\"Compose splats\" tab above).\n\nRealistic heightmaps themselves might be acquired from sattelite data - one may google for that, you can also consider making heightmap from scratch using photoshop (use perlin noise for example).",MessageType.None, true);
						if (GUILayout.Button("Save steepness")) {
							Texture2D tex=_targetRT.GetSteepnessHeightDirectionTexture(0);
							if (tex) {
								SaveTexture(ref tex, ref _target.save_path_terrain_steepness, "terrain_steepnessMap.png", 0, TextureImporterFormat.AutomaticCompressed, false, false);
							} else {
								EditorUtility.DisplayDialog("?", "Can't get steepness texture...","OK");
							}
						}
						if (GUILayout.Button("Save height")) {
							Texture2D tex=_targetRT.GetSteepnessHeightDirectionTexture(1);
							if (tex) {
								SaveTexture(ref tex, ref _target.save_path_terrain_height, "terrain_heightMap.png", 0, TextureImporterFormat.AutomaticCompressed, false, false);
							} else {
								EditorUtility.DisplayDialog("?", "Can't get height texture...","OK");
							}
						}
						
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Direction reference", GUILayout.MaxWidth(116));
						checkChange(ref _target.direction_object, (GameObject)EditorGUILayout.ObjectField(_target.direction_object, typeof(GameObject), true));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Skip y component", GUILayout.MaxWidth(116));
						checkChange(ref _target.flat_dir_ref, EditorGUILayout.Toggle(_target.flat_dir_ref));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Flip direction", GUILayout.MaxWidth(116));
						checkChange(ref _target.flip_dir_ref, EditorGUILayout.Toggle(_target.flip_dir_ref));
						EditorGUILayout.EndHorizontal();
						if (GUILayout.Button("Save direction")) {
							Texture2D tex=_targetRT.GetSteepnessHeightDirectionTexture(2,_target.direction_object);
							if (tex) {
								SaveTexture(ref tex, ref _target.save_path_terrain_direction, "terrain_directionMap.png", 0, TextureImporterFormat.AutomaticCompressed, false, false);
							} else {
								EditorUtility.DisplayDialog("?", "Can't get direction texture...","OK");
							}							
						}
					} else {
						EditorGUILayout.HelpBox("Option available for terrains only.",MessageType.Warning, true);
					}
					
					EditorGUILayout.Space();
					EditorGUILayout.EndVertical();
					#endregion Control maps - acquire mask textures					
					break;
				case ReliefTerrainControlTexturesItems.Controlmaps:
					#region Control maps - splats					
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Splatmaps (control maps)", EditorStyles.boldLabel);
					GUI.color=skin_color;
					EditorGUILayout.HelpBox("Here you can see control maps as they are stored and used by Unity terrain system. For terrains you can backup them using save feature. You can drag&drop (select) such splatmaps (ARGB32) to override existing one(s) - for example when you need to restore them from backup or need to apply your own on terrain.",MessageType.None, true);
					if (terrainComp) {
						if (GUILayout.Button("Refresh Controlmap(s) shown from TerrainData")) {
							_targetRT.GetControlMaps();
						}
					}
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Splat 0-3", GUILayout.MaxWidth(65));
					if (terrainComp!=null) {
						bool tmp_dirtyFlag=dirtyFlag;
						checkChange(ref _targetRT.controlA, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlA, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						if (dirtyFlag && !tmp_dirtyFlag) {
							AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.controlA));
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Control texture 0 ("+_targetRT.controlA.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.controlA),  ImportAssetOptions.ForceUpdate);
								}
							}					
							_targetRT.SetCustomControlMaps();
						}
					} else {
						checkChange(ref _targetRT.controlA, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlA, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					}
					if (_target.numLayers>4) {
						EditorGUILayout.LabelField("Splat 4-7", GUILayout.MaxWidth(65));
						if (terrainComp!=null) {
							bool tmp_dirtyFlag=dirtyFlag;
							checkChange(ref _targetRT.controlB, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlB, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
							if (dirtyFlag && !tmp_dirtyFlag) {
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.controlB));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Control texture 1 ("+_targetRT.controlB.name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.controlB),  ImportAssetOptions.ForceUpdate);
									}
								}					
								_targetRT.SetCustomControlMaps();
							}
						} else {
							checkChange(ref _targetRT.controlB, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlB, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						}
					}
					EditorGUILayout.EndHorizontal();
					
					EditorGUILayout.BeginHorizontal();
					if (GUILayout.Button("Save to file", GUILayout.MinWidth(170), GUILayout.MaxWidth(170))) {
						Texture2D tex=_targetRT.controlA;
						if (tex) {
							SaveTexture(ref tex, ref _targetRT.save_path_controlA, "terrain_splatMapA.png", 0, TextureImporterFormat.ARGB32, true, false, true);
						} else {
							EditorUtility.DisplayDialog("?", "Can't get height texture...","OK");
						}
					}								
					if (_target.numLayers>4) {
						if (GUILayout.Button("Save to file", GUILayout.MinWidth(170), GUILayout.MaxWidth(170))) {
							Texture2D tex=_targetRT.controlB;
							if (tex) {
								SaveTexture(ref tex, ref _targetRT.save_path_controlB, "terrain_splatMapB.png", 0, TextureImporterFormat.ARGB32, true, false, true);
							} else {
								EditorUtility.DisplayDialog("?", "Can't get height texture...","OK");
							}
						}								
					}
					EditorGUILayout.EndHorizontal();
					
					if (_target.numLayers>8) {
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Splat 8-11", GUILayout.MaxWidth(65));
						if (terrainComp!=null) {
							bool tmp_dirtyFlag=dirtyFlag;
							checkChange(ref _targetRT.controlC, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlC, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
							if (dirtyFlag && !tmp_dirtyFlag) {
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.controlC));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Control texture 2 ("+_targetRT.controlC.name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.controlC),  ImportAssetOptions.ForceUpdate);
									}
								}					
								_targetRT.SetCustomControlMaps();
							}
						} else {
							checkChange(ref _targetRT.controlC, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlC, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						}
						EditorGUILayout.EndHorizontal();
					}
					
					if (_target.numLayers>8) {
						if (GUILayout.Button("Save to file", GUILayout.MinWidth(170), GUILayout.MaxWidth(170))) {
							Texture2D tex=_targetRT.controlC;
							if (tex) {
								SaveTexture(ref tex, ref _targetRT.save_path_controlC, "terrain_splatMapC.png", 0, TextureImporterFormat.ARGB32, true, false, true);
							} else {
								EditorUtility.DisplayDialog("?", "Can't get height texture...","OK");
							}
						}								
					}
					#endregion Control maps - splats					
					EditorGUILayout.EndVertical();
					break;
				}		
				
				#endregion Control maps
			}
			
			//_target.show_heightmaps=EditorGUILayout.Foldout(_target.show_heightmaps, "Height maps (combined)");
			if (_target.show_derivedmaps) {
				#region Derived textures
				Color skin_color;
				toolbarStrings = new string[4]{"Atlasing", "Height maps", "Normal maps", "Special"};
				GUILayout.Space(6);
				EditorGUILayout.BeginHorizontal();
				GUILayout.FlexibleSpace();
				_target.submenu_derived_textures=(ReliefTerrainDerivedTexturesItems)(GUILayout.Toolbar((int)_target.submenu_derived_textures, toolbarStrings, EditorStyles.miniButton, GUILayout.MaxWidth(370)));
				GUILayout.FlexibleSpace();
				EditorGUILayout.EndHorizontal();
				GUILayout.Space(6);
				EditorGUILayout.HelpBox("Combined texures are what actually feeds shader. They're intended to be reused on multiple terrain tiles. You can also reuse them across scenes.",MessageType.Warning, true);
				switch(_target.submenu_derived_textures) {
				case ReliefTerrainDerivedTexturesItems.Atlasing:
					#region Derived textures - Atlasing features
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Color atlases", EditorStyles.boldLabel);
					GUI.color=skin_color;
					
					EditorGUI.BeginDisabledGroup( (!atlasA_needed) && (!atlasB_needed) && (!atlasC_needed) );
					if (GUILayout.Button("Prepare atlases from detail textures (may take a while)")) {
						if (atlasA_needed) PrepareAtlases(0);
						if (atlasB_needed) PrepareAtlases(1);
						if (atlasC_needed) PrepareAtlases(2);
						_target.Refresh(null, _targetRT);
					}
					EditorGUI.EndDisabledGroup();
					
					EditorGUILayout.BeginHorizontal();
					if (_target.numLayers>0) {
						EditorGUI.BeginDisabledGroup( !atlasA_needed );
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Layers 0-3", GUILayout.Width(100));
						Texture2D oRef=_target.splat_atlases[0];
						if (checkChange(ref _target.splat_atlases[0], (Texture2D)EditorGUILayout.ObjectField( _target.splat_atlases[0], typeof(Texture2D), false, GUILayout.Height(100), GUILayout.Width(100)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						if (SaveTexture(ref _target.splat_atlases[0], ref _target.save_path_atlasA, "atlas_texture_layers_0_to_3.png", 100, TextureImporterFormat.AutomaticCompressed, true)) {
							string path=AssetDatabase.GetAssetPath(_target.splat_atlases[0]);
							TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
							textureImporter.wrapMode = TextureWrapMode.Clamp;
							textureImporter.filterMode = FilterMode.Trilinear;
							AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
						}
						EditorGUILayout.EndVertical();
						EditorGUI.EndDisabledGroup();
					}
					
					if (_target.numLayers>4) {
						EditorGUI.BeginDisabledGroup( !atlasB_needed );
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Layers 4-7", GUILayout.Width(100));
						Texture2D oRef=_target.splat_atlases[1];
						if (checkChange(ref _target.splat_atlases[1], (Texture2D)EditorGUILayout.ObjectField( _target.splat_atlases[1], typeof(Texture2D), false, GUILayout.Height(100), GUILayout.Width(100)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						if (SaveTexture(ref _target.splat_atlases[1], ref _target.save_path_atlasB, "atlas_texture_layers_4_to_7.png", 100, TextureImporterFormat.AutomaticCompressed, true)) {
							_target.splat_atlases[1].wrapMode=TextureWrapMode.Clamp;
							_target.splat_atlases[1].filterMode=FilterMode.Trilinear;
						}
						EditorGUILayout.EndVertical();
						EditorGUI.EndDisabledGroup();
					}
					
					EditorGUILayout.EndHorizontal();		
					
					if (_target.numLayers>8) {
						EditorGUI.BeginDisabledGroup( !atlasC_needed );
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Layers 9-11", GUILayout.Width(100));
						Texture2D oRef=_target.splat_atlases[2];
						if (checkChange(ref _target.splat_atlases[2], (Texture2D)EditorGUILayout.ObjectField( _target.splat_atlases[2], typeof(Texture2D), false, GUILayout.Height(100), GUILayout.Width(100)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						if (SaveTexture(ref _target.splat_atlases[2], ref _target.save_path_atlasC, "atlas_texture_layers_8_to_11.png", 100, TextureImporterFormat.AutomaticCompressed, true)) {
							_target.splat_atlases[2].wrapMode=TextureWrapMode.Clamp;
							_target.splat_atlases[2].filterMode=FilterMode.Trilinear;
						}
						EditorGUILayout.EndVertical();
						EditorGUI.EndDisabledGroup();
					}
					
					EditorGUILayout.EndVertical();
					#endregion Derived textures - Atlasing features		
					break;
				case ReliefTerrainDerivedTexturesItems.Heightmaps:
					#region Derived textures - Heightmaps
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Combined heightmaps", EditorStyles.boldLabel);
					GUI.color=skin_color;
					
					EditorGUILayout.HelpBox("If you specified heightmaps for your layers you don't have to do anything while editing (heightmaps are refreshed as you modify any of separate heightmap). However, you might need to specify combined heightmaps by hand, so you can do it here (don't touch particular heightmaps in a layer properties then).",MessageType.None, true);
					EditorGUILayout.HelpBox("Every channel of height textures below stores heightmap for consecutive detail map (splats 0-3 -> heightmap channels RGBA). To generate such channel combined heightmaps you can also use attached tool (Window / Relief Tools / 4 to 1 texture channels mixer).",MessageType.None, true);
					
					EditorGUILayout.BeginHorizontal();
					
					if (_target.numLayers>0) {
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Heights 0-3", GUILayout.Width(80));
						Texture2D oRef=_target.HeightMap;
						if (checkChange(ref _target.HeightMap, (Texture2D)EditorGUILayout.ObjectField( _target.HeightMap, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						SaveTexture(ref _target.HeightMap, ref _target.save_path_HeightMap, "heightmap_layers_0_to_3.png", 80, TextureImporterFormat.AutomaticCompressed, true,true,true);
						EditorGUILayout.EndVertical();
					}
					
					if (_target.numLayers>4) {
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Heights 4-7", GUILayout.Width(80));
						Texture2D oRef=_target.HeightMap2;
						if (checkChange(ref _target.HeightMap2, (Texture2D)EditorGUILayout.ObjectField( _target.HeightMap2, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						SaveTexture(ref _target.HeightMap2, ref _target.save_path_HeightMap2, "heightmap_layers_4_to_7.png", 80, TextureImporterFormat.AutomaticCompressed, true,true,true);
						EditorGUILayout.EndVertical();
					}
					
					if (_target.numLayers>8) {
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Heights 8-12", GUILayout.Width(80));
						Texture2D oRef=_target.HeightMap3;
						if (checkChange(ref _target.HeightMap3, (Texture2D)EditorGUILayout.ObjectField( _target.HeightMap3, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						SaveTexture(ref _target.HeightMap3, ref _target.save_path_HeightMap3, "heightmap_layers_8_to_11.png", 80, TextureImporterFormat.AutomaticCompressed, true,true,true);
						EditorGUILayout.EndVertical();
					}
					
					EditorGUILayout.EndHorizontal();						
					
					EditorGUILayout.EndVertical();
					#endregion Derived textures - Heightmaps
					break;
				case ReliefTerrainDerivedTexturesItems.Bumpmaps:
					#region Derived textures - Bumpmaps
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Combined bumpmaps", EditorStyles.boldLabel);
					GUI.color=skin_color;
					
					EditorGUILayout.HelpBox("Each layer pair share the same normal texture (RG + BA).They're automatically composed/refreshed when you change bump map in a layer. However, you might need to specify combined bumpmaps by hand, so you can do it here (don't touch particular bumpmaps in a layer properties then).",MessageType.None, true);
					
					EditorGUILayout.BeginHorizontal();
					if (_target.numLayers>0) {
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Bumps 0+1", GUILayout.Width(80));
						Texture2D oRef=_target.Bump01;
						if (checkChange(ref _target.Bump01, (Texture2D)EditorGUILayout.ObjectField( _target.Bump01, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						SaveTexture(ref _target.Bump01, ref _target.save_path_Bump01, "bumpmap_layers01.png", 80, TextureImporterFormat.ARGB32, true,true,true);
						EditorGUILayout.EndVertical();
					}
					
					if (_target.numLayers>2) {
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Bumps 2+3", GUILayout.Width(80));
						Texture2D oRef=_target.Bump23;
						if (checkChange(ref _target.Bump23, (Texture2D)EditorGUILayout.ObjectField( _target.Bump23, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						SaveTexture(ref _target.Bump23, ref _target.save_path_Bump23, "bumpmap_layers23.png", 80, TextureImporterFormat.ARGB32, true,true,true);
						EditorGUILayout.EndVertical();
					}
					
					if (_target.numLayers>4) {
						EditorGUILayout.BeginVertical();
						EditorGUILayout.LabelField("Bumps 4+5", GUILayout.Width(80));
						Texture2D oRef=_target.Bump45;
						if (checkChange(ref _target.Bump45, (Texture2D)EditorGUILayout.ObjectField( _target.Bump45, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
							DestroyUnusedCombinedTexture(oRef);
						}
						SaveTexture(ref _target.Bump45, ref _target.save_path_Bump45, "bumpmap_layers45.png", 80, TextureImporterFormat.ARGB32, true,true,true);
						EditorGUILayout.EndVertical();
					}
					
					EditorGUILayout.EndHorizontal();
					GUILayout.Space(10);
					
					if (_target.numLayers>6) {
						EditorGUILayout.BeginHorizontal();
						if (_target.numLayers>6) {							
							EditorGUILayout.BeginVertical();
							EditorGUILayout.LabelField("Bumps 6+7", GUILayout.Width(80));
							Texture2D oRef=_target.Bump67;
							if (checkChange(ref _target.Bump67, (Texture2D)EditorGUILayout.ObjectField( _target.Bump67, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
								DestroyUnusedCombinedTexture(oRef);
							}
							SaveTexture(ref _target.Bump67, ref _target.save_path_Bump67, "bumpmap_layers67.png", 80, TextureImporterFormat.ARGB32, true,true,true);
							EditorGUILayout.EndVertical();
						}
						
						if (_target.numLayers>8) {
							EditorGUILayout.BeginVertical();
							EditorGUILayout.LabelField("Bumps 8+9", GUILayout.Width(80));
							Texture2D oRef=_target.Bump89;
							if (checkChange(ref _target.Bump89, (Texture2D)EditorGUILayout.ObjectField( _target.Bump89, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
								DestroyUnusedCombinedTexture(oRef);
							}
							SaveTexture(ref _target.Bump89, ref _target.save_path_Bump89, "bumpmap_layers89.png", 80, TextureImporterFormat.ARGB32, true,true,true);
							EditorGUILayout.EndVertical();
						}
						
						if (_target.numLayers>10) {
							EditorGUILayout.BeginVertical();
							EditorGUILayout.LabelField("Bumps 10+11", GUILayout.Width(80));
							Texture2D oRef=_target.BumpAB;
							if (checkChange(ref _target.BumpAB, (Texture2D)EditorGUILayout.ObjectField( _target.BumpAB, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)))) {
								DestroyUnusedCombinedTexture(oRef);
							}
							SaveTexture(ref _target.BumpAB, ref _target.save_path_BumpAB, "bumpmap_layersAB.png", 80, TextureImporterFormat.ARGB32, true,true,true);
							EditorGUILayout.EndVertical();
						}
						
						EditorGUILayout.EndHorizontal();
						GUILayout.Space(10);
					}
					
					EditorGUILayout.EndVertical();
					#endregion Derived textures - Bumpmaps
					break;						
				case ReliefTerrainDerivedTexturesItems.Globalnormal:
					#region Derived textures - Global normal
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Perlin normal + superdetail / water&reflection", EditorStyles.boldLabel);
					GUI.color=skin_color;
					
					EditorGUILayout.HelpBox("Texture below use perlin normal map specified on channels RG.\n\nChannels BA are used for superdetail additional channels or (mutually exclusive) wet mask (B) and reflection map (A).",MessageType.None, true);
					
					//EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Texture", GUILayout.Width(80));
					bool sync_tex=false;
					Texture2D oRef2=_targetRT.BumpGlobalCombined;
					if (checkChange(ref _targetRT.BumpGlobalCombined, (Texture2D)EditorGUILayout.ObjectField( _targetRT.BumpGlobalCombined, typeof(Texture2D), false, GUILayout.Height(100), GUILayout.Width(100)))) {
						DestroyUnusedCombinedTexture(oRef2);
						sync_tex=true;
					}
					GUI.color=new Color(0.5f,1,0.5f,1);
					if (SaveTexture(ref _targetRT.BumpGlobalCombined, ref _targetRT.save_path_BumpGlobalCombined, "perlin_normal_aux.png", 100, TextureImporterFormat.AutomaticCompressed, true,true,true)) sync_tex=true;
					GUI.color=skin_color;
					if (sync_tex) {
						RTP_LODmanager manager=_target.Get_RTP_LODmanagerScript();
						if (manager && !manager.RTP_WETNESS_FIRST && !manager.RTP_WETNESS_ADD) {
							ReliefTerrain[] objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
							for(int i=0; i<objs.Length; i++) {
								objs[i].BumpGlobalCombined=_targetRT.BumpGlobalCombined;
								objs[i].globalCombinedModifed_flag=false;
							}
						}
						_targetRT.globalCombinedModifed_flag=false;
					}
					//EditorGUILayout.EndVertical();
					
					EditorGUILayout.EndVertical();
					#endregion Derived textures - Global normal
					break;						
				} // derived textures submenu switch
				#endregion Derived textures
			}
			
			if (_target.show_settings) {
				#region ALLSettings
				GUIContent[] toolbarIcons1 = new GUIContent[5]{ new GUIContent("Main", icoLayersSmall ), new GUIContent("UV blend", icoUVBlend), new GUIContent("Global\nmaps", icoGlobalcolor), new GUIContent("Perlin\nnormal", icoPerlinNormal), new GUIContent("S. detail", icoSuperdetail) };
				GUIContent[] toolbarIcons2 = new GUIContent[5]{ new GUIContent("Parallax", icoPOM ), new GUIContent("Vertical\ntexture", icoVerticalTexture), new GUIContent("Snow", icoSnow), new GUIContent("Water &\ncaustic", icoWater), new GUIContent("Reflection", icoReflection) };
				ReliefTerrainSettingsItems prev_submenu_settings=_target.submenu_settings;
				GUILayout.Space(10);
				EditorGUILayout.BeginHorizontal();
				GUILayout.FlexibleSpace();
				_target.submenu_settings=(ReliefTerrainSettingsItems)(GUILayout.Toolbar((int)_target.submenu_settings, toolbarIcons1, EditorStyles.miniButton, GUILayout.MaxWidth(370)));
				GUILayout.FlexibleSpace();
				EditorGUILayout.EndHorizontal();
				GUILayout.Space(5);
				EditorGUILayout.BeginHorizontal();
				GUILayout.FlexibleSpace();
				_target.submenu_settings=(ReliefTerrainSettingsItems)(GUILayout.Toolbar((int)_target.submenu_settings-5, toolbarIcons2, EditorStyles.miniButton, GUILayout.MaxWidth(370))+5);
				GUILayout.FlexibleSpace();
				EditorGUILayout.EndHorizontal();
				GUILayout.Space(10);
				
				if (prev_submenu_settings!=_target.submenu_settings && _target.paint_flag) {
					_target.paint_flag=false;
					UnityEditor.Tools.current=prev_tool;
					SceneView.onSceneGUIDelegate -= ReliefTerrain._SceneGUI;
					EditorUtility.SetDirty(target);
				}
				
				Color skin_color;
				switch(_target.submenu_settings) {
				case ReliefTerrainSettingsItems.MainSettings:
					#region Settings	 - main settings
					
					GUILayout.Space(6);
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoLayers),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Main settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					EditorGUILayout.HelpBox("For performance reasons shader uses the same tiling for every detail map.",MessageType.None, true);
					if (RTP_INDEPENDENT_TILING) {
						EditorGUILayout.HelpBox("You've got enabled independent tiling for every terrain object",MessageType.Warning, true);
						checkChange(ref _targetRT.customTiling.x, EditorGUILayout.FloatField("Tile Size X [m]", _targetRT.customTiling.x));
						checkChange(ref _targetRT.customTiling.y, EditorGUILayout.FloatField("Tile Size Y [m]", _targetRT.customTiling.y));
					} else {
						checkChange(ref _target.ReliefTransform.x, EditorGUILayout.FloatField("Tile Size X [m]", _target.ReliefTransform.x));
//						EditorGUILayout.BeginHorizontal();
//						checkChange(ref _target.ReliefTransform.x, _target.terrainTileSizeX/EditorGUILayout.FloatField("Tile Size X [m] ("+(Mathf.Round(_target.ReliefTransform.x*100)/100)+")", _target.terrainTileSizeX/_target.ReliefTransform.x));
//						if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
//							float ratio=_target.ReliefTransform.x/_target.ReliefTransform.y;
//							_target.ReliefTransform.x=Mathf.Round(_target.ReliefTransform.x);
//							_target.ReliefTransform.y=_target.ReliefTransform.x/ratio;
//							_target.ReliefTransform.y=Mathf.Round(_target.ReliefTransform.y);
//							_target.RefreshAll();
//						}
//						EditorGUILayout.EndHorizontal();

						checkChange(ref _target.ReliefTransform.y, EditorGUILayout.FloatField("Tile Size Y [m]", _target.ReliefTransform.y));
//						EditorGUILayout.BeginHorizontal();					
//						checkChange(ref _target.ReliefTransform.y, _target.terrainTileSizeZ/EditorGUILayout.FloatField("Tile Size Y [m] ("+(Mathf.Round(_target.ReliefTransform.y*100)/100)+")", _target.terrainTileSizeZ/_target.ReliefTransform.y));
//						if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
//							float ratio=_target.ReliefTransform.x/_target.ReliefTransform.y;
//							_target.ReliefTransform.y=Mathf.Round(_target.ReliefTransform.y);
//							_target.ReliefTransform.x=_target.ReliefTransform.y*ratio;
//							_target.ReliefTransform.x=Mathf.Round(_target.ReliefTransform.x);
//							_target.RefreshAll();
//						}
//						EditorGUILayout.EndHorizontal();
						float tile_sizex=_target.ReliefTransform.x;
						float tile_sizey=_target.ReliefTransform.y;
						checkChange(ref _target.ReliefTransform.z, EditorGUILayout.FloatField("Tile Offset X [m]", _target.ReliefTransform.z*tile_sizex)/tile_sizex);
						checkChange(ref _target.ReliefTransform.w, EditorGUILayout.FloatField("Tile Offset Y [m]", _target.ReliefTransform.w*tile_sizey)/tile_sizey);
//						float tile_sizex=_target.terrainTileSizeX/_target.ReliefTransform.x;
//						float tile_sizey=_target.terrainTileSizeZ/_target.ReliefTransform.y;
//						checkChange(ref _target.ReliefTransform.z, EditorGUILayout.FloatField("Tile Offset X [m]", _target.ReliefTransform.z*tile_sizex)/tile_sizex);
//						checkChange(ref _target.ReliefTransform.w, EditorGUILayout.FloatField("Tile Offset Y [m]", _target.ReliefTransform.w*tile_sizey)/tile_sizey);
					}
					
					EditorGUILayout.Space();	
					
					EditorGUILayout.LabelField("Near distance values");
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("", GUILayout.MaxWidth(10));
					EditorGUILayout.BeginVertical();
					#if !UNITY_3_5
					float prev_distance_start=_target.distance_start;
					float prev_distance_transition=_target.distance_transition;
					#endif
					checkChange(ref _target.distance_start, EditorGUILayout.Slider("Distance start", _target.distance_start, 0, 50));
					if (_target.distance_start_bumpglobal<_target.distance_start) _target.distance_start_bumpglobal=_target.distance_start;
					checkChange(ref _target.distance_transition, EditorGUILayout.Slider("Fade length", _target.distance_transition, 0, 50));
					#if !UNITY_3_5
					if (_target.useTerrainMaterial) {
						if (prev_distance_start!=_target.distance_start || prev_distance_transition!=_target.distance_transition) {
							Terrain[] terrainComps=(Terrain[])GameObject.FindObjectsOfType(typeof(Terrain));
							for(int ter=0; ter<terrainComps.Length; ter++) {
								// U5
								#if UNITY_5_0
									terrainComps[ter].basemapDistance=0;
								#else
									if (_target.super_simple_active) {
										terrainComps[ter].basemapDistance=_target.distance_start_bumpglobal+_target.distance_transition_bumpglobal;
									} else {
										terrainComps[ter].basemapDistance=_target.distance_start+_target.distance_transition;
									}
								#endif
							}
						}
					}
					#endif
					
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndHorizontal();
					
					EditorGUILayout.Space();	
					EditorGUILayout.HelpBox("Note that some texture lookups are MIP bias independent (use regular tex2D call)",MessageType.None, true);
					checkChange(ref _target.RTP_MIP_BIAS, EditorGUILayout.Slider("MIP level bias", _target.RTP_MIP_BIAS, -0.75f, 0.75f));
					EditorGUILayout.EndVertical();
					
					EditorGUILayout.Space();
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Shading color adjustements", EditorStyles.boldLabel);
					GUI.color=skin_color;
					EditorGUILayout.BeginVertical("Box");
					checkChange(ref _target._SpecColor, EditorGUILayout.ColorField("Specular Color", _target._SpecColor));
					checkChange(ref _target.rtp_customAmbientCorrection	, EditorGUILayout.ColorField("Ambient correction", _target.rtp_customAmbientCorrection));
					checkChange(ref _target.MasterLayerBrightness, EditorGUILayout.Slider("Layers detail brightness", _target.MasterLayerBrightness,0,2));
					checkChange(ref _target.MasterLayerSaturation, EditorGUILayout.Slider("Layers detail saturation", _target.MasterLayerSaturation,0,2));
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Gloss for deferred AddPass", GUILayout.MinWidth(165), GUILayout.MaxWidth(165));
						checkChange(ref _target.RTP_DeferredAddPassSpec, EditorGUILayout.Slider(_target.RTP_DeferredAddPassSpec,0,1));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
					
					if (RTP_IBL_DIFFUSE_FIRST || RTP_IBL_DIFFUSE_ADD || RTP_IBL_SPEC_FIRST || RTP_IBL_SPEC_ADD || REFLECTION_ENABLED_FIRST || REFLECTION_ENABLED_ADD) {
						EditorGUILayout.Space();
						GUI.color=new Color(1,1,0.5f,1);						
						EditorGUILayout.LabelField("IBL / Reflections", EditorStyles.boldLabel);
						GUI.color=skin_color;
						EditorGUILayout.BeginVertical("Box");
						EditorGUILayout.HelpBox("AO damp below means AO that comes from POM self-shadowing or baked shadows map (alpha channel of ambient emissive or pixeltrees texture).",MessageType.None, true);
						if (RTP_IBL_DIFFUSE_FIRST || RTP_IBL_DIFFUSE_ADD) {
							checkChange(ref _target.TERRAIN_IBL_DiffAO_Damp, EditorGUILayout.Slider("Diffuse IBL AO damp", _target.TERRAIN_IBL_DiffAO_Damp,0,1));
						}
						if (RTP_IBL_SPEC_FIRST || RTP_IBL_SPEC_ADD || REFLECTION_ENABLED_FIRST || REFLECTION_ENABLED_ADD) {
							checkChange(ref _target.TERRAIN_IBLRefl_SpecAO_Damp, EditorGUILayout.Slider("Spec IBL / Refl AO damp", _target.TERRAIN_IBLRefl_SpecAO_Damp,0,1));
						}
						if (!RTP_SKYSHOP_SYNC && (RTP_IBL_DIFFUSE_FIRST || RTP_IBL_DIFFUSE_ADD || RTP_IBL_SPEC_FIRST || RTP_IBL_SPEC_ADD)) {
							EditorGUILayout.BeginHorizontal();
							#if UNITY_5
							// we don't use cubemap in Unity5 (SH instead)
							EditorGUI.BeginDisabledGroup(true);
							#endif
							if (RTP_IBL_DIFFUSE_FIRST || RTP_IBL_DIFFUSE_ADD) {
								EditorGUILayout.BeginVertical();
								EditorGUILayout.LabelField("IBL diffuse map", EditorStyles.boldLabel, GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
								checkChange(ref _target._CubemapDiff, (Cubemap)EditorGUILayout.ObjectField(_target._CubemapDiff, typeof(Cubemap), false, GUILayout.MinHeight(120), GUILayout.MinWidth(120), GUILayout.MaxWidth(120)));
								EditorGUILayout.EndVertical();
							}
							#if UNITY_5
							EditorGUI.EndDisabledGroup();
							#endif
							if (RTP_IBL_SPEC_FIRST || RTP_IBL_SPEC_ADD) {
								EditorGUILayout.BeginVertical();
								EditorGUILayout.LabelField("IBL specular map", EditorStyles.boldLabel, GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
								checkChange(ref _target._CubemapSpec, (Cubemap)EditorGUILayout.ObjectField(_target._CubemapSpec, typeof(Cubemap), false, GUILayout.MinHeight(120), GUILayout.MinWidth(120), GUILayout.MaxWidth(120)));
								EditorGUILayout.EndVertical();
							}
							EditorGUILayout.EndHorizontal();
						}
						
						EditorGUILayout.EndVertical();
					}
					
					{
						EditorGUILayout.Space();	
						GUI.color=new Color(1,1,0.5f,1);						
						EditorGUILayout.LabelField("Global complementary ambience lighting "+(RTP_COMPLEMENTARY_LIGHTS?"":"(disabled for terrains)"), EditorStyles.boldLabel);
						GUI.color=skin_color;
						
						EditorGUILayout.BeginVertical("Box");
						EditorGUILayout.HelpBox("Features below works only in forward rendering path and directional lights.",MessageType.Info, true);
						
						checkChange(ref _target.RTP_LightDefVector.y, EditorGUILayout.Slider("Reflex diffuse softness", _target.RTP_LightDefVector.y,0,0.7f));
						checkChange(ref _target.RTP_ReflexLightDiffuseColor, EditorGUILayout.ColorField("Reflex light diffuse 1", _target.RTP_ReflexLightDiffuseColor));
						checkChange(ref _target.RTP_ReflexLightDiffuseColor.a, EditorGUILayout.Slider("      strength", _target.RTP_ReflexLightDiffuseColor.a,0,1));
						checkChange(ref _target.RTP_ReflexLightDiffuseColor2, EditorGUILayout.ColorField("Reflex light diffuse 2", _target.RTP_ReflexLightDiffuseColor2));
						checkChange(ref _target.RTP_ReflexLightDiffuseColor2.a, EditorGUILayout.Slider("      strength", _target.RTP_ReflexLightDiffuseColor2.a,0,1));
						EditorGUILayout.Space();
						if(RTP_SPEC_COMPLEMENTARY_LIGHTS) {
							//checkChange(ref _target.RTP_LightDefVector.z, EditorGUILayout.Slider("Reflex Specular Softness", _target.RTP_LightDefVector.z,0,1));
							checkChange(ref _target.RTP_LightDefVector.w, EditorGUILayout.Slider("Reflex specularity", _target.RTP_LightDefVector.w,2,40));
							checkChange(ref _target.RTP_ReflexLightSpecColor, EditorGUILayout.ColorField("Reflex light specular", _target.RTP_ReflexLightSpecColor));
							checkChange(ref _target.RTP_ReflexLightSpecColor.a, EditorGUILayout.Slider("Specular strength", _target.RTP_ReflexLightSpecColor.a,0,1));
						}
						checkChange(ref _target.RTP_LightDefVector.x, EditorGUILayout.Slider("Negative light power", _target.RTP_LightDefVector.x,0,1f));
						EditorGUILayout.EndVertical();
					}
					
					bool showLightmapShading=false;
					#if UNITY_5
					if (terrainComp) {
						if ((terrainComp.lightmapIndex!=65535) && (terrainComp.lightmapIndex!=65534) && LightmapSettings.lightmapsMode==LightmapsMode.NonDirectional) {
							showLightmapShading=true;
						}
					} else {
						if ((_targetRT.GetComponent<Renderer>().lightmapIndex!=65535) && (_targetRT.GetComponent<Renderer>().lightmapIndex!=65534) && LightmapSettings.lightmapsMode!=LightmapsMode.NonDirectional) {
							showLightmapShading=true;
						}
					}
					#else
					if (terrainComp) {
						if ((terrainComp.lightmapIndex!=255) && (terrainComp.lightmapIndex!=-1) && LightmapSettings.lightmapsMode!=LightmapsMode.Directional) {
							showLightmapShading=true;
						}
					} else {
						if ((_targetRT.GetComponent<Renderer>().lightmapIndex!=255) && (_targetRT.GetComponent<Renderer>().lightmapIndex!=-1) && LightmapSettings.lightmapsMode!=LightmapsMode.Directional) {
							showLightmapShading=true;
						}
					}
					#endif
					if (showLightmapShading) {
						EditorGUILayout.Space();	
						EditorGUILayout.BeginVertical("Box");
						EditorGUILayout.HelpBox("Helpful when lightmapping in single mode. Shader can mimic diffuse lighting with normal maps used. In dual lightmap mode (deferred) this is applied only beyond near distance, so you need to sync its values with realtime shadows distance/fade.",MessageType.None, true);
						checkChange(ref _target.LightmapShading, EditorGUILayout.Slider("Shading strength for lightmaps", _target.LightmapShading, 0, 2));
						EditorGUILayout.EndVertical();
					}
					
					if ( RTP_HEIGHTBLEND_AO_FIRST || RTP_HEIGHTBLEND_AO_ADD ) {
						EditorGUILayout.Space();	
						GUI.color=new Color(1,1,0.5f,1);						
						EditorGUILayout.LabelField("Heightblend AO", EditorStyles.boldLabel);
						GUI.color=skin_color;
						EditorGUILayout.BeginVertical("Box");
						checkChange(ref _target.RTP_AOsharpness, EditorGUILayout.Slider("Fake AO 2 HB sharpness", _target.RTP_AOsharpness, 0,10));
						checkChange(ref _target.RTP_AOamp, EditorGUILayout.Slider("Fake AO 2 HB value", _target.RTP_AOamp, 0,2));
						EditorGUILayout.EndVertical();
					}
					if ( (RTP_HEIGHTBLEND_AO_FIRST && RTP_HOTAIR_EMISSION_FIRST) || (RTP_HEIGHTBLEND_AO_ADD && RTP_HOTAIR_EMISSION_ADD) ) {
						EditorGUILayout.Space();	
						GUI.color=new Color(1,1,0.5f,1);						
						EditorGUILayout.LabelField("Hot air refraction on emissive layers", EditorStyles.boldLabel);
						GUI.color=skin_color;
						EditorGUILayout.BeginVertical("Box");
						checkChange(ref _target.EmissionRefractFiltering, EditorGUILayout.Slider("Refraction filtering", _target.EmissionRefractFiltering, 0,8));
						checkChange(ref _target.EmissionRefractAnimSpeed, EditorGUILayout.Slider("Refraction anim speed", _target.EmissionRefractAnimSpeed, 0,20) );
						EditorGUILayout.EndVertical();
					}
					
					// presets
					EditorGUILayout.Space();	
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Presets", EditorStyles.boldLabel);
					GUI.color=skin_color;					
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.HelpBox("Here you can save / restore object state in preset. You can also use use function InterpolatePresets(PresetID1, PresetID2, float t) via script to blend between numeric settings of 2 presets.",MessageType.Info, true);
					if (_targetRT.presetHolders!=null) {
						for(int k=0; k<_targetRT.presetHolders.Length; k++) {
							EditorGUILayout.BeginHorizontal();
							ReliefTerrainPresetHolder[] holders=null;
							
							if (_targetRT.presetHolders[k]!=null) {
								if (GUILayout.Button("restore", GUILayout.Width(60))) {
									if (EditorUtility.DisplayDialog("Warning", "Restore to preset "+_targetRT.presetHolders[k].PresetName+" state ?","Yes","Cancel")) {
										#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
										Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
										#else
										Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
										#endif
										_targetRT.RestorePreset(_targetRT.presetHolders[k]);
										_targetRT.RefreshTextures();				
										_target.Refresh(null, _targetRT);									
										EditorUtility.SetDirty(_targetRT);
									}
								}
								GUI.color=new Color(1,0.4f,0.2f,1);
								if (GUILayout.Button("del", GUILayout.Width(35))) {
									if (EditorUtility.DisplayDialog("Warning", "Remove preset "+_targetRT.presetHolders[k].PresetName+" ?","Yes","Cancel")) {
										#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
										Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
										#else
										Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
										#endif
										holders=new ReliefTerrainPresetHolder[_targetRT.presetHolders.Length-1];
										int l=0;
										for(int r=0; r<_targetRT.presetHolders.Length; r++) {
											if (r!=k) {
												holders[l++]=_targetRT.presetHolders[r];
											}
										}
										_targetRT.presetHolders=holders;
										break;
									}
								}
								GUI.color=new Color(0.5f, 1, 0.5f, 1);
								if (GUILayout.Button("save", GUILayout.Width(45))) {
									string path = EditorUtility.SaveFilePanel("Save preset", "Assets", "RTPpreset", "asset");
									if (path!="") {	
										int idx=path.IndexOf("/Assets/")+1;
										if (idx>0) {
											path=path.Substring(idx);
											ReliefTerrainPresetHolder savedPreset=UnityEngine.Object.Instantiate(_targetRT.presetHolders[k]) as ReliefTerrainPresetHolder;
											Debug.Log("RTP "+_targetRT.presetHolders[k].name+" preset saved at "+path);
											if (AssetDatabase.LoadAssetAtPath(path, typeof(ReliefTerrainPresetHolder))!=null) AssetDatabase.DeleteAsset(path);
											AssetDatabase.CreateAsset(savedPreset, path);
											//_targetRT.presetHolders[k].CheckUnsavedTextures();
										} else {
											Debug.Log ("Nothing saved...");
										}
									}
								}
								GUI.color=skin_color;
								EditorGUILayout.LabelField("Preset " +k+": ", GUILayout.Width(60));
								EditorGUILayout.LabelField(_targetRT.presetHolders[k].PresetName, EditorStyles.boldLabel);
								
								if (holders!=null) {
									_targetRT.presetHolders=holders;
								}
							}
							EditorGUILayout.EndHorizontal();
						}
					}
					EditorGUI.BeginDisabledGroup(_targetRT.presetHolders!=null && _targetRT.presetHolders.Length==8);
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("New preset name: ", GUILayout.Width(120));	
					_target.newPresetName=EditorGUILayout.TextField(_target.newPresetName);
					if (GUILayout.Button("+ Add new preset")) {
						#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
						Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
						#else
						Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
						#endif
						ReliefTerrainPresetHolder[] holders;
						int k=0;
						if (_targetRT.presetHolders!=null) {
							holders=new ReliefTerrainPresetHolder[_targetRT.presetHolders.Length+1];
							for(; k<_targetRT.presetHolders.Length; k++) {
								holders[k]=_targetRT.presetHolders[k];
							}
						} else {
							holders=new ReliefTerrainPresetHolder[1];
						}
						holders[k]=ScriptableObject.CreateInstance(typeof(ReliefTerrainPresetHolder)) as ReliefTerrainPresetHolder;
						holders[k].Init(_target.newPresetName);
						_targetRT.SavePreset(ref holders[k]);
						holders[k].type = (terrainComp!=null) ? "TERRAIN" : "MESH";
						_targetRT.presetHolders=holders;
					}
					EditorGUILayout.EndHorizontal();
					if (GUILayout.Button("Load & restore saved preset")) {
						string path = EditorUtility.OpenFilePanel("Load preset", "Assets", "asset");
						if (path!="") {
							int idx=path.IndexOf("/Assets/")+1;
							if (idx>0) {
								path=path.Substring(idx);
							}
							ReliefTerrainPresetHolder loadedPreset=AssetDatabase.LoadAssetAtPath(path, typeof(ReliefTerrainPresetHolder)) as ReliefTerrainPresetHolder;
							if (loadedPreset!=null) {
								if (loadedPreset.numLayers==_target.numLayers) {
									if ( (loadedPreset.type=="TERRAIN" && terrainComp!=null) || (loadedPreset.type=="MESH" && terrainComp==null) ) {
										// to not deal with assets on disk but only with instances in mem saved in scene
										ReliefTerrainPresetHolder loadedPresetCopy=UnityEngine.Object.Instantiate(loadedPreset) as ReliefTerrainPresetHolder;
										int dgres=EditorUtility.DisplayDialogComplex("RTP Notification", "What would you like to restore current terrain object specific textures, too ?", "Yes", "No, only globals", "Cancel");
										if (dgres!=2) {
											#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
											Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
											#else
											Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
											#endif
											if (dgres==0) {
												_targetRT.RestorePreset(loadedPresetCopy);
											} else {
												_target.RestorePreset(loadedPresetCopy);
											}
											_target.RefreshAll();
										}
									} else {
										EditorUtility.DisplayDialog("Error", "Mismatched type - you can't load RTP preset that has been taken from mesh when you're using terrain and vice versa.","OK");
									}
								} else {
									EditorUtility.DisplayDialog("Error", "Number of layers in preset being loaded ("+loadedPreset.numLayers+") and in current setup ("+_target.numLayers+") differs.","OK");
								}
							} else {
								EditorUtility.DisplayDialog("Error", "No RTP preset available at specified location.","OK");
							}
						}
					}					
					if (GUILayout.Button("Clear all presets")) {
						if (EditorUtility.DisplayDialog("Warning", "Remove all presets (can NOT be undone) ?","Yes","Cancel")) {
							_targetRT.presetHolders=null;
						}
					}					
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndVertical();						
					// EOF presets
					
					GUILayout.Space(10);
					
					{
						Color c=GUI.color;
						GUI.color=new Color(0.9f,1, 0.9f);
						if (GUILayout.Button(new GUIContent("Refresh all", "Refreshes all terrain object on the scene."), GUILayout.Height (40))) {
							_target.RefreshAll();
						}
						GUI.color=c;
					}
					if (GUILayout.Button(new GUIContent("Purge scene", ""), GUILayout.Height (40))) {
						EditorUtility.UnloadUnusedAssetsImmediate();
					}

					GUILayout.Space(15);							
					if (GUILayout.Button("Reset main settings numeric params to default")) {
						#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
						Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
						#else
						Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
						#endif
						_target.ReturnToDefaults("main");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh(null, _targetRT);
					}	
					
					#endregion Settings - main settings
					
					break;
					
				case ReliefTerrainSettingsItems.UVblend:
					
					#region Detail maps unfold - UV blend
					// UV blend on/off global properties
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoUVBlend),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("UV blending (tiling patterns reduction)", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					if (UV_BLEND_ENABLED_FIRST || UV_BLEND_ENABLED_ADD) {
						EditorGUILayout.HelpBox("UV blend feature can be helpful to remove tiling patterns at mid/far distance.\nIt blends detail maps with themselves using different tiling.\n\nPer layer settings can be found in \"Layers properties\" tab.",MessageType.None, true);
						checkChange(ref _target.blendMultiplier, EditorGUILayout.Slider("Mix Multiplier", _target.blendMultiplier, 0, 2));
						if (GUILayout.Button("Disable UV blend (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_UV_BLEND_FIRST=false;
							_RTP_LODmanagerScript.RTP_UV_BLEND_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
						
						GUILayout.Space(15);							
						if (GUILayout.Button("Reset uv blend settings numeric params to default")) {
							#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
							Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
							#else
							Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
							#endif
							_target.ReturnToDefaults("uvblend");
							EditorUtility.SetDirty(_targetRT);
							_target.Refresh(null, _targetRT);
						}								
					} else {
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable UV blend (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_UV_BLEND_FIRST=true;
							_RTP_LODmanagerScript.RTP_UV_BLEND_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
					}
					EditorGUILayout.EndVertical();
					
					#endregion Detail maps unfold - UV blend						
					break;
					
				case ReliefTerrainSettingsItems.POMSettings:
					#region Settings - POM
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoPOM),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Parallax (POM/PM) settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					//checkChange(ref _target.ExtrudeHeight, EditorGUILayout.Slider("POM/PM Extrude Height", _target.ExtrudeHeight*Mathf.Max(tile_sizex, tile_sizey), 0.001f, 0.3f)/Mathf.Max(tile_sizex, tile_sizey));
					checkChange(ref _target.ExtrudeHeight, EditorGUILayout.Slider("Extrude Height", _target.ExtrudeHeight, 0.001f, 0.3f));
					
					EditorGUILayout.LabelField("Color/position solver (used in POM only)");
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("", GUILayout.MaxWidth(10));
					EditorGUILayout.BeginVertical();				
					checkChange(ref _target.DIST_STEPS, EditorGUILayout.IntSlider("Max search steps", Mathf.FloorToInt(_target.DIST_STEPS), 4, 255));
					checkChange(ref _target.WAVELENGTH, EditorGUILayout.Slider("Step length (in texels)", _target.WAVELENGTH, 0.5f, 16));
					EditorGUILayout.EndVertical();				
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.LabelField("Self-shadow solver (used in POM only)");
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("", GUILayout.MaxWidth(10));
					EditorGUILayout.BeginVertical();
					EditorGUILayout.HelpBox("To turn off self-shadowing in shader use RTP_LODmanager script (attach it to any scene object).",MessageType.None, true);
					checkChange(ref _target.SHADOW_STEPS, EditorGUILayout.IntSlider("Max search steps", Mathf.FloorToInt(_target.SHADOW_STEPS), 0, 80));
					checkChange(ref _target.WAVELENGTH_SHADOWS, EditorGUILayout.Slider("Step length (in texels)", _target.WAVELENGTH_SHADOWS, 0.5f, 16));
					//checkChange(ref _target.SHADOW_SMOOTH_STEPS, EditorGUILayout.IntSlider("Max smoothing steps", Mathf.FloorToInt(_target.SHADOW_SMOOTH_STEPS), 3, 20));
					checkChange(ref _target.SelfShadowStrength, EditorGUILayout.Slider("Self-shadow strength", _target.SelfShadowStrength, 0.1f, 1));
					checkChange(ref _target.ShadowSmoothing, EditorGUILayout.Slider("Self-shadow smoothing", _target.ShadowSmoothing, 0f, 1));
					checkChange(ref _target.ShadowSoftnessFade, EditorGUILayout.Slider("Self-shadow softness fade", _target.ShadowSoftnessFade, 0.2f, 1.5f));
					EditorGUILayout.EndVertical();		
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset POM/PM settings numeric params to default")) {
						#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
						Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
						#else
						Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
						#endif
						_target.ReturnToDefaults("pom/pm");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh(null, _targetRT);
					}	
					
					#endregion Settings - POM
					break;
					
				case ReliefTerrainSettingsItems.GlobalColor:
					#region Settings - Global color
					_target.paint_wetmask=false;
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoGlobalcolor),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Global color settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					EditorGUILayout.HelpBox("Color is blended via multiplication (easy to find/change in shader code - look for #ifdef COLOR_MAP).\n\nALPHA channel is used to remove locally parallax effects - extrude height (necessary for seamless geometry blending or when objects on the surface seem to hover on at the surface due to high extrude height).\n\nIf you don't use ColorMap - set below blending values to zero (you may use Alpha8 compressing w/o RGB channels, but still need alpha for parallax removing at blend areas - terrain vs mesh).",MessageType.None, true);
					EditorGUILayout.HelpBox("Near / Mid blend is realised at Main settings / Near distance values\n\nFar blend is realised at Perlin normal settings / start&fade distances.\n\nMIP level adjustement allows to take any MIP level below far distance (blended).", MessageType.None, true);
					EditorGUILayout.HelpBox("Note that saturation on far distance might work different when shader doesn't use detail/splat colors there, but only global colormap (refer to LODmanager settings - \"No detail colors at far distance\").", MessageType.None, true);
					EditorGUILayout.BeginHorizontal();
					Texture2D prev_globalColor=_targetRT.ColorGlobal;
					checkChange(ref _targetRT.ColorGlobal, (Texture2D)EditorGUILayout.ObjectField(_targetRT.ColorGlobal, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					if (_targetRT.ColorGlobal && _targetRT.ColorGlobal!=prev_globalColor) {
						AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.ColorGlobal));
						if (_importer) {
							TextureImporter tex_importer=(TextureImporter)_importer;
							if (tex_importer) {
								tex_importer.wrapMode=TextureWrapMode.Clamp;
								AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.ColorGlobal),  ImportAssetOptions.ForceUpdate);
							}
						}					
						_targetRT.globalColorModifed_flag=false;
						_targetRT.tmp_globalColorMap=null;
						_targetRT.save_path_colormap=AssetDatabase.GetAssetPath(_targetRT.ColorGlobal);
						if (_targetRT.save_path_colormap=="") _targetRT.save_path_colormap="Assets/_output_colormap.png";
						_targetRT.RefreshTextures();
					}
					EditorGUILayout.BeginVertical();
					
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Near blend", GUILayout.MinWidth(80), GUILayout.MaxWidth(80));
					checkChange(ref _target.GlobalColorMapBlendValues.x, EditorGUILayout.Slider(_target.GlobalColorMapBlendValues.x, 0, 1));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Mid blend", GUILayout.MinWidth(80), GUILayout.MaxWidth(80));
					checkChange(ref _target.GlobalColorMapBlendValues.y, EditorGUILayout.Slider(_target.GlobalColorMapBlendValues.y, 0, 1));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Far blend", GUILayout.MinWidth(80), GUILayout.MaxWidth(80));
					checkChange(ref _target.GlobalColorMapBlendValues.z, EditorGUILayout.Slider(_target.GlobalColorMapBlendValues.z, 0, 1));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("MIP level below far", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target._GlobalColorMapNearMIP, EditorGUILayout.Slider(_target._GlobalColorMapNearMIP, 0, 10));
					EditorGUILayout.EndHorizontal();						
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Saturation near", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
					checkChange(ref _target.GlobalColorMapSaturation, EditorGUILayout.Slider(_target.GlobalColorMapSaturation, 0, 1));
					EditorGUILayout.EndHorizontal(); 
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Saturation far", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
					checkChange(ref _target.GlobalColorMapSaturationFar, EditorGUILayout.Slider(_target.GlobalColorMapSaturationFar, 0, 1));
					EditorGUILayout.EndHorizontal(); 
					if (!RTP_SUPER_SIMPLE || RTP_USE_PERLIN_ADD || RTP_USE_PERLIN_FIRST ) {
						//EditorGUILayout.BeginHorizontal();
						//EditorGUILayout.LabelField("   mod by perlin", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
						//checkChange(ref _target.GlobalColorMapSaturationByPerlin, EditorGUILayout.Slider(_target.GlobalColorMapSaturationByPerlin, 0, 1));
						//EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Distort by perlin", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
						checkChange(ref _target.GlobalColorMapDistortByPerlin, EditorGUILayout.Slider(_target.GlobalColorMapDistortByPerlin, 0, 0.02f));
						EditorGUILayout.EndHorizontal();
					}
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Brightness near", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
					checkChange(ref _target.GlobalColorMapBrightness, EditorGUILayout.Slider(_target.GlobalColorMapBrightness, 0.01f, 4));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Brightness far", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
					checkChange(ref _target.GlobalColorMapBrightnessFar, EditorGUILayout.Slider(_target.GlobalColorMapBrightnessFar, 0.01f, 4));
					EditorGUILayout.EndHorizontal();
					
					EditorGUILayout.Space();
					
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndHorizontal();
					
					if (_targetRT.ColorGlobal) {
						if (_targetRT.globalColorModifed_flag) {
							GUILayout.Space (8);
							GUI.color=new Color(0.5f,1,0.5f,1);
							if (GUILayout.Button("Colormap uncompressed & readable - save to file")) {
								string directory;
								string file;
								if (_targetRT.save_path_colormap=="") {
									directory=Application.dataPath;
									file="_output_colormap.png";
								} else {
									directory=Path.GetDirectoryName(_targetRT.save_path_colormap);
									file=Path.GetFileNameWithoutExtension(_targetRT.save_path_colormap)+".png";
								}
								string path = EditorUtility.SaveFilePanel("Save edited Global color map", directory, file, "png");
								if (path!="") {
									path=path.Substring(Application.dataPath.Length-6);
									_targetRT.save_path_colormap=path;
									byte[] bytes = _targetRT.ColorGlobal.EncodeToPNG();
									System.IO.File.WriteAllBytes(path, bytes);
									AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
									TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
									textureImporter.wrapMode=TextureWrapMode.Clamp; 
									AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
									_targetRT.ColorGlobal = (Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
									_targetRT.globalColorModifed_flag=false;
									_targetRT.tmp_globalColorMap=null;
								}										
							}
							GUI.color=skin_color;
							GUILayout.Space (4);
						}
					}
					
					
					Color[] avg_cols=new Color[_target.numLayers];
					for(int n=0; n<_target.numLayers; n++) {
						Color[] col=new Color[1] { Color.black };
						Texture2D tex=_target.splats[n];
						string path=AssetDatabase.GetAssetPath(tex);
						if (path!="") {
							AssetImporter _importer=AssetImporter.GetAtPath(path);
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Texture ("+tex.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex),  ImportAssetOptions.ForceUpdate);
								}
							}							
						}
						col=tex.GetPixels(tex.mipmapCount-1);
						col[0].a=1;
						avg_cols[n]=col[0];
					}						
					if (GUILayout.Button("Construct colormap from detail colors of layers (below)")) {
						if (_targetRT.controlA!=null) {
							Color[] colorMap;
							Color[] cols;
							int u;
							cols=_targetRT.controlA.GetPixels(0);
							colorMap=new Color[cols.Length];
							for(u=0; u<cols.Length; u++) {
								colorMap[u]=new Color(0,0,0,0);
							}
							for(int k=0; k<_target.numLayers; k++) {
								if (k==4) {
									cols=_targetRT.controlB.GetPixels(0);
								} else if (k==8) {
									cols=_targetRT.controlC.GetPixels(0);
								}
								if (cols!=null) {
									for(u=0; u<cols.Length; u++) {
										colorMap[u]+=cols[u][k%4]*avg_cols[k];
									}
								}
							}
							_targetRT.ColorGlobal=new Texture2D(_targetRT.controlA.width, _targetRT.controlA.height, TextureFormat.ARGB32, true);
							_targetRT.ColorGlobal.SetPixels(colorMap,0);
							_targetRT.ColorGlobal.Apply(true);
							_targetRT.ColorGlobal.wrapMode=TextureWrapMode.Clamp;
							_targetRT.globalColorModifed_flag=true;
						}
					}
					EditorGUILayout.BeginHorizontal();
					int thumb_size=32;
					for(int n=0; n<_target.numLayers; n++) {
						Color ccol = GUI.contentColor;
						GUI.contentColor=avg_cols[n];
						if (GUILayout.Button(_target.get_dumb_tex(), "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
							_target.paintColor=avg_cols[n];
						}
						GUI.contentColor = ccol;
					}
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.Space();						
					
					int copy_splat_idx=0;
					if ( _4LAYERS_SHADER_USED && (_target.numLayers>4) )  {
						copy_splat_idx=1;
					} else if ( (!_4LAYERS_SHADER_USED) && (_target.numLayers>8) ) {
						copy_splat_idx=2;
					}
					if (copy_splat_idx>0) {
						EditorGUILayout.Space();
						EditorGUILayout.HelpBox("Due to parallax effects to get better transitions between AddPass and FirstPass areas you need to cancel extrusion there.\n\nNote, that any height painting already done by either geometry blend or this script will be overwritten.",MessageType.Warning, true);
						if (GUILayout.Button("Overlap coverage to alpha (flatten overlapped areas)")) {
							colorAlphaFromSplat(copy_splat_idx);	
						}
					}
					
					EditorGUILayout.EndVertical();
					
					//
					// paint tools
					//
					GUILayout.Space(8);
					EditorGUILayout.BeginVertical("Box");		
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Paint tools", EditorStyles.boldLabel);
					GUI.color=skin_color;
					
					bool prev_paint_flag=_target.paint_flag;
					
					if (!_target.paint_flag) {
						Color c=GUI.color;
						GUI.color=new Color(0.9f,1, 0.9f);
						if (GUILayout.Button(new GUIContent("Begin painting (M)",icoPaintOn, "Click to turn on painting"))) {
							_target.paint_flag=true;
							_target.paint_wetmask=false;
							//							if (!_target.prepare_tmpTexture(true)) {
							//								_target.paint_flag=false;
							//							}
						}
						if (!_targetRT.GetComponent<Collider>() || !_targetRT.GetComponent<Collider>().enabled) _target.paint_flag=false;
						GUI.color=c;
					} else if (_target.paint_flag) {
						Color c=GUI.color;
						GUI.color=new Color(1,0.9f,0.9f);
						if (GUILayout.Button(new GUIContent("End painting (M)",icoPaintOff, "Click to turn off painting"))) {
							_target.paint_flag=false;
						}
						GUI.color=c;
					}
					if (!prev_paint_flag && _target.paint_flag) {
						UnityEditor.Tools.current=Tool.View;
						ReliefTerrain._SceneGUI = new SceneView.OnSceneFunc(CustomOnSceneGUI);
						SceneView.onSceneGUIDelegate += ReliefTerrain._SceneGUI;
					} else if (prev_paint_flag && !_target.paint_flag) {
						UnityEditor.Tools.current=prev_tool;
						SceneView.onSceneGUIDelegate -= ReliefTerrain._SceneGUI;
					}
					if (prev_paint_flag!=_target.paint_flag) EditorUtility.SetDirty(target);
					if (_target.paint_flag) {
						if (!_targetRT.GetComponent<Collider>() || !_targetRT.GetComponent<Collider>().enabled) EditorGUILayout.HelpBox("Object doesn't have collider (necessary for painting).",MessageType.Error, true);
						
						string[] modes;
						if (RTP_CUT_HOLES) {
							modes=new string[3] {"Color", "Extrude Height", "Cut holes"};
						} else {
							modes=new string[2] {"Color", "Extrude Height"};
							_target.cut_holes=false;
						}	
						int npaint_mode=GUILayout.SelectionGrid(_target.paint_alpha_flag ? (1+(_target.cut_holes ? 1:0)):0, modes, modes.Length);
						if ( npaint_mode != (_target.paint_alpha_flag ? (1+(_target.cut_holes ? 1:0)):0) ) {
							EditorUtility.SetDirty(target);
						}
						_target.paint_alpha_flag = (npaint_mode==0) ? false : true;
						_target.cut_holes = (npaint_mode==2);
						
						if (_target.paint_alpha_flag) {
							EditorGUILayout.HelpBox("Hold SHIFT while painting to apply eraser.",MessageType.Info, true);
						} else {
							EditorGUILayout.BeginVertical("Box");
							skin_color=GUI.color;
							GUI.color=new Color(1,1,0.5f,1);
							if (_target.paintColorSwatches!=null && _target.paintColorSwatches.Length>0) EditorGUILayout.LabelField("Color swatches", EditorStyles.boldLabel);
							GUI.color=skin_color;
							EditorGUILayout.BeginHorizontal();
							thumb_size=16;
							for(int n=0; _target.paintColorSwatches!=null && n<_target.paintColorSwatches.Length; n++) {
								Color ccol = GUI.contentColor;
								GUI.contentColor=_target.paintColorSwatches[n];
								if (GUILayout.Button(_target.get_dumb_tex(), "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
									_target.paintColor=_target.paintColorSwatches[n];
								}
								GUI.contentColor = ccol;
							}
							EditorGUILayout.EndHorizontal();								
							EditorGUILayout.BeginHorizontal();
							EditorGUI.BeginDisabledGroup(_target.paintColorSwatches==null || _target.paintColorSwatches.Length==12);
							if (GUILayout.Button("Add swatch")) {
								Color[] ns=new Color[_target.paintColorSwatches.Length+1];
								for(int k=0; k<_target.paintColorSwatches.Length; k++) ns[k]=_target.paintColorSwatches[k];
								ns[ns.Length-1]=new Color(_target.paintColor.r, _target.paintColor.g, _target.paintColor.b, 1);
								_target.paintColorSwatches=ns;
							}
							EditorGUI.EndDisabledGroup();
							EditorGUI.BeginDisabledGroup(_target.paintColorSwatches==null || _target.paintColorSwatches.Length==0);
							if (GUILayout.Button("Remove swatch")) {
								Color[] ns=new Color[_target.paintColorSwatches.Length-1];
								for(int k=0; k<ns.Length; k++) ns[k]=_target.paintColorSwatches[k];
								_target.paintColorSwatches=ns;
							}
							EditorGUI.EndDisabledGroup();
							EditorGUILayout.EndHorizontal();								
							
							_target.paintColor=EditorGUILayout.ColorField("Paint color", _target.paintColor);
							_target.preserveBrightness=EditorGUILayout.Toggle("Preserve luminosity", _target.preserveBrightness);
							EditorGUILayout.EndVertical();
						}
						
						Texture2D tmp_tex=_targetRT.tmp_globalColorMap;
						if (tmp_tex && (tmp_tex.format!=TextureFormat.Alpha8 && tmp_tex.format!=TextureFormat.ARGB32)) {
							EditorGUILayout.HelpBox("Global colormap need to be readable and uncompressed for painting.",MessageType.Error, true);
						}
						GUILayout.BeginHorizontal();
						GUILayout.Label ("Area size", EditorStyles.label );
						_target.paint_size = EditorGUILayout.Slider(_target.paint_size, 0.1f, 6);
						GUILayout.EndHorizontal();	
						GUILayout.BeginHorizontal();
						GUILayout.Label ("Area smoothness", EditorStyles.label );
						_target.paint_smoothness = EditorGUILayout.Slider (_target.paint_smoothness, 0.001f, 1);
						GUILayout.EndHorizontal();
						GUILayout.BeginHorizontal();
						GUILayout.Label ("Opacity", EditorStyles.label );
						_target.paint_opacity = EditorGUILayout.Slider (_target.paint_opacity, 0, 1);
						GUILayout.EndHorizontal();	
						GUILayout.Space(10);
					}
					EditorGUILayout.EndVertical();	
					
					GUILayout.Space(10);
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					GUI.color=new Color(1,1,0.5f,1);
					if (RTP_TESSELLATION) {
						EditorGUILayout.LabelField("Tessellation height & normal map settings", EditorStyles.boldLabel);
					} else {
						EditorGUILayout.LabelField("Global normal settings", EditorStyles.boldLabel);
					}
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;

					if (RTP_TESSELLATION) {

						EditorGUILayout.HelpBox("To get texture needed use attached tool -\nWindow/Relief Tools/Prepare Height&Normal Texture for Tessellation\nWhen tessellating terrain you can increase pixel error (to get low poly terrain mesh handled by Unity itself) while maintaining very detailed and pop-minimized look.",MessageType.None, true);
						if (!RTP_TESSELLATION_SAMPLE_TEXTURE) {
							_targetRT.NormalGlobal=null;
						}
						EditorGUILayout.BeginHorizontal();

							EditorGUI.BeginDisabledGroup(!RTP_TESSELLATION_SAMPLE_TEXTURE);
								if (checkChange(ref _targetRT.NormalGlobal, (Texture2D)EditorGUILayout.ObjectField(_targetRT.NormalGlobal, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)))) {
									AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.NormalGlobal));
									if (_importer) {
										TextureImporter tex_importer=(TextureImporter)_importer;
										if (tex_importer.textureFormat!=TextureImporterFormat.AutomaticTruecolor && tex_importer.textureFormat!=TextureImporterFormat.RGBA32 && tex_importer.textureFormat!=TextureImporterFormat.ARGB32) {
											Debug.LogWarning("Texture ("+_targetRT.NormalGlobal.name+") seems to be NOT compatible with RTP Height&normal format. Use attached tool to make the texture.");
										}
									}							
								}
							EditorGUI.EndDisabledGroup();

							EditorGUILayout.BeginVertical();
							
								EditorGUI.BeginDisabledGroup(!RTP_TESSELLATION_SAMPLE_TEXTURE);
									EditorGUILayout.BeginHorizontal();
									EditorGUILayout.LabelField("Normal strength", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
									checkChange(ref _target.global_normalMap_multiplier, EditorGUILayout.Slider(_target.global_normalMap_multiplier, 0f, 6f));
									EditorGUILayout.EndHorizontal();
								EditorGUI.EndDisabledGroup();
								EditorGUILayout.BeginHorizontal();
									EditorGUILayout.LabelField("Tess. substeps (close)", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
									if (checkChange(ref _target._TessSubdivisions, EditorGUILayout.Slider(_target._TessSubdivisions, 1f, 63f))) {
										_target._TessSubdivisions=Mathf.Floor((_target._TessSubdivisions-1)/2)*2+1;
									}
									EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();
									EditorGUILayout.LabelField("Tess. substeps (far)", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
									if (checkChange(ref _target._TessSubdivisionsFar, EditorGUILayout.Slider(_target._TessSubdivisionsFar, 1f, 63f))) {
										_target._TessSubdivisionsFar=Mathf.Floor((_target._TessSubdivisionsFar-1)/2)*2+1;
									}
								EditorGUILayout.EndHorizontal();
								EditorGUI.BeginDisabledGroup(RTP_TESSELLATION_SAMPLE_TEXTURE);
									if (RTP_TESSELLATION_SAMPLE_TEXTURE) _target._Phong=0;
									EditorGUILayout.BeginHorizontal();
									EditorGUILayout.LabelField("Phong smoothening", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
									checkChange(ref _target._Phong, EditorGUILayout.Slider(_target._Phong, 0f, 1f));
									EditorGUILayout.EndHorizontal();
								EditorGUI.EndDisabledGroup();

								Terrain terrain=_targetRT.gameObject.GetComponent<Terrain>();
								if (terrain!=null) {
									EditorGUILayout.BeginHorizontal();
									EditorGUILayout.LabelField("Terrain pixel error", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
									float nPixelError = EditorGUILayout.Slider(terrain.heightmapPixelError, 1f, 200f);
									if (terrain.heightmapPixelError!=nPixelError) {
										terrain.heightmapPixelError=nPixelError;
										ReliefTerrain[] rtp_objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
										for(int i=0; i<rtp_objs.Length; i++) {
											Terrain ter=rtp_objs[i].gameObject.GetComponent<Terrain>();
											if (ter) {
												ter.heightmapPixelError=nPixelError;
											}
										}
									}
									EditorGUILayout.EndHorizontal();
									EditorGUI.BeginDisabledGroup(_targetRT.NormalGlobal==null);
									if (GUILayout.Button("Reapply height texture to terrain data")) {
										if (EditorUtility.DisplayDialog("Warning", "Are you sure to overwrite terrain height data ?","Yes","Cancel")) {
											AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.NormalGlobal));
											if (_importer) {
												TextureImporter tex_importer=(TextureImporter)_importer;
												if (!tex_importer.isReadable) {
													Debug.LogWarning("Global normal texture ("+_targetRT.NormalGlobal.name+") has been reimported as readable.");
													tex_importer.isReadable=true;
													AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.NormalGlobal),  ImportAssetOptions.ForceUpdate);
												}
											}
											{
												TerrainData terrainData = terrain.terrainData;
												float[,] heights;
												float _ratio = 1.0f*_targetRT.NormalGlobal.width/terrainData.heightmapResolution;
												if (_ratio>1.9f) {
													// sample from hi-res texture to lower res heightmap
													// we take max sample
													// this is used to conform lo-res terrain mesh with its occlusion data (useful in Unity5 where terrain surface can be rendered separately)
													heights = ReliefTerrain.ConformTerrain2Occlusion(terrainData, _targetRT.NormalGlobal);
												} else {
													// sample from hi-res texture to similar or higher res heightmap
													// we take exact sample
													// this is used to conform detail placement and collider fit
													heights = ReliefTerrain.ConformTerrain2Detail(terrainData, _targetRT.NormalGlobal, RTP_HEIGHTMAP_SAMPLE_BICUBIC);
												}
												terrainData.SetHeights(0,0,heights);
											}
										}
									}
									EditorGUI.EndDisabledGroup();									
								} else if (RTP_TESSELLATION_SAMPLE_TEXTURE) {
									EditorGUILayout.BeginHorizontal();
									EditorGUILayout.LabelField("Displacement height", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
									if (checkChange(ref _target.tessHeight, EditorGUILayout.FloatField(_target.tessHeight))) {
										MeshFilter mf=_targetRT.GetComponent<MeshFilter>();
										if (mf && mf.sharedMesh) {
											mf.sharedMesh.RecalculateBounds();
											Bounds bounds=mf.sharedMesh.bounds;
											Vector3 center=bounds.center;
											Vector3 extents=bounds.extents;
											center.y=(_target.tessHeight+_target._TessYOffset*2)/_targetRT.transform.localScale.y*0.5f;
											extents.y=_target.tessHeight/_targetRT.transform.localScale.y;
											extents.x*=2;
											extents.z*=2;
											mf.sharedMesh.bounds=new Bounds(center, extents);
										}
									}
									EditorGUILayout.EndHorizontal();
									EditorGUILayout.BeginHorizontal();
									EditorGUILayout.LabelField("Y offset", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
									if (checkChange(ref _target._TessYOffset, EditorGUILayout.FloatField(_target._TessYOffset))) {
										MeshFilter mf=_targetRT.GetComponent<MeshFilter>();
										if (mf && mf.sharedMesh) {
											mf.sharedMesh.RecalculateBounds();
											Bounds bounds=mf.sharedMesh.bounds;
											Vector3 center=bounds.center;
											Vector3 extents=bounds.extents;
											center.y=(_target.tessHeight+_target._TessYOffset*2)/_targetRT.transform.localScale.y*0.5f;
											extents.y=_target.tessHeight/_targetRT.transform.localScale.y;
											extents.x*=2;
											extents.z*=2;
											mf.sharedMesh.bounds=new Bounds(center, extents);
										}
									}
									EditorGUILayout.EndHorizontal();


								}
							EditorGUILayout.EndVertical();

						EditorGUILayout.EndHorizontal();	

					} else {

						if (RTP_NORMALGLOBAL) {
							EditorGUILayout.HelpBox("Using global normal below we won't use mesh normals - will be treated flat (0,1,0), but you can greately improve look when lo-res heightmap or high pixelError settings are used.",MessageType.None, true);
							if (GUILayout.Button("Disable global normal (rebuild shaders via RTP_LODmanager)")) {
								_RTP_LODmanagerScript.RTP_NORMALGLOBAL=false;
								if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
									Selection.activeObject=_RTP_LODmanagerScript.gameObject;
									_RTP_LODmanagerScript.dont_sync=true;
								}
								//_RTP_LODmanagerScript.RefreshLODlevel();
								//EditorUtility.SetDirty(_targetRT);
							}							
							
							EditorGUILayout.BeginHorizontal();
							if (checkChange(ref _targetRT.NormalGlobal, (Texture2D)EditorGUILayout.ObjectField(_targetRT.NormalGlobal, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)))) {
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.NormalGlobal));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (tex_importer) {
										tex_importer.wrapMode=TextureWrapMode.Clamp;
										tex_importer.textureType=TextureImporterType.Bump;
										Debug.LogWarning("Global normal texture ("+_targetRT.NormalGlobal.name+") has been imported as normalmap type.");
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.NormalGlobal),  ImportAssetOptions.ForceUpdate);
									}
								}							
							}
							EditorGUILayout.BeginVertical();
							
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("Normal strength", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
							checkChange(ref _target.global_normalMap_multiplier, EditorGUILayout.Slider(_target.global_normalMap_multiplier, 0.5f, 6f));
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("Far distance use", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
							checkChange(ref _target.global_normalMap_farUsage, EditorGUILayout.Slider(_target.global_normalMap_farUsage, 0f, 1f));
							EditorGUILayout.EndHorizontal();
							
							EditorGUILayout.EndVertical();
							EditorGUILayout.EndHorizontal();	
						} else {
							EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
							if (GUILayout.Button("Enable global normal (rebuild shaders via RTP_LODmanager)")) {
								_RTP_LODmanagerScript.RTP_NORMALGLOBAL=true;
								if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
									Selection.activeObject=_RTP_LODmanagerScript.gameObject;
									_RTP_LODmanagerScript.dont_sync=true;
								}
								//_RTP_LODmanagerScript.RefreshLODlevel();
								//EditorUtility.SetDirty(_targetRT);
							}
						}

					}


					EditorGUILayout.EndVertical();	
					
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Global trees/shadow settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					if (RTP_TREESGLOBAL) {
						EditorGUILayout.HelpBox("RGB - trees color at very far distance (billboard trees drawing distance). Blending done via brightness, so black means - no pixel tree.\n\nA channel - shadows (mean to be used when you don't use lightmaps).",MessageType.None, true);
						if (GUILayout.Button("Disable global trees/shadows (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_TREESGLOBAL=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}							
						
						EditorGUILayout.BeginHorizontal();
						checkChange(ref _targetRT.TreesGlobal, (Texture2D)EditorGUILayout.ObjectField(_targetRT.TreesGlobal, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						EditorGUILayout.BeginVertical();
						
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Trees distance", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_pixel_distance_start, EditorGUILayout.FloatField(_target.trees_pixel_distance_start));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Trees fade length", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_pixel_distance_transition, EditorGUILayout.Slider(_target.trees_pixel_distance_transition, 0, 100));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Trees blending", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_pixel_blend_val, EditorGUILayout.Slider(_target.trees_pixel_blend_val, 0, 10));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows distance", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_distance_start, EditorGUILayout.FloatField(_target.trees_shadow_distance_start));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows fade length", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_distance_transition, EditorGUILayout.Slider(_target.trees_shadow_distance_transition, 0, 30));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows blending", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_value, 1-EditorGUILayout.Slider(1-_target.trees_shadow_value, 0, 1));
						EditorGUILayout.EndHorizontal();
						
						EditorGUILayout.EndVertical();
						EditorGUILayout.EndHorizontal();	
					} else {
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable global trees/shadows (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_TREESGLOBAL=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
					}
					EditorGUILayout.EndVertical();	
					
					GUILayout.Space(10);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Global ambient emissive map settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					if (RTP_AMBIENT_EMISSIVE_MAP) {
						EditorGUILayout.HelpBox("RGB - ambient emissive color.\n\nA channel - shadows (mean to be used when you don't use lightmaps).",MessageType.None, true);
						if (GUILayout.Button("Disable ambient emissive map (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_AMBIENT_EMISSIVE_MAP=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
						
						EditorGUILayout.BeginHorizontal();
						checkChange(ref _targetRT.AmbientEmissiveMap, (Texture2D)EditorGUILayout.ObjectField(_targetRT.AmbientEmissiveMap, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						EditorGUILayout.BeginVertical();
						
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Emission brightness", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target._AmbientEmissiveMultiplier, EditorGUILayout.Slider(_target._AmbientEmissiveMultiplier,0,4));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Normal/height mod", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target._AmbientEmissiveRelief, EditorGUILayout.Slider(_target._AmbientEmissiveRelief,0,1));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows distance", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_distance_start, EditorGUILayout.FloatField(_target.trees_shadow_distance_start));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows fade length", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_distance_transition, EditorGUILayout.Slider(_target.trees_shadow_distance_transition, 0, 30));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows blending", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_value, 1-EditorGUILayout.Slider(1-_target.trees_shadow_value, 0, 1));
						EditorGUILayout.EndHorizontal();
						
						EditorGUILayout.EndVertical();
						EditorGUILayout.EndHorizontal();	
					} else {
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable ambient emissive map (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_AMBIENT_EMISSIVE_MAP=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
					}
					EditorGUILayout.EndVertical();					
					
					if (RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST || RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD) {
						EditorGUILayout.BeginVertical("Box");
						skin_color=GUI.color;
						EditorGUILayout.BeginHorizontal();
						GUI.color=new Color(1,1,0.5f,1);
						EditorGUILayout.LabelField("Grayscale detail textures", EditorStyles.boldLabel);
						EditorGUILayout.EndHorizontal();
						GUI.color=skin_color;						
						EditorGUILayout.HelpBox("In massive terrain mode (refer to RTP LOD manager for 4 layers mode) you can use even simplier close-distance detail colors as grayscale and global colorMap to tint them. RGBA channels refers to grayscaled detail textures for layers.",MessageType.None, true);
						EditorGUILayout.BeginHorizontal();
							EditorGUI.BeginDisabledGroup(!RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST);
							EditorGUILayout.BeginVertical();
								Texture2D oRef=_target.SSColorCombinedA;
								if (checkChange(ref _target.SSColorCombinedA, (Texture2D)EditorGUILayout.ObjectField(_target.SSColorCombinedA, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)))) {
									DestroyUnusedCombinedTexture(oRef);
								}
								SaveTexture(ref _target.SSColorCombinedA, ref _target.save_path_SSColorCombinedA, "terrain_detail_grayscale_combined.png", 100, TextureImporterFormat.DXT5, true);
							EditorGUILayout.EndVertical();
							EditorGUI.EndDisabledGroup();
							EditorGUI.BeginDisabledGroup(!RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD);
							EditorGUILayout.BeginVertical();
								oRef=_target.SSColorCombinedB;
								if (checkChange(ref _target.SSColorCombinedB, (Texture2D)EditorGUILayout.ObjectField(_target.SSColorCombinedB, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)))) {
									DestroyUnusedCombinedTexture(oRef);
								}
								SaveTexture(ref _target.SSColorCombinedB, ref _target.save_path_SSColorCombinedB, "terrain_detail_grayscale_combined.png", 100, TextureImporterFormat.DXT5, true);
							EditorGUILayout.EndVertical();
							EditorGUI.EndDisabledGroup();
						EditorGUILayout.EndHorizontal();	
						
						if (GUILayout.Button("Make combined grayscale texture(s)")) {
							if (RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST) MakeCombinedGrayscale(0, ref _target.SSColorCombinedA);
							if (RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD) MakeCombinedGrayscale(4, ref _target.SSColorCombinedB);
							_target.RefreshAll();
						}
						
						if (GUILayout.Button("Disable grayscale detail textures")) {
							_RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST=false;
							_RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}	
						
						EditorGUILayout.EndVertical();	
					}
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset global color settings numeric params to default")) {
						#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
						Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
						#else
						Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
						#endif
						_target.ReturnToDefaults("global_color");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh(null, _targetRT);
					}	
					
					#endregion Settings - Global color
					break;
					
				case ReliefTerrainSettingsItems.GlobalNormal:
					#region Settings - Global normal 
					GUILayout.Space(6);
					;
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoPerlinNormal),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Perlin normal map settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					EditorGUILayout.HelpBox("Feature below are applied per layer in \"Layer properties\".", MessageType.None, true);
					EditorGUILayout.HelpBox("REMEMBER - this map is also used for water flow animation, water/snow random coverage and superdetail normal mapping.", MessageType.None, true);
					
					EditorGUILayout.BeginHorizontal();
					Texture2D tex_bump=_target.BumpGlobal;
					Texture2D ntex=tex_bump;
					checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.BumpGlobal, typeof(Texture2D), false, GUILayout.MinHeight(90), GUILayout.MinWidth(90), GUILayout.MaxWidth(90)));
					if (ntex==null) {
						ntex=(Texture2D)AssetDatabase.LoadAssetAtPath("Assets/ReliefPack/Textures/ReliefTerrain/perlin_noise.png", typeof(Texture2D));
						_targetRT.TERRAIN_WetMask=null;
						_target.TERRAIN_ReflectionMap=null;
						_target.SuperDetailA=null;
						_target.SuperDetailB=null;
					}
					if (ntex!=tex_bump) {
						Texture2D tex_prev=_target.BumpGlobal;
						_target.BumpGlobal=ntex;
						if (ntex) {
							AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Global normal texture ("+ntex.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
								}
							}
						}
						if (!_targetRT.PrepareGlobalNormalsAndSuperDetails()) {
							Debug.LogWarning("Due to rebuilding special combined texture superdetail textures, water mask and reflection map have been cleared (you have to reassign them again).");
							_target.BumpGlobal=tex_prev;
							_targetRT.TERRAIN_WetMask=null;
							_target.TERRAIN_ReflectionMap=null;
							_target.SuperDetailA=null;
							_target.SuperDetailB=null;
							if (_targetRT.PrepareGlobalNormalsAndSuperDetails()) {
								_target.BumpGlobal=ntex;
							}
						}
						_target.Refresh(null, _targetRT);
					}
					EditorGUILayout.BeginVertical();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Tiling scale ("+(Mathf.Round(_target.ReliefTransform.x/_target.BumpMapGlobalScale*10)/10)+" m)", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
					EditorGUILayout.BeginHorizontal();
					checkChange(ref _target.BumpMapGlobalScale, EditorGUILayout.Slider(_target.BumpMapGlobalScale, 0.01f, 0.25f));
//					if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
//						float ratio=Mathf.Round(_target.ReliefTransform.x*_target.BumpMapGlobalScale);
//						_target.BumpMapGlobalScale=ratio/_target.ReliefTransform.x;
//						_target.RefreshAll();
//					}
					EditorGUILayout.EndHorizontal();						
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("MIP offset", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target.rtp_mipoffset_globalnorm, EditorGUILayout.IntSlider(_target.rtp_mipoffset_globalnorm, 0, 5));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Distance start", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target.distance_start_bumpglobal, EditorGUILayout.Slider(_target.distance_start_bumpglobal, 0, 100));
					if (_target.distance_start_bumpglobal<_target.distance_start) _target.distance_start_bumpglobal=_target.distance_start;
					EditorGUILayout.EndHorizontal();
					
					EditorGUI.BeginDisabledGroup( _target.distance_start_bumpglobal>0 );
					if (_target.distance_start_bumpglobal>0) _target.rtp_perlin_start_val=0;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Starting value", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target.rtp_perlin_start_val, EditorGUILayout.Slider(_target.rtp_perlin_start_val, 0, 1.0f));
					EditorGUILayout.EndHorizontal();
					EditorGUI.EndDisabledGroup();
					
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Fade length", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target.distance_transition_bumpglobal, EditorGUILayout.Slider(_target.distance_transition_bumpglobal, 0, 300));
					EditorGUILayout.EndHorizontal();
//					EditorGUILayout.BeginHorizontal();
//					EditorGUILayout.LabelField("Far normal damp", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
//					checkChange(ref _target._FarNormalDamp, EditorGUILayout.Slider(_target._FarNormalDamp, 0, 1));
//					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndHorizontal();
					
					EditorGUILayout.EndVertical();
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset perlin normal settings numeric params to default")) {
						#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
						Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
						#else
						Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
						#endif
						_target.ReturnToDefaults("perlin");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh(null, _targetRT);
					}		
					
					#endregion Settings - Global normal	
					break;					
					
				case ReliefTerrainSettingsItems.Superdetail:
					#region Settings - superdetail					
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoSuperdetail),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Superdetail settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					if (SUPER_DETAIL_ENABLED_FIRST || SUPER_DETAIL_ENABLED_ADD) {
						EditorGUILayout.HelpBox("Superdetail is texture consisting of Perlin normalmap and optional 2 additional multiplicative channels. They're shared on combined texture with water mask and reflection map, so CAN NOT be used (with water/reflection) at the same time.\n\nSuperdetail normal is applied only on near distance.", MessageType.None, true);
						
						if (GUILayout.Button("Disable superdetails (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_SUPER_DETAIL_FIRST=false;
							_RTP_LODmanagerScript.RTP_SUPER_DETAIL_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
						
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Superdetail tiling scale", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._SuperDetailTiling, EditorGUILayout.IntSlider(Mathf.RoundToInt(_target._SuperDetailTiling), 1, 16));
						EditorGUILayout.EndHorizontal();
						
						if (SUPER_DETAIL_MULTS_ENABLED_FIRST || SUPER_DETAIL_MULTS_ENABLED_ADD) {
							GUILayout.Space(8);
							EditorGUILayout.HelpBox("Superdetail multiplicative channles can be applied on both near and far distances with optional self-masking (works the way multiplicative channel masks itself using Perlin normal tiling).\n\nColor multiplication is realised classic way (color x mult_channel x 2) giving opportunity to make it lighten/darken (grey texture gives neutral effect).\n\nOn far distance selfmasking set to 0 means we've got no blending (otherwise we would see distinct superdetail patterns over large areas).", MessageType.None, true);
							EditorGUILayout.BeginHorizontal();
							Texture2D tmp_tex=_target.SuperDetailA;
							ntex=tmp_tex;
							checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.SuperDetailA, typeof(Texture2D), false, GUILayout.MinHeight(90), GUILayout.MinWidth(90), GUILayout.MaxWidth(90)));
							if (ntex!=tmp_tex) {
								Texture2D tex_prev=_target.SuperDetailA;
								_target.SuperDetailA=ntex;
								if (ntex) {
									AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
									if (_importer) {
										TextureImporter tex_importer=(TextureImporter)_importer;
										if (!tex_importer.isReadable) {
											Debug.LogWarning("Superdetail 1st texture ("+ntex.name+") has been reimported as readable.");
											tex_importer.isReadable=true;
											AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
										}
									}
								}
								if (!_targetRT.PrepareGlobalNormalsAndSuperDetails()) _target.SuperDetailA=tex_prev;
								_target.Refresh(null, _targetRT);
							}
							RTPColorChannels nchannel=RTPColorChannels.R;
							EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							checkChange(ref nchannel, (RTPColorChannels)EditorGUILayout.EnumPopup(_target.SuperDetailA_channel));
							if (nchannel!=_target.SuperDetailA_channel) {
								_target.SuperDetailA_channel=nchannel;
								_targetRT.PrepareGlobalNormalsAndSuperDetails();
							}
							EditorGUILayout.EndHorizontal();
							
							EditorGUILayout.Space();
							EditorGUILayout.BeginHorizontal();
							tmp_tex=_target.SuperDetailB;
							ntex=tmp_tex;
							checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.SuperDetailB, typeof(Texture2D), false, GUILayout.MinHeight(90), GUILayout.MinWidth(90), GUILayout.MaxWidth(90)));
							if (ntex!=tmp_tex) {
								Texture2D tex_prev=_target.SuperDetailB;
								_target.SuperDetailB=ntex;
								if (ntex) {
									AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
									if (_importer) {
										TextureImporter tex_importer=(TextureImporter)_importer;
										if (!tex_importer.isReadable) {
											Debug.LogWarning("Superdetail 2st texture ("+ntex.name+") has been reimported as readable.");
											tex_importer.isReadable=true;
											AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
										}
									}
								}
								if (!_targetRT.PrepareGlobalNormalsAndSuperDetails()) _target.SuperDetailB=tex_prev;
								_target.Refresh(null, _targetRT);
							}
							EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							checkChange(ref nchannel, (RTPColorChannels)EditorGUILayout.EnumPopup(_target.SuperDetailB_channel));
							if (nchannel!=_target.SuperDetailB_channel) {
								_target.SuperDetailB_channel=nchannel;
								_targetRT.PrepareGlobalNormalsAndSuperDetails();
							}
							EditorGUILayout.EndHorizontal();
						} // superdetail mults
						
						if (SUPER_DETAIL_MULTS_ENABLED_FIRST || SUPER_DETAIL_MULTS_ENABLED_ADD) {
							if (GUILayout.Button("Disable superdetails mult (rebuild shaders via RTP_LODmanager)")) {
								_RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_FIRST=false;
								_RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_ADD=false;
								if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
									Selection.activeObject=_RTP_LODmanagerScript.gameObject;
									_RTP_LODmanagerScript.dont_sync=true;
								}
								//_RTP_LODmanagerScript.RefreshLODlevel();
								//EditorUtility.SetDirty(_targetRT);
							}
						} else {
							EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
							if (GUILayout.Button("Enable superdetails mult (rebuild shaders via RTP_LODmanager)")) {
								_RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_FIRST=true;
								_RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_ADD=true;
								if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
									Selection.activeObject=_RTP_LODmanagerScript.gameObject;
									_RTP_LODmanagerScript.dont_sync=true;
								}
								//_RTP_LODmanagerScript.RefreshLODlevel();
								//EditorUtility.SetDirty(_targetRT);
							}
						}		
						
						GUILayout.Space(15);							
						if (GUILayout.Button("Reset superdetail settings numeric params to default")) {
							#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
							Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
							#else
							Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
							#endif
							_target.ReturnToDefaults("superdetail");
							EditorUtility.SetDirty(_targetRT);
							_target.Refresh(null, _targetRT);							
						}	
						
					} else {
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable superdetails (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_SUPER_DETAIL_FIRST=true;
							_RTP_LODmanagerScript.RTP_SUPER_DETAIL_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
					}
					
					EditorGUILayout.EndVertical();
					
					#endregion Settings - superdetail					
					break;	
				case ReliefTerrainSettingsItems.VerticalTex:
					#region Settings - Vertical texture		
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoVerticalTexture),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Vertical texturing", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					if (	RTP_VERTICAL_TEXTURE_FIRST || RTP_VERTICAL_TEXTURE_ADD) {
						EditorGUILayout.HelpBox("This texture is applied along world y axis using V coord. Pixel color is multiplied, controlled per layer (\"Layer properties\" - Vertical map strength).",MessageType.None, true);
						
						bool vertTexUnused=false;
						//bool AddPass_flag=(_4LAYERS_SHADER_USED && _target.numLayers>4) || (_target.numLayers>8);
						if (RTP_VERTALPHA_CAUSTICS) {
							vertTexUnused=true;
						}
						if (vertTexUnused) {
							EditorGUILayout.HelpBox("Shader is configured to take vertical texture data from caustics tex (RGB).",MessageType.Warning, true);
						}		
						EditorGUILayout.BeginHorizontal();
						if (!vertTexUnused) {
							checkChange(ref _target.VerticalTexture, (Texture2D)EditorGUILayout.ObjectField(_target.VerticalTexture, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						}
						EditorGUILayout.BeginVertical();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Tiling [m]", GUILayout.MinWidth(145), GUILayout.MaxWidth(145));
						checkChange(ref _target.VerticalTextureTiling, EditorGUILayout.FloatField(_target.VerticalTextureTiling));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Offset via Perlin normal", GUILayout.MinWidth(145), GUILayout.MaxWidth(145));
						checkChange(ref _target.VerticalTextureGlobalBumpInfluence, EditorGUILayout.Slider(_target.VerticalTextureGlobalBumpInfluence, 0, 0.1f));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.EndVertical();
						EditorGUILayout.EndHorizontal();
					} // v-tex
					
					if (		RTP_VERTICAL_TEXTURE_FIRST || RTP_VERTICAL_TEXTURE_ADD) {
						if (GUILayout.Button("Disable feature (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_FIRST=false;
							_RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
						
						GUILayout.Space(15);							
						if (GUILayout.Button("Reset vertical texture settings numeric params to default")) {
							#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
							Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
							#else
							Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
							#endif
							_target.ReturnToDefaults("vertical");
							EditorUtility.SetDirty(_targetRT);
							_target.Refresh(null, _targetRT);
						}	
						
					} else {
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable feature (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_FIRST=true;
							_RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
					}
					
					EditorGUILayout.EndVertical();
					
					#endregion Settings - Vertical texture
					break;
					
				case ReliefTerrainSettingsItems.Snow:
					#region Settings - Snow
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoSnow),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Snow settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					if (SNOW_ENABLED_FIRST || SNOW_ENABLED_ADD) {
						#if !UNITY_3_5
						EditorGUILayout.HelpBox("Snow settings are set globally and its params are visible in any shader using RTP dynamic snow feature (Bonus snow shaders). This also means that you can't use different snow settings on multiple terrains (Unity4).",MessageType.Warning, true);
						#endif
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Strength", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_strength, EditorGUILayout.Slider(_target._snow_strength, 0, 1));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.HelpBox("Global color influence means the darker is global color the more snow is present.",MessageType.None, true);
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Global color influence", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._global_color_brightness_to_snow, EditorGUILayout.Slider(_target._global_color_brightness_to_snow, 0, 0.3f));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.HelpBox("Reduction by slope is factor for decreasing snow coverage on slopes.",MessageType.None, true);
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Reduction by slope", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_slope_factor, EditorGUILayout.Slider(_target._snow_slope_factor, 0, 10f));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.HelpBox("Height threshold/transition allows to put snow on choosen height only (i.e. high mountais).",MessageType.None, true);
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Height threshold [units]", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_height_treshold, EditorGUILayout.Slider(_target._snow_height_treshold, -200, 7000));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Height transition", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_height_transition, EditorGUILayout.Slider(_target._snow_height_transition, 1, 4000));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.Space ();
						
						EditorGUILayout.HelpBox("Color / spec / gloss are used for far distance.\nFor near distance you can choose a layer to get its color/normalmap as snow (refer to _RTP_LODmanager game object inspector).",MessageType.None, true);
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Color", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_color, EditorGUILayout.ColorField(_target._snow_color));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Spec (gloss mask)", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_specular, EditorGUILayout.Slider(_target._snow_specular, 0f, 1f));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.HelpBox("When you're in deferred and snow is present for AddPass you should keep below gloss value similar to \"Gloss for deferred AddPass\" in Settings/Main to avoid overbright specular problems.",MessageType.Warning, true);
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Gloss", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_gloss, EditorGUILayout.Slider(_target._snow_gloss, 0.01f, 1f));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Fresnel", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_fresnel, EditorGUILayout.Slider(_target._snow_fresnel, 0f, 1f));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Diffuse scattering", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_diff_fresnel, EditorGUILayout.Slider(_target._snow_diff_fresnel, 0f, 2f));
						EditorGUILayout.EndHorizontal();
						bool AddPass_flag=(_4LAYERS_SHADER_USED && _target.numLayers>4) || (_target.numLayers>8);
						if ( (!AddPass_flag && RTP_IBL_DIFFUSE_FIRST) || (AddPass_flag && RTP_IBL_SPEC_ADD) ) {
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("IBL diffuse exposure", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
							checkChange(ref _target._snow_IBL_DiffuseStrength, EditorGUILayout.Slider(_target._snow_IBL_DiffuseStrength, 0f, 8f));
							EditorGUILayout.EndHorizontal();
						}
						if ( (!AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) || (AddPass_flag && (REFLECTION_ENABLED_FIRST || RTP_IBL_SPEC_FIRST)) ) {
							EditorGUILayout.BeginHorizontal();
							if (GUILayout.Button(new GUIContent(icoReflection, "Reflection settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
								_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
								_target.submenu_settings=ReliefTerrainSettingsItems.Reflections;
							}
							EditorGUILayout.LabelField("IBL spec / Refl exposure", GUILayout.MinWidth(150), GUILayout.MaxWidth(150));
							checkChange(ref _target._snow_IBL_SpecStrength, EditorGUILayout.Slider(_target._snow_IBL_SpecStrength, 0f, 8f));
							EditorGUILayout.EndHorizontal();
						}
						
						EditorGUILayout.Space ();
						
						EditorGUILayout.HelpBox("Edges definition makes snow transition smooth (snow color gradualy blends underlying surface) or sharp.",MessageType.None, true);
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Edges definition", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_edge_definition, EditorGUILayout.Slider(_target._snow_edge_definition, 0.5f, 20f));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.Space ();
						EditorGUILayout.HelpBox("Deep factor adjusts how fast covered surface will get dedicated normals (from texture) and extrusion height canceled (in POM/PM shading).",MessageType.None, true);
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Deep factor", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_deep_factor, EditorGUILayout.Slider(_target._snow_deep_factor, 0, 6));
						EditorGUILayout.EndHorizontal();
						
					} // snow
					EditorGUILayout.Space ();
					
					if (SNOW_ENABLED_FIRST || SNOW_ENABLED_ADD) {
						if (GUILayout.Button("Disable snow (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_SNOW_FIRST=false;
							_RTP_LODmanagerScript.RTP_SNOW_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
						
						GUILayout.Space(15);							
						if (GUILayout.Button("Reset snow settings numeric params to default")) {
							#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
							Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
							#else
							Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
							#endif
							_target.ReturnToDefaults("snow");
							EditorUtility.SetDirty(_targetRT);
							_target.Refresh(null, _targetRT);
						}	
						
					} else {
						_target._snow_strength=1;
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable snow (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_SNOW_FIRST=true;
							_RTP_LODmanagerScript.RTP_SNOW_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
					}					
					
					EditorGUILayout.EndVertical();
					
					#endregion Settings - Snow
					break;					
					
				case ReliefTerrainSettingsItems.Water:
					#region Settings - Water
					_target.paint_wetmask=true;
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoWater),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Water settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					if (WATER_ENABLED_FIRST || WATER_ENABLED_ADD) {
						EditorGUILayout.HelpBox("Water has 3 states due to wetness applied - diffuse color darken for initial water, then surface becomes wet, then water may accumulate in lower parts (lower in terms of heightmap applied).\n\nReflection is taken from reflection map (the same as in Reflection settings). Most params are applied per layer.",MessageType.None, true);
						checkChange(ref _target.TERRAIN_GlobalWetness, EditorGUILayout.Slider("Global wetness", _target.TERRAIN_GlobalWetness, 0, 1));
						checkChange(ref _target.TERRAIN_WetHeight_Treshold, EditorGUILayout.Slider("Height threshold [units]", _target.TERRAIN_WetHeight_Treshold, -500, 8000));
						checkChange(ref _target.TERRAIN_WetHeight_Transition, EditorGUILayout.Slider("Height transition", _target.TERRAIN_WetHeight_Transition, 1, 1000));
						checkChange(ref _target.TERRAIN_FlowSpeed, EditorGUILayout.Slider("Flow speed", _target.TERRAIN_FlowSpeed, 0, 2f));
						checkChange(ref _target.TERRAIN_FlowCycleScale, EditorGUILayout.Slider("Flow cycle scale", _target.TERRAIN_FlowCycleScale, 0.5f, 4));
						EditorGUILayout.BeginHorizontal();
						checkChange(ref _target.TERRAIN_FlowScale, EditorGUILayout.Slider("Flow tex tiling ("+(Mathf.Round(_target.ReliefTransform.x/_target.TERRAIN_FlowScale*10)/10)+" m)", _target.TERRAIN_FlowScale, 0.25f, 8f));
//						if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
//							float ratio=Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_FlowScale);
//							_target.TERRAIN_FlowScale=ratio/_target.ReliefTransform.x;
//							_target.RefreshAll();
//						}
						EditorGUILayout.EndHorizontal();
						checkChange(ref _target.TERRAIN_FlowMipOffset, EditorGUILayout.Slider("Flow tex filter", _target.TERRAIN_FlowMipOffset/4f, 0, 1)*4f);
						checkChange(ref _target.TERRAIN_mipoffset_flowSpeed, EditorGUILayout.Slider("Filter by flow speed", _target.TERRAIN_mipoffset_flowSpeed, 0, 4));
						checkChange(ref _target.TERRAIN_WetDarkening, EditorGUILayout.Slider("Water surface darkening", _target.TERRAIN_WetDarkening, 0.1f, 0.9f));
						EditorGUILayout.HelpBox("You can exclude any parts from wetness - shelter mask is put on derived/combined texture channel B together with Perlin normal (RG) and reflection map (A) (see Combined textures in RTP main inspector menu tab).\n\nWhen you don't specify texture below it will be treated black(full water).\n\nWhen you start painting the mask will be automatically made for you (with size of Special combined texture).",MessageType.None, true);
						
						Texture2D tmp_tex=_targetRT.TERRAIN_WetMask;
						ntex=tmp_tex;
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.BeginVertical();
						Texture2D oRef=ntex;
						if (checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_targetRT.TERRAIN_WetMask, typeof(Texture2D), false, GUILayout.MinHeight(140), GUILayout.MinWidth(140), GUILayout.MaxWidth(140)))) {
							_targetRT.RefreshTextures();
							DestroyUnusedCombinedTexture(oRef);
						}
						if (SaveTexture(ref _targetRT.TERRAIN_WetMask, ref _targetRT.save_path_WetMask, "terrain_wetmask.png", 140, TextureImporterFormat.Alpha8, true)) {
							_targetRT.globalWaterModifed_flag=false;
						}
						EditorGUILayout.EndVertical();
						EditorGUILayout.BeginVertical();
						int fill_flag=0;
						if (GUILayout.Button("Dry all terrain")) {
							fill_flag=1;
							_targetRT.RefreshTextures();
						}
						if (GUILayout.Button("Fill all terrain with water")) {
							fill_flag=2;
							_targetRT.RefreshTextures();
						}
						if (fill_flag>0) {
							if (_targetRT.TERRAIN_WetMask) DestroyImmediate(_targetRT.TERRAIN_WetMask, false);
							if (_targetRT.BumpGlobalCombined) {
								_targetRT.TERRAIN_WetMask=new Texture2D(_targetRT.BumpGlobalCombined.width, _targetRT.BumpGlobalCombined.height, TextureFormat.Alpha8, false);
							} else if (_target.TERRAIN_ReflectionMap) {
								_targetRT.TERRAIN_WetMask=new Texture2D(_target.TERRAIN_ReflectionMap.width, _target.TERRAIN_ReflectionMap.height, TextureFormat.Alpha8, false);
							} else {
								_targetRT.TERRAIN_WetMask=new Texture2D(1024, 1024, TextureFormat.Alpha8, false);
							}
							Color32[] cols=new Color32[_targetRT.TERRAIN_WetMask.width*_targetRT.TERRAIN_WetMask.height];
							if (fill_flag==1) {
								for(int k=0; k<cols.Length; k++) cols[k]=Color.white;
							}
							_targetRT.TERRAIN_WetMask.SetPixels32(cols,0);
							_targetRT.TERRAIN_WetMask.Apply(true,false);
							_targetRT.globalWaterModifed_flag=true;
							_targetRT.PrepareGlobalNormalsAndSuperDetails(true,false);
						}
						EditorGUILayout.EndVertical();
						EditorGUILayout.EndHorizontal();
						if (ntex!=tmp_tex) {
							Texture2D tex_prev=_targetRT.TERRAIN_WetMask;
							_targetRT.TERRAIN_WetMask=ntex;
							if (ntex) {
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									bool modified_flag=false;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Wet mask texture ("+ntex.name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										modified_flag=true;
									}
									if (tex_importer.textureFormat!=TextureImporterFormat.Alpha8) {
										Debug.LogWarning("Wet mask texture ("+ntex.name+") has been reimported as Alpha8.");
										tex_importer.grayscaleToAlpha=true;
										tex_importer.textureFormat=TextureImporterFormat.Alpha8;
										modified_flag=true;
									}
									if (modified_flag) {
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
									}	
								}
							}
							if (!_targetRT.PrepareGlobalNormalsAndSuperDetails(true,false)) _targetRT.TERRAIN_WetMask=tex_prev;
							_target.Refresh(null, _targetRT);
						}
						
						//
						// paint tools
						//						
						GUILayout.Space(8);
						EditorGUILayout.BeginVertical("Box");		
						skin_color=GUI.color;
						GUI.color=new Color(1,1,0.5f,1);
						EditorGUILayout.LabelField("Wetmask paint tool", EditorStyles.boldLabel);
						GUI.color=skin_color;
						
						prev_paint_flag=_target.paint_flag;
						
						if (!_target.paint_flag) {
							Color c=GUI.color;
							GUI.color=new Color(0.9f,1, 0.9f);
							if (GUILayout.Button(new GUIContent("Begin painting (M)",icoPaintOn, "Click to turn on painting"))) {
								_target.paint_flag=true;
								_target.paint_wetmask=true;
								_target.paint_alpha_flag=true;
								if (!_targetRT.TERRAIN_WetMask) {
									if (_targetRT.BumpGlobalCombined) {
										_targetRT.TERRAIN_WetMask=new Texture2D(_targetRT.BumpGlobalCombined.width, _targetRT.BumpGlobalCombined.height, TextureFormat.Alpha8, false);
									} else if (_target.TERRAIN_ReflectionMap) {
										_targetRT.TERRAIN_WetMask=new Texture2D(_target.TERRAIN_ReflectionMap.width, _target.TERRAIN_ReflectionMap.height, TextureFormat.Alpha8, false);
									} else {
										_targetRT.TERRAIN_WetMask=new Texture2D(1024, 1024, TextureFormat.Alpha8, false);
									}
									Color32[] cols=new Color32[_targetRT.TERRAIN_WetMask.width*_targetRT.TERRAIN_WetMask.height];
									_targetRT.TERRAIN_WetMask.SetPixels32(cols,0);
									_targetRT.TERRAIN_WetMask.Apply(true,false);
								}
								if (!_targetRT.BumpGlobalCombined) {
									if (!_targetRT.PrepareGlobalNormalsAndSuperDetails(true, false)) {
										_target.paint_flag=false;
									}
								}
							}
							if (!_targetRT.GetComponent<Collider>() || !_targetRT.GetComponent<Collider>().enabled) _target.paint_flag=false;
							GUI.color=c;
						} else if (_target.paint_flag) {
							Color c=GUI.color;
							GUI.color=new Color(1,0.9f,0.9f);
							if (GUILayout.Button(new GUIContent("End painting (M)",icoPaintOff, "Click to turn off painting"))) {
								_target.paint_flag=false;
							}
							GUI.color=c;
						}
						if (!prev_paint_flag && _target.paint_flag) {
							UnityEditor.Tools.current=Tool.View;
							ReliefTerrain._SceneGUI = new SceneView.OnSceneFunc(CustomOnSceneGUI);
							SceneView.onSceneGUIDelegate += ReliefTerrain._SceneGUI;
						} else if (prev_paint_flag && !_target.paint_flag) {
							UnityEditor.Tools.current=prev_tool;
							SceneView.onSceneGUIDelegate -= ReliefTerrain._SceneGUI;
						}
						if (prev_paint_flag!=_target.paint_flag) EditorUtility.SetDirty(target);
						if (_target.paint_flag) {
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("", GUILayout.MaxWidth(10));
							EditorGUILayout.BeginVertical();			
							
							if (!_targetRT.GetComponent<Collider>() || !_targetRT.GetComponent<Collider>().enabled) EditorGUILayout.HelpBox("Object doesn't have collider (necessary for painting).",MessageType.Error, true);
							
							EditorGUILayout.HelpBox("Hold SHIFT while painting to add water.",MessageType.Info, true);
							
							if (_targetRT.tmp_WaterMap && _targetRT.tmp_WaterMap.format!=TextureFormat.Alpha8) {
								EditorGUILayout.HelpBox("Wet mask need to be readable and uncompressed for painting.",MessageType.Error, true);
							}
							if (_targetRT.tmp_CombinedMap && _targetRT.tmp_CombinedMap.format!=TextureFormat.ARGB32) {
								EditorGUILayout.HelpBox("Special combined map need to be readable and uncompressed for painting.",MessageType.Error, true);
							}
							GUILayout.BeginHorizontal();
							GUILayout.Label ("Area size", EditorStyles.label );
							_target.paint_size = EditorGUILayout.Slider(_target.paint_size, 0.1f, 6);
							GUILayout.EndHorizontal();	
							GUILayout.BeginHorizontal();
							GUILayout.Label ("Area smoothness", EditorStyles.label );
							_target.paint_smoothness = EditorGUILayout.Slider (_target.paint_smoothness, 0.001f, 1);
							GUILayout.EndHorizontal();
							GUILayout.BeginHorizontal();
							GUILayout.Label ("Opacity", EditorStyles.label );
							_target.paint_opacity = EditorGUILayout.Slider (_target.paint_opacity, 0, 1);
							GUILayout.EndHorizontal();	
							
							EditorGUILayout.EndVertical();
							EditorGUILayout.EndHorizontal();
							GUILayout.Space(10);
						}
						EditorGUILayout.EndVertical();	
						
						EditorGUILayout.HelpBox("Below feature simulates drops on the water surface. Texture used for animation is predefined so you don't have to touch it. Ripples appears on accumulated water surface, for wet surface only when \"Rain on wet\" is positive. Ripples can be also damped on slopes via \"Water level slope damp\" layer param.",MessageType.None, true);
						if (RIPPLEMAP_ENABLED_FIRST || RIPPLEMAP_ENABLED_ADD) {
							if (GUILayout.Button("Disable droplets anim (rebuild shaders via RTP_LODmanager)")) {
								_RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_FIRST=false;
								_RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_ADD=false;
								if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
									Selection.activeObject=_RTP_LODmanagerScript.gameObject;
									_RTP_LODmanagerScript.dont_sync=true;
								}
							}
						} else {
							//EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
							if (GUILayout.Button("Enable droplets anim (rebuild shaders via RTP_LODmanager)")) {
								_RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_FIRST=true;
								_RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_ADD=true;
								if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
									Selection.activeObject=_RTP_LODmanagerScript.gameObject;
									_RTP_LODmanagerScript.dont_sync=true;
								}
							}
						}						
						EditorGUI.BeginDisabledGroup( !(RIPPLEMAP_ENABLED_FIRST || RIPPLEMAP_ENABLED_ADD));
						checkChange(ref _target.TERRAIN_RainIntensity, EditorGUILayout.Slider("Rain intensity", _target.TERRAIN_RainIntensity, 0, 1f));
						checkChange(ref _target.TERRAIN_WetDropletsStrength, EditorGUILayout.Slider("Rain on wet", _target.TERRAIN_WetDropletsStrength, 0, 1));
						checkChange(ref _target.TERRAIN_DropletsSpeed, EditorGUILayout.Slider("Anim speed", _target.TERRAIN_DropletsSpeed, 1, 30f));
						EditorGUILayout.BeginHorizontal();
						checkChange(ref _target.TERRAIN_RippleScale, EditorGUILayout.Slider("Ripple tex tiling ("+(Mathf.Round(_target.ReliefTransform.x/_target.TERRAIN_RippleScale*10)/10)+" m)", _target.TERRAIN_RippleScale, 0.25f, 8));
//						if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
//							float ratio=Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_RippleScale);
//							_target.TERRAIN_RippleScale=ratio/_target.ReliefTransform.x;
//							_target.RefreshAll();
//						}
						EditorGUILayout.EndHorizontal();						
						if ((RIPPLEMAP_ENABLED_FIRST || RIPPLEMAP_ENABLED_ADD) && _target.TERRAIN_RippleMap==null) {
							_target.TERRAIN_RippleMap=(Texture2D)AssetDatabase.LoadAssetAtPath("Assets/ReliefPack/Textures/ReliefTerrain/water_drops_anim.png", typeof(Texture2D));
						}
						checkChange(ref _target.TERRAIN_RippleMap, (Texture2D)EditorGUILayout.ObjectField(_target.TERRAIN_RippleMap, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						EditorGUI.EndDisabledGroup();
					} else {
						_target.TERRAIN_GlobalWetness=1;
					}
					
					GUILayout.Space(15);
					if (WATER_ENABLED_FIRST || WATER_ENABLED_ADD) {
						if (GUILayout.Button("Disable water (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_WETNESS_FIRST=false;
							_RTP_LODmanagerScript.RTP_WETNESS_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
						
						GUILayout.Space(15);							
						if (GUILayout.Button("Reset water settings numeric params to default")) {
							#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
							Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
							#else
							Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
							#endif
							_target.ReturnToDefaults("water");
							EditorUtility.SetDirty(_targetRT);
							_target.Refresh(null, _targetRT);
						}		
						
					} else {
						_target.TERRAIN_GlobalWetness=1;
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable water (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_WETNESS_FIRST=true;
							_RTP_LODmanagerScript.RTP_WETNESS_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
					}						
					
					EditorGUILayout.EndVertical();
					
					#endregion Settings - Water
					
					#region Settings - Caustics
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoWater),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Caustics settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					if (CAUSTICS_ENABLED_FIRST || CAUSTICS_ENABLED_ADD) {
						checkChange(ref _target.TERRAIN_CausticsAnimSpeed, EditorGUILayout.Slider("Anim speed", _target.TERRAIN_CausticsAnimSpeed, 0, 10f));
						checkChange(ref _target.TERRAIN_CausticsColor, EditorGUILayout.ColorField("Color", _target.TERRAIN_CausticsColor));
						checkChange(ref _target.TERRAIN_CausticsWaterLevelRefObject, (GameObject)EditorGUILayout.ObjectField("Water Level Ref", _target.TERRAIN_CausticsWaterLevelRefObject, typeof(GameObject), true));
						EditorGUI.BeginDisabledGroup(_target.TERRAIN_CausticsWaterLevelRefObject);
						checkChange(ref _target.TERRAIN_CausticsWaterLevel, EditorGUILayout.FloatField("Water Level", _target.TERRAIN_CausticsWaterLevel));
						EditorGUI.EndDisabledGroup();
						checkChange(ref _target.TERRAIN_CausticsWaterLevelByAngle, EditorGUILayout.Slider("Water level by slope", _target.TERRAIN_CausticsWaterLevelByAngle, 0f, 8f));
						checkChange(ref _target.TERRAIN_CausticsWaterShallowFadeLength, EditorGUILayout.Slider("Shallow fade length", _target.TERRAIN_CausticsWaterShallowFadeLength, 0.1f, 10f));
						checkChange(ref _target.TERRAIN_CausticsWaterDeepFadeLength, EditorGUILayout.Slider("Deep fade length", _target.TERRAIN_CausticsWaterDeepFadeLength, 1f, 100f));
						EditorGUILayout.BeginHorizontal();
						checkChange(ref _target.TERRAIN_CausticsTilingScale, EditorGUILayout.Slider("Texture tiling  ("+(Mathf.Round(_target.ReliefTransform.x/_target.TERRAIN_CausticsTilingScale*10)/10)+" m)", _target.TERRAIN_CausticsTilingScale, 0.5f, 4f));
//						if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
//							float ratio=Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_CausticsTilingScale);
//							_target.TERRAIN_CausticsTilingScale=ratio/_target.ReliefTransform.x;
//							_target.RefreshAll();
//						}
						EditorGUILayout.EndHorizontal();			
						//bool AddPass_flag=(_4LAYERS_SHADER_USED && _target.numLayers>4) || (_target.numLayers>8);
						if ( RTP_VERTALPHA_CAUSTICS ) {
							EditorGUILayout.HelpBox("Shader is configured to take vertical texture data from caustics tex (RGB). Caustics color will be taken from caustics tex A channel as grayscale.",MessageType.Warning, true);
						}							
						EditorGUILayout.LabelField("Caustics texture", EditorStyles.boldLabel);
						checkChange(ref _target.TERRAIN_CausticsTex, (Texture2D)EditorGUILayout.ObjectField(_target.TERRAIN_CausticsTex, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					}
					
					GUILayout.Space(15);
					if (CAUSTICS_ENABLED_FIRST || CAUSTICS_ENABLED_ADD) {
						if (GUILayout.Button("Disable caustics (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_CAUSTICS_FIRST=false;
							_RTP_LODmanagerScript.RTP_CAUSTICS_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
						
						GUILayout.Space(15);							
						if (GUILayout.Button("Reset caustics settings numeric params to default")) {
							#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
							Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
							#else
							Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
							#endif
							_target.ReturnToDefaults("caustics");
							EditorUtility.SetDirty(_targetRT);
							_target.Refresh(null, _targetRT);
						}		
						
					} else {
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable caustics (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_CAUSTICS_FIRST=true;
							_RTP_LODmanagerScript.RTP_CAUSTICS_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
					}						
					
					EditorGUILayout.EndVertical();
					
					#endregion Settings - Caustics
					break;					
					
				case ReliefTerrainSettingsItems.Reflections:
					#region Settings - Reflections
					GUILayout.Space(6);
					
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoReflection),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Reflections settings", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;
					
					if (REFLECTION_ENABLED_FIRST || REFLECTION_ENABLED_ADD) {
						EditorGUILayout.HelpBox("Reflection map, realised as grayscale 2D texture (planar mapped sphere) is put on channel A of combined texture together of Perlin normal map (RG) and wetness mask (B).\n\nWhites are mapped to Reflection Color A, blacks are mapped to Reflection Color C, greys/mids (depending on center value) are mapped to Reflection Color B.\n\nAmount of reflection is set per layer, taken from view angle (Fresnel like effect), layer specularity (alpha channel of diffuse map) and water on the surface.",MessageType.None, true);
						
						EditorGUILayout.BeginHorizontal();
						Texture2D tmp_tex=_target.TERRAIN_ReflectionMap;
						ntex=tmp_tex;
						checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.TERRAIN_ReflectionMap, typeof(Texture2D), false, GUILayout.MinHeight(90), GUILayout.MinWidth(90), GUILayout.MaxWidth(90)));
						if (ntex!=tmp_tex) {
							Texture2D tex_prev=_target.TERRAIN_ReflectionMap;
							_target.TERRAIN_ReflectionMap=ntex;
							if (ntex) {
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Reflection map texture ("+ntex.name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
									}
								}
							}
							if (!_targetRT.PrepareGlobalNormalsAndSuperDetails(false, true)) _target.TERRAIN_ReflectionMap=tex_prev;
							_targetRT.RefreshTextures();
							_target.Refresh(null, _targetRT);
						}
						RTPColorChannels nchannel=RTPColorChannels.R;
						EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
						checkChange(ref nchannel, (RTPColorChannels)EditorGUILayout.EnumPopup(_target.TERRAIN_ReflectionMap_channel));
						if (nchannel!=_target.TERRAIN_ReflectionMap_channel) {
							_target.TERRAIN_ReflectionMap_channel=nchannel;
							_targetRT.PrepareGlobalNormalsAndSuperDetails(false,true);
						}
						EditorGUILayout.EndHorizontal();
						
						checkChange(ref _target.TERRAIN_ReflColorA, EditorGUILayout.ColorField("Reflection color A", _target.TERRAIN_ReflColorA));
						checkChange(ref _target.TERRAIN_ReflColorB, EditorGUILayout.ColorField("Reflection color B", _target.TERRAIN_ReflColorB));
						checkChange(ref _target.TERRAIN_ReflColorC, EditorGUILayout.ColorField("Reflection color C", _target.TERRAIN_ReflColorC));
						checkChange(ref _target.TERRAIN_ReflColorCenter, EditorGUILayout.Slider("Reflection gradient center", _target.TERRAIN_ReflColorCenter,0.1f,0.9f));
						checkChange(ref _target.TERRAIN_ReflGlossAttenuation, EditorGUILayout.Slider("Roughness attenuation", _target.TERRAIN_ReflGlossAttenuation,0,1));
						EditorGUILayout.HelpBox("Reflection map can rotate (imitating clouds moving around), option below can be separately enabled in RTP_LODmanager.",MessageType.None, true);
						if (REFLECTION_ROTATION_ENABLED || REFLECTION_ROTATION_ENABLED) {
							if (GUILayout.Button("Disable reflection rotation (rebuild shaders via RTP_LODmanager)")) {
								_RTP_LODmanagerScript.RTP_ROTATE_REFLECTION=false;
								if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
									Selection.activeObject=_RTP_LODmanagerScript.gameObject;
									_RTP_LODmanagerScript.dont_sync=true;
								}
							}
						} else {
							//EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
							if (GUILayout.Button("Enable reflection rotation (rebuild shaders via RTP_LODmanager)")) {
								_RTP_LODmanagerScript.RTP_ROTATE_REFLECTION=true;
								if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
									Selection.activeObject=_RTP_LODmanagerScript.gameObject;
									_RTP_LODmanagerScript.dont_sync=true;
								}
							}
						}						
						EditorGUI.BeginDisabledGroup(!REFLECTION_ROTATION_ENABLED);
						checkChange(ref _target.TERRAIN_ReflectionRotSpeed, EditorGUILayout.Slider("Rotation speed", _target.TERRAIN_ReflectionRotSpeed, 0, 2));
						EditorGUI.EndDisabledGroup();
						//EditorGUILayout.Space();
						//checkChange(ref _target.TERRAIN_FresnelPow, EditorGUILayout.Slider("Fresnel exponent", _target.TERRAIN_FresnelPow, 0.5f, 32f));
						//checkChange(ref _target.TERRAIN_FresnelOffset, EditorGUILayout.Slider("Fresnel offset", _target.TERRAIN_FresnelOffset, 0, 0.9f));
					}
					GUILayout.Space(15);
					if (REFLECTION_ENABLED_FIRST || REFLECTION_ENABLED_ADD) {
						if (GUILayout.Button("Disable reflection (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_REFLECTION_FIRST=false;
							_RTP_LODmanagerScript.RTP_REFLECTION_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
						
						GUILayout.Space(15);	
						if (GUILayout.Button("Reset reflection settings numeric params to default")) {
							#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
							Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
							#else
							Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
							#endif
							_target.ReturnToDefaults("reflection");
							EditorUtility.SetDirty(_targetRT);
							_target.Refresh(null, _targetRT);
						}	
						
					} else {
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable reflection (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_REFLECTION_FIRST=true;
							_RTP_LODmanagerScript.RTP_REFLECTION_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
					}	
					
					EditorGUILayout.EndVertical();
					
					#endregion Settings - Reflections
					break;					
					
				}
				
				GUILayout.Space(8);
				//Begin_Global_Indent();
				if (GUILayout.Button("Reset all numeric params to default")) {
					if (EditorUtility.DisplayDialog("Warning", "Are you sure to reset all RTP numeric values to their defaults ?","Yes","Cancel")) {
						#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
						Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
						#else
						Undo.RecordObject((ReliefTerrain)target, "Undo relief terrain edit");
						#endif
						_target.ReturnToDefaults();
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh(null, _targetRT);
					}
				}	
				
				#endregion ALLSettings
			}
			
			if (dirtyFlag) {
				_target.SyncGlobalPropsAcrossTerrainGroups();
				EditorUtility.SetDirty(_targetRT);
				_targetRT.RefreshTextures();				
				_target.Refresh(null, _targetRT);
			}
			
			GUILayout.Space(10);
			//DrawDefaultInspector();
			if (_target.activateObject) {
				Selection.activeObject=_target.activateObject;
				_target.activateObject=null;
			}
			
			
			Event current = Event.current;
			switch(current.type) {
			case EventType.keyDown:
				if (current.keyCode==KeyCode.M) {
					_target.paint_flag=!_target.paint_flag;
					if (!_targetRT.GetComponent<Collider>() || !_targetRT.GetComponent<Collider>().enabled) _target.paint_flag=false;
					if (_target.paint_flag) {
						if (_target.submenu!=ReliefTerrainMenuItems.GeneralSettings || (_target.submenu_settings!=ReliefTerrainSettingsItems.GlobalColor && _target.submenu_settings!=ReliefTerrainSettingsItems.Water)) {
							_target.paint_flag=false;
						}
						if (_target.submenu==ReliefTerrainMenuItems.GeneralSettings) {
							if (_target.submenu_settings==ReliefTerrainSettingsItems.Water) {
								if (!_targetRT.PrepareGlobalNormalsAndSuperDetails(true, true)) {
									_target.paint_flag=false;
								}
								_target.paint_wetmask=true;
								_target.paint_alpha_flag=true;
							}
							//							if (_target.submenu_settings==ReliefTerrainSettingsItems.GlobalColor) {
							//								if (!_target.prepare_tmpTexture(true)) {
							//									_target.paint_flag=false;
							//								}
							//							}							
						}
					}					
					if (_target.paint_flag) {
						UnityEditor.Tools.current=Tool.View;
						ReliefTerrain._SceneGUI = new SceneView.OnSceneFunc(CustomOnSceneGUI);
						SceneView.onSceneGUIDelegate += ReliefTerrain._SceneGUI;
					} else {
						UnityEditor.Tools.current=prev_tool;
						SceneView.onSceneGUIDelegate -= ReliefTerrain._SceneGUI;
					}
					EditorUtility.SetDirty(target);
				}
				break;
			}			
		}
		
		private void PrepareAtlases(int which) {
			ReliefTerrain _targetRT=(ReliefTerrain)target;
			ReliefTerrainGlobalSettingsHolder _target=_targetRT.globalSettingsHolder;
			
			int min_size=9999;
			bool any_splat=false;
			for(int n=which*4; (n<which*4+4) && (n<_target.numLayers); n++) {
				if (_target.splats[n]) { // czasem może byc błędnie wprowadzony jako null
					if (_target.splats[n].width<min_size) min_size=_target.splats[n].width;
					any_splat=true;
				}		
			}
			if (!any_splat) min_size=512;
			for(int n=which*4; (n<which*4+4) && (n<_target.numLayers); n++) {
				AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.splats[n]));
				if (_importer) {
					TextureImporter tex_importer=(TextureImporter)_importer;
					bool reimport_flag=false;
					if (!tex_importer.isReadable) {
						Debug.LogWarning("Detail texture "+n+" ("+_target.splats[n].name+") has been reimported as readable.");
						tex_importer.isReadable=true;
						reimport_flag=true;
					}
					if (_target.splats[n] && _target.splats[n].width>min_size) {
						Debug.LogWarning("Detail texture "+n+" ("+_target.splats[n].name+") has been reimported with "+min_size+" size.");
						tex_importer.maxTextureSize=min_size;
						reimport_flag=true;
					}
					if (reimport_flag) {
						AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.splats[n]),  ImportAssetOptions.ForceUpdate);
					}
				}					
			}				
			
			int i;
			for(i=0; i<_target.numLayers; i++) {
				try { 
					_target.splats[i].GetPixels(0,0,4,4,0);
				} catch (Exception e) {
					Debug.LogError("Splat texture "+i+" has to be marked as isReadable...");
					Debug.LogError(e.Message);
					return;
				}
			}
			int w=_target.splats[0].width;
			for(i=1; i<_target.numLayers; i++) {
				if (_target.splats[i].width!=w) {
					Debug.LogError("For performance reasons - all splats (detail textures) should have the same size");
					Debug.LogError("Detail tex 0 size="+w+" while detail tex "+i+" size="+_target.splats[i].width);
					return;
				}
			}
			
			ResetProgress( (4+8), "Padding textures" );
			
			int num=which*4;
			Texture2D[] splats=new Texture2D[4];
			for(i=0; i<splats.Length; i++) {
				if (num<_target.numLayers && _target.splats[num]!=null) {
					splats[i]=_target.splats[num];
					splats[i]=PadTex(splats[i], 16);
					CheckProgress();							
				} else {
					splats[i]=new Texture2D(min_size, min_size);
				}
				num++;
			}
			progress_description="Packing textures";
			
			if ( _target.splat_atlases[which] && AssetDatabase.GetAssetPath(_target.splat_atlases[which])=="") {
				DestroyImmediate(_target.splat_atlases[which]);
			}
			
			_target.atlas_glossBaked[which]=null;
			_target.splat_atlases[which]=new Texture2D(splats[0].width*2, splats[0].width*2);
			_target.splat_atlases[which].wrapMode=TextureWrapMode.Clamp;
			_target.splat_atlases[which].PackTextures( new Texture2D[4] { splats[0],splats[1],splats[2],splats[3] } , 0, _target.splat_atlases[which].width, false);
			progress_description="Blending corners";
			CheckProgress();
			//if (splats[0].width<=128) BlendMip(_target.splat_atlases[0], 3, 0.5f);
			//if (splats[0].width<=256) BlendMip(_target.splat_atlases[0], 4, 0.5f);
			//if (splats[0].width<=512) BlendMip(_target.splat_atlases[0], 5, 0.5f);
			BlendMip(_target.splat_atlases[which], 0, 0.5f, 16); BlendMip(_target.splat_atlases[which], 0, 0.5f, 15);
			CheckProgress();					
			BlendMip(_target.splat_atlases[which], 1, 0.5f, 8); BlendMip(_target.splat_atlases[which], 1, 0.5f, 7);
			CheckProgress();					
			BlendMip(_target.splat_atlases[which], 2, 0.5f, 4); BlendMip(_target.splat_atlases[which], 2, 0.5f, 3);
			CheckProgress();					
			BlendMip(_target.splat_atlases[which], 3, 0.5f, 2); BlendMip(_target.splat_atlases[which], 3, 0.5f, 1);
			CheckProgress();					
			BlendMip(_target.splat_atlases[which], 4, 0.5f, 2); BlendMip(_target.splat_atlases[which], 4, 0.5f, 1);
			CheckProgress();					
			BlendMip(_target.splat_atlases[which], 5, 0.5f, 1); BlendMip(_target.splat_atlases[which], 5, 0.5f, 0);
			CheckProgress();					
			for(i=6; i<_target.splat_atlases[which].mipmapCount-2; i++) BlendMip(_target.splat_atlases[which], i, 0.5f);
			progress_description="Packing textures";
			CheckProgress();					
			_target.splat_atlases[which].Compress(true);
			_target.splat_atlases[which].Apply(false,false);
			_target.splat_atlases[which].filterMode=FilterMode.Trilinear;
			_target.splat_atlases[which].anisoLevel=0;
			
			for(i=0; i<splats.Length; i++) {
				DestroyImmediate(splats[i]);
			}
			EditorUtility.ClearProgressBar();
			
		}
Beispiel #6
0
    public void SavePreset(ref ReliefTerrainPresetHolder holder)
    {
        holder.controlA=UnityEngine.Object.Instantiate(controlA) as Texture2D;
        holder.controlB=UnityEngine.Object.Instantiate(controlB) as Texture2D;
        holder.controlC=UnityEngine.Object.Instantiate(controlC) as Texture2D;

        holder.ColorGlobal=ColorGlobal;
        holder.NormalGlobal=NormalGlobal;
        holder.TreesGlobal=TreesGlobal;
        holder.BumpGlobalCombined=BumpGlobalCombined;
        holder.TERRAIN_WetMask=TERRAIN_WetMask;

        holder.globalColorModifed_flag=globalColorModifed_flag;
        holder.globalCombinedModifed_flag=globalCombinedModifed_flag;
        holder.globalWaterModifed_flag=globalWaterModifed_flag;

        // store global settigns
        globalSettingsHolder.SavePreset(ref holder);
    }
Beispiel #7
0
    public void RestorePreset(ReliefTerrainPresetHolder holder)
    {
        controlA=holder.controlA;
        controlB=holder.controlB;
        controlC=holder.controlC;

        SetCustomControlMaps();

        ColorGlobal=holder.ColorGlobal;
        NormalGlobal=holder.NormalGlobal;
        TreesGlobal=holder.TreesGlobal;
        BumpGlobalCombined=holder.BumpGlobalCombined;
        TERRAIN_WetMask=holder.TERRAIN_WetMask;

        globalColorModifed_flag=holder.globalColorModifed_flag;
        globalCombinedModifed_flag=holder.globalCombinedModifed_flag;
        globalWaterModifed_flag=holder.globalWaterModifed_flag;

        // local textures to splat textures
        RefreshTextures();

        // restore global settigns
        globalSettingsHolder.RestorePreset(holder);
    }
	public void SavePreset(ref ReliefTerrainPresetHolder holder) {
		Terrain terrainComp = (Terrain)GetComponent(typeof(Terrain));
		if (terrainComp) {
			if (controlA) holder.controlA=UnityEngine.Object.Instantiate(controlA) as Texture2D;
			if (controlB) holder.controlB=UnityEngine.Object.Instantiate(controlB) as Texture2D;
			if (controlC) holder.controlC=UnityEngine.Object.Instantiate(controlC) as Texture2D;
		} else {
			holder.controlA=controlA;
			holder.controlB=controlB;
			holder.controlC=controlC;
		}
		
		holder.ColorGlobal=ColorGlobal;
		holder.NormalGlobal=NormalGlobal;
		holder.TreesGlobal=TreesGlobal;
		holder.AmbientEmissiveMap=AmbientEmissiveMap;
		holder.BumpGlobalCombined=BumpGlobalCombined;
		holder.TERRAIN_WetMask=TERRAIN_WetMask;
		
		holder.globalColorModifed_flag=globalColorModifed_flag;
		holder.globalCombinedModifed_flag=globalCombinedModifed_flag;
		holder.globalWaterModifed_flag=globalWaterModifed_flag;	
		
		// store global settigns		
		globalSettingsHolder.SavePreset(ref holder);
	}	
    public void InterpolatePresets(ReliefTerrainPresetHolder holderA, ReliefTerrainPresetHolder holderB, float t)
    {
        RTP_MIP_BIAS=Mathf.Lerp(holderA.RTP_MIP_BIAS, holderB.RTP_MIP_BIAS, t);
        _SpecColor=Color.Lerp(holderA._SpecColor, holderB._SpecColor, t);
        RTP_DeferredAddPassSpec=Mathf.Lerp(holderA.RTP_DeferredAddPassSpec, holderB.RTP_DeferredAddPassSpec, t);

        MasterLayerBrightness=Mathf.Lerp(holderA.MasterLayerBrightness, holderB.MasterLayerBrightness, t);
        MasterLayerSaturation=Mathf.Lerp(holderA.MasterLayerSaturation, holderB.MasterLayerSaturation, t);

        BumpMapGlobalScale=Mathf.Lerp(holderA.BumpMapGlobalScale, holderB.BumpMapGlobalScale, t);
        GlobalColorMapBlendValues=Vector3.Lerp(holderA.GlobalColorMapBlendValues, holderB.GlobalColorMapBlendValues, t);
        GlobalColorMapSaturation=Mathf.Lerp(holderA.GlobalColorMapSaturation, holderB.GlobalColorMapSaturation, t);
        GlobalColorMapSaturationFar=Mathf.Lerp(holderA.GlobalColorMapSaturationFar, holderB.GlobalColorMapSaturationFar, t);
        //GlobalColorMapSaturationByPerlin=Mathf.Lerp(holderA.GlobalColorMapSaturationByPerlin, holderB.GlobalColorMapSaturationByPerlin, t);
        GlobalColorMapDistortByPerlin=Mathf.Lerp(holderA.GlobalColorMapDistortByPerlin, holderB.GlobalColorMapDistortByPerlin, t);
        GlobalColorMapBrightness=Mathf.Lerp(holderA.GlobalColorMapBrightness, holderB.GlobalColorMapBrightness, t);
        GlobalColorMapBrightnessFar=Mathf.Lerp(holderA.GlobalColorMapBrightnessFar, holderB.GlobalColorMapBrightnessFar, t);
        _GlobalColorMapNearMIP=Mathf.Lerp(holderA._GlobalColorMapNearMIP, holderB._GlobalColorMapNearMIP, t);
        _FarNormalDamp=Mathf.Lerp(holderA._FarNormalDamp, holderB._FarNormalDamp, t);

        blendMultiplier=Mathf.Lerp(holderA.blendMultiplier, holderB.blendMultiplier, t);

        ReliefTransform=Vector4.Lerp(holderA.ReliefTransform, holderB.ReliefTransform, t);
        DIST_STEPS=Mathf.Lerp(holderA.DIST_STEPS, holderB.DIST_STEPS, t);
        WAVELENGTH=Mathf.Lerp(holderA.WAVELENGTH, holderB.WAVELENGTH, t);
        ReliefBorderBlend=Mathf.Lerp(holderA.ReliefBorderBlend, holderB.ReliefBorderBlend, t);

        ExtrudeHeight=Mathf.Lerp(holderA.ExtrudeHeight, holderB.ExtrudeHeight, t);
        LightmapShading=Mathf.Lerp(holderA.LightmapShading, holderB.LightmapShading, t);

        SHADOW_STEPS=Mathf.Lerp(holderA.SHADOW_STEPS, holderB.SHADOW_STEPS, t);
        WAVELENGTH_SHADOWS=Mathf.Lerp(holderA.WAVELENGTH_SHADOWS, holderB.WAVELENGTH_SHADOWS, t);
        SHADOW_SMOOTH_STEPS=Mathf.Lerp(holderA.SHADOW_SMOOTH_STEPS, holderB.SHADOW_SMOOTH_STEPS, t);
        SelfShadowStrength=Mathf.Lerp(holderA.SelfShadowStrength, holderB.SelfShadowStrength, t);
        ShadowSmoothing=Mathf.Lerp(holderA.ShadowSmoothing, holderB.ShadowSmoothing, t);

        distance_start=Mathf.Lerp(holderA.distance_start, holderB.distance_start, t);
        distance_transition=Mathf.Lerp(holderA.distance_transition, holderB.distance_transition, t);
        distance_start_bumpglobal=Mathf.Lerp(holderA.distance_start_bumpglobal, holderB.distance_start_bumpglobal, t);
        distance_transition_bumpglobal=Mathf.Lerp(holderA.distance_transition_bumpglobal, holderB.distance_transition_bumpglobal, t);
        rtp_perlin_start_val=Mathf.Lerp(holderA.rtp_perlin_start_val, holderB.rtp_perlin_start_val, t);

        // (interpolating this makes no sense)
        //_Phong=Mathf.Lerp(holderA._Phong, holderB._Phong, t);
        //tessHeight=Mathf.Lerp(holderA.tessHeight, holderB.tessHeight, t);

        trees_shadow_distance_start=Mathf.Lerp(holderA.trees_shadow_distance_start, holderB.trees_shadow_distance_start, t);
        trees_shadow_distance_transition=Mathf.Lerp(holderA.trees_shadow_distance_transition, holderB.trees_shadow_distance_transition, t);
        trees_shadow_value=Mathf.Lerp(holderA.trees_shadow_value, holderB.trees_shadow_value, t);
        trees_pixel_distance_start=Mathf.Lerp(holderA.trees_pixel_distance_start, holderB.trees_pixel_distance_start, t);
        trees_pixel_distance_transition=Mathf.Lerp(holderA.trees_pixel_distance_transition, holderB.trees_pixel_distance_transition, t);
        trees_pixel_blend_val=Mathf.Lerp(holderA.trees_pixel_blend_val, holderB.trees_pixel_blend_val, t);
        global_normalMap_multiplier=Mathf.Lerp (holderA.global_normalMap_multiplier, holderB.global_normalMap_multiplier, t);
        global_normalMap_farUsage=Mathf.Lerp (holderA.global_normalMap_farUsage, holderB.global_normalMap_farUsage, t);

        _AmbientEmissiveMultiplier=Mathf.Lerp (holderA._AmbientEmissiveMultiplier, holderB._AmbientEmissiveMultiplier, t);
        _AmbientEmissiveRelief=Mathf.Lerp(holderA._AmbientEmissiveRelief, holderB._AmbientEmissiveRelief, t);

        _SuperDetailTiling=Mathf.Lerp(holderA._SuperDetailTiling, holderB._SuperDetailTiling, t);

        // reflection
        TERRAIN_ReflColorA=Color.Lerp(holderA.TERRAIN_ReflColorA, holderB.TERRAIN_ReflColorA, t);
        TERRAIN_ReflColorB=Color.Lerp(holderA.TERRAIN_ReflColorB, holderB.TERRAIN_ReflColorB, t);
        TERRAIN_ReflColorC=Color.Lerp(holderA.TERRAIN_ReflColorC, holderB.TERRAIN_ReflColorC, t);
        TERRAIN_ReflColorCenter=Mathf.Lerp(holderA.TERRAIN_ReflColorCenter, holderB.TERRAIN_ReflColorCenter, t);
        TERRAIN_ReflGlossAttenuation=Mathf.Lerp(holderA.TERRAIN_ReflGlossAttenuation, holderB.TERRAIN_ReflGlossAttenuation, t);
        TERRAIN_ReflectionRotSpeed=Mathf.Lerp(holderA.TERRAIN_ReflectionRotSpeed, holderB.TERRAIN_ReflectionRotSpeed, t);

        // water/wet
        TERRAIN_GlobalWetness=Mathf.Lerp(holderA.TERRAIN_GlobalWetness, holderB.TERRAIN_GlobalWetness, t);

        TERRAIN_RippleScale=Mathf.Lerp(holderA.TERRAIN_RippleScale, holderB.TERRAIN_RippleScale, t);
        TERRAIN_FlowScale=Mathf.Lerp(holderA.TERRAIN_FlowScale, holderB.TERRAIN_FlowScale, t);
        TERRAIN_FlowSpeed=Mathf.Lerp(holderA.TERRAIN_FlowSpeed, holderB.TERRAIN_FlowSpeed, t);
        TERRAIN_FlowCycleScale=Mathf.Lerp(holderA.TERRAIN_FlowCycleScale, holderB.TERRAIN_FlowCycleScale, t);
        TERRAIN_FlowMipOffset=Mathf.Lerp(holderA.TERRAIN_FlowMipOffset, holderB.TERRAIN_FlowMipOffset, t);
        TERRAIN_WetDarkening=Mathf.Lerp (holderA.TERRAIN_WetDarkening, holderB.TERRAIN_WetDarkening, t);
        TERRAIN_WetDropletsStrength=Mathf.Lerp(holderA.TERRAIN_WetDropletsStrength, holderB.TERRAIN_WetDropletsStrength, t);
        TERRAIN_WetHeight_Treshold=Mathf.Lerp(holderA.TERRAIN_WetHeight_Treshold, holderB.TERRAIN_WetHeight_Treshold, t);
        TERRAIN_WetHeight_Transition=Mathf.Lerp(holderA.TERRAIN_WetHeight_Transition, holderB.TERRAIN_WetHeight_Transition, t);

        TERRAIN_RainIntensity=Mathf.Lerp(holderA.TERRAIN_RainIntensity, holderB.TERRAIN_RainIntensity, t);
        TERRAIN_DropletsSpeed=Mathf.Lerp(holderA.TERRAIN_DropletsSpeed, holderB.TERRAIN_DropletsSpeed, t);

        TERRAIN_mipoffset_flowSpeed=Mathf.Lerp(holderA.TERRAIN_mipoffset_flowSpeed, holderB.TERRAIN_mipoffset_flowSpeed, t);

        TERRAIN_CausticsAnimSpeed=Mathf.Lerp(holderA.TERRAIN_CausticsAnimSpeed, holderB.TERRAIN_CausticsAnimSpeed, t);
        TERRAIN_CausticsColor=Color.Lerp(holderA.TERRAIN_CausticsColor, holderB.TERRAIN_CausticsColor,t);
        TERRAIN_CausticsWaterLevel=Mathf.Lerp(holderA.TERRAIN_CausticsWaterLevel, holderB.TERRAIN_CausticsWaterLevel, t);
        TERRAIN_CausticsWaterLevelByAngle=Mathf.Lerp(holderA.TERRAIN_CausticsWaterLevelByAngle, holderB.TERRAIN_CausticsWaterLevelByAngle, t);
        TERRAIN_CausticsWaterDeepFadeLength=Mathf.Lerp(holderA.TERRAIN_CausticsWaterDeepFadeLength, holderB.TERRAIN_CausticsWaterDeepFadeLength, t);
        TERRAIN_CausticsWaterShallowFadeLength=Mathf.Lerp(holderA.TERRAIN_CausticsWaterShallowFadeLength, holderB.TERRAIN_CausticsWaterShallowFadeLength, t);
        TERRAIN_CausticsTilingScale=Mathf.Lerp (holderA.TERRAIN_CausticsTilingScale, holderB.TERRAIN_CausticsTilingScale, t);

        rtp_customAmbientCorrection=Color.Lerp(holderA.rtp_customAmbientCorrection, holderB.rtp_customAmbientCorrection, t);
        TERRAIN_IBL_DiffAO_Damp=Mathf.Lerp(holderA.TERRAIN_IBL_DiffAO_Damp, holderB.TERRAIN_IBL_DiffAO_Damp, t);
        TERRAIN_IBLRefl_SpecAO_Damp=Mathf.Lerp(holderA.TERRAIN_IBLRefl_SpecAO_Damp, holderB.TERRAIN_IBLRefl_SpecAO_Damp, t);

        RTP_AOsharpness=Mathf.Lerp(holderA.RTP_AOsharpness, holderB.RTP_AOsharpness, t);
        RTP_AOamp=Mathf.Lerp(holderA.RTP_AOamp, holderB.RTP_AOamp, t);
        RTP_LightDefVector=Vector4.Lerp(holderA.RTP_LightDefVector, holderB.RTP_LightDefVector, t);
        RTP_ReflexLightDiffuseColor=Color.Lerp(holderA.RTP_ReflexLightDiffuseColor, holderB.RTP_ReflexLightDiffuseColor, t);
        RTP_ReflexLightDiffuseColor2=Color.Lerp(holderA.RTP_ReflexLightDiffuseColor2, holderB.RTP_ReflexLightDiffuseColor2, t);
        RTP_ReflexLightSpecColor=Color.Lerp(holderA.RTP_ReflexLightSpecColor, holderB.RTP_ReflexLightSpecColor, t);

        EmissionRefractFiltering=Mathf.Lerp(holderA.EmissionRefractFiltering, holderB.EmissionRefractFiltering, t);
        EmissionRefractAnimSpeed=Mathf.Lerp(holderA.EmissionRefractAnimSpeed, holderB.EmissionRefractAnimSpeed, t);

        VerticalTextureGlobalBumpInfluence=Mathf.Lerp(holderA.VerticalTextureGlobalBumpInfluence, holderB.VerticalTextureGlobalBumpInfluence, t);
        VerticalTextureTiling=Mathf.Lerp(holderA.VerticalTextureTiling, holderB.VerticalTextureTiling, t);

        // snow
        _snow_strength=Mathf.Lerp(holderA._snow_strength, holderB._snow_strength, t);
        _global_color_brightness_to_snow=Mathf.Lerp(holderA._global_color_brightness_to_snow, holderB._global_color_brightness_to_snow, t);
        _snow_slope_factor=Mathf.Lerp(holderA._snow_slope_factor, holderB._snow_slope_factor, t);
        _snow_edge_definition=Mathf.Lerp(holderA._snow_edge_definition, holderB._snow_edge_definition, t);
        _snow_height_treshold=Mathf.Lerp(holderA._snow_height_treshold, holderB._snow_height_treshold, t);
        _snow_height_transition=Mathf.Lerp(holderA._snow_height_transition, holderB._snow_height_transition, t);
        _snow_color=Color.Lerp(holderA._snow_color, holderB._snow_color, t);
        _snow_specular=Mathf.Lerp(holderA._snow_specular, holderB._snow_specular, t);
        _snow_gloss=Mathf.Lerp(holderA._snow_gloss, holderB._snow_gloss, t);
        _snow_reflectivness=Mathf.Lerp(holderA._snow_reflectivness, holderB._snow_reflectivness, t);
        _snow_deep_factor=Mathf.Lerp(holderA._snow_deep_factor, holderB._snow_deep_factor, t);
        _snow_fresnel=Mathf.Lerp(holderA._snow_fresnel, holderB._snow_fresnel, t);
        _snow_diff_fresnel=Mathf.Lerp(holderA._snow_diff_fresnel, holderB._snow_diff_fresnel, t);
        _snow_IBL_DiffuseStrength=Mathf.Lerp(holderA._snow_IBL_DiffuseStrength, holderB._snow_IBL_DiffuseStrength, t);
        _snow_IBL_SpecStrength=Mathf.Lerp(holderA._snow_IBL_SpecStrength, holderB._snow_IBL_SpecStrength, t);

        //////////////////////
        // layer_dependent arrays
        //////////////////////
        for(int i=0; i<holderA.Spec.Length; i++) {
            if (i<Spec.Length) {
                Spec[i]=Mathf.Lerp(holderA.Spec[i], holderB.Spec[i], t);
                FarSpecCorrection[i]=Mathf.Lerp(holderA.FarSpecCorrection[i], holderB.FarSpecCorrection[i], t);
                MixScale[i]=Mathf.Lerp(holderA.MixScale[i], holderB.MixScale[i], t);
                MixBlend[i]=Mathf.Lerp(holderA.MixBlend[i], holderB.MixBlend[i], t);
                MixSaturation[i]=Mathf.Lerp(holderA.MixSaturation[i], holderB.MixSaturation[i], t);

                // RTP3.1
                RTP_gloss2mask[i]=Mathf.Lerp(holderA.RTP_gloss2mask[i], holderB.RTP_gloss2mask[i], t);
                RTP_gloss_mult[i]=Mathf.Lerp(holderA.RTP_gloss_mult[i], holderB.RTP_gloss_mult[i], t);
                RTP_gloss_shaping[i]=Mathf.Lerp(holderA.RTP_gloss_shaping[i], holderB.RTP_gloss_shaping[i], t);
                RTP_Fresnel[i]=Mathf.Lerp(holderA.RTP_Fresnel[i], holderB.RTP_Fresnel[i], t);
                RTP_FresnelAtten[i]=Mathf.Lerp(holderA.RTP_FresnelAtten[i], holderB.RTP_FresnelAtten[i], t);
                RTP_DiffFresnel[i]=Mathf.Lerp(holderA.RTP_DiffFresnel[i], holderB.RTP_DiffFresnel[i], t);
                RTP_IBL_bump_smoothness[i]=Mathf.Lerp(holderA.RTP_IBL_bump_smoothness[i], holderB.RTP_IBL_bump_smoothness[i], t);
                RTP_IBL_DiffuseStrength[i]=Mathf.Lerp(holderA.RTP_IBL_DiffuseStrength[i], holderB.RTP_IBL_DiffuseStrength[i], t);
                RTP_IBL_SpecStrength[i]=Mathf.Lerp(holderA.RTP_IBL_SpecStrength[i], holderB.RTP_IBL_SpecStrength[i], t);
                _DeferredSpecDampAddPass[i]=Mathf.Lerp(holderA._DeferredSpecDampAddPass[i], holderB._DeferredSpecDampAddPass[i], t);

                MixBrightness[i]=Mathf.Lerp(holderA.MixBrightness[i], holderB.MixBrightness[i], t);
                MixReplace[i]=Mathf.Lerp(holderA.MixReplace[i], holderB.MixReplace[i], t);
                LayerBrightness[i]=Mathf.Lerp(holderA.LayerBrightness[i], holderB.LayerBrightness[i], t);
                LayerBrightness2Spec[i]=Mathf.Lerp(holderA.LayerBrightness2Spec[i], holderB.LayerBrightness2Spec[i], t);
                LayerAlbedo2SpecColor[i]=Mathf.Lerp(holderA.LayerAlbedo2SpecColor[i], holderB.LayerAlbedo2SpecColor[i], t);
                LayerSaturation[i]=Mathf.Lerp(holderA.LayerSaturation[i], holderB.LayerSaturation[i], t);
                LayerEmission[i]=Mathf.Lerp(holderA.LayerEmission[i], holderB.LayerEmission[i], t);
                LayerEmissionColor[i]=Color.Lerp(holderA.LayerEmissionColor[i], holderB.LayerEmissionColor[i], t);
                LayerEmissionRefractStrength[i]=Mathf.Lerp(holderA.LayerEmissionRefractStrength[i], holderB.LayerEmissionRefractStrength[i], t);
                LayerEmissionRefractHBedge[i]=Mathf.Lerp(holderA.LayerEmissionRefractHBedge[i], holderB.LayerEmissionRefractHBedge[i], t);

                GlobalColorPerLayer[i]=Mathf.Lerp(holderA.GlobalColorPerLayer[i], holderB.GlobalColorPerLayer[i], t);
                GlobalColorBottom[i]=Mathf.Lerp(holderA.GlobalColorBottom[i], holderB.GlobalColorBottom[i], t);
                GlobalColorTop[i]=Mathf.Lerp(holderA.GlobalColorTop[i], holderB.GlobalColorTop[i], t);
                GlobalColorColormapLoSat[i]=Mathf.Lerp(holderA.GlobalColorColormapLoSat[i], holderB.GlobalColorColormapLoSat[i], t);
                GlobalColorColormapHiSat[i]=Mathf.Lerp(holderA.GlobalColorColormapHiSat[i], holderB.GlobalColorColormapHiSat[i], t);
                GlobalColorLayerLoSat[i]=Mathf.Lerp(holderA.GlobalColorLayerLoSat[i], holderB.GlobalColorLayerLoSat[i], t);
                GlobalColorLayerHiSat[i]=Mathf.Lerp(holderA.GlobalColorLayerHiSat[i], holderB.GlobalColorLayerHiSat[i], t);
                GlobalColorLoBlend[i]=Mathf.Lerp(holderA.GlobalColorLoBlend[i], holderB.GlobalColorLoBlend[i], t);
                GlobalColorHiBlend[i]=Mathf.Lerp(holderA.GlobalColorHiBlend[i], holderB.GlobalColorHiBlend[i], t);

                PER_LAYER_HEIGHT_MODIFIER[i]=Mathf.Lerp(holderA.PER_LAYER_HEIGHT_MODIFIER[i], holderB.PER_LAYER_HEIGHT_MODIFIER[i], t);
                _SuperDetailStrengthMultA[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultA[i], holderB._SuperDetailStrengthMultA[i], t);
                _SuperDetailStrengthMultASelfMaskNear[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultASelfMaskNear[i], holderB._SuperDetailStrengthMultASelfMaskNear[i], t);
                _SuperDetailStrengthMultASelfMaskFar[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultASelfMaskFar[i], holderB._SuperDetailStrengthMultASelfMaskFar[i], t);
                _SuperDetailStrengthMultB[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultB[i], holderB._SuperDetailStrengthMultB[i], t);
                _SuperDetailStrengthMultBSelfMaskNear[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultBSelfMaskNear[i], holderB._SuperDetailStrengthMultBSelfMaskNear[i], t);
                _SuperDetailStrengthMultBSelfMaskFar[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultBSelfMaskFar[i], holderB._SuperDetailStrengthMultBSelfMaskFar[i], t);
                _SuperDetailStrengthNormal[i]=Mathf.Lerp(holderA._SuperDetailStrengthNormal[i], holderB._SuperDetailStrengthNormal[i], t);
                _BumpMapGlobalStrength[i]=Mathf.Lerp(holderA._BumpMapGlobalStrength[i], holderB._BumpMapGlobalStrength[i], t);

                AO_strength[i]=Mathf.Lerp(holderA.AO_strength[i], holderB.AO_strength[i], t);
                VerticalTextureStrength[i]=Mathf.Lerp(holderA.VerticalTextureStrength[i], holderB.VerticalTextureStrength[i], t);

                _snow_strength_per_layer[i]=Mathf.Lerp(holderA._snow_strength_per_layer[i], holderB._snow_strength_per_layer[i], t);

                // wet
                TERRAIN_LayerWetStrength[i]=Mathf.Lerp(holderA.TERRAIN_LayerWetStrength[i], holderB.TERRAIN_LayerWetStrength[i], t);
                TERRAIN_WaterLevel[i]=Mathf.Lerp(holderA.TERRAIN_WaterLevel[i], holderB.TERRAIN_WaterLevel[i], t);
                TERRAIN_WaterLevelSlopeDamp[i]=Mathf.Lerp(holderA.TERRAIN_WaterLevelSlopeDamp[i], holderB.TERRAIN_WaterLevelSlopeDamp[i], t);
                TERRAIN_WaterEdge[i]=Mathf.Lerp(holderA.TERRAIN_WaterEdge[i], holderB.TERRAIN_WaterEdge[i], t);
                TERRAIN_WaterSpecularity[i]=Mathf.Lerp(holderA.TERRAIN_WaterSpecularity[i], holderB.TERRAIN_WaterSpecularity[i], t);
                TERRAIN_WaterGloss[i]=Mathf.Lerp(holderA.TERRAIN_WaterGloss[i], holderB.TERRAIN_WaterGloss[i], t);
                TERRAIN_WaterGlossDamper[i]=Mathf.Lerp(holderA.TERRAIN_WaterGlossDamper[i], holderB.TERRAIN_WaterGlossDamper[i], t);
                TERRAIN_WaterOpacity[i]=Mathf.Lerp(holderA.TERRAIN_WaterOpacity[i], holderB.TERRAIN_WaterOpacity[i], t);
                TERRAIN_Refraction[i]=Mathf.Lerp(holderA.TERRAIN_Refraction[i], holderB.TERRAIN_Refraction[i], t);
                TERRAIN_WetRefraction[i]=Mathf.Lerp(holderA.TERRAIN_WetRefraction[i], holderB.TERRAIN_WetRefraction[i], t);
                TERRAIN_Flow[i]=Mathf.Lerp(holderA.TERRAIN_Flow[i], holderB.TERRAIN_Flow[i], t);
                TERRAIN_WetFlow[i]=Mathf.Lerp(holderA.TERRAIN_WetFlow[i], holderB.TERRAIN_WetFlow[i], t);
                TERRAIN_WetSpecularity[i]=Mathf.Lerp(holderA.TERRAIN_WetSpecularity[i], holderB.TERRAIN_WetSpecularity[i], t);
                TERRAIN_WetGloss[i]=Mathf.Lerp(holderA.TERRAIN_WetGloss[i], holderB.TERRAIN_WetGloss[i], t);
                TERRAIN_WaterColor[i]=Color.Lerp(holderA.TERRAIN_WaterColor[i], holderB.TERRAIN_WaterColor[i], t);
                TERRAIN_WaterIBL_SpecWetStrength[i]=Mathf.Lerp(holderA.TERRAIN_WaterIBL_SpecWetStrength[i], holderB.TERRAIN_WaterIBL_SpecWetStrength[i], t);
                TERRAIN_WaterIBL_SpecWaterStrength[i]=Mathf.Lerp(holderA.TERRAIN_WaterIBL_SpecWaterStrength[i], holderB.TERRAIN_WaterIBL_SpecWaterStrength[i], t);
                TERRAIN_WaterEmission[i]=Mathf.Lerp(holderA.TERRAIN_WaterEmission[i], holderB.TERRAIN_WaterEmission[i], t);
            }
        }
    }
    public void SavePreset(ref ReliefTerrainPresetHolder holder)
    {
        holder.numLayers=numLayers;
        holder.splats=new Texture2D[splats.Length];
        for(int i=0; i<holder.splats.Length; i++) {
            holder.splats[i]=splats[i];
        }

        holder.splat_atlases=new Texture2D[3];
        for(int i=0; i<splat_atlases.Length; i++) {
            holder.splat_atlases[i]=splat_atlases[i];
        }

        holder.gloss_baked=gloss_baked;

        holder.RTP_MIP_BIAS=RTP_MIP_BIAS;
        holder._SpecColor=_SpecColor;
        holder.RTP_DeferredAddPassSpec=RTP_DeferredAddPassSpec;

        holder.MasterLayerBrightness=MasterLayerBrightness;
        holder.MasterLayerSaturation=MasterLayerSaturation;

        holder.SuperDetailA_channel=SuperDetailA_channel;
        holder.SuperDetailB_channel=SuperDetailB_channel;

        holder.Bump01=Bump01;
        holder.Bump23=Bump23;
        holder.Bump45=Bump45;
        holder.Bump67=Bump67;
        holder.Bump89=Bump89;
        holder.BumpAB=BumpAB;

        holder.SSColorCombinedA=SSColorCombinedA;
        holder.SSColorCombinedB=SSColorCombinedB;

        holder.BumpGlobal=BumpGlobal;

        holder.VerticalTexture=VerticalTexture;
        holder.BumpMapGlobalScale=BumpMapGlobalScale;
        holder.GlobalColorMapBlendValues=GlobalColorMapBlendValues;
        holder.GlobalColorMapSaturation=GlobalColorMapSaturation;
        holder.GlobalColorMapSaturationFar=GlobalColorMapSaturationFar;
        //holder.GlobalColorMapSaturationByPerlin=GlobalColorMapSaturationByPerlin;
        holder.GlobalColorMapDistortByPerlin=GlobalColorMapDistortByPerlin;
        holder.GlobalColorMapBrightness=GlobalColorMapBrightness;
        holder.GlobalColorMapBrightnessFar=GlobalColorMapBrightnessFar;
        holder._GlobalColorMapNearMIP=_GlobalColorMapNearMIP;
        holder._FarNormalDamp=_FarNormalDamp;

        holder.blendMultiplier=blendMultiplier;

        holder.HeightMap=HeightMap;
        holder.HeightMap2=HeightMap2;
        holder.HeightMap3=HeightMap3;

        holder.ReliefTransform=ReliefTransform;
        holder.DIST_STEPS=DIST_STEPS;
        holder.WAVELENGTH=WAVELENGTH;
        holder.ReliefBorderBlend=ReliefBorderBlend;

        holder.ExtrudeHeight=ExtrudeHeight;
        holder.LightmapShading=LightmapShading;

        holder.SHADOW_STEPS=SHADOW_STEPS;
        holder.WAVELENGTH_SHADOWS=WAVELENGTH_SHADOWS;
        holder.SHADOW_SMOOTH_STEPS=SHADOW_SMOOTH_STEPS;
        holder.SelfShadowStrength=SelfShadowStrength;
        holder.ShadowSmoothing=ShadowSmoothing;

        holder.distance_start=distance_start;
        holder.distance_transition=distance_transition;
        holder.distance_start_bumpglobal=distance_start_bumpglobal;
        holder.distance_transition_bumpglobal=distance_transition_bumpglobal;
        holder.rtp_perlin_start_val=rtp_perlin_start_val;

        holder._Phong = _Phong;
        holder.tessHeight = tessHeight;
        holder._TessSubdivisions = _TessSubdivisions;
        holder._TessSubdivisionsFar = _TessSubdivisionsFar;
        holder._TessYOffset = _TessYOffset;

        holder.trees_shadow_distance_start=trees_shadow_distance_start;
        holder.trees_shadow_distance_transition=trees_shadow_distance_transition;
        holder.trees_shadow_value=trees_shadow_value;
        holder.trees_pixel_distance_start=trees_pixel_distance_start;
        holder.trees_pixel_distance_transition=trees_pixel_distance_transition;
        holder.trees_pixel_blend_val=trees_pixel_blend_val;
        holder.global_normalMap_multiplier=global_normalMap_multiplier;
        holder.global_normalMap_farUsage=global_normalMap_farUsage;

        holder._AmbientEmissiveMultiplier=_AmbientEmissiveMultiplier;
        holder._AmbientEmissiveRelief=_AmbientEmissiveRelief;

        holder.rtp_mipoffset_globalnorm=rtp_mipoffset_globalnorm;
        holder._SuperDetailTiling=_SuperDetailTiling;
        holder.SuperDetailA=SuperDetailA;
        holder.SuperDetailB=SuperDetailB;

        // reflection
        holder.TERRAIN_ReflectionMap=TERRAIN_ReflectionMap;
        holder.TERRAIN_ReflectionMap_channel=TERRAIN_ReflectionMap_channel;
        holder.TERRAIN_ReflColorA=TERRAIN_ReflColorA;
        holder.TERRAIN_ReflColorB=TERRAIN_ReflColorB;
        holder.TERRAIN_ReflColorC=TERRAIN_ReflColorC;
        holder.TERRAIN_ReflColorCenter=TERRAIN_ReflColorCenter;
        holder.TERRAIN_ReflGlossAttenuation=TERRAIN_ReflGlossAttenuation;
        holder.TERRAIN_ReflectionRotSpeed=TERRAIN_ReflectionRotSpeed;

        // water/wet
        holder.TERRAIN_GlobalWetness=TERRAIN_GlobalWetness;

        holder.TERRAIN_RippleMap=TERRAIN_RippleMap;
        holder.TERRAIN_RippleScale=TERRAIN_RippleScale;
        holder.TERRAIN_FlowScale=TERRAIN_FlowScale;
        holder.TERRAIN_FlowSpeed=TERRAIN_FlowSpeed;
        holder.TERRAIN_FlowCycleScale=TERRAIN_FlowCycleScale;
        holder.TERRAIN_FlowMipOffset=TERRAIN_FlowMipOffset;
        holder.TERRAIN_WetDarkening=TERRAIN_WetDarkening;
        holder.TERRAIN_WetDropletsStrength=TERRAIN_WetDropletsStrength;
        holder.TERRAIN_WetHeight_Treshold=TERRAIN_WetHeight_Treshold;
        holder.TERRAIN_WetHeight_Transition=TERRAIN_WetHeight_Transition;

        holder.TERRAIN_RainIntensity=TERRAIN_RainIntensity;
        holder.TERRAIN_DropletsSpeed=TERRAIN_DropletsSpeed;

        holder.TERRAIN_mipoffset_flowSpeed=TERRAIN_mipoffset_flowSpeed;

        // caustics
        holder.TERRAIN_CausticsAnimSpeed=TERRAIN_CausticsAnimSpeed;
        holder.TERRAIN_CausticsColor=TERRAIN_CausticsColor;
        holder.TERRAIN_CausticsWaterLevel=TERRAIN_CausticsWaterLevel;
        holder.TERRAIN_CausticsWaterLevelByAngle=TERRAIN_CausticsWaterLevelByAngle;
        holder.TERRAIN_CausticsWaterDeepFadeLength=TERRAIN_CausticsWaterDeepFadeLength;
        holder.TERRAIN_CausticsWaterShallowFadeLength=TERRAIN_CausticsWaterShallowFadeLength;
        holder.TERRAIN_CausticsTilingScale=TERRAIN_CausticsTilingScale;
        holder.TERRAIN_CausticsTex=TERRAIN_CausticsTex;

        holder.rtp_customAmbientCorrection=rtp_customAmbientCorrection;
        holder.TERRAIN_IBL_DiffAO_Damp=TERRAIN_IBL_DiffAO_Damp;
        holder.TERRAIN_IBLRefl_SpecAO_Damp=TERRAIN_IBLRefl_SpecAO_Damp;
        holder._CubemapDiff=_CubemapDiff;
        holder._CubemapSpec=_CubemapSpec;

        holder.RTP_AOsharpness=RTP_AOsharpness;
        holder.RTP_AOamp=RTP_AOamp;
        holder.RTP_LightDefVector=RTP_LightDefVector;
        holder.RTP_ReflexLightDiffuseColor=RTP_ReflexLightDiffuseColor;
        holder.RTP_ReflexLightDiffuseColor2=RTP_ReflexLightDiffuseColor2;
        holder.RTP_ReflexLightSpecColor=RTP_ReflexLightSpecColor;

        holder.EmissionRefractFiltering=EmissionRefractFiltering;
        holder.EmissionRefractAnimSpeed=EmissionRefractAnimSpeed;

        holder.VerticalTextureGlobalBumpInfluence=VerticalTextureGlobalBumpInfluence;
        holder.VerticalTextureTiling=VerticalTextureTiling;

        // snow
        holder._snow_strength=_snow_strength;
        holder._global_color_brightness_to_snow=_global_color_brightness_to_snow;
        holder._snow_slope_factor=_snow_slope_factor;
        holder._snow_edge_definition=_snow_edge_definition;
        holder._snow_height_treshold=_snow_height_treshold;
        holder._snow_height_transition=_snow_height_transition;
        holder._snow_color=_snow_color;
        holder._snow_specular=_snow_specular;
        holder._snow_gloss=_snow_gloss;
        holder._snow_reflectivness=_snow_reflectivness;
        holder._snow_deep_factor=_snow_deep_factor;
        holder._snow_fresnel=_snow_fresnel;
        holder._snow_diff_fresnel=_snow_diff_fresnel;
        holder._snow_IBL_DiffuseStrength=_snow_IBL_DiffuseStrength;
        holder._snow_IBL_SpecStrength=_snow_IBL_SpecStrength;

        //////////////////////
        // layer_dependent arrays
        //////////////////////
        holder.Bumps=new Texture2D[numLayers];
        holder.Spec=new float[numLayers];
        holder.FarSpecCorrection=new float[numLayers];
        holder.MixScale=new float[numLayers];
        holder.MixBlend=new float[numLayers];
        holder.MixSaturation=new float[numLayers];

        // RTP3.1
        holder.RTP_gloss2mask=new float[numLayers];
        holder.RTP_gloss_mult=new float[numLayers];
        holder.RTP_gloss_shaping=new float[numLayers];
        holder.RTP_Fresnel=new float[numLayers];
        holder.RTP_FresnelAtten=new float[numLayers];
        holder.RTP_DiffFresnel=new float[numLayers];
        holder.RTP_IBL_bump_smoothness=new float[numLayers];
        holder.RTP_IBL_DiffuseStrength=new float[numLayers];
        holder.RTP_IBL_SpecStrength=new float[numLayers];
        holder._DeferredSpecDampAddPass=new float[numLayers];

        holder.MixBrightness=new float[numLayers];
        holder.MixReplace=new float[numLayers];
        holder.LayerBrightness=new float[numLayers];
        holder.LayerBrightness2Spec=new float[numLayers];
        holder.LayerAlbedo2SpecColor=new float[numLayers];
        holder.LayerSaturation=new float[numLayers];
        holder.LayerEmission=new float[numLayers];
        holder.LayerEmissionColor=new Color[numLayers];
        holder.LayerEmissionRefractStrength=new float[numLayers];
        holder.LayerEmissionRefractHBedge=new float[numLayers];

        holder.GlobalColorPerLayer=new float[numLayers];
        holder.GlobalColorBottom=new float[numLayers];
        holder.GlobalColorTop=new float[numLayers];
        holder.GlobalColorColormapLoSat=new float[numLayers];
        holder.GlobalColorColormapHiSat=new float[numLayers];
        holder.GlobalColorLayerLoSat=new float[numLayers];
        holder.GlobalColorLayerHiSat=new float[numLayers];
        holder.GlobalColorLoBlend=new float[numLayers];
        holder.GlobalColorHiBlend=new float[numLayers];

        holder.PER_LAYER_HEIGHT_MODIFIER=new float[numLayers];
        holder._SuperDetailStrengthMultA=new float[numLayers];
        holder._SuperDetailStrengthMultASelfMaskNear=new float[numLayers];
        holder._SuperDetailStrengthMultASelfMaskFar=new float[numLayers];
        holder._SuperDetailStrengthMultB=new float[numLayers];
        holder._SuperDetailStrengthMultBSelfMaskNear=new float[numLayers];
        holder._SuperDetailStrengthMultBSelfMaskFar=new float[numLayers];
        holder._SuperDetailStrengthNormal=new float[numLayers];
        holder._BumpMapGlobalStrength=new float[numLayers];

        holder.VerticalTextureStrength=new float[numLayers];
        holder.AO_strength=new float[numLayers];

        holder.Heights=new Texture2D[numLayers];

        holder._snow_strength_per_layer=new float[numLayers];
        holder.Substances=new ProceduralMaterial[numLayers];

        // wet
        holder.TERRAIN_LayerWetStrength=new float[numLayers];
        holder.TERRAIN_WaterLevel=new float[numLayers];
        holder.TERRAIN_WaterLevelSlopeDamp=new float[numLayers];
        holder.TERRAIN_WaterEdge=new float[numLayers];
        holder.TERRAIN_WaterSpecularity=new float[numLayers];
        holder.TERRAIN_WaterGloss=new float[numLayers];
        holder.TERRAIN_WaterGlossDamper=new float[numLayers];
        holder.TERRAIN_WaterOpacity=new float[numLayers];
        holder.TERRAIN_Refraction=new float[numLayers];
        holder.TERRAIN_WetRefraction=new float[numLayers];
        holder.TERRAIN_Flow=new float[numLayers];
        holder.TERRAIN_WetFlow=new float[numLayers];
        holder.TERRAIN_WetSpecularity=new float[numLayers];
        holder.TERRAIN_WetGloss=new float[numLayers];
        holder.TERRAIN_WaterColor=new Color[numLayers];
        holder.TERRAIN_WaterIBL_SpecWetStrength=new float[numLayers];
        holder.TERRAIN_WaterIBL_SpecWaterStrength=new float[numLayers];
        holder.TERRAIN_WaterEmission=new float[numLayers];

        for(int i=0; i<numLayers; i++) {
            holder.Bumps[i]=Bumps[i];
            holder.Spec[i]=Spec[i];
            holder.FarSpecCorrection[i]=FarSpecCorrection[i];
            holder.MixScale[i]=MixScale[i];
            holder.MixBlend[i]=MixBlend[i];
            holder.MixSaturation[i]=MixSaturation[i];

            // >RTP3.1
            // update-set to default
            if (CheckAndUpdate(ref RTP_gloss2mask, 0.5f, numLayers)) {
                for(int k=0; k<numLayers; k++) {
                    Spec[k]=1; // zresetuj od razu mnożnik glossa (RTP3.1 - zmienna ma inne znaczenie)
                }
            }
            CheckAndUpdate(ref RTP_gloss_mult, 1f, numLayers);
            CheckAndUpdate(ref RTP_gloss_shaping, 0.5f, numLayers);
            CheckAndUpdate(ref RTP_Fresnel, 0, numLayers);
            CheckAndUpdate(ref RTP_FresnelAtten, 0, numLayers);
            CheckAndUpdate(ref RTP_DiffFresnel, 0, numLayers);
            CheckAndUpdate(ref RTP_IBL_bump_smoothness, 0.7f, numLayers);
            CheckAndUpdate(ref RTP_IBL_DiffuseStrength, 0.5f, numLayers);
            CheckAndUpdate(ref RTP_IBL_SpecStrength, 0.5f, numLayers);
            CheckAndUpdate(ref _DeferredSpecDampAddPass, 1f, numLayers);

            CheckAndUpdate(ref TERRAIN_WaterSpecularity, 0.5f, numLayers);
            CheckAndUpdate(ref TERRAIN_WaterGloss, 0.1f, numLayers);
            CheckAndUpdate(ref TERRAIN_WaterGlossDamper, 0f, numLayers);
            CheckAndUpdate(ref TERRAIN_WetSpecularity, 0.2f, numLayers);
            CheckAndUpdate(ref TERRAIN_WetGloss, 0.05f, numLayers);
            CheckAndUpdate(ref TERRAIN_WetFlow, 0.05f, numLayers);

            CheckAndUpdate(ref MixBrightness, 2.0f, numLayers);
            CheckAndUpdate(ref MixReplace, 0.0f, numLayers);
            CheckAndUpdate(ref LayerBrightness, 1.0f, numLayers);
            CheckAndUpdate(ref LayerBrightness2Spec, 0.0f, numLayers);
            CheckAndUpdate(ref LayerAlbedo2SpecColor, 0.0f, numLayers);
            CheckAndUpdate(ref LayerSaturation, 1.0f, numLayers);
            CheckAndUpdate(ref LayerEmission, 0f, numLayers);
            CheckAndUpdate(ref LayerEmissionColor, Color.black, numLayers);
            CheckAndUpdate(ref LayerEmissionRefractStrength, 0f, numLayers);
            CheckAndUpdate(ref LayerEmissionRefractHBedge, 0f, numLayers);

            CheckAndUpdate(ref TERRAIN_WaterIBL_SpecWetStrength, 0.1f, numLayers);
            CheckAndUpdate(ref TERRAIN_WaterIBL_SpecWaterStrength, 0.5f, numLayers);
            CheckAndUpdate(ref TERRAIN_WaterEmission, 0.5f, numLayers);

            holder.RTP_gloss2mask[i]=RTP_gloss2mask[i];
            holder.RTP_gloss_mult[i]=RTP_gloss_mult[i];
            holder.RTP_gloss_shaping[i]=RTP_gloss_shaping[i];
            holder.RTP_Fresnel[i]=RTP_Fresnel[i];
            holder.RTP_FresnelAtten[i]=RTP_FresnelAtten[i];
            holder.RTP_DiffFresnel[i]=RTP_DiffFresnel[i];
            holder.RTP_IBL_bump_smoothness[i]=RTP_IBL_bump_smoothness[i];
            holder.RTP_IBL_DiffuseStrength[i]=RTP_IBL_DiffuseStrength[i];
            holder.RTP_IBL_SpecStrength[i]=RTP_IBL_SpecStrength[i];
            holder._DeferredSpecDampAddPass[i]=_DeferredSpecDampAddPass[i];
            holder.TERRAIN_WaterIBL_SpecWetStrength[i]=TERRAIN_WaterIBL_SpecWetStrength[i];
            holder.TERRAIN_WaterIBL_SpecWaterStrength[i]=TERRAIN_WaterIBL_SpecWaterStrength[i];
            holder.TERRAIN_WaterEmission[i]=TERRAIN_WaterEmission[i];

            holder.MixBrightness[i]=MixBrightness[i];
            holder.MixReplace[i]=MixReplace[i];
            holder.LayerBrightness[i]=LayerBrightness[i];
            holder.LayerBrightness2Spec[i]=LayerBrightness2Spec[i];
            holder.LayerAlbedo2SpecColor[i]=LayerAlbedo2SpecColor[i];
            holder.LayerSaturation[i]=LayerSaturation[i];
            holder.LayerEmission[i]=LayerEmission[i];
            holder.LayerEmissionColor[i]=LayerEmissionColor[i];
            holder.LayerEmissionRefractStrength[i]=LayerEmissionRefractStrength[i];
            holder.LayerEmissionRefractHBedge[i]=LayerEmissionRefractHBedge[i];

            holder.GlobalColorPerLayer[i]=GlobalColorPerLayer[i];
            holder.GlobalColorBottom[i]=GlobalColorBottom[i];
            holder.GlobalColorTop[i]=GlobalColorTop[i];
            holder.GlobalColorColormapLoSat[i]=GlobalColorColormapLoSat[i];
            holder.GlobalColorColormapHiSat[i]=GlobalColorColormapHiSat[i];
            holder.GlobalColorLayerLoSat[i]=GlobalColorLayerLoSat[i];
            holder.GlobalColorLayerHiSat[i]=GlobalColorLayerHiSat[i];
            holder.GlobalColorLoBlend[i]=GlobalColorLoBlend[i];
            holder.GlobalColorHiBlend[i]=GlobalColorHiBlend[i];

            holder.PER_LAYER_HEIGHT_MODIFIER[i]=PER_LAYER_HEIGHT_MODIFIER[i];
            holder._SuperDetailStrengthMultA[i]=_SuperDetailStrengthMultA[i];
            holder._SuperDetailStrengthMultASelfMaskNear[i]=_SuperDetailStrengthMultASelfMaskNear[i];
            holder._SuperDetailStrengthMultASelfMaskFar[i]=_SuperDetailStrengthMultASelfMaskFar[i];
            holder._SuperDetailStrengthMultB[i]=_SuperDetailStrengthMultB[i];
            holder._SuperDetailStrengthMultBSelfMaskNear[i]=_SuperDetailStrengthMultBSelfMaskNear[i];
            holder._SuperDetailStrengthMultBSelfMaskFar[i]=_SuperDetailStrengthMultBSelfMaskFar[i];
            holder._SuperDetailStrengthNormal[i]=_SuperDetailStrengthNormal[i];
            holder._BumpMapGlobalStrength[i]=_BumpMapGlobalStrength[i];

            holder.VerticalTextureStrength[i]=VerticalTextureStrength[i];
            holder.AO_strength[i]=AO_strength[i];

            holder.Heights[i]=Heights[i];

            holder._snow_strength_per_layer[i]=_snow_strength_per_layer[i];
            holder.Substances[i]=Substances[i];

            // wet
            holder.TERRAIN_LayerWetStrength[i]=TERRAIN_LayerWetStrength[i];
            holder.TERRAIN_WaterLevel[i]=TERRAIN_WaterLevel[i];
            holder.TERRAIN_WaterLevelSlopeDamp[i]=TERRAIN_WaterLevelSlopeDamp[i];
            holder.TERRAIN_WaterEdge[i]=TERRAIN_WaterEdge[i];
            holder.TERRAIN_WaterSpecularity[i]=TERRAIN_WaterSpecularity[i];
            holder.TERRAIN_WaterGloss[i]=TERRAIN_WaterGloss[i];
            holder.TERRAIN_WaterGlossDamper[i]=TERRAIN_WaterGlossDamper[i];
            holder.TERRAIN_WaterOpacity[i]=TERRAIN_WaterOpacity[i];
            holder.TERRAIN_Refraction[i]=TERRAIN_Refraction[i];
            holder.TERRAIN_WetRefraction[i]=TERRAIN_WetRefraction[i];
            holder.TERRAIN_Flow[i]=TERRAIN_Flow[i];
            holder.TERRAIN_WetFlow[i]=TERRAIN_WetFlow[i];
            holder.TERRAIN_WetSpecularity[i]=TERRAIN_WetSpecularity[i];
            holder.TERRAIN_WetGloss[i]=TERRAIN_WetGloss[i];
            holder.TERRAIN_WaterColor[i]=TERRAIN_WaterColor[i];
        }
    }
    public void RestorePreset(ReliefTerrainPresetHolder holder)
    {
        numLayers=holder.numLayers;
        splats=new Texture2D[holder.splats.Length];
        for(int i=0; i<holder.splats.Length; i++) {
            splats[i]=holder.splats[i];
        }

        splat_atlases=new Texture2D[3];
        for(int i=0; i<splat_atlases.Length; i++) {
            splat_atlases[i]=holder.splat_atlases[i];
        }

        gloss_baked=holder.gloss_baked;
        // actualy used textures will be rebuild on next Refresh()
        splats_glossBaked=new Texture2D[12];
        atlas_glossBaked=new Texture2D[3];

        RTP_MIP_BIAS=holder.RTP_MIP_BIAS;
        _SpecColor=holder._SpecColor;
        RTP_DeferredAddPassSpec=holder.RTP_DeferredAddPassSpec;

        MasterLayerBrightness=holder.MasterLayerBrightness;
        MasterLayerSaturation=holder.MasterLayerSaturation;

        SuperDetailA_channel=holder.SuperDetailA_channel;
        SuperDetailB_channel=holder.SuperDetailB_channel;

        Bump01=holder.Bump01;
        Bump23=holder.Bump23;
        Bump45=holder.Bump45;
        Bump67=holder.Bump67;
        Bump89=holder.Bump89;
        BumpAB=holder.BumpAB;

        SSColorCombinedA=holder.SSColorCombinedA;
        SSColorCombinedB=holder.SSColorCombinedB;

        BumpGlobal=holder.BumpGlobal;

        VerticalTexture=holder.VerticalTexture;
        BumpMapGlobalScale=holder.BumpMapGlobalScale;
        GlobalColorMapBlendValues=holder.GlobalColorMapBlendValues;
        GlobalColorMapSaturation=holder.GlobalColorMapSaturation;
        GlobalColorMapSaturationFar=holder.GlobalColorMapSaturationFar;
        //GlobalColorMapSaturationByPerlin=holder.GlobalColorMapSaturationByPerlin;
        GlobalColorMapDistortByPerlin=holder.GlobalColorMapDistortByPerlin;
        GlobalColorMapBrightness=holder.GlobalColorMapBrightness;
        GlobalColorMapBrightnessFar=holder.GlobalColorMapBrightnessFar;
        _GlobalColorMapNearMIP=holder._GlobalColorMapNearMIP;
        _FarNormalDamp=holder._FarNormalDamp;

        blendMultiplier=holder.blendMultiplier;

        HeightMap=holder.HeightMap;
        HeightMap2=holder.HeightMap2;
        HeightMap3=holder.HeightMap3;

        ReliefTransform=holder.ReliefTransform;
        DIST_STEPS=holder.DIST_STEPS;
        WAVELENGTH=holder.WAVELENGTH;
        ReliefBorderBlend=holder.ReliefBorderBlend;

        ExtrudeHeight=holder.ExtrudeHeight;
        LightmapShading=holder.LightmapShading;

        SHADOW_STEPS=holder.SHADOW_STEPS;
        WAVELENGTH_SHADOWS=holder.WAVELENGTH_SHADOWS;
        SHADOW_SMOOTH_STEPS=holder.SHADOW_SMOOTH_STEPS;
        SelfShadowStrength=holder.SelfShadowStrength;
        ShadowSmoothing=holder.ShadowSmoothing;

        distance_start=holder.distance_start;
        distance_transition=holder.distance_transition;
        distance_start_bumpglobal=holder.distance_start_bumpglobal;
        distance_transition_bumpglobal=holder.distance_transition_bumpglobal;
        rtp_perlin_start_val=holder.rtp_perlin_start_val;

        _Phong = holder._Phong;
        tessHeight = holder.tessHeight;
        _TessSubdivisions = holder._TessSubdivisions;
        _TessSubdivisionsFar = holder._TessSubdivisionsFar;
        _TessYOffset = holder._TessYOffset;

        trees_shadow_distance_start=holder.trees_shadow_distance_start;
        trees_shadow_distance_transition=holder.trees_shadow_distance_transition;
        trees_shadow_value=holder.trees_shadow_value;
        trees_pixel_distance_start=holder.trees_pixel_distance_start;
        trees_pixel_distance_transition=holder.trees_pixel_distance_transition;
        trees_pixel_blend_val=holder.trees_pixel_blend_val;
        global_normalMap_multiplier=holder.global_normalMap_multiplier;
        global_normalMap_farUsage=holder.global_normalMap_farUsage;

        _AmbientEmissiveMultiplier=holder._AmbientEmissiveMultiplier;
        _AmbientEmissiveRelief=holder._AmbientEmissiveRelief;

        rtp_mipoffset_globalnorm=holder.rtp_mipoffset_globalnorm;
        _SuperDetailTiling=holder._SuperDetailTiling;
        SuperDetailA=holder.SuperDetailA;
        SuperDetailB=holder.SuperDetailB;

        // reflection
        TERRAIN_ReflectionMap=holder.TERRAIN_ReflectionMap;
        TERRAIN_ReflectionMap_channel=holder.TERRAIN_ReflectionMap_channel;
        TERRAIN_ReflColorA=holder.TERRAIN_ReflColorA;
        TERRAIN_ReflColorB=holder.TERRAIN_ReflColorB;
        TERRAIN_ReflColorC=holder.TERRAIN_ReflColorC;
        TERRAIN_ReflColorCenter=holder.TERRAIN_ReflColorCenter;
        TERRAIN_ReflGlossAttenuation=holder.TERRAIN_ReflGlossAttenuation;
        TERRAIN_ReflectionRotSpeed=holder.TERRAIN_ReflectionRotSpeed;

        // water/wet
        TERRAIN_GlobalWetness=holder.TERRAIN_GlobalWetness;

        TERRAIN_RippleMap=holder.TERRAIN_RippleMap;
        TERRAIN_RippleScale=holder.TERRAIN_RippleScale;
        TERRAIN_FlowScale=holder.TERRAIN_FlowScale;
        TERRAIN_FlowSpeed=holder.TERRAIN_FlowSpeed;
        TERRAIN_FlowCycleScale=holder.TERRAIN_FlowCycleScale;
        TERRAIN_FlowMipOffset=holder.TERRAIN_FlowMipOffset;
        TERRAIN_WetDarkening=holder.TERRAIN_WetDarkening;
        TERRAIN_WetDropletsStrength=holder.TERRAIN_WetDropletsStrength;
        TERRAIN_WetHeight_Treshold=holder.TERRAIN_WetHeight_Treshold;
        TERRAIN_WetHeight_Transition=holder.TERRAIN_WetHeight_Transition;

        TERRAIN_RainIntensity=holder.TERRAIN_RainIntensity;
        TERRAIN_DropletsSpeed=holder.TERRAIN_DropletsSpeed;

        TERRAIN_mipoffset_flowSpeed=holder.TERRAIN_mipoffset_flowSpeed;

        // caustics
        TERRAIN_CausticsAnimSpeed=holder.TERRAIN_CausticsAnimSpeed;
        TERRAIN_CausticsColor=holder.TERRAIN_CausticsColor;
        TERRAIN_CausticsWaterLevel=holder.TERRAIN_CausticsWaterLevel;
        TERRAIN_CausticsWaterLevelByAngle=holder.TERRAIN_CausticsWaterLevelByAngle;
        TERRAIN_CausticsWaterDeepFadeLength=holder.TERRAIN_CausticsWaterDeepFadeLength;
        TERRAIN_CausticsWaterShallowFadeLength=holder.TERRAIN_CausticsWaterShallowFadeLength;
        TERRAIN_CausticsTilingScale=holder.TERRAIN_CausticsTilingScale;
        TERRAIN_CausticsTex=holder.TERRAIN_CausticsTex;

        rtp_customAmbientCorrection=holder.rtp_customAmbientCorrection;
        TERRAIN_IBL_DiffAO_Damp=holder.TERRAIN_IBL_DiffAO_Damp;
        TERRAIN_IBLRefl_SpecAO_Damp=holder.TERRAIN_IBLRefl_SpecAO_Damp;
        _CubemapDiff=holder._CubemapDiff;
        _CubemapSpec=holder._CubemapSpec;

        RTP_AOsharpness=holder.RTP_AOsharpness;
        RTP_AOamp=holder.RTP_AOamp;
        RTP_LightDefVector=holder.RTP_LightDefVector;
        RTP_ReflexLightDiffuseColor=holder.RTP_ReflexLightDiffuseColor;
        RTP_ReflexLightDiffuseColor2=holder.RTP_ReflexLightDiffuseColor2;
        RTP_ReflexLightSpecColor=holder.RTP_ReflexLightSpecColor;

        EmissionRefractFiltering=holder.EmissionRefractFiltering;
        EmissionRefractAnimSpeed=holder.EmissionRefractAnimSpeed;

        VerticalTextureGlobalBumpInfluence=holder.VerticalTextureGlobalBumpInfluence;
        VerticalTextureTiling=holder.VerticalTextureTiling;

        // snow
        _snow_strength=holder._snow_strength;
        _global_color_brightness_to_snow=holder._global_color_brightness_to_snow;
        _snow_slope_factor=holder._snow_slope_factor;
        _snow_edge_definition=holder._snow_edge_definition;
        _snow_height_treshold=holder._snow_height_treshold;
        _snow_height_transition=holder._snow_height_transition;
        _snow_color=holder._snow_color;
        _snow_specular=holder._snow_specular;
        _snow_gloss=holder._snow_gloss;
        _snow_reflectivness=holder._snow_reflectivness;
        _snow_deep_factor=holder._snow_deep_factor;
        _snow_fresnel=holder._snow_fresnel;
        _snow_diff_fresnel=holder._snow_diff_fresnel;
        _snow_IBL_DiffuseStrength=holder._snow_IBL_DiffuseStrength;
        _snow_IBL_SpecStrength=holder._snow_IBL_SpecStrength;

        //////////////////////
        // layer_dependent arrays
        //////////////////////
        Bumps=new Texture2D[holder.Bumps.Length];
        Spec=new float[holder.Bumps.Length];
        FarSpecCorrection=new float[holder.Bumps.Length];
        MixScale=new float[holder.Bumps.Length];
        MixBlend=new float[holder.Bumps.Length];
        MixSaturation=new float[holder.Bumps.Length];

        // RTP3.1
        RTP_gloss2mask=new float[holder.Bumps.Length];
        RTP_gloss_mult=new float[holder.Bumps.Length];
        RTP_gloss_shaping=new float[holder.Bumps.Length];
        RTP_Fresnel=new float[holder.Bumps.Length];
        RTP_FresnelAtten=new float[holder.Bumps.Length];
        RTP_DiffFresnel=new float[holder.Bumps.Length];
        RTP_IBL_bump_smoothness=new float[holder.Bumps.Length];
        RTP_IBL_DiffuseStrength=new float[holder.Bumps.Length];
        RTP_IBL_SpecStrength=new float[holder.Bumps.Length];
        _DeferredSpecDampAddPass=new float[holder.Bumps.Length];

        MixBrightness=new float[holder.Bumps.Length];
        MixReplace=new float[holder.Bumps.Length];
        LayerBrightness=new float[holder.Bumps.Length];
        LayerBrightness2Spec=new float[holder.Bumps.Length];
        LayerAlbedo2SpecColor=new float[holder.Bumps.Length];
        LayerSaturation=new float[holder.Bumps.Length];
        LayerEmission=new float[holder.Bumps.Length];
        LayerEmissionColor=new Color[holder.Bumps.Length];
        LayerEmissionRefractStrength=new float[holder.Bumps.Length];
        LayerEmissionRefractHBedge=new float[holder.Bumps.Length];

        GlobalColorPerLayer=new float[holder.Bumps.Length];
        GlobalColorBottom=new float[holder.Bumps.Length];
        GlobalColorTop=new float[holder.Bumps.Length];
        GlobalColorColormapLoSat=new float[holder.Bumps.Length];
        GlobalColorColormapHiSat=new float[holder.Bumps.Length];
        GlobalColorLayerLoSat=new float[holder.Bumps.Length];
        GlobalColorLayerHiSat=new float[holder.Bumps.Length];
        GlobalColorLoBlend=new float[holder.Bumps.Length];
        GlobalColorHiBlend=new float[holder.Bumps.Length];

        PER_LAYER_HEIGHT_MODIFIER=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultA=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultASelfMaskNear=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultASelfMaskFar=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultB=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultBSelfMaskNear=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultBSelfMaskFar=new float[holder.Bumps.Length];
        _SuperDetailStrengthNormal=new float[holder.Bumps.Length];
        _BumpMapGlobalStrength=new float[holder.Bumps.Length];

        AO_strength=new float[holder.Bumps.Length];
        VerticalTextureStrength=new float[holder.Bumps.Length];

        Heights=new Texture2D[holder.Bumps.Length];

        _snow_strength_per_layer=new float[holder.Bumps.Length];
        Substances=new ProceduralMaterial[holder.Bumps.Length];

        // wet
        TERRAIN_LayerWetStrength=new float[holder.Bumps.Length];
        TERRAIN_WaterLevel=new float[holder.Bumps.Length];
        TERRAIN_WaterLevelSlopeDamp=new float[holder.Bumps.Length];
        TERRAIN_WaterEdge=new float[holder.Bumps.Length];
        TERRAIN_WaterSpecularity=new float[holder.Bumps.Length];
        TERRAIN_WaterGloss=new float[holder.Bumps.Length];
        TERRAIN_WaterGlossDamper=new float[holder.Bumps.Length];
        TERRAIN_WaterOpacity=new float[holder.Bumps.Length];
        TERRAIN_Refraction=new float[holder.Bumps.Length];
        TERRAIN_WetRefraction=new float[holder.Bumps.Length];
        TERRAIN_Flow=new float[holder.Bumps.Length];
        TERRAIN_WetFlow=new float[holder.Bumps.Length];
        TERRAIN_WetSpecularity=new float[holder.Bumps.Length];
        TERRAIN_WetGloss=new float[holder.Bumps.Length];
        TERRAIN_WaterColor=new Color[holder.Bumps.Length];

        TERRAIN_WaterIBL_SpecWetStrength=new float[holder.Bumps.Length];
        TERRAIN_WaterIBL_SpecWaterStrength=new float[holder.Bumps.Length];
        TERRAIN_WaterEmission=new float[holder.Bumps.Length];

        for(int i=0; i<holder.Bumps.Length; i++) {
            Bumps[i]=holder.Bumps[i];
            Spec[i]=holder.Spec[i];
            FarSpecCorrection[i]=holder.FarSpecCorrection[i];
            MixScale[i]=holder.MixScale[i];
            MixBlend[i]=holder.MixBlend[i];
            MixSaturation[i]=holder.MixSaturation[i];

            // RTP3.1
            // update-set to default
            if (CheckAndUpdate(ref holder.RTP_gloss2mask, 0.5f, holder.Bumps.Length)) {
                for(int k=0; k<numLayers; k++) {
                    Spec[k]=1; // zresetuj od razu mnożnik glossa (RTP3.1 - zmienna ma inne znaczenie)
                }
            }
            CheckAndUpdate(ref holder.RTP_gloss_mult, 1f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.RTP_gloss_shaping, 0.5f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.RTP_Fresnel, 0, holder.Bumps.Length);
            CheckAndUpdate(ref holder.RTP_FresnelAtten, 0, holder.Bumps.Length);
            CheckAndUpdate(ref holder.RTP_DiffFresnel, 0, holder.Bumps.Length);
            CheckAndUpdate(ref holder.RTP_IBL_bump_smoothness, 0.7f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.RTP_IBL_DiffuseStrength, 0.5f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.RTP_IBL_SpecStrength, 0.5f, holder.Bumps.Length);
            CheckAndUpdate(ref holder._DeferredSpecDampAddPass, 1f, holder.Bumps.Length);

            CheckAndUpdate(ref holder.TERRAIN_WaterSpecularity, 0.5f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.TERRAIN_WaterGloss, 0.1f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.TERRAIN_WaterGlossDamper, 0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.TERRAIN_WetSpecularity, 0.2f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.TERRAIN_WetGloss, 0.05f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.TERRAIN_WetFlow, 0.05f, holder.Bumps.Length);

            CheckAndUpdate(ref holder.MixBrightness, 2.0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.MixReplace, 0.0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.LayerBrightness, 1.0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.LayerBrightness2Spec, 0.0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.LayerAlbedo2SpecColor, 0.0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.LayerSaturation, 1.0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.LayerEmission, 1.0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.LayerEmissionColor, Color.black, holder.Bumps.Length);
            CheckAndUpdate(ref holder.FarSpecCorrection, 0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.LayerEmissionRefractStrength, 0f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.LayerEmissionRefractHBedge, 0f, holder.Bumps.Length);

            CheckAndUpdate(ref holder.TERRAIN_WaterIBL_SpecWetStrength, 0.1f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.TERRAIN_WaterIBL_SpecWaterStrength, 0.5f, holder.Bumps.Length);
            CheckAndUpdate(ref holder.TERRAIN_WaterEmission, 0f, holder.Bumps.Length);

            RTP_gloss2mask[i]=holder.RTP_gloss2mask[i];
            RTP_gloss_mult[i]=holder.RTP_gloss_mult[i];
            RTP_gloss_shaping[i]=holder.RTP_gloss_shaping[i];
            RTP_Fresnel[i]=holder.RTP_Fresnel[i];
            RTP_FresnelAtten[i]=holder.RTP_FresnelAtten[i];
            RTP_DiffFresnel[i]=holder.RTP_DiffFresnel[i];
            RTP_IBL_bump_smoothness[i]=holder.RTP_IBL_bump_smoothness[i];
            RTP_IBL_DiffuseStrength[i]=holder.RTP_IBL_DiffuseStrength[i];
            RTP_IBL_SpecStrength[i]=holder.RTP_IBL_SpecStrength[i];
            _DeferredSpecDampAddPass[i]=holder._DeferredSpecDampAddPass[i];

            MixBrightness[i]=holder.MixBrightness[i];
            MixReplace[i]=holder.MixReplace[i];
            LayerBrightness[i]=holder.LayerBrightness[i];
            LayerBrightness2Spec[i]=holder.LayerBrightness2Spec[i];
            LayerAlbedo2SpecColor[i]=holder.LayerAlbedo2SpecColor[i];
            LayerSaturation[i]=holder.LayerSaturation[i];
            LayerEmission[i]=holder.LayerEmission[i];
            LayerEmissionColor[i]=holder.LayerEmissionColor[i];
            LayerEmissionRefractStrength[i]=holder.LayerEmissionRefractStrength[i];
            LayerEmissionRefractHBedge[i]=holder.LayerEmissionRefractHBedge[i];

            GlobalColorPerLayer[i]=holder.GlobalColorPerLayer[i];
            GlobalColorBottom[i]=holder.GlobalColorBottom[i];
            GlobalColorTop[i]=holder.GlobalColorTop[i];
            GlobalColorColormapLoSat[i]=holder.GlobalColorColormapLoSat[i];
            GlobalColorColormapHiSat[i]=holder.GlobalColorColormapHiSat[i];
            GlobalColorLayerLoSat[i]=holder.GlobalColorLayerLoSat[i];
            GlobalColorLayerHiSat[i]=holder.GlobalColorLayerHiSat[i];
            GlobalColorLoBlend[i]=holder.GlobalColorLoBlend[i];
            GlobalColorHiBlend[i]=holder.GlobalColorHiBlend[i];

            PER_LAYER_HEIGHT_MODIFIER[i]=holder.PER_LAYER_HEIGHT_MODIFIER[i];
            _SuperDetailStrengthMultA[i]=holder._SuperDetailStrengthMultA[i];
            _SuperDetailStrengthMultASelfMaskNear[i]=holder._SuperDetailStrengthMultASelfMaskNear[i];
            _SuperDetailStrengthMultASelfMaskFar[i]=holder._SuperDetailStrengthMultASelfMaskFar[i];
            _SuperDetailStrengthMultB[i]=holder._SuperDetailStrengthMultB[i];
            _SuperDetailStrengthMultBSelfMaskNear[i]=holder._SuperDetailStrengthMultBSelfMaskNear[i];
            _SuperDetailStrengthMultBSelfMaskFar[i]=holder._SuperDetailStrengthMultBSelfMaskFar[i];
            _SuperDetailStrengthNormal[i]=holder._SuperDetailStrengthNormal[i];
            _BumpMapGlobalStrength[i]=holder._BumpMapGlobalStrength[i];

            VerticalTextureStrength[i]=holder.VerticalTextureStrength[i];
            AO_strength[i]=holder.AO_strength[i];

            Heights[i]=holder.Heights[i];

            _snow_strength_per_layer[i]=holder._snow_strength_per_layer[i];
            Substances[i]=holder.Substances[i];

            // wet
            TERRAIN_LayerWetStrength[i]=holder.TERRAIN_LayerWetStrength[i];
            TERRAIN_WaterLevel[i]=holder.TERRAIN_WaterLevel[i];
            TERRAIN_WaterLevelSlopeDamp[i]=holder.TERRAIN_WaterLevelSlopeDamp[i];
            TERRAIN_WaterEdge[i]=holder.TERRAIN_WaterEdge[i];
            TERRAIN_WaterSpecularity[i]=holder.TERRAIN_WaterSpecularity[i];
            TERRAIN_WaterGloss[i]=holder.TERRAIN_WaterGloss[i];
            TERRAIN_WaterGlossDamper[i]=holder.TERRAIN_WaterGlossDamper[i];
            TERRAIN_WaterOpacity[i]=holder.TERRAIN_WaterOpacity[i];
            TERRAIN_Refraction[i]=holder.TERRAIN_Refraction[i];
            TERRAIN_WetRefraction[i]=holder.TERRAIN_WetRefraction[i];
            TERRAIN_Flow[i]=holder.TERRAIN_Flow[i];
            TERRAIN_WetFlow[i]=holder.TERRAIN_WetFlow[i];
            TERRAIN_WetSpecularity[i]=holder.TERRAIN_WetSpecularity[i];
            TERRAIN_WetGloss[i]=holder.TERRAIN_WetGloss[i];
            TERRAIN_WaterColor[i]=holder.TERRAIN_WaterColor[i];
            TERRAIN_WaterIBL_SpecWetStrength[i]=holder.TERRAIN_WaterIBL_SpecWetStrength[i];
            TERRAIN_WaterIBL_SpecWaterStrength[i]=holder.TERRAIN_WaterIBL_SpecWaterStrength[i];
            TERRAIN_WaterEmission[i]=holder.TERRAIN_WaterEmission[i];
        }
    }
    IEnumerator ChangeCurrentPreset(ReliefTerrainPresetHolder me)
    {
        yield return(new WaitForSeconds(1f));

        currentPreset = me;
    }
    public void RestorePreset(ReliefTerrainPresetHolder holder)
    {
        numLayers=holder.numLayers;
        splats=new Texture2D[holder.splats.Length];
        for(int i=0; i<holder.splats.Length; i++) {
            splats[i]=holder.splats[i];
        }

        splat_atlases=new Texture2D[holder.splat_atlases.Length];
        for(int i=0; i<splat_atlases.Length; i++) {
            splat_atlases[i]=holder.splat_atlases[i];
        }

        RTP_MIP_BIAS=holder.RTP_MIP_BIAS;
        _SpecColor=holder._SpecColor;

        SuperDetailA_channel=holder.SuperDetailA_channel;
        SuperDetailB_channel=holder.SuperDetailB_channel;

        Bump01=holder.Bump01;
        Bump23=holder.Bump23;
        Bump45=holder.Bump45;
        Bump67=holder.Bump67;
        Bump89=holder.Bump89;
        BumpAB=holder.BumpAB;

        SSColorCombined=holder.SSColorCombined;

        BumpGlobal=holder.BumpGlobal;

        VerticalTexture=holder.VerticalTexture;
        BumpMapGlobalScale=holder.BumpMapGlobalScale;
        GlobalColorMapBlendValues=holder.GlobalColorMapBlendValues;
        GlobalColorMapSaturation=holder.GlobalColorMapSaturation;
        GlobalColorMapBrightness=holder.GlobalColorMapBrightness;
        _GlobalColorMapNearMIP=holder._GlobalColorMapNearMIP;
        _FarNormalDamp=holder._FarNormalDamp;

        blendMultiplier=holder.blendMultiplier;

        HeightMap=holder.HeightMap;
        HeightMap2=holder.HeightMap2;
        HeightMap3=holder.HeightMap3;

        ReliefTransform=holder.ReliefTransform;
        DIST_STEPS=holder.DIST_STEPS;
        WAVELENGTH=holder.WAVELENGTH;
        ReliefBorderBlend=holder.ReliefBorderBlend;

        ExtrudeHeight=holder.ExtrudeHeight;
        LightmapShading=holder.LightmapShading;

        SHADOW_STEPS=holder.SHADOW_STEPS;
        WAVELENGTH_SHADOWS=holder.WAVELENGTH_SHADOWS;
        SHADOW_SMOOTH_STEPS=holder.SHADOW_SMOOTH_STEPS;
        SelfShadowStrength=holder.SelfShadowStrength;
        ShadowSmoothing=holder.ShadowSmoothing;
        ShadowColor=holder.ShadowColor;

        distance_start=holder.distance_start;
        distance_transition=holder.distance_transition;
        distance_start_bumpglobal=holder.distance_start_bumpglobal;
        distance_transition_bumpglobal=holder.distance_transition_bumpglobal;
        rtp_perlin_start_val=holder.rtp_perlin_start_val;

        trees_shadow_distance_start=holder.trees_shadow_distance_start;
        trees_shadow_distance_transition=holder.trees_shadow_distance_transition;
        trees_shadow_value=holder.trees_shadow_value;
        trees_pixel_distance_start=holder.trees_pixel_distance_start;
        trees_pixel_distance_transition=holder.trees_pixel_distance_transition;
        trees_pixel_blend_val=holder.trees_pixel_blend_val;
        global_normalMap_multiplier=holder.global_normalMap_multiplier;

        rtp_mipoffset_globalnorm=holder.rtp_mipoffset_globalnorm;
        _SuperDetailTiling=holder._SuperDetailTiling;
        SuperDetailA=holder.SuperDetailA;
        SuperDetailB=holder.SuperDetailB;

        // reflection
        TERRAIN_ReflectionMap=holder.TERRAIN_ReflectionMap;
        TERRAIN_ReflectionMap_channel=holder.TERRAIN_ReflectionMap_channel;
        TERRAIN_ReflColorA=holder.TERRAIN_ReflColorA;
        TERRAIN_ReflColorB=holder.TERRAIN_ReflColorB;
        TERRAIN_ReflDistortion=holder.TERRAIN_ReflDistortion;
        TERRAIN_ReflectionRotSpeed=holder.TERRAIN_ReflectionRotSpeed;
        TERRAIN_FresnelPow=holder.TERRAIN_FresnelPow;
        TERRAIN_FresnelOffset=holder.TERRAIN_FresnelOffset;

        // water/wet
        TERRAIN_GlobalWetness=holder.TERRAIN_GlobalWetness;

        TERRAIN_WaterSpecularity=holder.TERRAIN_WaterSpecularity;

        TERRAIN_RippleMap=holder.TERRAIN_RippleMap;
        TERRAIN_RippleScale=holder.TERRAIN_RippleScale;
        TERRAIN_FlowScale=holder.TERRAIN_FlowScale;
        TERRAIN_FlowSpeed=holder.TERRAIN_FlowSpeed;
        TERRAIN_FlowMipOffset=holder.TERRAIN_FlowMipOffset;
        TERRAIN_WetDarkening=holder.TERRAIN_WetDarkening;
        TERRAIN_WetDropletsStrength=holder.TERRAIN_WetDropletsStrength;

        TERRAIN_RainIntensity=holder.TERRAIN_RainIntensity;
        TERRAIN_DropletsSpeed=holder.TERRAIN_DropletsSpeed;

        TERRAIN_mipoffset_flowSpeed=holder.TERRAIN_mipoffset_flowSpeed;

        // caustics
        TERRAIN_CausticsAnimSpeed=holder.TERRAIN_CausticsAnimSpeed;
        TERRAIN_CausticsColor=holder.TERRAIN_CausticsColor;
        TERRAIN_CausticsWaterLevel=holder.TERRAIN_CausticsWaterLevel;
        TERRAIN_CausticsWaterLevelByAngle=holder.TERRAIN_CausticsWaterLevelByAngle;
        TERRAIN_CausticsWaterDeepFadeLength=holder.TERRAIN_CausticsWaterDeepFadeLength;
        TERRAIN_CausticsWaterShallowFadeLength=holder.TERRAIN_CausticsWaterShallowFadeLength;
        TERRAIN_CausticsTilingScale=holder.TERRAIN_CausticsTilingScale;
        TERRAIN_CausticsTex=holder.TERRAIN_CausticsTex;

        rtp_customAmbientCorrection=holder.rtp_customAmbientCorrection;

        RTP_AOsharpness=holder.RTP_AOsharpness;
        RTP_AOamp=holder.RTP_AOamp;
        RTP_LightDefVector=holder.RTP_LightDefVector;
        RTP_ReflexLightDiffuseColor=holder.RTP_ReflexLightDiffuseColor;
        RTP_ReflexLightSpecColor=holder.RTP_ReflexLightSpecColor;

        VerticalTextureGlobalBumpInfluence=holder.VerticalTextureGlobalBumpInfluence;
        VerticalTextureTiling=holder.VerticalTextureTiling;

        // snow
        _snow_strength=holder._snow_strength;
        _global_color_brightness_to_snow=holder._global_color_brightness_to_snow;
        _snow_slope_factor=holder._snow_slope_factor;
        _snow_edge_definition=holder._snow_edge_definition;
        _snow_height_treshold=holder._snow_height_treshold;
        _snow_height_transition=holder._snow_height_transition;
        _snow_color=holder._snow_color;
        _snow_specular=holder._snow_specular;
        _snow_gloss=holder._snow_gloss;
        _snow_reflectivness=holder._snow_reflectivness;
        _snow_deep_factor=holder._snow_deep_factor;

        //////////////////////
        // layer_dependent arrays
        //////////////////////
        Bumps=new Texture2D[holder.Bumps.Length];
        Spec=new float[holder.Bumps.Length];
        FarGlossCorrection=new float[holder.Bumps.Length];
        MixScale=new float[holder.Bumps.Length];
        MixBlend=new float[holder.Bumps.Length];
        MixSaturation=new float[holder.Bumps.Length];
        GlobalColorPerLayer=new float[holder.Bumps.Length];
        PER_LAYER_HEIGHT_MODIFIER=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultA=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultASelfMaskNear=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultASelfMaskFar=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultB=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultBSelfMaskNear=new float[holder.Bumps.Length];
        _SuperDetailStrengthMultBSelfMaskFar=new float[holder.Bumps.Length];
        _SuperDetailStrengthNormal=new float[holder.Bumps.Length];
        _BumpMapGlobalStrength=new float[holder.Bumps.Length];

        AO_strength=new float[holder.Bumps.Length];
        VerticalTextureStrength=new float[holder.Bumps.Length];

        Heights=new Texture2D[holder.Bumps.Length];

        _snow_strength_per_layer=new float[holder.Bumps.Length];
        Substances=new ProceduralMaterial[holder.Bumps.Length];

        // wet
        TERRAIN_LayerWetStrength=new float[holder.Bumps.Length];
        TERRAIN_WaterLevel=new float[holder.Bumps.Length];
        TERRAIN_WaterLevelSlopeDamp=new float[holder.Bumps.Length];
        TERRAIN_WaterEdge=new float[holder.Bumps.Length];
        TERRAIN_WaterGloss=new float[holder.Bumps.Length];
        TERRAIN_WaterOpacity=new float[holder.Bumps.Length];
        TERRAIN_Refraction=new float[holder.Bumps.Length];
        TERRAIN_WetRefraction=new float[holder.Bumps.Length];
        TERRAIN_Flow=new float[holder.Bumps.Length];
        TERRAIN_WetSpecularity=new float[holder.Bumps.Length];
        TERRAIN_WetReflection=new float[holder.Bumps.Length];
        TERRAIN_WaterColor=new Color[holder.Bumps.Length];
        TERRAIN_LayerReflection=new float[holder.Bumps.Length];

        for(int i=0; i<holder.Bumps.Length; i++) {
            Bumps[i]=holder.Bumps[i];
            Spec[i]=holder.Spec[i];
            FarGlossCorrection[i]=holder.FarGlossCorrection[i];
            MixScale[i]=holder.MixScale[i];
            MixBlend[i]=holder.MixBlend[i];
            MixSaturation[i]=holder.MixSaturation[i];
            GlobalColorPerLayer[i]=holder.GlobalColorPerLayer[i];
            PER_LAYER_HEIGHT_MODIFIER[i]=holder.PER_LAYER_HEIGHT_MODIFIER[i];
            _SuperDetailStrengthMultA[i]=holder._SuperDetailStrengthMultA[i];
            _SuperDetailStrengthMultASelfMaskNear[i]=holder._SuperDetailStrengthMultASelfMaskNear[i];
            _SuperDetailStrengthMultASelfMaskFar[i]=holder._SuperDetailStrengthMultASelfMaskFar[i];
            _SuperDetailStrengthMultB[i]=holder._SuperDetailStrengthMultB[i];
            _SuperDetailStrengthMultBSelfMaskNear[i]=holder._SuperDetailStrengthMultBSelfMaskNear[i];
            _SuperDetailStrengthMultBSelfMaskFar[i]=holder._SuperDetailStrengthMultBSelfMaskFar[i];
            _SuperDetailStrengthNormal[i]=holder._SuperDetailStrengthNormal[i];
            _BumpMapGlobalStrength[i]=holder._BumpMapGlobalStrength[i];

            VerticalTextureStrength[i]=holder.VerticalTextureStrength[i];
            AO_strength[i]=holder.AO_strength[i];

            Heights[i]=holder.Heights[i];

            _snow_strength_per_layer[i]=holder._snow_strength_per_layer[i];
            Substances[i]=holder.Substances[i];

            // wet
            TERRAIN_LayerWetStrength[i]=holder.TERRAIN_LayerWetStrength[i];
            TERRAIN_WaterLevel[i]=holder.TERRAIN_WaterLevel[i];
            TERRAIN_WaterLevelSlopeDamp[i]=holder.TERRAIN_WaterLevelSlopeDamp[i];
            TERRAIN_WaterEdge[i]=holder.TERRAIN_WaterEdge[i];
            TERRAIN_WaterGloss[i]=holder.TERRAIN_WaterGloss[i];
            TERRAIN_WaterOpacity[i]=holder.TERRAIN_WaterOpacity[i];
            TERRAIN_Refraction[i]=holder.TERRAIN_Refraction[i];
            TERRAIN_WetRefraction[i]=holder.TERRAIN_WetRefraction[i];
            TERRAIN_Flow[i]=holder.TERRAIN_Flow[i];
            TERRAIN_WetSpecularity[i]=holder.TERRAIN_WetSpecularity[i];
            TERRAIN_WetReflection[i]=holder.TERRAIN_WetReflection[i];
            TERRAIN_WaterColor[i]=holder.TERRAIN_WaterColor[i];
            TERRAIN_LayerReflection[i]=holder.TERRAIN_LayerReflection[i];
        }
    }
    public void InterpolatePresets(ReliefTerrainPresetHolder holderA, ReliefTerrainPresetHolder holderB, float t)
    {
        RTP_MIP_BIAS=Mathf.Lerp(holderA.RTP_MIP_BIAS, holderB.RTP_MIP_BIAS, t);
        _SpecColor=Color.Lerp(holderA._SpecColor, holderB._SpecColor, t);

        BumpMapGlobalScale=Mathf.Lerp(holderA.BumpMapGlobalScale, holderB.BumpMapGlobalScale, t);
        GlobalColorMapBlendValues=Vector3.Lerp(holderA.GlobalColorMapBlendValues, holderB.GlobalColorMapBlendValues, t);
        GlobalColorMapSaturation=Mathf.Lerp(holderA.GlobalColorMapSaturation, holderB.GlobalColorMapSaturation, t);
        GlobalColorMapBrightness=Mathf.Lerp(holderA.GlobalColorMapBrightness, holderB.GlobalColorMapBrightness, t);
        _GlobalColorMapNearMIP=Mathf.Lerp(holderA._GlobalColorMapNearMIP, holderB._GlobalColorMapNearMIP, t);
        _FarNormalDamp=Mathf.Lerp(holderA._FarNormalDamp, holderB._FarNormalDamp, t);

        blendMultiplier=Mathf.Lerp(holderA.blendMultiplier, holderB.blendMultiplier, t);

        ReliefTransform=Vector4.Lerp(holderA.ReliefTransform, holderB.ReliefTransform, t);
        DIST_STEPS=Mathf.Lerp(holderA.DIST_STEPS, holderB.DIST_STEPS, t);
        WAVELENGTH=Mathf.Lerp(holderA.WAVELENGTH, holderB.WAVELENGTH, t);
        ReliefBorderBlend=Mathf.Lerp(holderA.ReliefBorderBlend, holderB.ReliefBorderBlend, t);

        ExtrudeHeight=Mathf.Lerp(holderA.ExtrudeHeight, holderB.ExtrudeHeight, t);
        LightmapShading=Mathf.Lerp(holderA.LightmapShading, holderB.LightmapShading, t);

        SHADOW_STEPS=Mathf.Lerp(holderA.SHADOW_STEPS, holderB.SHADOW_STEPS, t);
        WAVELENGTH_SHADOWS=Mathf.Lerp(holderA.WAVELENGTH_SHADOWS, holderB.WAVELENGTH_SHADOWS, t);
        SHADOW_SMOOTH_STEPS=Mathf.Lerp(holderA.SHADOW_SMOOTH_STEPS, holderB.SHADOW_SMOOTH_STEPS, t);
        SelfShadowStrength=Mathf.Lerp(holderA.SelfShadowStrength, holderB.SelfShadowStrength, t);
        ShadowSmoothing=Mathf.Lerp(holderA.ShadowSmoothing, holderB.ShadowSmoothing, t);
        ShadowColor=Color.Lerp(holderA.ShadowColor, holderB.ShadowColor, t);

        distance_start=Mathf.Lerp(holderA.distance_start, holderB.distance_start, t);
        distance_transition=Mathf.Lerp(holderA.distance_transition, holderB.distance_transition, t);
        distance_start_bumpglobal=Mathf.Lerp(holderA.distance_start_bumpglobal, holderB.distance_start_bumpglobal, t);
        distance_transition_bumpglobal=Mathf.Lerp(holderA.distance_transition_bumpglobal, holderB.distance_transition_bumpglobal, t);
        rtp_perlin_start_val=Mathf.Lerp(holderA.rtp_perlin_start_val, holderB.rtp_perlin_start_val, t);

        trees_shadow_distance_start=Mathf.Lerp(holderA.trees_shadow_distance_start, holderB.trees_shadow_distance_start, t);
        trees_shadow_distance_transition=Mathf.Lerp(holderA.trees_shadow_distance_transition, holderB.trees_shadow_distance_transition, t);
        trees_shadow_value=Mathf.Lerp(holderA.trees_shadow_value, holderB.trees_shadow_value, t);
        trees_pixel_distance_start=Mathf.Lerp(holderA.trees_pixel_distance_start, holderB.trees_pixel_distance_start, t);
        trees_pixel_distance_transition=Mathf.Lerp(holderA.trees_pixel_distance_transition, holderB.trees_pixel_distance_transition, t);
        trees_pixel_blend_val=Mathf.Lerp(holderA.trees_pixel_blend_val, holderB.trees_pixel_blend_val, t);
        global_normalMap_multiplier=Mathf.Lerp (holderA.global_normalMap_multiplier, holderB.global_normalMap_multiplier, t);

        _SuperDetailTiling=Mathf.Lerp(holderA._SuperDetailTiling, holderB._SuperDetailTiling, t);

        // reflection
        TERRAIN_ReflColorA=Color.Lerp(holderA.TERRAIN_ReflColorA, holderB.TERRAIN_ReflColorA, t);
        TERRAIN_ReflColorB=Color.Lerp(holderA.TERRAIN_ReflColorB, holderB.TERRAIN_ReflColorB, t);
        TERRAIN_ReflDistortion=Mathf.Lerp(holderA.TERRAIN_ReflDistortion, holderB.TERRAIN_ReflDistortion, t);
        TERRAIN_ReflectionRotSpeed=Mathf.Lerp(holderA.TERRAIN_ReflectionRotSpeed, holderB.TERRAIN_ReflectionRotSpeed, t);
        TERRAIN_FresnelPow=Mathf.Lerp(holderA.TERRAIN_FresnelPow, holderB.TERRAIN_FresnelPow, t);
        TERRAIN_FresnelOffset=Mathf.Lerp(holderA.TERRAIN_FresnelOffset, holderB.TERRAIN_FresnelOffset, t);

        // water/wet
        TERRAIN_GlobalWetness=Mathf.Lerp(holderA.TERRAIN_GlobalWetness, holderB.TERRAIN_GlobalWetness, t);

        TERRAIN_WaterSpecularity=Mathf.Lerp(holderA.TERRAIN_WaterSpecularity, holderB.TERRAIN_WaterSpecularity, t);

        TERRAIN_RippleScale=Mathf.Lerp(holderA.TERRAIN_RippleScale, holderB.TERRAIN_RippleScale, t);
        TERRAIN_FlowScale=Mathf.Lerp(holderA.TERRAIN_FlowScale, holderB.TERRAIN_FlowScale, t);
        TERRAIN_FlowSpeed=Mathf.Lerp(holderA.TERRAIN_FlowSpeed, holderB.TERRAIN_FlowSpeed, t);
        TERRAIN_FlowMipOffset=Mathf.Lerp(holderA.TERRAIN_FlowMipOffset, holderB.TERRAIN_FlowMipOffset, t);
        TERRAIN_WetDarkening=Mathf.Lerp (holderA.TERRAIN_WetDarkening, holderB.TERRAIN_WetDarkening, t);
        TERRAIN_WetDropletsStrength=Mathf.Lerp(holderA.TERRAIN_WetDropletsStrength, holderB.TERRAIN_WetDropletsStrength, t);

        TERRAIN_RainIntensity=Mathf.Lerp(holderA.TERRAIN_RainIntensity, holderB.TERRAIN_RainIntensity, t);
        TERRAIN_DropletsSpeed=Mathf.Lerp(holderA.TERRAIN_DropletsSpeed, holderB.TERRAIN_DropletsSpeed, t);

        TERRAIN_mipoffset_flowSpeed=Mathf.Lerp(holderA.TERRAIN_mipoffset_flowSpeed, holderB.TERRAIN_mipoffset_flowSpeed, t);

        TERRAIN_CausticsAnimSpeed=Mathf.Lerp(holderA.TERRAIN_CausticsAnimSpeed, holderB.TERRAIN_CausticsAnimSpeed, t);
        TERRAIN_CausticsColor=Color.Lerp(holderA.TERRAIN_CausticsColor, holderB.TERRAIN_CausticsColor,t);
        TERRAIN_CausticsWaterLevel=Mathf.Lerp(holderA.TERRAIN_CausticsWaterLevel, holderB.TERRAIN_CausticsWaterLevel, t);
        TERRAIN_CausticsWaterLevelByAngle=Mathf.Lerp(holderA.TERRAIN_CausticsWaterLevelByAngle, holderB.TERRAIN_CausticsWaterLevelByAngle, t);
        TERRAIN_CausticsWaterDeepFadeLength=Mathf.Lerp(holderA.TERRAIN_CausticsWaterDeepFadeLength, holderB.TERRAIN_CausticsWaterDeepFadeLength, t);
        TERRAIN_CausticsWaterShallowFadeLength=Mathf.Lerp(holderA.TERRAIN_CausticsWaterShallowFadeLength, holderB.TERRAIN_CausticsWaterShallowFadeLength, t);
        TERRAIN_CausticsTilingScale=Mathf.Lerp (holderA.TERRAIN_CausticsTilingScale, holderB.TERRAIN_CausticsTilingScale, t);

        rtp_customAmbientCorrection=Color.Lerp(holderA.rtp_customAmbientCorrection, holderB.rtp_customAmbientCorrection, t);

        RTP_AOsharpness=Mathf.Lerp(holderA.RTP_AOsharpness, holderB.RTP_AOsharpness, t);
        RTP_AOamp=Mathf.Lerp(holderA.RTP_AOamp, holderB.RTP_AOamp, t);
        RTP_LightDefVector=Vector4.Lerp(holderA.RTP_LightDefVector, holderB.RTP_LightDefVector, t);
        RTP_ReflexLightDiffuseColor=Color.Lerp(holderA.RTP_ReflexLightDiffuseColor, holderB.RTP_ReflexLightDiffuseColor, t);
        RTP_ReflexLightSpecColor=Color.Lerp(holderA.RTP_ReflexLightSpecColor, holderB.RTP_ReflexLightSpecColor, t);

        VerticalTextureGlobalBumpInfluence=Mathf.Lerp(holderA.VerticalTextureGlobalBumpInfluence, holderB.VerticalTextureGlobalBumpInfluence, t);
        VerticalTextureTiling=Mathf.Lerp(holderA.VerticalTextureTiling, holderB.VerticalTextureTiling, t);

        // snow
        _snow_strength=Mathf.Lerp(holderA._snow_strength, holderB._snow_strength, t);
        _global_color_brightness_to_snow=Mathf.Lerp(holderA._global_color_brightness_to_snow, holderB._global_color_brightness_to_snow, t);
        _snow_slope_factor=Mathf.Lerp(holderA._snow_slope_factor, holderB._snow_slope_factor, t);
        _snow_edge_definition=Mathf.Lerp(holderA._snow_edge_definition, holderB._snow_edge_definition, t);
        _snow_height_treshold=Mathf.Lerp(holderA._snow_height_treshold, holderB._snow_height_treshold, t);
        _snow_height_transition=Mathf.Lerp(holderA._snow_height_transition, holderB._snow_height_transition, t);
        _snow_color=Color.Lerp(holderA._snow_color, holderB._snow_color, t);
        _snow_specular=Mathf.Lerp(holderA._snow_specular, holderB._snow_specular, t);
        _snow_gloss=Mathf.Lerp(holderA._snow_gloss, holderB._snow_gloss, t);
        _snow_reflectivness=Mathf.Lerp(holderA._snow_reflectivness, holderB._snow_reflectivness, t);
        _snow_deep_factor=Mathf.Lerp(holderA._snow_deep_factor, holderB._snow_deep_factor, t);

        //////////////////////
        // layer_dependent arrays
        //////////////////////
        for(int i=0; i<holderA.Spec.Length; i++) {
            if (i<Spec.Length) {
                Spec[i]=Mathf.Lerp(holderA.Spec[i], holderB.Spec[i], t);
                FarGlossCorrection[i]=Mathf.Lerp(holderA.FarGlossCorrection[i], holderB.FarGlossCorrection[i], t);
                MixScale[i]=Mathf.Lerp(holderA.MixScale[i], holderB.MixScale[i], t);
                MixBlend[i]=Mathf.Lerp(holderA.MixBlend[i], holderB.MixBlend[i], t);
                MixSaturation[i]=Mathf.Lerp(holderA.MixSaturation[i], holderB.MixSaturation[i], t);
                GlobalColorPerLayer[i]=Mathf.Lerp(holderA.GlobalColorPerLayer[i], holderB.GlobalColorPerLayer[i], t);
                PER_LAYER_HEIGHT_MODIFIER[i]=Mathf.Lerp(holderA.PER_LAYER_HEIGHT_MODIFIER[i], holderB.PER_LAYER_HEIGHT_MODIFIER[i], t);
                _SuperDetailStrengthMultA[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultA[i], holderB._SuperDetailStrengthMultA[i], t);
                _SuperDetailStrengthMultASelfMaskNear[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultASelfMaskNear[i], holderB._SuperDetailStrengthMultASelfMaskNear[i], t);
                _SuperDetailStrengthMultASelfMaskFar[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultASelfMaskFar[i], holderB._SuperDetailStrengthMultASelfMaskFar[i], t);
                _SuperDetailStrengthMultB[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultB[i], holderB._SuperDetailStrengthMultB[i], t);
                _SuperDetailStrengthMultBSelfMaskNear[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultBSelfMaskNear[i], holderB._SuperDetailStrengthMultBSelfMaskNear[i], t);
                _SuperDetailStrengthMultBSelfMaskFar[i]=Mathf.Lerp(holderA._SuperDetailStrengthMultBSelfMaskFar[i], holderB._SuperDetailStrengthMultBSelfMaskFar[i], t);
                _SuperDetailStrengthNormal[i]=Mathf.Lerp(holderA._SuperDetailStrengthNormal[i], holderB._SuperDetailStrengthNormal[i], t);
                _BumpMapGlobalStrength[i]=Mathf.Lerp(holderA._BumpMapGlobalStrength[i], holderB._BumpMapGlobalStrength[i], t);

                AO_strength[i]=Mathf.Lerp(holderA.AO_strength[i], holderB.AO_strength[i], t);
                VerticalTextureStrength[i]=Mathf.Lerp(holderA.VerticalTextureStrength[i], holderB.VerticalTextureStrength[i], t);

                _snow_strength_per_layer[i]=Mathf.Lerp(holderA._snow_strength_per_layer[i], holderB._snow_strength_per_layer[i], t);

                // wet
                TERRAIN_LayerWetStrength[i]=Mathf.Lerp(holderA.TERRAIN_LayerWetStrength[i], holderB.TERRAIN_LayerWetStrength[i], t);
                TERRAIN_WaterLevel[i]=Mathf.Lerp(holderA.TERRAIN_WaterLevel[i], holderB.TERRAIN_WaterLevel[i], t);
                TERRAIN_WaterLevelSlopeDamp[i]=Mathf.Lerp(holderA.TERRAIN_WaterLevelSlopeDamp[i], holderB.TERRAIN_WaterLevelSlopeDamp[i], t);
                TERRAIN_WaterEdge[i]=Mathf.Lerp(holderA.TERRAIN_WaterEdge[i], holderB.TERRAIN_WaterEdge[i], t);
                TERRAIN_WaterGloss[i]=Mathf.Lerp(holderA.TERRAIN_WaterGloss[i], holderB.TERRAIN_WaterGloss[i], t);
                TERRAIN_WaterOpacity[i]=Mathf.Lerp(holderA.TERRAIN_WaterOpacity[i], holderB.TERRAIN_WaterOpacity[i], t);
                TERRAIN_Refraction[i]=Mathf.Lerp(holderA.TERRAIN_Refraction[i], holderB.TERRAIN_Refraction[i], t);
                TERRAIN_WetRefraction[i]=Mathf.Lerp(holderA.TERRAIN_WetRefraction[i], holderB.TERRAIN_WetRefraction[i], t);
                TERRAIN_Flow[i]=Mathf.Lerp(holderA.TERRAIN_Flow[i], holderB.TERRAIN_Flow[i], t);
                TERRAIN_WetSpecularity[i]=Mathf.Lerp(holderA.TERRAIN_WetSpecularity[i], holderB.TERRAIN_WetSpecularity[i], t);
                TERRAIN_WetReflection[i]=Mathf.Lerp(holderA.TERRAIN_WetReflection[i], holderB.TERRAIN_WetReflection[i], t);
                TERRAIN_WaterColor[i]=Color.Lerp(holderA.TERRAIN_WaterColor[i], holderB.TERRAIN_WaterColor[i], t);
                TERRAIN_LayerReflection[i]=Mathf.Lerp(holderA.TERRAIN_LayerReflection[i], holderB.TERRAIN_LayerReflection[i], t);
            }
        }
    }
    public void SavePreset(ref ReliefTerrainPresetHolder holder)
    {
        holder.numLayers=numLayers;
        holder.splats=new Texture2D[splats.Length];
        for(int i=0; i<holder.splats.Length; i++) {
            holder.splats[i]=splats[i];
        }

        holder.splat_atlases=new Texture2D[splat_atlases.Length];
        for(int i=0; i<splat_atlases.Length; i++) {
            holder.splat_atlases[i]=splat_atlases[i];
        }

        holder.RTP_MIP_BIAS=RTP_MIP_BIAS;
        holder._SpecColor=_SpecColor;

        holder.SuperDetailA_channel=SuperDetailA_channel;
        holder.SuperDetailB_channel=SuperDetailB_channel;

        holder.Bump01=Bump01;
        holder.Bump23=Bump23;
        holder.Bump45=Bump45;
        holder.Bump67=Bump67;
        holder.Bump89=Bump89;
        holder.BumpAB=BumpAB;

        holder.SSColorCombined=SSColorCombined;

        holder.BumpGlobal=BumpGlobal;

        holder.VerticalTexture=VerticalTexture;
        holder.BumpMapGlobalScale=BumpMapGlobalScale;
        holder.GlobalColorMapBlendValues=GlobalColorMapBlendValues;
        holder.GlobalColorMapSaturation=GlobalColorMapSaturation;
        holder.GlobalColorMapBrightness=GlobalColorMapBrightness;
        holder._GlobalColorMapNearMIP=_GlobalColorMapNearMIP;
        holder._FarNormalDamp=_FarNormalDamp;

        holder.blendMultiplier=blendMultiplier;

        holder.HeightMap=HeightMap;
        holder.HeightMap2=HeightMap2;
        holder.HeightMap3=HeightMap3;

        holder.ReliefTransform=ReliefTransform;
        holder.DIST_STEPS=DIST_STEPS;
        holder.WAVELENGTH=WAVELENGTH;
        holder.ReliefBorderBlend=ReliefBorderBlend;

        holder.ExtrudeHeight=ExtrudeHeight;
        holder.LightmapShading=LightmapShading;

        holder.SHADOW_STEPS=SHADOW_STEPS;
        holder.WAVELENGTH_SHADOWS=WAVELENGTH_SHADOWS;
        holder.SHADOW_SMOOTH_STEPS=SHADOW_SMOOTH_STEPS;
        holder.SelfShadowStrength=SelfShadowStrength;
        holder.ShadowSmoothing=ShadowSmoothing;
        holder.ShadowColor=ShadowColor;

        holder.distance_start=distance_start;
        holder.distance_transition=distance_transition;
        holder.distance_start_bumpglobal=distance_start_bumpglobal;
        holder.distance_transition_bumpglobal=distance_transition_bumpglobal;
        holder.rtp_perlin_start_val=rtp_perlin_start_val;

        holder.trees_shadow_distance_start=trees_shadow_distance_start;
        holder.trees_shadow_distance_transition=trees_shadow_distance_transition;
        holder.trees_shadow_value=trees_shadow_value;
        holder.trees_pixel_distance_start=trees_pixel_distance_start;
        holder.trees_pixel_distance_transition=trees_pixel_distance_transition;
        holder.trees_pixel_blend_val=trees_pixel_blend_val;
        holder.global_normalMap_multiplier=global_normalMap_multiplier;

        holder.rtp_mipoffset_globalnorm=rtp_mipoffset_globalnorm;
        holder._SuperDetailTiling=_SuperDetailTiling;
        holder.SuperDetailA=SuperDetailA;
        holder.SuperDetailB=SuperDetailB;

        // reflection
        holder.TERRAIN_ReflectionMap=TERRAIN_ReflectionMap;
        holder.TERRAIN_ReflectionMap_channel=TERRAIN_ReflectionMap_channel;
        holder.TERRAIN_ReflColorA=TERRAIN_ReflColorA;
        holder.TERRAIN_ReflColorB=TERRAIN_ReflColorB;
        holder.TERRAIN_ReflDistortion=TERRAIN_ReflDistortion;
        holder.TERRAIN_ReflectionRotSpeed=TERRAIN_ReflectionRotSpeed;
        holder.TERRAIN_FresnelPow=TERRAIN_FresnelPow;
        holder.TERRAIN_FresnelOffset=TERRAIN_FresnelOffset;

        // water/wet
        holder.TERRAIN_GlobalWetness=TERRAIN_GlobalWetness;

        holder.TERRAIN_WaterSpecularity=TERRAIN_WaterSpecularity;

        holder.TERRAIN_RippleMap=TERRAIN_RippleMap;
        holder.TERRAIN_RippleScale=TERRAIN_RippleScale;
        holder.TERRAIN_FlowScale=TERRAIN_FlowScale;
        holder.TERRAIN_FlowSpeed=TERRAIN_FlowSpeed;
        holder.TERRAIN_FlowMipOffset=TERRAIN_FlowMipOffset;
        holder.TERRAIN_WetDarkening=TERRAIN_WetDarkening;
        holder.TERRAIN_WetDropletsStrength=TERRAIN_WetDropletsStrength;

        holder.TERRAIN_RainIntensity=TERRAIN_RainIntensity;
        holder.TERRAIN_DropletsSpeed=TERRAIN_DropletsSpeed;

        holder.TERRAIN_mipoffset_flowSpeed=TERRAIN_mipoffset_flowSpeed;

        // caustics
        holder.TERRAIN_CausticsAnimSpeed=TERRAIN_CausticsAnimSpeed;
        holder.TERRAIN_CausticsColor=TERRAIN_CausticsColor;
        holder.TERRAIN_CausticsWaterLevel=TERRAIN_CausticsWaterLevel;
        holder.TERRAIN_CausticsWaterLevelByAngle=TERRAIN_CausticsWaterLevelByAngle;
        holder.TERRAIN_CausticsWaterDeepFadeLength=TERRAIN_CausticsWaterDeepFadeLength;
        holder.TERRAIN_CausticsWaterShallowFadeLength=TERRAIN_CausticsWaterShallowFadeLength;
        holder.TERRAIN_CausticsTilingScale=TERRAIN_CausticsTilingScale;
        holder.TERRAIN_CausticsTex=TERRAIN_CausticsTex;

        holder.rtp_customAmbientCorrection=rtp_customAmbientCorrection;

        holder.RTP_AOsharpness=RTP_AOsharpness;
        holder.RTP_AOamp=RTP_AOamp;
        holder.RTP_LightDefVector=RTP_LightDefVector;
        holder.RTP_ReflexLightDiffuseColor=RTP_ReflexLightDiffuseColor;
        holder.RTP_ReflexLightSpecColor=RTP_ReflexLightSpecColor;

        holder.VerticalTextureGlobalBumpInfluence=VerticalTextureGlobalBumpInfluence;
        holder.VerticalTextureTiling=VerticalTextureTiling;

        // snow
        holder._snow_strength=_snow_strength;
        holder._global_color_brightness_to_snow=_global_color_brightness_to_snow;
        holder._snow_slope_factor=_snow_slope_factor;
        holder._snow_edge_definition=_snow_edge_definition;
        holder._snow_height_treshold=_snow_height_treshold;
        holder._snow_height_transition=_snow_height_transition;
        holder._snow_color=_snow_color;
        holder._snow_specular=_snow_specular;
        holder._snow_gloss=_snow_gloss;
        holder._snow_reflectivness=_snow_reflectivness;
        holder._snow_deep_factor=_snow_deep_factor;

        //////////////////////
        // layer_dependent arrays
        //////////////////////
        holder.Bumps=new Texture2D[numLayers];
        holder.Spec=new float[numLayers];
        holder.FarGlossCorrection=new float[numLayers];
        holder.MixScale=new float[numLayers];
        holder.MixBlend=new float[numLayers];
        holder.MixSaturation=new float[numLayers];
        holder.GlobalColorPerLayer=new float[numLayers];
        holder.PER_LAYER_HEIGHT_MODIFIER=new float[numLayers];
        holder._SuperDetailStrengthMultA=new float[numLayers];
        holder._SuperDetailStrengthMultASelfMaskNear=new float[numLayers];
        holder._SuperDetailStrengthMultASelfMaskFar=new float[numLayers];
        holder._SuperDetailStrengthMultB=new float[numLayers];
        holder._SuperDetailStrengthMultBSelfMaskNear=new float[numLayers];
        holder._SuperDetailStrengthMultBSelfMaskFar=new float[numLayers];
        holder._SuperDetailStrengthNormal=new float[numLayers];
        holder._BumpMapGlobalStrength=new float[numLayers];

        holder.VerticalTextureStrength=new float[numLayers];
        holder.AO_strength=new float[numLayers];

        holder.Heights=new Texture2D[numLayers];

        holder._snow_strength_per_layer=new float[numLayers];
        holder.Substances=new ProceduralMaterial[numLayers];

        // wet
        holder.TERRAIN_LayerWetStrength=new float[numLayers];
        holder.TERRAIN_WaterLevel=new float[numLayers];
        holder.TERRAIN_WaterLevelSlopeDamp=new float[numLayers];
        holder.TERRAIN_WaterEdge=new float[numLayers];
        holder.TERRAIN_WaterGloss=new float[numLayers];
        holder.TERRAIN_WaterOpacity=new float[numLayers];
        holder.TERRAIN_Refraction=new float[numLayers];
        holder.TERRAIN_WetRefraction=new float[numLayers];
        holder.TERRAIN_Flow=new float[numLayers];
        holder.TERRAIN_WetSpecularity=new float[numLayers];
        holder.TERRAIN_WetReflection=new float[numLayers];
        holder.TERRAIN_WaterColor=new Color[numLayers];
        holder.TERRAIN_LayerReflection=new float[numLayers];

        for(int i=0; i<numLayers; i++) {
            holder.Bumps[i]=Bumps[i];
            holder.Spec[i]=Spec[i];
            holder.FarGlossCorrection[i]=FarGlossCorrection[i];
            holder.MixScale[i]=MixScale[i];
            holder.MixBlend[i]=MixBlend[i];
            holder.MixSaturation[i]=MixSaturation[i];
            holder.GlobalColorPerLayer[i]=GlobalColorPerLayer[i];
            holder.PER_LAYER_HEIGHT_MODIFIER[i]=PER_LAYER_HEIGHT_MODIFIER[i];
            holder._SuperDetailStrengthMultA[i]=_SuperDetailStrengthMultA[i];
            holder._SuperDetailStrengthMultASelfMaskNear[i]=_SuperDetailStrengthMultASelfMaskNear[i];
            holder._SuperDetailStrengthMultASelfMaskFar[i]=_SuperDetailStrengthMultASelfMaskFar[i];
            holder._SuperDetailStrengthMultB[i]=_SuperDetailStrengthMultB[i];
            holder._SuperDetailStrengthMultBSelfMaskNear[i]=_SuperDetailStrengthMultBSelfMaskNear[i];
            holder._SuperDetailStrengthMultBSelfMaskFar[i]=_SuperDetailStrengthMultBSelfMaskFar[i];
            holder._SuperDetailStrengthNormal[i]=_SuperDetailStrengthNormal[i];
            holder._BumpMapGlobalStrength[i]=_BumpMapGlobalStrength[i];

            holder.VerticalTextureStrength[i]=VerticalTextureStrength[i];
            holder.AO_strength[i]=AO_strength[i];

            holder.Heights[i]=Heights[i];

            holder._snow_strength_per_layer[i]=_snow_strength_per_layer[i];
            holder.Substances[i]=Substances[i];

            // wet
            holder.TERRAIN_LayerWetStrength[i]=TERRAIN_LayerWetStrength[i];
            holder.TERRAIN_WaterLevel[i]=TERRAIN_WaterLevel[i];
            holder.TERRAIN_WaterLevelSlopeDamp[i]=TERRAIN_WaterLevelSlopeDamp[i];
            holder.TERRAIN_WaterEdge[i]=TERRAIN_WaterEdge[i];
            holder.TERRAIN_WaterGloss[i]=TERRAIN_WaterGloss[i];
            holder.TERRAIN_WaterOpacity[i]=TERRAIN_WaterOpacity[i];
            holder.TERRAIN_Refraction[i]=TERRAIN_Refraction[i];
            holder.TERRAIN_WetRefraction[i]=TERRAIN_WetRefraction[i];
            holder.TERRAIN_Flow[i]=TERRAIN_Flow[i];
            holder.TERRAIN_WetSpecularity[i]=TERRAIN_WetSpecularity[i];
            holder.TERRAIN_WetReflection[i]=TERRAIN_WetReflection[i];
            holder.TERRAIN_WaterColor[i]=TERRAIN_WaterColor[i];
            holder.TERRAIN_LayerReflection[i]=TERRAIN_LayerReflection[i];
        }
    }
	public override void OnInspectorGUI () {
		ReliefTerrain _targetRT=(ReliefTerrain)target;
		ReliefTerrainGlobalSettingsHolder _target=_targetRT.globalSettingsHolder;
		if (_target==null) {
			_targetRT.RefreshTextures();
			_target=_targetRT.globalSettingsHolder;
		}
		dirtyFlag=false;
		
		RTP_LODmanager _RTP_LODmanagerScript = _target.Get_RTP_LODmanagerScript();
		
		Terrain terrainComp = (Terrain)_targetRT.GetComponent(typeof(Terrain));
		if (terrainComp) {
			if (_target.numLayers!=terrainComp.terrainData.splatPrototypes.Length) {
				// a layer removed or added
				_target.ReInit(terrainComp);
				ReliefTerrain[] script_objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
				for(int s=0; s<script_objs.Length; s++) {
					script_objs[s].splat_layer_seq=new int[12] {0,1,2,3,4,5,6,7,8,9,10,11};
				}				
			}
			if (!_target.useTerrainMaterial && _target.numTiles>1) {
				// U3 - multiple terrains or U4 w/o material - multiple terrains
				if (_target.numLayers!=4 && _target.numLayers!=8) {
					EditorGUILayout.HelpBox("RTP on multiple terrains w/o materials (available in U4) works only if we have 4 or 8 layers only !", MessageType.Error, true);
					return;
				}
			}
		}
		if (_target.splats==null || _target.numLayers!=_target.splats.Length) {
			EditorGUILayout.HelpBox("Problem with number of layers, try to reassign ReliefTerrain component script on this terrain...", MessageType.Error, true);
			return;
		}
		int sw=512;
		for(int i=0; i<_target.numLayers; i++) {
			if (_target.splats[i]) {
				sw=_target.splats[i].width;
				break;
			}
		}
		for(int i=0; i<_target.numLayers; i++) {
			if (_target.splats[i]==null) {
				Debug.LogError("Splat (detail) texture "+i+" was empty ! Assigning null texture");
				_target.splats[i]=new Texture2D(sw, sw, TextureFormat.ARGB32, true, QualitySettings.activeColorSpace==ColorSpace.Linear);
			}
		}		
			
		if (_RTP_LODmanagerScript) {
			if (!_RTP_LODmanagerScript.RTP_4LAYERS_MODE) {
				if (_target.numLayers<=4) {
					EditorGUILayout.HelpBox("Shaders are set to 8 layers mode while number of layers is less than 5. Add layers or recompile shaders in RTP_LODmanager to not use 8 layers in first pass.", MessageType.Error, true);
				} else {
					if (_target.splat_atlases[0]==null) {
						PrepareAtlases(1);
					}
					if (_target.splat_atlases[1]==null) {
						PrepareAtlases(2);
					}
				}
			}
		}
		if (_RTP_LODmanagerScript) _RTP_LODmanagerScript.numLayers=_target.numLayers;
			
		bool _4LAYERS_SHADER_USED=false;
		if (_RTP_LODmanagerScript) {
			_target._4LAYERS_SHADER_USED=_4LAYERS_SHADER_USED=_RTP_LODmanagerScript.RTP_4LAYERS_MODE;
		}
		
		bool UV_BLEND_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_UV_BLEND_FIRST;
		bool UV_BLEND_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_UV_BLEND_ADD;
		int[] UV_BLEND_ROUTE_NUM_FIRST;
		int[] UV_BLEND_ROUTE_NUM_ADD;
		if (_RTP_LODmanagerScript) {
			UV_BLEND_ROUTE_NUM_FIRST=_RTP_LODmanagerScript.UV_BLEND_ROUTE_NUM_FIRST;
			UV_BLEND_ROUTE_NUM_ADD=_RTP_LODmanagerScript.UV_BLEND_ROUTE_NUM_ADD;
		} else {
			UV_BLEND_ROUTE_NUM_FIRST=new int[8]{0,1,2,3,4,5,6,7};
			UV_BLEND_ROUTE_NUM_ADD=new int[8]{0,1,2,3,4,5,6,7};
		}
		
		bool RTP_USE_EXTRUDE_REDUCTION_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_USE_EXTRUDE_REDUCTION_FIRST;
		bool RTP_USE_EXTRUDE_REDUCTION_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_USE_EXTRUDE_REDUCTION_ADD;
		
		bool RTP_VERTICAL_TEXTURE_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_FIRST;
		bool RTP_VERTICAL_TEXTURE_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_ADD;
		
		bool RTP_NORMALGLOBAL_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_NORMALGLOBAL_FIRST;
		bool RTP_NORMALGLOBAL_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_NORMALGLOBAL_ADD;
		bool RTP_TREESGLOBAL_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_TREESGLOBAL_FIRST;
		bool RTP_TREESGLOBAL_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_TREESGLOBAL_ADD;
		
		bool RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_SIMPLE  && _RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST;
		//bool RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_SIMPLE  && _RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD;
			
		bool SUPER_DETAIL_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_DETAIL_FIRST;
		bool SUPER_DETAIL_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_DETAIL_ADD;
		bool SUPER_DETAIL_MULTS_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_FIRST;
		bool SUPER_DETAIL_MULTS_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_ADD;
		
		bool SNOW_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SNOW_FIRST;
		bool SNOW_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_SNOW_ADD;
		
		bool REFLECTION_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_REFLECTION_FIRST;
		bool REFLECTION_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_REFLECTION_ADD;
		bool REFLECTION_ROTATION_ENABLED = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_ROTATE_REFLECTION;
		
		bool WATER_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_WETNESS_FIRST;
		bool WATER_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_WETNESS_ADD;
		bool RIPPLEMAP_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_FIRST;
		bool RIPPLEMAP_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_ADD;
		
		bool CAUSTICS_ENABLED_FIRST = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_CAUSTICS_FIRST;
		bool CAUSTICS_ENABLED_ADD = _RTP_LODmanagerScript && _RTP_LODmanagerScript.RTP_CAUSTICS_ADD;
		
			
		string[] toolbarStrings;
		GUIContent[] toolbarIcons = new GUIContent[4]{ new GUIContent("Layers", icoLayers), new GUIContent("Coverage", icoCoverage), new GUIContent("Combined\ntexures", icoCombinedTexutres), new GUIContent("Settings", icoSettings) };
		GUILayout.Space(10);			
		EditorGUILayout.BeginHorizontal();
		GUILayout.FlexibleSpace();
		_target.submenu=(ReliefTerrainMenuItems)(GUILayout.Toolbar((int)_target.submenu, toolbarIcons, EditorStyles.miniButton, GUILayout.MaxWidth(370)));
		GUILayout.FlexibleSpace();
		EditorGUILayout.EndHorizontal();
		GUILayout.Space(10);			
		
		_target.show_details = _target.submenu==ReliefTerrainMenuItems.Details;
		_target.show_controlmaps = _target.submenu==ReliefTerrainMenuItems.Control;
		_target.show_derivedmaps = _target.submenu==ReliefTerrainMenuItems.CombinedTextures;
		_target.show_settings = _target.submenu==ReliefTerrainMenuItems.GeneralSettings;
		
		if (_target.show_active_layer>=_target.numLayers) {
			_target.show_active_layer=_target.numLayers-1;
		}			
		//Debug.Log (_target.show_active_layer+","+_target.numLayers);
		
		if (_target.show_details) {
			#region Detail maps unfold

			if (_target.numLayers>0) {
				#region Detail maps unfold	- layers
				
				if (!terrainComp) {
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.BeginHorizontal();
					EditorGUI.BeginDisabledGroup(_target.numLayers==8);
					if (GUILayout.Button("Add layer")) {
						_target.numLayers++;
						int j=_target.numLayers-1;
						
						ReliefTerrain[] script_objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
						for(int s=0; s<script_objs.Length; s++) {
							script_objs[s].splat_layer_seq[j]=j;
							script_objs[s].splat_layer_boost[j]=1;
							script_objs[s].splat_layer_calc[j]=true;
							script_objs[s].splat_layer_masked[j]=false;
							script_objs[s].source_controls_invert[j]=false;
							script_objs[s].source_controls_mask_invert[j]=false;
						}
						
						_target.Bumps[j]=null;
						_target.Heights[j]=null;
						_target.Substances[j]=null;						
						
						_target.ReturnToDefaults("layer", j);
						
						Texture2D[] splats_new=new Texture2D[_target.numLayers];
						for(int i=0; i<_target.splats.Length; i++) splats_new[i]=_target.splats[i];
						_target.splats=splats_new;
						_target.splats[_target.numLayers-1]=_target.splats[((_target.numLayers-2) >=0) ? (_target.numLayers-2) : 0];
					}
					EditorGUI.EndDisabledGroup();
					EditorGUI.BeginDisabledGroup(_target.numLayers==1);
					if (GUILayout.Button("Remove layer")) {
						_target.numLayers--;
						Texture2D[] splats_new=new Texture2D[_target.numLayers];
						for(int i=0; i<splats_new.Length; i++) splats_new[i]=_target.splats[i];
						_target.splats=splats_new;
						ReliefTerrain[] script_objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
						for(int s=0; s<script_objs.Length; s++) {
							script_objs[s].splat_layer_seq=new int[12] {0,1,2,3,4,5,6,7,8,9,10,11};
						}
						if (_target.show_active_layer>=_target.numLayers) {
							_target.show_active_layer=_target.numLayers-1;
						}								
					}
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
				}
				
				bool handle_substances=false;
				#if UNITY_4_1 || UNITY_4_2 || UNITY_4_3  || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6
					handle_substances=true;
				#else
					if (PlayerSettings.advancedLicense) {
							handle_substances=true;
					}
				#endif
			
				EditorGUILayout.BeginVertical("Box");
				Color skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Choose layer", EditorStyles.boldLabel);
				GUI.color=skin_color;
				EditorGUILayout.HelpBox("Hint: to quickly select a layer - focus on scene view (by click) and press L holding cursor over the layer that should be selected.", MessageType.Info, true);
				
				GUISkin gs=EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector);
				RectOffset ro1=gs.label.padding;
				RectOffset ro2=gs.label.margin;
				gs.label.padding=new  RectOffset(0, 0, 0, 0);
				gs.label.margin=new  RectOffset(3, 3, 3, 3);
				int thumb_size=50;
				int per_row=Mathf.Max( 4, (Screen.width)/thumb_size - 1 );
				thumb_size=(Screen.width-50-2*per_row)/per_row;
				Color ccol=GUI.contentColor;
				for(int n=0; n<_target.numLayers; n++) {
					if ((n%per_row)==0) EditorGUILayout.BeginHorizontal();
					Color bcol=GUI.backgroundColor;
					if (n==_target.show_active_layer) {
						GUI.contentColor=new Color(1,1,1,1);
						GUI.backgroundColor=new Color(1,1,0,1);
						EditorGUILayout.BeginHorizontal("Box");
						if (_target.splats[n]) {
#if !UNITY_3_5
						GUILayout.Label((Texture2D)AssetPreview.GetAssetPreview(_target.splats[n]), GUILayout.Width(thumb_size-8), GUILayout.Height(thumb_size-8));
#else
						GUILayout.Label((Texture2D)EditorUtility.GetAssetPreview(_target.splats[n]), GUILayout.Width(thumb_size-8), GUILayout.Height(thumb_size-8));
#endif
						} else {
							GUILayout.Label(" ", GUILayout.Width(thumb_size-8), GUILayout.Height(thumb_size-8));
						}
					} else {
						GUI.contentColor=new Color(1,1,1,0.5f);
						if (_target.splats[n]) {
#if !UNITY_3_5
						if (GUILayout.Button((Texture2D)AssetPreview.GetAssetPreview(_target.splats[n]), "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
#else
						if (GUILayout.Button((Texture2D)EditorUtility.GetAssetPreview(_target.splats[n]), "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
#endif
							_target.show_active_layer=n;
						}
						} else {
							if (GUILayout.Button(" ", "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
								_target.show_active_layer=n;
							}
						}
					}
					if (n==_target.show_active_layer) {
						EditorGUILayout.EndHorizontal();
						GUI.backgroundColor=bcol;
					}
					if ((n%per_row)==(per_row-1) || n==_target.numLayers-1) EditorGUILayout.EndHorizontal();
				}
				GUI.contentColor=ccol;
				gs.label.padding=ro1;
				gs.label.margin=ro2;
				EditorGUILayout.EndVertical();
				EditorGUILayout.Space();
				
				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Layer properties", EditorStyles.boldLabel);
				GUI.color=skin_color;
				EditorGUILayout.HelpBox("All layers should share THE SAME size for given texture type\n(i.e. all detail textures should have the same size and so on). ", MessageType.Info, true);
				EditorGUILayout.Space();
				{
					int thW=(Screen.width-60)/3;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Detail", EditorStyles.boldLabel, GUILayout.Width(thW));
					EditorGUILayout.LabelField("Normal", EditorStyles.boldLabel, GUILayout.Width(thW));
					EditorGUILayout.LabelField("Height (A)", EditorStyles.boldLabel, GUILayout.Width(thW));
					EditorGUILayout.EndHorizontal();
				}
				
				{
					int n=_target.show_active_layer;
					EditorGUILayout.BeginHorizontal();
					
					int thW=(Screen.width-60)/3;
					//Debug.Log (_target.splats.Length+"  "+_target.numLayers);
					Texture2D tex=_target.splats[n];
					Texture2D ntex=tex;
					checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.splats[n], typeof(Texture2D), false, GUILayout.Width(thW), GUILayout.Height(thW)));
					if (ntex!=tex && ntex) {
						_target.splats[n]=ntex;
						if (_target.numLayers>4 && (!_4LAYERS_SHADER_USED) && (n<8)) {
							if (EditorUtility.DisplayDialog("RTP Notification", "In 8 layers mode you have to recalc atlases to see changes.", "OK, do it now", "Thanks, I'll do it later")) {
								PrepareAtlases((n<4) ? 1:2);
							}
						}
						_target.Refresh();
					}
						
					tex=_target.Bumps[n];
					ntex=tex;
					checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.Bumps[n], typeof(Texture2D), false, GUILayout.Width(thW), GUILayout.Height(thW)));
					if (ntex!=tex) {
						Texture2D tex_prev=_target.Bumps[n];
						_target.Bumps[n]=ntex;
						AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
						if (_importer) {
							TextureImporter tex_importer=(TextureImporter)_importer;
							bool changed=false;
							if (!tex_importer.isReadable) {
								Debug.LogWarning("Normal texture "+n+" ("+ntex.name+") has been reimported as readable.");
								tex_importer.isReadable=true;
								changed=true;
							}
							if (!tex_importer.normalmap) {
								Debug.LogWarning("Normal texture "+n+" ("+ntex.name+") has been reimported as normal map type.");
								tex_importer.normalmap=true;
								changed=true;
							}
							if (changed) {
								AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
							}
						}							
						if (!_target.PrepareNormals()) _target.Bumps[n]=tex_prev;
						_target.Refresh();
					}
					
					tex=_target.Heights[n];
					ntex=tex;
					checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.Heights[n], typeof(Texture2D), false, GUILayout.Width(thW), GUILayout.Height(thW)));
					if (ntex!=tex) {
						Texture2D tex_prev=_target.Heights[n];
						_target.Heights[n]=ntex;
						AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
						if (_importer) {
							TextureImporter tex_importer=(TextureImporter)_importer;
							bool changed=false;
							if (!tex_importer.isReadable) {
								Debug.LogWarning("Height texture "+n+" ("+ntex.name+") has been reimported as readable.");
								tex_importer.isReadable=true;
								changed=true;
							}
							if (!tex_importer.linearTexture) {
								Debug.LogWarning("Height texture "+n+" ("+ntex.name+") has been reimported as linear.");
								tex_importer.linearTexture=true;
								changed=true;
							}
							if (changed) {
								AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
							}
						}
						if (!PrepareHeights(n)) _target.Heights[n]=tex_prev;
						_target.Refresh();
					}
					EditorGUILayout.EndHorizontal();

					if (handle_substances) {
						EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("Substance", EditorStyles.boldLabel, GUILayout.MaxWidth(75));
							
							ProceduralMaterial subs=_target.Substances[n];
							ProceduralMaterial nsubs=subs;
							checkChange(ref nsubs, (ProceduralMaterial)EditorGUILayout.ObjectField(_target.Substances[n], typeof(ProceduralMaterial), false));
							if (nsubs!=subs) {
								_target.Substances[n]=nsubs;
								#if UNITY_4_1 || UNITY_4_2 || UNITY_4_3  || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6									
								if (nsubs) {
									_target.Substances[n].isReadable=true;
									SubstanceImporter s_importer=(SubstanceImporter)SubstanceImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.Substances[n]));
									if (_target.Substances[n].shader.name!="Parallax Specular") {
										_target.Substances[n].shader=Shader.Find("Parallax Specular");
										s_importer.OnShaderModified(_target.Substances[n]);
									}
									_target.Substances[n].RebuildTexturesImmediately();
									GetSubstanceTex("_Diffuse","_MainTex", n);		
									GetSubstanceTex("_Normal","_BumpMap", n, true);	
									GetSubstanceTex("_Height","_ParallaxMap", n);
									
								}
								#endif
							}
						EditorGUILayout.EndHorizontal();
						EditorGUI.BeginDisabledGroup(_target.Substances[n]==null || _target.Substances[n].isProcessing);
						if (GUILayout.Button("Get textures")) {
							
							#if UNITY_4_1 || UNITY_4_2 || UNITY_4_3  || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 || UNITY_5_6									
								_target.Substances[n].isReadable=true;
							#endif
							SubstanceImporter s_importer=(SubstanceImporter)SubstanceImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.Substances[n]));
							if (_target.Substances[n].shader.name!="Parallax Specular") {
								_target.Substances[n].shader=Shader.Find("Parallax Specular");
								s_importer.OnShaderModified(_target.Substances[n]);
							}
							_target.Substances[n].RebuildTexturesImmediately();
					
							AssetImporter _importer;
							string orig_path;
							string path="";
							bool override_flag;
							byte[] bytes;
							int option;
							
							_importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.splats[n]));
							if (_importer) {
								orig_path=AssetDatabase.GetAssetPath(_target.splats[n]);
								orig_path=orig_path.Substring(0,orig_path.LastIndexOf("/")+1);
							} else {
								orig_path=AssetDatabase.GetAssetPath(_target.Substances[n])+"/";
							}
							
							//
							// diffuse								
							//
							ntex=GetSubstanceTex("_Diffuse","_MainTex", n);		

							path=orig_path+_target.Substances[n].name+"_diffuse_spec"+".png";
							override_flag=AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null;
							if (override_flag) {
								option=EditorUtility.DisplayDialogComplex("RTP Notification", "Override color/diffuse texture ?", "OK", "Make copy", "Skip texture");
							} else {
								option=0;
							}
							if (option==1) {
								do {
									int suffix_pos=path.LastIndexOf(".");
									path=path.Substring(0,suffix_pos)+"_copy"+path.Substring(suffix_pos);
								} while(AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null);
							}
							if (option<2) {									
						 		bytes = ntex.EncodeToPNG();
								DestroyImmediate(ntex);
								ntex=null;
							    System.IO.File.WriteAllBytes(path, bytes);
								AssetDatabase.Refresh();
								_importer=AssetImporter.GetAtPath(path);
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									tex_importer.isReadable=true;
									tex_importer.maxTextureSize=_target.splats[n].width;
									AssetDatabase.ImportAsset(path,  ImportAssetOptions.ForceUpdate);
									ntex=(Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
									if (_target.numLayers>4 && (!_4LAYERS_SHADER_USED) && (n<8)) {
										if (EditorUtility.DisplayDialog("RTP Notification", "In 8 layers mode you have to recalc atlases to see changes.", "OK, do it now", "Thanks, I'll do it later")) {
											PrepareAtlases((n<4) ? 1:2);
										}
									}
								}				
							}
							
							//
							// normal						
							//
							ntex=GetSubstanceTex("_Normal","_BumpMap", n, true);	
							int nwidth=ntex.width;
							path=orig_path+_target.Substances[n].name+"_normal"+".png";
							override_flag=AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null;
							if (override_flag) {
								option=EditorUtility.DisplayDialogComplex("RTP Notification", "Override normal texture ?", "OK", "Make copy", "Skip texture");
							} else {
								option=0;
							}
							if (option==1) {
								do {
									int suffix_pos=path.LastIndexOf(".");
									path=path.Substring(0,suffix_pos)+"_copy"+path.Substring(suffix_pos);
								} while(AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null);
							}
							if (option<2) {
						 		bytes = ntex.EncodeToPNG();
								DestroyImmediate(ntex);
								ntex=null;
							    System.IO.File.WriteAllBytes(path, bytes);
								AssetDatabase.Refresh();
								_importer=AssetImporter.GetAtPath(path);
								if (_importer) {
									Texture2D tex_prev=_target.Bumps[n];
									TextureImporter tex_importer=(TextureImporter)_importer;
									tex_importer.isReadable=true;
									int compare_n;
									if ((n&1)==0) {
										if ((n+1)<_target.numLayers) {
											compare_n=n+1;
										} else {
											compare_n=-1;
										}
									} else {
										compare_n=n-1;
									}
									if (compare_n>=0 && _target.Bumps[compare_n]!=null) {
										if (nwidth<_target.Bumps[compare_n].width) {
											TextureImporter tex_importer_tmp=(TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.Bumps[compare_n].width));
											tex_importer_tmp.maxTextureSize=nwidth;
											Debug.LogWarning("Normal texture "+compare_n+" ("+_target.splats[compare_n].name+") has been reimported with "+tex_importer_tmp.maxTextureSize+" size.");
											AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.Bumps[compare_n].width),  ImportAssetOptions.ForceUpdate);
										} else if (nwidth>_target.Bumps[compare_n].width) {
											tex_importer.maxTextureSize=_target.Bumps[compare_n].width;
											Debug.LogWarning("Normal texture "+n+" ("+_target.splats[n].name+") has been imported with "+tex_importer.maxTextureSize+" size.");
										}
									}
									tex_importer.textureType=TextureImporterType.Bump;
									AssetDatabase.ImportAsset(path,  ImportAssetOptions.ForceUpdate);
									ntex=(Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
									_target.Bumps[n]=ntex;
									if (!_target.PrepareNormals()) _target.Bumps[n]=tex_prev;
									_target.Refresh();
								}
							}
							
							//
							// height				
							//
							ntex=GetSubstanceTex("_Height","_ParallaxMap", n);

							path=orig_path+_target.Substances[n].name+"_height"+".png";
							override_flag=AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null;
							if (override_flag) {
								option=EditorUtility.DisplayDialogComplex("RTP Notification", "Override height texture ?", "OK", "Make copy", "Skip texture");
							} else {
								option=0;
							}
							if (option==1) {
								do {
									int suffix_pos=path.LastIndexOf(".");
									path=path.Substring(0,suffix_pos)+"_copy"+path.Substring(suffix_pos);
								} while(AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D))!=null);
							}
							if (option<2) {
						 		bytes = ntex.EncodeToPNG();
								DestroyImmediate(ntex);
								ntex=null;
							    System.IO.File.WriteAllBytes(path, bytes);
								AssetDatabase.Refresh();
								_importer=AssetImporter.GetAtPath(path);
								if (_importer) {
									Texture2D tex_prev=_target.Heights[n];
									TextureImporter tex_importer=(TextureImporter)_importer;
									tex_importer.isReadable=true;
									tex_importer.linearTexture=true;
									tex_importer.textureFormat=TextureImporterFormat.Alpha8;
									AssetDatabase.ImportAsset(path,  ImportAssetOptions.ForceUpdate);
									ntex=(Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
									_target.Heights[n]=ntex;
									if (!PrepareHeights(n)) _target.Heights[n]=tex_prev;
									_target.Refresh();
								}						
							}
						
						}
							
						EditorGUI.EndDisabledGroup();
					} // handle substances
					
					GUILayout.Space(10);
					
					bool AddPass_flag=(_4LAYERS_SHADER_USED && n>=4) || (n>=8);
						
					EditorGUILayout.BeginVertical("Box");
					float nval;
					nval=_target.Spec[n];
					checkChange(ref nval, EditorGUILayout.Slider("Layer "+n+" specular", _target.Spec[n], 0.01f, 1f, GUILayout.ExpandWidth(true)));
					_target.Spec[n]=nval;
					nval=_target.FarGlossCorrection[n];
					checkChange(ref nval, EditorGUILayout.Slider("Far gloss correction", _target.FarGlossCorrection[n], -1f, 1f, GUILayout.ExpandWidth(true)));
					_target.FarGlossCorrection[n]=nval;
					EditorGUI.BeginDisabledGroup( !(AddPass_flag ? RTP_USE_EXTRUDE_REDUCTION_ADD : RTP_USE_EXTRUDE_REDUCTION_FIRST) );
					nval=_target.PER_LAYER_HEIGHT_MODIFIER[n];
					checkChange(ref nval, EditorGUILayout.Slider("Extrude reduction", _target.PER_LAYER_HEIGHT_MODIFIER[n], 0.0f, 1f, GUILayout.ExpandWidth(true)));
					_target.PER_LAYER_HEIGHT_MODIFIER[n]=nval;
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.BeginHorizontal();	
					EditorGUILayout.LabelField("Far filtering", GUILayout.Width(127));
					nval=_target.MIPmult[n];
					checkChange(ref nval, EditorGUILayout.Slider(_target.MIPmult[n], 0f, 7f, GUILayout.ExpandWidth(true)));
					_target.MIPmult[n]=nval;
					EditorGUILayout.EndHorizontal();	
					EditorGUILayout.BeginHorizontal();	
					EditorGUILayout.LabelField("Heightblend AO", GUILayout.Width(127));
					nval=_target.AO_strength[n];
					checkChange(ref nval, EditorGUILayout.Slider(_target.AO_strength[n], 0f, 1f, GUILayout.ExpandWidth(true)));
					_target.AO_strength[n]=nval;
					EditorGUILayout.EndHorizontal();	
					EditorGUILayout.EndVertical();
						
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.BeginHorizontal();	
					if (GUILayout.Button(new GUIContent(icoGlobalcolor, "Global maps settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
						_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
						_target.submenu_settings=ReliefTerrainSettingsItems.GlobalColor;
					}
					EditorGUILayout.LabelField("Global colormap", GUILayout.Width(130));
					nval=_target.GlobalColorPerLayer[n];
					checkChange(ref nval, EditorGUILayout.Slider(_target.GlobalColorPerLayer[n], 0f, 1f, GUILayout.ExpandWidth(true)));
					_target.GlobalColorPerLayer[n]=nval;
					EditorGUILayout.EndHorizontal();	
					EditorGUILayout.EndVertical();
						
					EditorGUILayout.BeginVertical("Box");
					EditorGUI.BeginDisabledGroup( !(AddPass_flag ? UV_BLEND_ENABLED_ADD : UV_BLEND_ENABLED_FIRST) );
					EditorGUILayout.BeginHorizontal();
						if (GUILayout.Button(new GUIContent(icoUVBlend, "UV blend settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
							_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
							_target.submenu_settings=ReliefTerrainSettingsItems.UVblend;
						}
						int routed_n=AddPass_flag ? UV_BLEND_ROUTE_NUM_ADD[n-4] : UV_BLEND_ROUTE_NUM_FIRST[n];
						if (routed_n>_target.MixScale.Length-1) routed_n=n; // at init
						nval=_target.MixScale[routed_n+(AddPass_flag?4:0)];
						EditorGUILayout.LabelField("UV blend scale"+((routed_n!=n-(AddPass_flag?4:0)) ? " (from "+routed_n+")":""), GUILayout.Width(130+((routed_n!=n-(AddPass_flag?4:0)) ? 10:0)));
						EditorGUILayout.BeginHorizontal();
							checkChange(ref nval, EditorGUILayout.Slider(_target.MixScale[routed_n+(AddPass_flag?4:0)], 0.01f, 0.5f));
							if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
								float ratio=Mathf.Round(_target.ReliefTransform.x*nval);
								nval=ratio/_target.ReliefTransform.x;
								EditorUtility.SetDirty(_targetRT);
							}
						EditorGUILayout.EndHorizontal();						
						_target.MixScale[routed_n+(AddPass_flag?4:0)]=nval;
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						nval=_target.MixBlend[n];
						EditorGUILayout.LabelField(" ", GUILayout.Width(16));
						EditorGUILayout.LabelField("UV blend val", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target.MixBlend[n], 0, 0.9f));
						_target.MixBlend[n]=nval;
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						nval=_target.MixSaturation[n];
						EditorGUILayout.LabelField(" ", GUILayout.Width(16));
						EditorGUILayout.LabelField("UV blend saturation", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target.MixSaturation[n], 0, 1.0f));
						_target.MixSaturation[n]=nval;
					EditorGUILayout.EndHorizontal();
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndVertical();
				
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.BeginHorizontal();
						if (GUILayout.Button(new GUIContent(icoPerlinNormal, "Perlin normal settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
							_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
							_target.submenu_settings=ReliefTerrainSettingsItems.GlobalNormal;
						}
						nval=_target._BumpMapGlobalStrength[n];
						EditorGUILayout.LabelField("Perlin normal", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target._BumpMapGlobalStrength[n], 0f, 2f));
						_target._BumpMapGlobalStrength[n]=nval;		
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
						
					EditorGUILayout.BeginVertical("Box");
						
					EditorGUILayout.BeginHorizontal();
						if (GUILayout.Button(new GUIContent(icoSuperdetail, "Superdetail settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
							_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
							_target.submenu_settings=ReliefTerrainSettingsItems.Superdetail;
						}
						EditorGUI.BeginDisabledGroup( !(AddPass_flag ? SUPER_DETAIL_ENABLED_ADD : SUPER_DETAIL_ENABLED_FIRST) );
						nval=_target._SuperDetailStrengthNormal[n];
						EditorGUILayout.LabelField("Superdetail normal", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthNormal[n], 0f, 1f));
						EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndHorizontal();
					
					EditorGUILayout.BeginHorizontal();							
					EditorGUI.BeginDisabledGroup( !(AddPass_flag ? SUPER_DETAIL_ENABLED_ADD : SUPER_DETAIL_ENABLED_FIRST)  || !(AddPass_flag ? SUPER_DETAIL_MULTS_ENABLED_ADD : SUPER_DETAIL_MULTS_ENABLED_FIRST));
						_target._SuperDetailStrengthNormal[n]=nval;							
						nval=_target._SuperDetailStrengthMultA[n];
						EditorGUILayout.LabelField(" ", GUILayout.Width(16));
						EditorGUILayout.LabelField("Superdetail mult A", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultA[n], 0f, 1f));
						_target._SuperDetailStrengthMultA[n]=nval;	
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();							
						nval=_target._SuperDetailStrengthMultASelfMaskNear[n];
						EditorGUILayout.LabelField(" ", GUILayout.Width(16));
						EditorGUILayout.LabelField("  SelfMask near", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultASelfMaskNear[n], 0f, 1f));
						_target._SuperDetailStrengthMultASelfMaskNear[n]=nval;	
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();							
						nval=_target._SuperDetailStrengthMultASelfMaskFar[n];
						EditorGUILayout.LabelField(" ", GUILayout.Width(16));
						EditorGUILayout.LabelField("  SelfMask far", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultASelfMaskFar[n], 0f, 1f));
						_target._SuperDetailStrengthMultASelfMaskFar[n]=nval;
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();							
						nval=_target._SuperDetailStrengthMultB[n];
						EditorGUILayout.LabelField(" ", GUILayout.Width(16));
						EditorGUILayout.LabelField("Superdetail mult B", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultB[n], 0f, 1f));
						_target._SuperDetailStrengthMultB[n]=nval;							
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();							
						nval=_target._SuperDetailStrengthMultBSelfMaskNear[n];
						EditorGUILayout.LabelField(" ", GUILayout.Width(16));
						EditorGUILayout.LabelField("  SelfMask near", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultBSelfMaskNear[n], 0f, 1f));
						_target._SuperDetailStrengthMultBSelfMaskNear[n]=nval;	
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();							
						nval=_target._SuperDetailStrengthMultBSelfMaskFar[n];
						EditorGUILayout.LabelField(" ", GUILayout.Width(16));
						EditorGUILayout.LabelField("  SelfMask far", GUILayout.Width(130));
						checkChange(ref nval, EditorGUILayout.Slider(_target._SuperDetailStrengthMultBSelfMaskFar[n], 0f, 1f));
						_target._SuperDetailStrengthMultBSelfMaskFar[n]=nval;	
					EditorGUILayout.EndHorizontal();
					EditorGUI.EndDisabledGroup();
						
					EditorGUILayout.EndVertical();
						
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.BeginHorizontal();
						if (GUILayout.Button(new GUIContent(icoVerticalTexture, "Vertical map settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
							_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
							_target.submenu_settings=ReliefTerrainSettingsItems.VerticalTex;
						}
						EditorGUI.BeginDisabledGroup( !(AddPass_flag ? RTP_VERTICAL_TEXTURE_ADD : RTP_VERTICAL_TEXTURE_FIRST) );
						nval=_target.VerticalTextureStrength[n];
						checkChange(ref nval, EditorGUILayout.Slider("Vertical map strength", _target.VerticalTextureStrength[n], 0f, 1f));
						_target.VerticalTextureStrength[n]=nval;							
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
						
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.BeginHorizontal();
						if (GUILayout.Button(new GUIContent(icoSnow, "Snow settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
							_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
							_target.submenu_settings=ReliefTerrainSettingsItems.Snow;
						}
						EditorGUI.BeginDisabledGroup( !(AddPass_flag ? SNOW_ENABLED_ADD : SNOW_ENABLED_FIRST) );
						nval=_target._snow_strength_per_layer[n];
						checkChange(ref nval, EditorGUILayout.Slider("Snow strength", _target._snow_strength_per_layer[n], 0f, 1f));
						_target._snow_strength_per_layer[n]=nval;							
						EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
						
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.BeginHorizontal();
					if (GUILayout.Button(new GUIContent(icoWater, "Water settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
						_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
						_target.submenu_settings=ReliefTerrainSettingsItems.Water;
					}
					EditorGUI.BeginDisabledGroup( !(AddPass_flag ? WATER_ENABLED_ADD : WATER_ENABLED_FIRST) );
						
					nval=_target.TERRAIN_LayerWetStrength[n];
					checkChange(ref nval, EditorGUILayout.Slider("Layer wetness", _target.TERRAIN_LayerWetStrength[n], 0f, 1f));
					_target.TERRAIN_LayerWetStrength[n]=nval;							
					EditorGUILayout.EndHorizontal();
						
					EditorGUILayout.HelpBox("Accumulated water color (below water level).\nRealised multiplicative (unless you set high water opacity).\nColor alpha makes water color dependent from Fresnel effect.",MessageType.None, true);
					checkChange(ref _target.TERRAIN_WaterColor[n], EditorGUILayout.ColorField("Water color", _target.TERRAIN_WaterColor[n]));
					checkChange(ref _target.TERRAIN_FresnelPow, EditorGUILayout.Slider("Fresnel exponent (global)", _target.TERRAIN_FresnelPow, 0.5f, 32f));
					checkChange(ref _target.TERRAIN_FresnelOffset, EditorGUILayout.Slider("Fresnel offset (global)", _target.TERRAIN_FresnelOffset, 0, 0.9f));
					GUILayout.Space(6);
						
					nval=_target.TERRAIN_WaterLevel[n];
					checkChange(ref nval, EditorGUILayout.Slider("Water level", _target.TERRAIN_WaterLevel[n]/2f, 0f, 1f)*2f);
					_target.TERRAIN_WaterLevel[n]=nval;		
						
					nval=_target.TERRAIN_WaterLevelSlopeDamp[n];
					checkChange(ref nval, EditorGUILayout.Slider("Water level slope damp", _target.TERRAIN_WaterLevelSlopeDamp[n], 0.1f, 2));
					_target.TERRAIN_WaterLevelSlopeDamp[n]=nval;		
						
					nval=_target.TERRAIN_WaterEdge[n];
					checkChange(ref nval, Mathf.Pow(2, EditorGUILayout.Slider("Water level sharpness", Mathf.Log(_target.TERRAIN_WaterEdge[n])/Mathf.Log(2)/2, 0, 1)*2));
					_target.TERRAIN_WaterEdge[n]=nval;		
						
					GUILayout.Space(6);
						
					nval=_target.TERRAIN_WaterOpacity[n];
					checkChange(ref nval, EditorGUILayout.Slider("Water opacity", _target.TERRAIN_WaterOpacity[n], 0f, 1f));
					_target.TERRAIN_WaterOpacity[n]=nval;		
						
					nval=_target.TERRAIN_WaterGloss[n];
					checkChange(ref nval, EditorGUILayout.Slider("Water gloss", _target.TERRAIN_WaterGloss[n], 0f, 6f));
					_target.TERRAIN_WaterGloss[n]=nval;		
						
					nval=_target.TERRAIN_Refraction[n];
					checkChange(ref nval, EditorGUILayout.Slider("Water refraction", _target.TERRAIN_Refraction[n], 0f, 0.04f));
					_target.TERRAIN_Refraction[n]=nval;		
						
					GUILayout.Space(6);
						
					nval=_target.TERRAIN_Flow[n];
					checkChange(ref nval, EditorGUILayout.Slider("Water flow", _target.TERRAIN_Flow[n], 0f, 1f));
					_target.TERRAIN_Flow[n]=nval;		
						
					GUILayout.Space(3);
					EditorGUILayout.HelpBox("Wet means layer surface covered by thin water layer, but above water level",MessageType.None,true);							
					nval=_target.TERRAIN_WetSpecularity[n];
					checkChange(ref nval, EditorGUILayout.Slider("Wet gloss", _target.TERRAIN_WetSpecularity[n], 0f, 6f));
					_target.TERRAIN_WetSpecularity[n]=nval;		
						
					nval=_target.TERRAIN_WetReflection[n];
					checkChange(ref nval, EditorGUILayout.Slider("Wet reflection", _target.TERRAIN_WetReflection[n]/2f, 0f, 1f)*2f);
					_target.TERRAIN_WetReflection[n]=nval;		
						
					nval=_target.TERRAIN_WetRefraction[n];
					checkChange(ref nval, EditorGUILayout.Slider("Wet refraction factor", _target.TERRAIN_WetRefraction[n], 0f, 1f));
					_target.TERRAIN_WetRefraction[n]=nval;		

					GUILayout.Space(6);
					string[] options=new string[_target.numLayers];
					options[0]="Choose layer to copy water params from";
					for(int k=0; k<_target.numLayers; k++) {
						if (k<=n) {
							if (k<_target.numLayers-1) options[k+1]="layer "+k;
						} else {
							options[k]="layer "+k;
						}
					}
					int idx=EditorGUILayout.Popup(0, options);
					if (idx>0) {
						if (idx-1<n) {
							idx--;
						}
						Undo.RegisterUndo((ReliefTerrain)target, "Undo relief terrain edit");
						_target.CopyWaterParams(idx, n);
					}
						
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndVertical();
						
					EditorGUILayout.BeginVertical("Box");
					EditorGUILayout.HelpBox("Reflection independent from water effect:\n0 - no reflection\n0.5 - value from detail texture A (specularity) channel\n1 - full reflection",MessageType.None,true);
					EditorGUILayout.BeginHorizontal();
					if (GUILayout.Button(new GUIContent(icoReflection, "Reflection settings"),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16))) {
						_target.submenu=ReliefTerrainMenuItems.GeneralSettings;
						_target.submenu_settings=ReliefTerrainSettingsItems.Reflections;
					}
					EditorGUI.BeginDisabledGroup( !(AddPass_flag ? REFLECTION_ENABLED_ADD : REFLECTION_ENABLED_FIRST) );
					nval=_target.TERRAIN_LayerReflection[n];
					checkChange(ref nval, EditorGUILayout.Slider("Layer reflection", _target.TERRAIN_LayerReflection[n]/2f, 0f, 1f)*2f);
					_target.TERRAIN_LayerReflection[n]=nval;							
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
						
					EditorGUILayout.Space();
				}
				EditorGUILayout.EndVertical();
					
				GUILayout.Space(8);							
				if (GUILayout.Button("Reset layer numeric params to default")) {
					Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
					_target.ReturnToDefaults("layer");
					EditorUtility.SetDirty(_targetRT);
					_target.Refresh();
				}	
					
				#endregion Detail maps unfold	- layers
			}
			
			
			#endregion Detail maps unfold
		}	
		
		//bool nshow_controlmaps=EditorGUILayout.Foldout(_target.show_controlmaps, "Control (alpha) maps");
		//if (nshow_controlmaps) {
		if (_target.show_controlmaps) {
			#region Control maps
			Color skin_color;
    		toolbarStrings = new string[3]{"Compose", "Acquire", "Control maps"};
			GUILayout.Space(6);
			EditorGUILayout.BeginHorizontal();
			GUILayout.FlexibleSpace();
			_target.submenu_control_textures=(ReliefTerrainControlTexturesItems )(GUILayout.Toolbar((int)_target.submenu_control_textures, toolbarStrings, EditorStyles.miniButton, GUILayout.MaxWidth(370)));
			GUILayout.FlexibleSpace();
			EditorGUILayout.EndHorizontal();
			
			switch(_target.submenu_control_textures) {
			case ReliefTerrainControlTexturesItems.Compose:
				#region Control maps - compose maps
				GUILayout.Space(10);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Compose splats", EditorStyles.boldLabel);
				GUI.color=skin_color;
				EditorGUILayout.HelpBox("Here you can manipulate alpha maps that control layers coverage,\n1. Source splat is coverage texture and you can choose its channel,\n2. Value taken from coverage texture (can be inverted) is multiplied by given factor,\n3. Result is normalized,\n4. Blank source splats are considered 1 (white),\n5. In case you unset \"active\", input value is taken from current control map.",MessageType.None, true);				
				EditorGUILayout.BeginHorizontal();
				EditorGUILayout.LabelField("Layer", EditorStyles.boldLabel, GUILayout.MaxWidth(100));
				EditorGUILayout.LabelField("Source splats", EditorStyles.boldLabel, GUILayout.MaxWidth(100));
				EditorGUILayout.EndHorizontal();		
	
				for(int i=0; i<_target.numLayers; i++) {
					int n=_targetRT.splat_layer_seq[i];
					Texture2D tex=_targetRT.source_controls[n];
					Texture2D ntex=tex;
					EditorGUILayout.BeginHorizontal();
#if !UNITY_3_5
						GUILayout.Label((Texture2D)AssetPreview.GetAssetPreview(_target.splats[n]), GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
#else
						GUILayout.Label((Texture2D)EditorUtility.GetAssetPreview(_target.splats[n]), GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
#endif						
						if (_targetRT.splat_layer_calc[n]) {
							if (_targetRT.source_controls[n]) {
								checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_targetRT.source_controls[n], typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
							} else {
								if (!blank_white_tex) {
									blank_white_tex=new Texture2D(4,4,TextureFormat.ARGB32,false);
									Color[] cols=new Color[16];
									for(int k=0; k<16; k++) cols[k]=Color.white;
									blank_white_tex.SetPixels(cols);
									blank_white_tex.Apply(false, true);
								}
								if (!blank_black_tex) {
									blank_black_tex=new Texture2D(4,4,TextureFormat.ARGB32,false);
									Color[] cols=new Color[16];
									for(int k=0; k<16; k++) cols[k]=Color.black;
									blank_black_tex.SetPixels(cols);
									blank_black_tex.Apply(false, true);
								}
								if (_targetRT.source_controls_invert[n]) {
									ntex=tex=blank_black_tex;
								} else {
									ntex=tex=blank_white_tex;
								}
								checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(tex, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
								if (ntex==null) {
									_targetRT.source_controls[n]=tex=null;
								}
							}
							if (_targetRT.source_controls[n]==blank_white_tex || ntex==blank_white_tex || _targetRT.source_controls[n]==blank_black_tex || ntex==blank_black_tex || ntex==null) _targetRT.source_controls[n]=ntex=tex=null;
							if (ntex!=tex) {
								int wdth=1024;
								if (_targetRT.controlA!=null) {
									wdth=_targetRT.controlA.width;
									for(int j=0; j<_targetRT.source_controls.Length; j++) {
										Color[] cols=new Color[wdth*wdth];
										bool cols_inited=false;
										if (_targetRT.source_controls[j]) {
											if (_targetRT.source_controls[j].width!=wdth) {
												if (!cols_inited) {
													cols_inited=true;
													for(int u=0; u<cols.Length; u++) cols[u]=Color.white;
												}
												_targetRT.source_controls[j]=new Texture2D(wdth,wdth);
												_targetRT.source_controls[j].SetPixels(cols);
												_targetRT.source_controls[j].Apply(true);
											}
										}
									}
								} else {
									for(int j=0; j<_targetRT.source_controls.Length; j++) {
										if (_targetRT.source_controls[j]) {
											wdth=_targetRT.source_controls[j].width;
											break;
										}
									}
								}
								if (ntex && ntex.width==wdth) {
									_targetRT.source_controls[n]=ntex;
									AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
									if (_importer) {
										TextureImporter tex_importer=(TextureImporter)_importer;
										if (!tex_importer.isReadable) {
											Debug.LogWarning("Source splat texture "+n+" ("+ntex.name+") has been reimported as readable.");
											tex_importer.isReadable=true;
											AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
										}
									}
									if ( _targetRT.source_controls_invert[n] ) {
										Color[] cols=_targetRT.source_controls[n].GetPixels();
										_target.InvertChannel(cols, -1);
										int w=_targetRT.source_controls[n].width;
										_targetRT.source_controls[n]=new Texture2D(w,w);
										_targetRT.source_controls[n].SetPixels(cols);
										_targetRT.source_controls[n].Apply();
									}									
								} else {
									if (_targetRT.controlA) {
										EditorUtility.DisplayDialog("Error", "Source control alpha maps should have "+wdth+" size.","OK");
									} else {
										///////////////////
										if (EditorUtility.DisplayDialog("Error", "Should I reset all source control alpha maps to "+ntex.width+" size?","Yes, please","No, thanks")) {
											wdth=ntex.width;
											Color[] cols=new Color[wdth*wdth];
											for(int u=0; u<cols.Length; u++) cols[u]=Color.white;
											for(int j=0; j<_targetRT.source_controls.Length; j++) {
												if (j!=n) {
													if (_targetRT.source_controls[j].width!=wdth) {
														_targetRT.source_controls[j]=new Texture2D(wdth,wdth);
														_targetRT.source_controls[j].SetPixels(cols);
														_targetRT.source_controls[j].Apply(true);
													}
												} else {
													_targetRT.source_controls[n]=ntex;
												}
											}
										}
										/////////////////										
									}
								}
							}
						} else {
							GUILayout.Label((Texture2D)null, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
						}
						EditorGUILayout.BeginVertical(); // layer props
						EditorGUILayout.BeginHorizontal();
						checkChange(ref _targetRT.splat_layer_calc[n], EditorGUILayout.Toggle(_targetRT.splat_layer_calc[n], GUILayout.MinWidth(10), GUILayout.MaxWidth(10)));
						EditorGUILayout.LabelField("active", GUILayout.MinWidth(40), GUILayout.MaxWidth(40));
						EditorGUILayout.EndHorizontal();
						if (_targetRT.splat_layer_calc[n]) {
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							checkChange(ref _targetRT.source_controls_channels[n], (ColorChannels)EditorGUILayout.EnumPopup(_targetRT.source_controls_channels[n]));
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("multiplier", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
							checkChange(ref _targetRT.splat_layer_boost[n], EditorGUILayout.FloatField(_targetRT.splat_layer_boost[n]));
							EditorGUILayout.EndHorizontal();
						
							EditorGUILayout.BeginHorizontal();
								EditorGUILayout.BeginHorizontal();
								EditorGUILayout.LabelField("masked", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
								checkChange(ref _targetRT.splat_layer_masked[n], EditorGUILayout.Toggle(_targetRT.splat_layer_masked[n], GUILayout.MinWidth(10), GUILayout.MaxWidth(10)));
//									if (_targetRT.splat_layer_masked[n] && !_targetRT.source_controls[n]) {
//										_targetRT.splat_layer_masked[n]=false;
//										EditorUtility.DisplayDialog("Error", "Blank input can not be masked.","OK");
//									}
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.BeginHorizontal();
								EditorGUILayout.LabelField("invert", GUILayout.MinWidth(40), GUILayout.MaxWidth(40));
								bool nval=_targetRT.source_controls_invert[n];
								checkChange(ref nval, EditorGUILayout.Toggle(_targetRT.source_controls_invert[n], GUILayout.MinWidth(10), GUILayout.MaxWidth(10)));
								if ( (_targetRT.source_controls_invert[n]!=nval)  && (_targetRT.source_controls[n])) {
									Color[] cols=_targetRT.source_controls[n].GetPixels();
									_target.InvertChannel(cols, -1);
									int w=_targetRT.source_controls[n].width;
									_targetRT.source_controls[n]=new Texture2D(w,w);
									_targetRT.source_controls[n].SetPixels(cols);
									_targetRT.source_controls[n].Apply();
								}
								_targetRT.source_controls_invert[n]=nval;								
//									if (_targetRT.source_controls_invert[n] && !_targetRT.source_controls[n]) {
//										_targetRT.source_controls_invert[n]=false;
//										EditorUtility.DisplayDialog("Error", "Blank input can not be inverted.","OK");
//									}
								EditorGUILayout.EndHorizontal();						
							EditorGUILayout.EndHorizontal();
						}
					
						EditorGUILayout.BeginHorizontal(); // move up/down
						if (GUILayout.Button("Move up")) {
							if (i>0) {
								int tmp=_targetRT.splat_layer_seq[i];
								_targetRT.splat_layer_seq[i]=_targetRT.splat_layer_seq[i-1];
								_targetRT.splat_layer_seq[i-1]=tmp;
							}
							//_targetRT.splat_layer_seq=new int[8]{0,1,2,3,4,5,6,7};
						}
						if (GUILayout.Button("Move down")) {
							if (i<_target.numLayers-1) {
								int tmp=_targetRT.splat_layer_seq[i];
								_targetRT.splat_layer_seq[i]=_targetRT.splat_layer_seq[i+1];
								_targetRT.splat_layer_seq[i+1]=tmp;
							}
						}
						EditorGUILayout.EndHorizontal(); // move up/down
						EditorGUILayout.EndVertical(); // layer props
					
					EditorGUILayout.EndHorizontal();
					// optional mask
					if (	_targetRT.splat_layer_masked[n] && _targetRT.splat_layer_calc[n]) {
						EditorGUILayout.BeginHorizontal();
						GUILayout.Label("Source splat\nmask >", GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
						tex=ntex=_targetRT.source_controls_mask[n];
						checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(tex, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						if (ntex!=tex) {
							if (ntex && ntex.width==_targetRT.controlA.width) {
								_targetRT.source_controls_mask[n]=ntex;
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Mask texture "+n+" ("+ntex.name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
									}
								}
								if ( _targetRT.source_controls_mask_invert[n] ) {
									Color[] cols=_targetRT.source_controls_mask[n].GetPixels();
									_target.InvertChannel(cols, -1);
									int w=_targetRT.source_controls_mask[n].width;
									_targetRT.source_controls_mask[n]=new Texture2D(w,w);
									_targetRT.source_controls_mask[n].SetPixels(cols);
									_targetRT.source_controls_mask[n].Apply();
								}									
							} else if (ntex) {
								EditorUtility.DisplayDialog("Error", "Mask texture should have "+_targetRT.controlA.width+" size.","OK");
							} else {
								_targetRT.source_controls_mask[n]=ntex; // null
								_targetRT.splat_layer_masked[n]=false;
							}
						}
						EditorGUILayout.BeginVertical(); // mask props
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
						checkChange(ref _targetRT.source_controls_mask_channels[n], (ColorChannels)EditorGUILayout.EnumPopup(_targetRT.source_controls_mask_channels[n]));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("invert", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
						bool nval=_targetRT.source_controls_mask_invert[n];
						checkChange(ref nval, EditorGUILayout.Toggle(_targetRT.source_controls_mask_invert[n]));
						if ( (_targetRT.source_controls_mask_invert[n]!=nval)  && (_targetRT.source_controls_mask[n])) {
							Color[] cols=_targetRT.source_controls_mask[n].GetPixels();
							_target.InvertChannel(cols, -1);
							int w=_targetRT.source_controls_mask[n].width;
							_targetRT.source_controls_mask[n]=new Texture2D(w,w);
							_targetRT.source_controls_mask[n].SetPixels(cols);
							_targetRT.source_controls_mask[n].Apply();
						}
						_targetRT.source_controls_mask_invert[n]=nval;									
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.EndVertical(); // mask props						
						
						EditorGUILayout.EndHorizontal();
					}
					
				}
				EditorGUILayout.BeginHorizontal();
				if (GUILayout.Button("Set all \"active\" flags")) {
					for(int j=0; j<_target.numLayers; j++) {
						_targetRT.splat_layer_calc[j]=true;
					}
				}				
				if (GUILayout.Button("Clear all \"active\" flags")) {
					for(int j=0; j<_target.numLayers; j++) {
						_targetRT.splat_layer_calc[j]=false;
					}
				}
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.HelpBox("In layered mode highest (bottom) layer \"wins\". In unlayered mode order doesn't matter.",MessageType.None, true);
				EditorGUILayout.BeginHorizontal();
				EditorGUILayout.LabelField("Layered mode", EditorStyles.boldLabel, GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
				checkChange(ref _targetRT.splat_layer_ordered_mode, EditorGUILayout.Toggle(_targetRT.splat_layer_ordered_mode));
				EditorGUILayout.EndHorizontal();
				if (GUILayout.Button("Render Control maps from source splats")) {
					if (EditorUtility.DisplayDialog("Warning", "This will overwrite current splat controlmaps\n(you may backup them using save feature in \"Splatmaps...\" unfold below). Are you sure ?","Yes","Cancel")) {
						if (terrainComp) {
							_targetRT.RecalcControlMaps();
						} else {
							_targetRT.RecalcControlMapsForMesh();
						}
					}
				}
				
				EditorGUILayout.EndVertical();
				#endregion Control maps - compose maps
				break;
			case ReliefTerrainControlTexturesItems.Acquire:
				#region Control maps - acquire mask textures
				GUILayout.Space(10);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Acquire mask textures", EditorStyles.boldLabel);
				GUI.color=skin_color;
				if (terrainComp) {
					EditorGUILayout.HelpBox("Here you can get coverage textures taken from height, steepness or normal direction (relative to reference object's Z axis and Y component of compared direction vectors may be optionally skipped, if not - resultant texture might be considered lightmap when using light as ref direction object).\n\nProduced textures are esp. useful for users that don't use external terrain tools, but only heightmap as base for their work. Textures taken here may serve as splat sources (\"Compose splats\" tab above).\n\nRealistic heightmaps themselves might be acquired from sattelite data - one may google for that, you can also consider making heightmap from scratch using photoshop (use perlin noise for example).",MessageType.None, true);
					if (GUILayout.Button("Save steepness")) {
						Texture2D tex=_targetRT.GetSteepnessHeightDirectionTexture(0);
						if (tex) {
							SaveTexture(ref tex, ref _target.save_path_terrain_steepness, "terrain_steepnessMap.png", 0, TextureImporterFormat.AutomaticCompressed, false, false);
						} else {
							EditorUtility.DisplayDialog("?", "Can't get steepness texture...","OK");
						}
					}
					if (GUILayout.Button("Save height")) {
						Texture2D tex=_targetRT.GetSteepnessHeightDirectionTexture(1);
						if (tex) {
							SaveTexture(ref tex, ref _target.save_path_terrain_height, "terrain_heightMap.png", 0, TextureImporterFormat.AutomaticCompressed, false, false);
						} else {
							EditorUtility.DisplayDialog("?", "Can't get height texture...","OK");
						}
					}
	
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Direction reference", GUILayout.MaxWidth(116));
					checkChange(ref _target.direction_object, (GameObject)EditorGUILayout.ObjectField(_target.direction_object, typeof(GameObject), true));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Skip y component", GUILayout.MaxWidth(116));
					checkChange(ref _target.flat_dir_ref, EditorGUILayout.Toggle(_target.flat_dir_ref));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Flip direction", GUILayout.MaxWidth(116));
					checkChange(ref _target.flip_dir_ref, EditorGUILayout.Toggle(_target.flip_dir_ref));
					EditorGUILayout.EndHorizontal();
					if (GUILayout.Button("Save direction")) {
						Texture2D tex=_targetRT.GetSteepnessHeightDirectionTexture(2,_target.direction_object);
						if (tex) {
							SaveTexture(ref tex, ref _target.save_path_terrain_direction, "terrain_directionMap.png", 0, TextureImporterFormat.AutomaticCompressed, false, false);
						} else {
							EditorUtility.DisplayDialog("?", "Can't get direction texture...","OK");
						}							
					}
				} else {
					EditorGUILayout.HelpBox("Option available for terrains only.",MessageType.Warning, true);
				}
				
				EditorGUILayout.Space();
				EditorGUILayout.EndVertical();
				#endregion Control maps - acquire mask textures					
				break;
			case ReliefTerrainControlTexturesItems.Controlmaps:
				#region Control maps - splats					
				GUILayout.Space(10);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Splatmaps (control maps)", EditorStyles.boldLabel);
				GUI.color=skin_color;
				EditorGUILayout.HelpBox("Here you can see control maps as they are stored and used by Unity terrain system. For terrains you can backup them using save feature. You can drag&drop (select) such splatmaps (ARGB32) to override existing one(s) - for example when you need to restore them from backup or need to apply your own on terrain.",MessageType.None, true);
				if (terrainComp) {
					if (GUILayout.Button("Refresh Controlmap(s) shown from TerrainData")) {
						_targetRT.GetControlMaps();
					}
				}
				EditorGUILayout.BeginHorizontal();
				EditorGUILayout.LabelField("Splat 0-3", GUILayout.MaxWidth(65));
				if (terrainComp!=null) {
					bool tmp_dirtyFlag=dirtyFlag;
					checkChange(ref _targetRT.controlA, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlA, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					if (dirtyFlag && !tmp_dirtyFlag) {
						AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.controlA));
						if (_importer) {
							TextureImporter tex_importer=(TextureImporter)_importer;
							if (!tex_importer.isReadable) {
								Debug.LogWarning("Control texture 0 ("+_targetRT.controlA.name+") has been reimported as readable.");
								tex_importer.isReadable=true;
								AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.controlA),  ImportAssetOptions.ForceUpdate);
							}
						}					
						_targetRT.SetCustomControlMaps();
					}
				} else {
					checkChange(ref _targetRT.controlA, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlA, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
				}
				if (_target.numLayers>4) {
					EditorGUILayout.LabelField("Splat 4-7", GUILayout.MaxWidth(65));
					if (terrainComp!=null) {
						bool tmp_dirtyFlag=dirtyFlag;
						checkChange(ref _targetRT.controlB, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlB, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						if (dirtyFlag && !tmp_dirtyFlag) {
							AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.controlB));
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Control texture 1 ("+_targetRT.controlB.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.controlB),  ImportAssetOptions.ForceUpdate);
								}
							}					
							_targetRT.SetCustomControlMaps();
						}
					} else {
						checkChange(ref _targetRT.controlB, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlB, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					}
				}
				EditorGUILayout.EndHorizontal();
				
				EditorGUILayout.BeginHorizontal();
				if (GUILayout.Button("Save to file", GUILayout.MinWidth(170), GUILayout.MaxWidth(170))) {
					Texture2D tex=_targetRT.controlA;
					if (tex) {
						SaveTexture(ref tex, ref _targetRT.save_path_controlA, "terrain_splatMapA.png", 0, TextureImporterFormat.ARGB32, true, false, true);
					} else {
						EditorUtility.DisplayDialog("?", "Can't get height texture...","OK");
					}
				}								
				if (_target.numLayers>4) {
					if (GUILayout.Button("Save to file", GUILayout.MinWidth(170), GUILayout.MaxWidth(170))) {
						Texture2D tex=_targetRT.controlB;
						if (tex) {
							SaveTexture(ref tex, ref _targetRT.save_path_controlB, "terrain_splatMapB.png", 0, TextureImporterFormat.ARGB32, true, false, true);
						} else {
							EditorUtility.DisplayDialog("?", "Can't get height texture...","OK");
						}
					}								
				}
				EditorGUILayout.EndHorizontal();
				
				if (_target.numLayers>8) {
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Splat 8-11", GUILayout.MaxWidth(65));
					if (terrainComp!=null) {
						bool tmp_dirtyFlag=dirtyFlag;
						checkChange(ref _targetRT.controlC, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlC, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
						if (dirtyFlag && !tmp_dirtyFlag) {
							AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_targetRT.controlC));
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Control texture 2 ("+_targetRT.controlC.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_targetRT.controlC),  ImportAssetOptions.ForceUpdate);
								}
							}					
							_targetRT.SetCustomControlMaps();
						}
					} else {
						checkChange(ref _targetRT.controlC, (Texture2D)EditorGUILayout.ObjectField( _targetRT.controlC, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					}
					EditorGUILayout.EndHorizontal();
				}

				if (_target.numLayers>8) {
					if (GUILayout.Button("Save to file", GUILayout.MinWidth(170), GUILayout.MaxWidth(170))) {
						Texture2D tex=_targetRT.controlC;
						if (tex) {
							SaveTexture(ref tex, ref _targetRT.save_path_controlC, "terrain_splatMapC.png", 0, TextureImporterFormat.ARGB32, true, false, true);
						} else {
							EditorUtility.DisplayDialog("?", "Can't get height texture...","OK");
						}
					}								
				}
				#endregion Control maps - splats					
				EditorGUILayout.EndVertical();
				break;
			}		
			
			#endregion Control maps
		}

		//_target.show_heightmaps=EditorGUILayout.Foldout(_target.show_heightmaps, "Height maps (combined)");
		if (_target.show_derivedmaps) {
			#region Derived textures
			Color skin_color;
    		toolbarStrings = new string[4]{"Atlasing", "Height maps", "Normal maps", "Special"};
			GUILayout.Space(6);
			EditorGUILayout.BeginHorizontal();
			GUILayout.FlexibleSpace();
			_target.submenu_derived_textures=(ReliefTerrainDerivedTexturesItems)(GUILayout.Toolbar((int)_target.submenu_derived_textures, toolbarStrings, EditorStyles.miniButton, GUILayout.MaxWidth(370)));
			GUILayout.FlexibleSpace();
			EditorGUILayout.EndHorizontal();
			GUILayout.Space(6);
			EditorGUILayout.HelpBox("Combined texures are what actually feeds shader. They're intended to be reused on multiple terrain tiles. You can also reuse them across scenes.",MessageType.Warning, true);
			switch(_target.submenu_derived_textures) {
			case ReliefTerrainDerivedTexturesItems.Atlasing:
				#region Derived textures - Atlasing features
				GUILayout.Space(10);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Color atlases (necessary in 8 layers in one pass)", EditorStyles.boldLabel);
				GUI.color=skin_color;
				
				if (!_target.splat_atlases[0] && (_target.numLayers>4) && (!_4LAYERS_SHADER_USED)) {
					EditorGUILayout.HelpBox("Terrain detail textures have to be atlased for shader.",MessageType.Error, true);
				}
				EditorGUI.BeginDisabledGroup( _4LAYERS_SHADER_USED );
				if (GUILayout.Button("Prepare atlases from detail textures (may take a while)")) {
					PrepareAtlases( (_target.numLayers>4) ? 3:1);
					_target.Refresh();
				}
				EditorGUI.EndDisabledGroup();
					
				EditorGUILayout.BeginHorizontal();
					
					if (_4LAYERS_SHADER_USED) {
							_target.splat_atlases[0]=null;
							_target.splat_atlases[1]=null;
					}
					if (_target.numLayers>0) {
					EditorGUI.BeginDisabledGroup( _4LAYERS_SHADER_USED );
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Layers 0-3", GUILayout.Width(100));
					checkChange(ref _target.splat_atlases[0], (Texture2D)EditorGUILayout.ObjectField( _target.splat_atlases[0], typeof(Texture2D), false, GUILayout.Height(100), GUILayout.Width(100)));
					if (SaveTexture(ref _target.splat_atlases[0], ref _target.save_path_atlasA, "atlas_texture_layers_0_to_3.png", 100, TextureImporterFormat.AutomaticCompressed, true)) {
						string path=AssetDatabase.GetAssetPath(_target.splat_atlases[0]);
						TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
						textureImporter.wrapMode = TextureWrapMode.Clamp;
						textureImporter.filterMode = FilterMode.Trilinear;
						AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
					}
					EditorGUILayout.EndVertical();
					EditorGUI.EndDisabledGroup();
					}

					if (_target.numLayers>4) {
					EditorGUI.BeginDisabledGroup( _4LAYERS_SHADER_USED );
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Layers 4-7", GUILayout.Width(100));
					checkChange(ref _target.splat_atlases[1], (Texture2D)EditorGUILayout.ObjectField( _target.splat_atlases[1], typeof(Texture2D), false, GUILayout.Height(100), GUILayout.Width(100)));
					if (SaveTexture(ref _target.splat_atlases[1], ref _target.save_path_atlasB, "atlas_texture_layers_4_to_7.png", 100, TextureImporterFormat.AutomaticCompressed, true)) {
						_target.splat_atlases[1].wrapMode=TextureWrapMode.Clamp;
						_target.splat_atlases[1].filterMode=FilterMode.Trilinear;
					}
					EditorGUILayout.EndVertical();
					EditorGUI.EndDisabledGroup();
					}
					
				EditorGUILayout.EndHorizontal();									
				
				EditorGUILayout.EndVertical();
				#endregion Derived textures - Atlasing features		
				break;
			case ReliefTerrainDerivedTexturesItems.Heightmaps:
				#region Derived textures - Heightmaps
				GUILayout.Space(10);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Combined heightmaps", EditorStyles.boldLabel);
				GUI.color=skin_color;
			
				EditorGUILayout.HelpBox("If you specified heightmaps for your layers you don't have to do anything while editing (heightmaps are refreshed as you modify any of separate heightmap). However, you might need to specify combined heightmaps by hand, so you can do it here (don't touch particular heightmaps in a layer properties then).",MessageType.None, true);
				EditorGUILayout.HelpBox("Every channel of height textures below stores heightmap for consecutive detail map (splats 0-3 -> heightmap channels RGBA). To generate such channel combined heightmaps you can also use attached tool (Window / Relief Tools / 4 to 1 texture channels mixer).",MessageType.None, true);
					
				EditorGUILayout.BeginHorizontal();
					
					if (_target.numLayers>0) {
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Heights 0-3", GUILayout.Width(80));
					checkChange(ref _target.HeightMap, (Texture2D)EditorGUILayout.ObjectField( _target.HeightMap, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.HeightMap, ref _target.save_path_HeightMap, "heightmap_layers_0_to_3.png", 80, TextureImporterFormat.AutomaticCompressed, true,true,true);
					EditorGUILayout.EndVertical();
					}

					if (_target.numLayers>4) {
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Heights 4-7", GUILayout.Width(80));
					checkChange(ref _target.HeightMap2, (Texture2D)EditorGUILayout.ObjectField( _target.HeightMap2, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.HeightMap2, ref _target.save_path_HeightMap2, "heightmap_layers_4_to_7.png", 80, TextureImporterFormat.AutomaticCompressed, true,true,true);
					EditorGUILayout.EndVertical();
					}
					
					if (_target.numLayers>8) {
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Heights 8-12", GUILayout.Width(80));
					checkChange(ref _target.HeightMap3, (Texture2D)EditorGUILayout.ObjectField( _target.HeightMap3, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.HeightMap3, ref _target.save_path_HeightMap3, "heightmap_layers_8_to_11.png", 80, TextureImporterFormat.AutomaticCompressed, true,true,true);
					EditorGUILayout.EndVertical();
					}
					
				EditorGUILayout.EndHorizontal();						
				
				EditorGUILayout.EndVertical();
				#endregion Derived textures - Heightmaps
				break;
			case ReliefTerrainDerivedTexturesItems.Bumpmaps:
				#region Derived textures - Bumpmaps
				GUILayout.Space(10);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Combined bumpmaps", EditorStyles.boldLabel);
				GUI.color=skin_color;
			
				EditorGUILayout.HelpBox("Each layer pair share the same normal texture (RG + BA).They're automatically composed/refreshed when you change bump map in a layer. However, you might need to specify combined bumpmaps by hand, so you can do it here (don't touch particular bumpmaps in a layer properties then).",MessageType.None, true);
					
				EditorGUILayout.BeginHorizontal();
					if (_target.numLayers>0) {
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Bumps 0+1", GUILayout.Width(80));
					checkChange(ref _target.Bump01, (Texture2D)EditorGUILayout.ObjectField( _target.Bump01, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.Bump01, ref _target.save_path_Bump01, "bumpmap_layers01.png", 80, TextureImporterFormat.ARGB32, true,true,true);
					EditorGUILayout.EndVertical();
					}

					if (_target.numLayers>2) {
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Bumps 2+3", GUILayout.Width(80));
					checkChange(ref _target.Bump23, (Texture2D)EditorGUILayout.ObjectField( _target.Bump23, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.Bump23, ref _target.save_path_Bump23, "bumpmap_layers23.png", 80, TextureImporterFormat.ARGB32, true,true,true);
					EditorGUILayout.EndVertical();
					}
					
					if (_target.numLayers>4) {
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Bumps 4+5", GUILayout.Width(80));
					checkChange(ref _target.Bump45, (Texture2D)EditorGUILayout.ObjectField( _target.Bump45, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.Bump45, ref _target.save_path_Bump45, "bumpmap_layers45.png", 80, TextureImporterFormat.ARGB32, true,true,true);
					EditorGUILayout.EndVertical();
					}
					
				EditorGUILayout.EndHorizontal();
				GUILayout.Space(10);
					
				if (_target.numLayers>6) {
				EditorGUILayout.BeginHorizontal();
					if (_target.numLayers>6) {							
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Bumps 6+7", GUILayout.Width(80));
					checkChange(ref _target.Bump67, (Texture2D)EditorGUILayout.ObjectField( _target.Bump67, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.Bump67, ref _target.save_path_Bump67, "bumpmap_layers67.png", 80, TextureImporterFormat.ARGB32, true,true,true);
					EditorGUILayout.EndVertical();
					}
					
					if (_target.numLayers>8) {
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Bumps 8+9", GUILayout.Width(80));
					checkChange(ref _target.Bump89, (Texture2D)EditorGUILayout.ObjectField( _target.Bump89, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.Bump89, ref _target.save_path_Bump89, "bumpmap_layers89.png", 80, TextureImporterFormat.ARGB32, true,true,true);
					EditorGUILayout.EndVertical();
					}
					
					if (_target.numLayers>10) {
					EditorGUILayout.BeginVertical();
					EditorGUILayout.LabelField("Bumps 10+11", GUILayout.Width(80));
					checkChange(ref _target.BumpAB, (Texture2D)EditorGUILayout.ObjectField( _target.BumpAB, typeof(Texture2D), false, GUILayout.Height(80), GUILayout.Width(80)));
					SaveTexture(ref _target.BumpAB, ref _target.save_path_BumpAB, "bumpmap_layersAB.png", 80, TextureImporterFormat.ARGB32, true,true,true);
					EditorGUILayout.EndVertical();
					}
						
				EditorGUILayout.EndHorizontal();
				GUILayout.Space(10);
				}
				
				EditorGUILayout.EndVertical();
				#endregion Derived textures - Bumpmaps
				break;						
			case ReliefTerrainDerivedTexturesItems.Globalnormal:
				#region Derived textures - Global normal
				GUILayout.Space(10);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Perlin normal + superdetail / water&reflection", EditorStyles.boldLabel);
				GUI.color=skin_color;
			
				EditorGUILayout.HelpBox("Texture below use perlin normal map specified on channels RG.\n\nChannels BA are used for superdetail additional channels or (mutually exclusive) wet mask (B) and reflection map (A).",MessageType.None, true);
					
				//EditorGUILayout.BeginVertical();
				EditorGUILayout.LabelField("Texture", GUILayout.Width(80));
				bool sync_tex=false;
				if (checkChange(ref _targetRT.BumpGlobalCombined, (Texture2D)EditorGUILayout.ObjectField( _targetRT.BumpGlobalCombined, typeof(Texture2D), false, GUILayout.Height(100), GUILayout.Width(100)))) sync_tex=true;
				if (SaveTexture(ref _targetRT.BumpGlobalCombined, ref _targetRT.save_path_BumpGlobalCombined, "perlin_normal_aux.png", 100, TextureImporterFormat.AutomaticCompressed, true,true,true)) sync_tex=true;
				if (sync_tex) {
					RTP_LODmanager manager=_target.Get_RTP_LODmanagerScript();
					if (manager && !manager.RTP_WETNESS_FIRST && !manager.RTP_WETNESS_ADD) {
						ReliefTerrain[] objs=(ReliefTerrain[])GameObject.FindObjectsOfType(typeof(ReliefTerrain));
						for(int i=0; i<objs.Length; i++) {
							objs[i].BumpGlobalCombined=_targetRT.BumpGlobalCombined;
							objs[i].globalCombinedModifed_flag=false;
						}
					}
					_targetRT.globalCombinedModifed_flag=false;
				}
				//EditorGUILayout.EndVertical();
		
				EditorGUILayout.EndVertical();
				#endregion Derived textures - Global normal
				break;						
			} // derived textures submenu switch
			#endregion Derived textures
		}
		
		if (_target.show_settings) {
			#region ALLSettings
    		GUIContent[] toolbarIcons1 = new GUIContent[5]{ new GUIContent("Main", icoLayersSmall ), new GUIContent("UV blend", icoUVBlend), new GUIContent("Global\nmaps", icoGlobalcolor), new GUIContent("Perlin\nnormal", icoPerlinNormal), new GUIContent("S. detail", icoSuperdetail) };
			GUIContent[] toolbarIcons2 = new GUIContent[5]{ new GUIContent("Parallax", icoPOM ), new GUIContent("Vertical\ntexture", icoVerticalTexture), new GUIContent("Snow", icoSnow), new GUIContent("Water &\ncaustic", icoWater), new GUIContent("Reflection", icoReflection) };
			ReliefTerrainSettingsItems prev_submenu_settings=_target.submenu_settings;
			GUILayout.Space(10);
			EditorGUILayout.BeginHorizontal();
			GUILayout.FlexibleSpace();
			_target.submenu_settings=(ReliefTerrainSettingsItems)(GUILayout.Toolbar((int)_target.submenu_settings, toolbarIcons1, EditorStyles.miniButton, GUILayout.MaxWidth(370)));
			GUILayout.FlexibleSpace();
			EditorGUILayout.EndHorizontal();
			GUILayout.Space(5);
			EditorGUILayout.BeginHorizontal();
			GUILayout.FlexibleSpace();
			_target.submenu_settings=(ReliefTerrainSettingsItems)(GUILayout.Toolbar((int)_target.submenu_settings-5, toolbarIcons2, EditorStyles.miniButton, GUILayout.MaxWidth(370))+5);
			GUILayout.FlexibleSpace();
			EditorGUILayout.EndHorizontal();
			GUILayout.Space(10);
			
			if (prev_submenu_settings!=_target.submenu_settings && _target.paint_flag) {
				_target.paint_flag=false;
				Tools.current=prev_tool;
				SceneView.onSceneGUIDelegate -= ReliefTerrain._SceneGUI;
				EditorUtility.SetDirty(target);
			}
			
			Color skin_color;
			switch(_target.submenu_settings) {
			case ReliefTerrainSettingsItems.MainSettings:
				#region Settings	 - main settings

				GUILayout.Space(6);
				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
						
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoLayers),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Main settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;
				EditorGUILayout.HelpBox("For performance reasons shader uses the same tiling for every detail map.",MessageType.None, true);
				EditorGUILayout.BeginHorizontal();
					checkChange(ref _target.ReliefTransform.x, _target.terrainTileSizeX/EditorGUILayout.FloatField("Tile Size X [m] ("+(Mathf.Round(_target.ReliefTransform.x*100)/100)+")", _target.terrainTileSizeX/_target.ReliefTransform.x));
					if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
						float ratio=_target.ReliefTransform.x/_target.ReliefTransform.y;
						_target.ReliefTransform.x=Mathf.Round(_target.ReliefTransform.x);
						_target.ReliefTransform.y=_target.ReliefTransform.x/ratio;
						_target.ReliefTransform.y=Mathf.Round(_target.ReliefTransform.y);
						EditorUtility.SetDirty(_targetRT);
					}
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.BeginHorizontal();					
					checkChange(ref _target.ReliefTransform.y, _target.terrainTileSizeZ/EditorGUILayout.FloatField("Tile Size Y [m] ("+(Mathf.Round(_target.ReliefTransform.y*100)/100)+")", _target.terrainTileSizeZ/_target.ReliefTransform.y));
					if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
						float ratio=_target.ReliefTransform.x/_target.ReliefTransform.y;
						_target.ReliefTransform.y=Mathf.Round(_target.ReliefTransform.y);
						_target.ReliefTransform.x=_target.ReliefTransform.y*ratio;
						_target.ReliefTransform.x=Mathf.Round(_target.ReliefTransform.x);
						EditorUtility.SetDirty(_targetRT);
					}
				EditorGUILayout.EndHorizontal();
				float tile_sizex=_target.terrainTileSizeX/_target.ReliefTransform.x;
				float tile_sizey=_target.terrainTileSizeZ/_target.ReliefTransform.y;
				checkChange(ref _target.ReliefTransform.z, EditorGUILayout.FloatField("Tile Offset X [m]", _target.ReliefTransform.z*tile_sizex)/tile_sizex);
				checkChange(ref _target.ReliefTransform.w, EditorGUILayout.FloatField("Tile Offset Y [m]", _target.ReliefTransform.w*tile_sizey)/tile_sizey);
				
				EditorGUILayout.Space();	
				
				EditorGUILayout.LabelField("Near distance values");
				EditorGUILayout.BeginHorizontal();
				EditorGUILayout.LabelField("", GUILayout.MaxWidth(10));
				EditorGUILayout.BeginVertical();
				#if !UNITY_3_5
				float prev_distance_start=_target.distance_start;
				float prev_distance_transition=_target.distance_transition;
				#endif
				checkChange(ref _target.distance_start, EditorGUILayout.Slider("Distance start", _target.distance_start, 0, 20));
				if (_target.distance_start_bumpglobal<_target.distance_start) _target.distance_start_bumpglobal=_target.distance_start;
				checkChange(ref _target.distance_transition, EditorGUILayout.Slider("Fade length", _target.distance_transition, 0, 50));
				#if !UNITY_3_5
					if (_target.useTerrainMaterial) {
						if (prev_distance_start!=_target.distance_start || prev_distance_transition!=_target.distance_transition) {
							Terrain[] terrainComps=(Terrain[])GameObject.FindObjectsOfType(typeof(Terrain));
							for(int ter=0; ter<terrainComps.Length; ter++) {
								if (_target.super_simple_active) {
									terrainComps[ter].basemapDistance=_target.distance_start_bumpglobal+_target.distance_transition_bumpglobal;
								} else {
									terrainComps[ter].basemapDistance=_target.distance_start+_target.distance_transition;
								}
							}
						}
					}
				#endif

				EditorGUILayout.EndVertical();
				EditorGUILayout.EndHorizontal();
				
				EditorGUILayout.Space();	
				EditorGUILayout.HelpBox("Note that some texture lookups are MIP bias independent (use regular tex2D call)",MessageType.None, true);
				checkChange(ref _target.RTP_MIP_BIAS, EditorGUILayout.Slider("MIP level bias", _target.RTP_MIP_BIAS, -0.75f, 0.75f));
				EditorGUILayout.EndVertical();
					
				EditorGUILayout.Space();	
				
				#if !UNITY_3_5
					bool reflexDisabled = Camera.main.actualRenderingPath==RenderingPath.DeferredLighting || (Camera.main.actualRenderingPath==RenderingPath.UsePlayerSettings && PlayerSettings.renderingPath==RenderingPath.DeferredLighting);
					if (!reflexDisabled) {
						EditorGUILayout.HelpBox("In deferred rendering reflex lighting settings below are unavailable.",MessageType.Info, true);
					}
				#else
					bool reflexDisabled = false;
					EditorGUILayout.HelpBox("In deferred rendering reflex lighting settings below are unavailable.",MessageType.Info, true);
				#endif
				GUI.color=new Color(1,1,0.5f,1);						
				EditorGUILayout.LabelField("Shading color adjustements", EditorStyles.boldLabel);
				GUI.color=skin_color;
				EditorGUILayout.BeginVertical("Box");
				checkChange(ref _target._SpecColor, EditorGUILayout.ColorField("Specular Color", _target._SpecColor));
				checkChange(ref _target.rtp_customAmbientCorrection	, EditorGUILayout.ColorField("Ambient correction", _target.rtp_customAmbientCorrection));
				EditorGUI.BeginDisabledGroup(reflexDisabled);
				checkChange(ref _target.RTP_LightDefVector.x, EditorGUILayout.Slider("Negative light power", _target.RTP_LightDefVector.x,0,0.6f));
				EditorGUI.EndDisabledGroup();
				EditorGUILayout.EndVertical();
					
				EditorGUILayout.Space();	
				GUI.color=new Color(1,1,0.5f,1);						
				EditorGUILayout.LabelField("Complementary ambience lighting", EditorStyles.boldLabel);
				GUI.color=skin_color;
				EditorGUILayout.BeginVertical("Box");
					
				EditorGUI.BeginDisabledGroup(reflexDisabled);
				checkChange(ref _target.RTP_LightDefVector.y, EditorGUILayout.Slider("Reflex diffuse softness", _target.RTP_LightDefVector.y,0,0.7f));
				checkChange(ref _target.RTP_ReflexLightDiffuseColor, EditorGUILayout.ColorField("Reflex light diffuse", _target.RTP_ReflexLightDiffuseColor));
				checkChange(ref _target.RTP_ReflexLightDiffuseColor.a, EditorGUILayout.Slider("Diffuse strength", _target.RTP_ReflexLightDiffuseColor.a,0,1));
				EditorGUILayout.Space();	
				//checkChange(ref _target.RTP_LightDefVector.z, EditorGUILayout.Slider("Reflex Specular Softness", _target.RTP_LightDefVector.z,0,1));
				checkChange(ref _target.RTP_LightDefVector.w, EditorGUILayout.Slider("Reflex specularity", _target.RTP_LightDefVector.w,2,40));
				checkChange(ref _target.RTP_ReflexLightSpecColor, EditorGUILayout.ColorField("Reflex light specular", _target.RTP_ReflexLightSpecColor));
				checkChange(ref _target.RTP_ReflexLightSpecColor.a, EditorGUILayout.Slider("Specular strength", _target.RTP_ReflexLightSpecColor.a,0,1));
				EditorGUILayout.EndVertical();
				EditorGUI.EndDisabledGroup();
					
				if (terrainComp) {
					if ((terrainComp.lightmapIndex!=255) && (terrainComp.lightmapIndex!=-1) && LightmapSettings.lightmapsMode!=LightmapsMode.Directional) {
						EditorGUILayout.Space();	
						EditorGUILayout.BeginVertical("Box");
						EditorGUILayout.HelpBox("Helpful when lightmapping in single mode. Shader can mimic diffuse lighting with normal maps used. In dual lightmap mode (deferred) lower this value to avoid overbright at close distance (you might need put higher Perlin normal strength to compensate it at far distance). ",MessageType.None, true);
						checkChange(ref _target.LightmapShading, EditorGUILayout.Slider("Shading strength for lightmaps", _target.LightmapShading, 0, 2));
						EditorGUILayout.EndVertical();
					}
				} else {
					if ((_targetRT.renderer.lightmapIndex!=255) && (_targetRT.renderer.lightmapIndex!=-1) && LightmapSettings.lightmapsMode!=LightmapsMode.Directional) {
						EditorGUILayout.Space();	
						EditorGUILayout.BeginVertical("Box");
						EditorGUILayout.HelpBox("Helpful when lightmapping in single mode. Shader can mimic diffuse lighting with normal maps used. In dual lightmap mode (deferred) lower this value to avoid overbright at close distance (you might need put higher Perlin normal strength to compensate it at far distance). ",MessageType.None, true);
						checkChange(ref _target.LightmapShading, EditorGUILayout.Slider("Shading strength for lightmaps", _target.LightmapShading, 0, 2));
						EditorGUILayout.EndVertical();
					}
				}
					
				EditorGUILayout.Space();	
				GUI.color=new Color(1,1,0.5f,1);						
				EditorGUILayout.LabelField("Heightblend AO", EditorStyles.boldLabel);
				GUI.color=skin_color;
				EditorGUILayout.BeginVertical("Box");
				checkChange(ref _target.RTP_AOsharpness, EditorGUILayout.Slider("Fake AO 2 HB sharpness", _target.RTP_AOsharpness, 0,10));
				checkChange(ref _target.RTP_AOamp, EditorGUILayout.Slider("Fake AO 2 HB value", _target.RTP_AOamp, 0,2));
				EditorGUILayout.EndVertical();
					
				// presets
				EditorGUILayout.Space();	
				GUI.color=new Color(1,1,0.5f,1);						
				EditorGUILayout.LabelField("Presets", EditorStyles.boldLabel);
				GUI.color=skin_color;					
				EditorGUILayout.BeginVertical("Box");
				EditorGUILayout.HelpBox("Here you can save / restore object state in preset. You can also use use function InterpolatePresets(PresetID1, PresetID2, float t) via script to blend between numeric settings of 2 presets.",MessageType.Info, true);
				if (_targetRT.presetHolders!=null) {
					for(int k=0; k<_targetRT.presetHolders.Length; k++) {
						EditorGUILayout.BeginHorizontal();
						ReliefTerrainPresetHolder[] holders=null;
						if (GUILayout.Button("restore", GUILayout.Width(60))) {
							if (EditorUtility.DisplayDialog("Warning", "Restore to preset "+_targetRT.presetHolders[k].PresetName+" state ?","Yes","Cancel")) {
								Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
								_target.RestorePreset(_targetRT.presetHolders[k]);
								_targetRT.RefreshTextures();				
								_target.Refresh();									
								EditorUtility.SetDirty(_targetRT);
							}
						}
						if (GUILayout.Button("del", GUILayout.Width(35))) {
							if (EditorUtility.DisplayDialog("Warning", "Remove preset "+_targetRT.presetHolders[k].PresetName+" ?","Yes","Cancel")) {
								Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
								holders=new ReliefTerrainPresetHolder[_targetRT.presetHolders.Length-1];
								int l=0;
								for(int r=0; r<_targetRT.presetHolders.Length; r++) {
									if (r!=k) {
										holders[l++]=_targetRT.presetHolders[r];
									}
								}
							}
						}
						EditorGUILayout.LabelField("Preset " +k+": ", GUILayout.Width(60));
						EditorGUILayout.LabelField(_targetRT.presetHolders[k].PresetName, EditorStyles.boldLabel);
						
						if (holders!=null) {
							_targetRT.presetHolders=holders;
						}
						EditorGUILayout.EndHorizontal();
					}
				}
				EditorGUI.BeginDisabledGroup(_targetRT.presetHolders!=null && _targetRT.presetHolders.Length==8);
				EditorGUILayout.BeginHorizontal();
				EditorGUILayout.LabelField("New preset name: ", GUILayout.Width(120));	
				_target.newPresetName=EditorGUILayout.TextField(_target.newPresetName);
				EditorGUILayout.EndHorizontal();
				if (GUILayout.Button("Add new preset")) {
						Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
						ReliefTerrainPresetHolder[] holders;
						int k=0;
						if (_targetRT.presetHolders!=null) {
							holders=new ReliefTerrainPresetHolder[_targetRT.presetHolders.Length+1];
							for(; k<_targetRT.presetHolders.Length; k++) {
								holders[k]=_targetRT.presetHolders[k];
							}
						} else {
							holders=new ReliefTerrainPresetHolder[1];
						}
						holders[k]=new ReliefTerrainPresetHolder(_target.newPresetName);
						_target.SavePreset(ref holders[k]);
						_targetRT.presetHolders=holders;
				}
				EditorGUI.EndDisabledGroup();
				EditorGUILayout.EndVertical();						
				// EOF presets
				
				GUILayout.Space(10);
				
				{
					Color c=GUI.color;
					GUI.color=new Color(0.9f,1, 0.9f);
					if (GUILayout.Button(new GUIContent("Refresh all", "Refreshes all terrain object on the scene."), GUILayout.Height (40))) {
						_target.RefreshAll();
					}
					GUI.color=c;
				}
					
				GUILayout.Space(15);							
				if (GUILayout.Button("Reset main settings numeric params to default")) {
					Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
					_target.ReturnToDefaults("main");
					EditorUtility.SetDirty(_targetRT);
					_target.Refresh();
				}	

				#endregion Settings - main settings
	
			break;
					
			case ReliefTerrainSettingsItems.UVblend:
			
				#region Detail maps unfold - UV blend
				// UV blend on/off global properties
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoUVBlend),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("UV blending (tiling patterns reduction)", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;
				if (UV_BLEND_ENABLED_FIRST || UV_BLEND_ENABLED_ADD) {
					EditorGUILayout.HelpBox("UV blend feature can be helpful to remove tiling patterns at mid/far distance.\nIt blends detail maps with themselves using different tiling.\n\nPer layer settings can be found in \"Layers properties\" tab.",MessageType.None, true);
					checkChange(ref _target.blendMultiplier, EditorGUILayout.Slider("Mix Multiplier", _target.blendMultiplier, 0, 2));
					if (GUILayout.Button("Disable UV blend (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_UV_BLEND_FIRST=false;
						_RTP_LODmanagerScript.RTP_UV_BLEND_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset uv blend settings numeric params to default")) {
						Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
						_target.ReturnToDefaults("uvblend");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh();
					}								
				} else {
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable UV blend (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_UV_BLEND_FIRST=true;
						_RTP_LODmanagerScript.RTP_UV_BLEND_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}
				}
				EditorGUILayout.EndVertical();

				#endregion Detail maps unfold - UV blend						
			break;
					
			case ReliefTerrainSettingsItems.POMSettings:
				#region Settings - POM
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoPOM),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Parallax (POM/PM) settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;
				//checkChange(ref _target.ExtrudeHeight, EditorGUILayout.Slider("POM/PM Extrude Height", _target.ExtrudeHeight*Mathf.Max(tile_sizex, tile_sizey), 0.001f, 0.3f)/Mathf.Max(tile_sizex, tile_sizey));
				checkChange(ref _target.ExtrudeHeight, EditorGUILayout.Slider("Extrude Height", _target.ExtrudeHeight, 0.001f, 0.3f));
					
				EditorGUILayout.LabelField("Color/position solver (used in POM only)");
				EditorGUILayout.BeginHorizontal();
				EditorGUILayout.LabelField("", GUILayout.MaxWidth(10));
				EditorGUILayout.BeginVertical();				
				checkChange(ref _target.DIST_STEPS, EditorGUILayout.IntSlider("Max search steps", Mathf.FloorToInt(_target.DIST_STEPS), 4, 255));
				checkChange(ref _target.WAVELENGTH, EditorGUILayout.Slider("Step length (in texels)", _target.WAVELENGTH, 0.5f, 16));
				EditorGUILayout.EndVertical();				
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.LabelField("Self-shadow solver (used in POM only)");
				EditorGUILayout.BeginHorizontal();
				EditorGUILayout.LabelField("", GUILayout.MaxWidth(10));
				EditorGUILayout.BeginVertical();
				EditorGUILayout.HelpBox("To turn off self-shadowing in shader use RTP_LODmanager script (attach it to any scene object).",MessageType.None, true);
				checkChange(ref _target.SHADOW_STEPS, EditorGUILayout.IntSlider("Max search steps", Mathf.FloorToInt(_target.SHADOW_STEPS), 0, 80));
				checkChange(ref _target.WAVELENGTH_SHADOWS, EditorGUILayout.Slider("Step length (in texels)", _target.WAVELENGTH_SHADOWS, 0.5f, 16));
				checkChange(ref _target.SHADOW_SMOOTH_STEPS, EditorGUILayout.IntSlider("Max smoothing steps", Mathf.FloorToInt(_target.SHADOW_SMOOTH_STEPS), 3, 20));
				checkChange(ref _target.SelfShadowStrength, EditorGUILayout.Slider("Self-shadow strength", _target.SelfShadowStrength, 0.1f, 1));
				checkChange(ref _target.ShadowSmoothing, EditorGUILayout.Slider("Self-shadow smoothing", _target.ShadowSmoothing, 0.5f, 8));
				checkChange(ref _target.ShadowColor, EditorGUILayout.ColorField("Shadow colorization", _target.ShadowColor));
				EditorGUILayout.EndVertical();		
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.EndVertical();
					
				GUILayout.Space(15);							
				if (GUILayout.Button("Reset POM/PM settings numeric params to default")) {
					Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
					_target.ReturnToDefaults("pom/pm");
					EditorUtility.SetDirty(_targetRT);
					_target.Refresh();
				}	
										
				#endregion Settings - POM
			break;
				
			case ReliefTerrainSettingsItems.GlobalColor:
				#region Settings - Global color
				_target.paint_wetmask=false;
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoGlobalcolor),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Global color settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;

				EditorGUILayout.HelpBox("Color is blended via multiplication (easy to find/change in shader code - look for #ifdef COLOR_MAP).\n\nALPHA channel is used to remove locally parallax effects - extrude height (necessary for seamless geometry blending or when objects on the surface seem to hover on at the surface due to high extrude height).\n\nIf you don't use ColorMap - set below blending values to zero (you may use Alpha8 compressing w/o RGB channels, but still need alpha for parallax removing at blend areas - terrain vs mesh).",MessageType.None, true);
				EditorGUILayout.HelpBox("Near / Mid blend is realised at Main settings / Near distance values\n\nFar blend is realised at Perlin normal settings / start&fade distances.\n\nMIP level adjustement allows to take any MIP level below far distance (blended).", MessageType.None, true);
				EditorGUILayout.HelpBox("Note that saturation on far distance might work different when shader doesn't use detail/splat colors there, but only global colormap (refer to LODmanager settings - \"No detail colors at far distance\").", MessageType.None, true);
				EditorGUILayout.BeginHorizontal();
				Texture2D prev_globalColor=_targetRT.ColorGlobal;
				checkChange(ref _targetRT.ColorGlobal, (Texture2D)EditorGUILayout.ObjectField(_targetRT.ColorGlobal, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
				if (_targetRT.ColorGlobal && _targetRT.ColorGlobal!=prev_globalColor) {
					_targetRT.globalColorModifed_flag=false;
					_targetRT.tmp_globalColorMap=null;
					_targetRT.save_path_colormap=AssetDatabase.GetAssetPath(_targetRT.ColorGlobal);
					if (_targetRT.save_path_colormap=="") _targetRT.save_path_colormap="Assets/_output_colormap.png";
					_targetRT.RefreshTextures();
				}
				EditorGUILayout.BeginVertical();
					
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Near blend", GUILayout.MinWidth(80), GUILayout.MaxWidth(80));
					checkChange(ref _target.GlobalColorMapBlendValues.x, EditorGUILayout.Slider(_target.GlobalColorMapBlendValues.x, 0, 1));
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Mid blend", GUILayout.MinWidth(80), GUILayout.MaxWidth(80));
					checkChange(ref _target.GlobalColorMapBlendValues.y, EditorGUILayout.Slider(_target.GlobalColorMapBlendValues.y, 0, 1));
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Far blend", GUILayout.MinWidth(80), GUILayout.MaxWidth(80));
					checkChange(ref _target.GlobalColorMapBlendValues.z, EditorGUILayout.Slider(_target.GlobalColorMapBlendValues.z, 0, 1));
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("MIP level below far", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target._GlobalColorMapNearMIP, EditorGUILayout.Slider(_target._GlobalColorMapNearMIP, 0, 10));
				EditorGUILayout.EndHorizontal();						
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Saturation", GUILayout.MinWidth(80), GUILayout.MaxWidth(80));
					checkChange(ref _target.GlobalColorMapSaturation, EditorGUILayout.Slider(_target.GlobalColorMapSaturation, 0, 1));
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Brightness", GUILayout.MinWidth(80), GUILayout.MaxWidth(80));
					checkChange(ref _target.GlobalColorMapBrightness, EditorGUILayout.Slider(_target.GlobalColorMapBrightness, 0, 2));
				EditorGUILayout.EndHorizontal();
					
				EditorGUILayout.Space();
					
				EditorGUILayout.EndVertical();
				EditorGUILayout.EndHorizontal();
					
				if (_targetRT.ColorGlobal) {
					if (_targetRT.globalColorModifed_flag) {
						GUILayout.Space (8);
						if (GUILayout.Button("Colormap uncompressed & readable - save to file")) {
							string directory;
							string file;
							if (_targetRT.save_path_colormap=="") {
								directory=Application.dataPath;
								file="_output_colormap.png";
							} else {
								directory=Path.GetDirectoryName(_targetRT.save_path_colormap);
								file=Path.GetFileNameWithoutExtension(_targetRT.save_path_colormap)+".png";
							}
							string path = EditorUtility.SaveFilePanel("Save edited Global color map", directory, file, "png");
							if (path!="") {
								path=path.Substring(Application.dataPath.Length-6);
								_targetRT.save_path_colormap=path;
						 		byte[] bytes = _targetRT.ColorGlobal.EncodeToPNG();
							    System.IO.File.WriteAllBytes(path, bytes);
								AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
//									TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
//									textureImporter.textureFormat = TextureImporterFormat.ARGB32; 
//									textureImporter.isReadable = true;
//									AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
								_targetRT.ColorGlobal = (Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
								_targetRT.globalColorModifed_flag=false;
								_targetRT.tmp_globalColorMap=null;
							}										
						}
						GUILayout.Space (4);
					}
				}
					
					
				Color[] avg_cols=new Color[_target.numLayers];
				for(int n=0; n<_target.numLayers; n++) {
					Color[] col=new Color[1] { Color.black };
					Texture2D tex=_target.splats[n];
					string path=AssetDatabase.GetAssetPath(tex);
					if (path!="") {
						AssetImporter _importer=AssetImporter.GetAtPath(path);
						if (_importer) {
							TextureImporter tex_importer=(TextureImporter)_importer;
							if (!tex_importer.isReadable) {
								Debug.LogWarning("Texture ("+tex.name+") has been reimported as readable.");
								tex_importer.isReadable=true;
								AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(tex),  ImportAssetOptions.ForceUpdate);
							}
						}							
					}
					col=tex.GetPixels(tex.mipmapCount-1);
					col[0].a=1;
					avg_cols[n]=col[0];
				}						
				if (GUILayout.Button("Construct colormap from detail colors of layers (below)")) {
					if (_targetRT.controlA!=null) {
						Color[] colorMap;
						Color[] cols;
						int u;
						cols=_targetRT.controlA.GetPixels(0);
						colorMap=new Color[cols.Length];
						for(u=0; u<cols.Length; u++) {
							colorMap[u]=new Color(0,0,0,0);
						}
						for(int k=0; k<_target.numLayers; k++) {
							if (k==4) {
								cols=_targetRT.controlB.GetPixels(0);
							} else if (k==8) {
								cols=_targetRT.controlC.GetPixels(0);
							}
							if (cols!=null) {
								for(u=0; u<cols.Length; u++) {
									colorMap[u]+=cols[u][k%4]*avg_cols[k];
								}
							}
						}
						_targetRT.ColorGlobal=new Texture2D(_targetRT.controlA.width, _targetRT.controlA.height, TextureFormat.ARGB32, true);
						_targetRT.ColorGlobal.SetPixels(colorMap,0);
						_targetRT.ColorGlobal.Apply(true);
						_targetRT.globalColorModifed_flag=true;
					}
				}
				EditorGUILayout.BeginHorizontal();
					int thumb_size=32;
					for(int n=0; n<_target.numLayers; n++) {
						Color ccol = GUI.contentColor;
						GUI.contentColor=avg_cols[n];
				        if (GUILayout.Button(_target.get_dumb_tex(), "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
							_target.paintColor=avg_cols[n];
						}
				        GUI.contentColor = ccol;
					}
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.Space();						
				
				int copy_splat_idx=0;
				if ( _4LAYERS_SHADER_USED && (_target.numLayers>4) )  {
					copy_splat_idx=1;
				} else if ( (!_4LAYERS_SHADER_USED) && (_target.numLayers>8) ) {
					copy_splat_idx=2;
				}
				if (copy_splat_idx>0) {
					EditorGUILayout.Space();
					EditorGUILayout.HelpBox("Due to parallax effects to get better transitions between AddPass and FirstPass areas you need to cancel extrusion there.\n\nNote, that any height painting already done by either geometry blend or this script will be overwritten.",MessageType.Warning, true);
					if (GUILayout.Button("Overlap coverage to alpha (flatten overlapped areas)")) {
						colorAlphaFromSplat(copy_splat_idx);	
					}
				}
				
				EditorGUILayout.EndVertical();
					
				//
				// paint tools
				//
				GUILayout.Space(8);
				EditorGUILayout.BeginVertical("Box");		
				skin_color=GUI.color;
				GUI.color=new Color(1,1,0.5f,1);
				EditorGUILayout.LabelField("Paint tools", EditorStyles.boldLabel);
				GUI.color=skin_color;
					
				bool prev_paint_flag=_target.paint_flag;
				
				if (!_target.paint_flag) {
					Color c=GUI.color;
					GUI.color=new Color(0.9f,1, 0.9f);
					if (GUILayout.Button(new GUIContent("Begin painting (M)",icoPaintOn, "Click to turn on painting"))) {
						_target.paint_flag=true;
						_target.paint_wetmask=false;
//							if (!_target.prepare_tmpTexture(true)) {
//								_target.paint_flag=false;
//							}
					}
					if (!_targetRT.collider || !_targetRT.collider.enabled) _target.paint_flag=false;
					GUI.color=c;
				} else if (_target.paint_flag) {
					Color c=GUI.color;
					GUI.color=new Color(1,0.9f,0.9f);
					if (GUILayout.Button(new GUIContent("End painting (M)",icoPaintOff, "Click to turn off painting"))) {
						_target.paint_flag=false;
					}
					GUI.color=c;
				}
				if (!prev_paint_flag && _target.paint_flag) {
					Tools.current=Tool.View;
					ReliefTerrain._SceneGUI = new SceneView.OnSceneFunc(CustomOnSceneGUI);
					SceneView.onSceneGUIDelegate += ReliefTerrain._SceneGUI;
				} else if (prev_paint_flag && !_target.paint_flag) {
					Tools.current=prev_tool;
					SceneView.onSceneGUIDelegate -= ReliefTerrain._SceneGUI;
				}
				if (prev_paint_flag!=_target.paint_flag) EditorUtility.SetDirty(target);
				if (_target.paint_flag) {
					if (!_targetRT.collider || !_targetRT.collider.enabled) EditorGUILayout.HelpBox("Object doesn't have collider (necessary for painting).",MessageType.Error, true);
						
					string[] modes=new string[2] {"Color", "Extrude Height"};
					int npaint_mode=GUILayout.SelectionGrid(_target.paint_alpha_flag ? 1:0, modes, 2);
					if (npaint_mode!=(_target.paint_alpha_flag ? 1:0)) {
						EditorUtility.SetDirty(target);
					}
					_target.paint_alpha_flag = (npaint_mode==0) ? false : true;

					if (_target.paint_alpha_flag) {
						EditorGUILayout.HelpBox("Hold SHIFT while painting to apply eraser.",MessageType.Info, true);
					} else {
						EditorGUILayout.BeginVertical("Box");
						skin_color=GUI.color;
						GUI.color=new Color(1,1,0.5f,1);
						if (_target.paintColorSwatches.Length>0) EditorGUILayout.LabelField("Color swatches", EditorStyles.boldLabel);
						GUI.color=skin_color;
						EditorGUILayout.BeginHorizontal();
							thumb_size=16;
							for(int n=0; n<_target.paintColorSwatches.Length; n++) {
								Color ccol = GUI.contentColor;
								GUI.contentColor=_target.paintColorSwatches[n];
						        if (GUILayout.Button(_target.get_dumb_tex(), "Label", GUILayout.Width(thumb_size), GUILayout.Height(thumb_size))) {
									_target.paintColor=_target.paintColorSwatches[n];
								}
						        GUI.contentColor = ccol;
							}
						EditorGUILayout.EndHorizontal();								
						EditorGUILayout.BeginHorizontal();
							EditorGUI.BeginDisabledGroup(_target.paintColorSwatches.Length==12);
					        if (GUILayout.Button("Add swatch")) {
								Color[] ns=new Color[_target.paintColorSwatches.Length+1];
								for(int k=0; k<_target.paintColorSwatches.Length; k++) ns[k]=_target.paintColorSwatches[k];
								ns[ns.Length-1]=new Color(_target.paintColor.r, _target.paintColor.g, _target.paintColor.b, 1);
								_target.paintColorSwatches=ns;
							}
							EditorGUI.EndDisabledGroup();
							EditorGUI.BeginDisabledGroup(_target.paintColorSwatches.Length==0);
					        if (GUILayout.Button("Remove swatch")) {
								Color[] ns=new Color[_target.paintColorSwatches.Length-1];
								for(int k=0; k<ns.Length; k++) ns[k]=_target.paintColorSwatches[k];
								_target.paintColorSwatches=ns;
							}
							EditorGUI.EndDisabledGroup();
						EditorGUILayout.EndHorizontal();								
								
						_target.paintColor=EditorGUILayout.ColorField("Paint color", _target.paintColor);
						_target.preserveBrightness=EditorGUILayout.Toggle("Preserve luminosity", _target.preserveBrightness);
						EditorGUILayout.EndVertical();
					}
						
					Texture2D tmp_tex=_targetRT.tmp_globalColorMap;
					if (tmp_tex && (tmp_tex.format!=TextureFormat.Alpha8 && tmp_tex.format!=TextureFormat.ARGB32)) {
						EditorGUILayout.HelpBox("Global colormap need to be readable and uncompressed for painting.",MessageType.Error, true);
					}
					GUILayout.BeginHorizontal();
						GUILayout.Label ("Area size", EditorStyles.label );
						_target.paint_size = EditorGUILayout.Slider(_target.paint_size, 0.1f, 6);
					GUILayout.EndHorizontal();	
					GUILayout.BeginHorizontal();
						GUILayout.Label ("Area smoothness", EditorStyles.label );
						_target.paint_smoothness = EditorGUILayout.Slider (_target.paint_smoothness, 0.001f, 1);
					GUILayout.EndHorizontal();
					GUILayout.BeginHorizontal();
						GUILayout.Label ("Opacity", EditorStyles.label );
						_target.paint_opacity = EditorGUILayout.Slider (_target.paint_opacity, 0, 1);
					GUILayout.EndHorizontal();	
					GUILayout.Space(10);
				}
				EditorGUILayout.EndVertical();	
					
				GUILayout.Space(10);
				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Global normal settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;

				if (RTP_NORMALGLOBAL_FIRST||RTP_NORMALGLOBAL_ADD) {
					EditorGUILayout.HelpBox("Using global normal below we won't use mesh normals - will be treated flat (0,1,0 ), but you can greately improve look when lo-res heightmap or high pixelError settings are used.",MessageType.None, true);
					if (GUILayout.Button("Disable global normal (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_NORMALGLOBAL_FIRST=false;
						_RTP_LODmanagerScript.RTP_NORMALGLOBAL_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}							
						
					EditorGUILayout.BeginHorizontal();
					checkChange(ref _targetRT.NormalGlobal, (Texture2D)EditorGUILayout.ObjectField(_targetRT.NormalGlobal, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					EditorGUILayout.BeginVertical();
						
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Normal strength", GUILayout.MinWidth(100), GUILayout.MaxWidth(100));
						checkChange(ref _target.global_normalMap_multiplier, EditorGUILayout.Slider(_target.global_normalMap_multiplier, 0.5f, 6f));
					EditorGUILayout.EndHorizontal();
						
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndHorizontal();	
				} else {
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable global normal (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_NORMALGLOBAL_FIRST=true;
						_RTP_LODmanagerScript.RTP_NORMALGLOBAL_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}
				}
				EditorGUILayout.EndVertical();	
					
				GUILayout.Space(10);
					
				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Global trees/shadow settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;

				if (RTP_TREESGLOBAL_FIRST||RTP_TREESGLOBAL_ADD) {
					EditorGUILayout.HelpBox("RGB - trees color at very far distance (billboard trees drawing distance). Blending done via brightness, so black means - no pixel tree.\n\nA channel - shadows (mean to be used when you don't use lightmaps).",MessageType.None, true);
					if (GUILayout.Button("Disable global trees/shadows (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_TREESGLOBAL_FIRST=false;
						_RTP_LODmanagerScript.RTP_TREESGLOBAL_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}							
						
					EditorGUILayout.BeginHorizontal();
					checkChange(ref _targetRT.TreesGlobal, (Texture2D)EditorGUILayout.ObjectField(_targetRT.TreesGlobal, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					EditorGUILayout.BeginVertical();
						
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Trees distance", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_pixel_distance_start, EditorGUILayout.FloatField(_target.trees_pixel_distance_start));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Trees fade length", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_pixel_distance_transition, EditorGUILayout.Slider(_target.trees_pixel_distance_transition, 0, 100));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Trees blending", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_pixel_blend_val, EditorGUILayout.Slider(_target.trees_pixel_blend_val, 0, 10));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows distance", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_distance_start, EditorGUILayout.FloatField(_target.trees_shadow_distance_start));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows fade length", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_distance_transition, EditorGUILayout.Slider(_target.trees_shadow_distance_transition, 0, 30));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Shadows blending", GUILayout.MinWidth(125), GUILayout.MaxWidth(125));
						checkChange(ref _target.trees_shadow_value, 1-EditorGUILayout.Slider(1-_target.trees_shadow_value, 0, 1));
					EditorGUILayout.EndHorizontal();
						
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndHorizontal();	
				} else {
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable global trees/shadows (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_TREESGLOBAL_FIRST=true;
						_RTP_LODmanagerScript.RTP_TREESGLOBAL_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}
				}
				EditorGUILayout.EndVertical();	
					
				//if (RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST || RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD) {
				if (RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST) {
					EditorGUILayout.BeginVertical("Box");
					skin_color=GUI.color;
					EditorGUILayout.BeginHorizontal();
						GUI.color=new Color(1,1,0.5f,1);
						EditorGUILayout.LabelField("Grayscale detail textures", EditorStyles.boldLabel);
					EditorGUILayout.EndHorizontal();
					GUI.color=skin_color;						
					EditorGUILayout.HelpBox("In massive terrain mode (refer to RTP LOD manager for 4 layers mode) you can use even simplier close-distance detail colors as grayscale and global colorMap to tint them. RGBA channels refers to grayscaled detail textures for layers.",MessageType.None, true);
					if (GUILayout.Button("Disable massive terain mode  & grayscale detail textures")) {
						//_RTP_LODmanagerScript.RTP_SUPER_SIMPLE=false;
						_RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST=false;
						//_RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}	
						
					EditorGUILayout.BeginHorizontal();
					checkChange(ref _target.SSColorCombined, (Texture2D)EditorGUILayout.ObjectField(_target.SSColorCombined, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					EditorGUILayout.BeginVertical();
						
					EditorGUILayout.BeginHorizontal();
						if (GUILayout.Button("Make combined grayscale texture")) {
							MakeCombinedGrayscale();
						}
					EditorGUILayout.EndHorizontal();
						
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndHorizontal();	
					SaveTexture(ref _target.SSColorCombined, ref _target.save_path_SSColorCombined, "terrain_detail_grayscale_combined.png", 100, TextureImporterFormat.DXT5, true);
						
//					} else {
//						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
//						if (GUILayout.Button("Enable massive terain mode  & grayscale detail textures")) {
//							_RTP_LODmanagerScript.RTP_SUPER_SIMPLE=true;
//							_RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_FIRST=true;
//							//_RTP_LODmanagerScript.RTP_SS_GRAYSCALE_DETAIL_COLORS_ADD=true;
//							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
//								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
//								_RTP_LODmanagerScript.dont_sync=true;
//							}
//							//_RTP_LODmanagerScript.RefreshLODlevel();
//							//EditorUtility.SetDirty(_targetRT);
//						}
					EditorGUILayout.EndVertical();	
				}
					
				GUILayout.Space(15);							
				if (GUILayout.Button("Reset global color settings numeric params to default")) {
					Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
					_target.ReturnToDefaults("global_color");
					EditorUtility.SetDirty(_targetRT);
					_target.Refresh();
				}	
					
				#endregion Settings - Global color
			break;
				
			case ReliefTerrainSettingsItems.GlobalNormal:
				#region Settings - Global normal 
				GUILayout.Space(6);
;
				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoPerlinNormal),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Perlin normal map settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;
			
				EditorGUILayout.HelpBox("Feature below are applied per layer in \"Layer properties\".", MessageType.None, true);
				EditorGUILayout.HelpBox("REMEMBER - this map is also used for water flow animation, water/snow random coverage and superdetail normal mapping.\n\nFar normal damp flattens normals stored in vertices at far distance. It's useful in situation you're using lighting info baked into global colorMap (like in the example scene).", MessageType.None, true);
				
				EditorGUILayout.BeginHorizontal();
				Texture2D tex_bump=_target.BumpGlobal;
				Texture2D ntex=tex_bump;
				checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.BumpGlobal, typeof(Texture2D), false, GUILayout.MinHeight(90), GUILayout.MinWidth(90), GUILayout.MaxWidth(90)));
				if (ntex==null) {
					ntex=(Texture2D)AssetDatabase.LoadAssetAtPath("Assets/ReliefPack/Textures/ReliefTerrain/perlin_noise.png", typeof(Texture2D));
					_targetRT.TERRAIN_WetMask=null;
					_target.TERRAIN_ReflectionMap=null;
					_target.SuperDetailA=null;
					_target.SuperDetailB=null;
				}
				if (ntex!=tex_bump) {
					Texture2D tex_prev=_target.BumpGlobal;
					_target.BumpGlobal=ntex;
					if (ntex) {
						AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
						if (_importer) {
							TextureImporter tex_importer=(TextureImporter)_importer;
							if (!tex_importer.isReadable) {
								Debug.LogWarning("Global normal texture ("+ntex.name+") has been reimported as readable.");
								tex_importer.isReadable=true;
								AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
							}
						}
					}
					if (!_targetRT.PrepareGlobalNormalsAndSuperDetails()) {
						Debug.LogWarning("Due to rebuilding special combined texture superdetail textures, water mask and reflection map have been cleared (you have to reassign them again).");
						_target.BumpGlobal=tex_prev;
						_targetRT.TERRAIN_WetMask=null;
						_target.TERRAIN_ReflectionMap=null;
						_target.SuperDetailA=null;
						_target.SuperDetailB=null;
						if (_targetRT.PrepareGlobalNormalsAndSuperDetails()) {
							_target.BumpGlobal=ntex;
						}
					}
					_target.Refresh();
				}
				EditorGUILayout.BeginVertical();
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Tiling scale ("+(Mathf.Round(_target.ReliefTransform.x*_target.BumpMapGlobalScale*100)/100)+")", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					EditorGUILayout.BeginHorizontal();
						checkChange(ref _target.BumpMapGlobalScale, EditorGUILayout.Slider(_target.BumpMapGlobalScale, 0.01f, 0.25f));
						if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
							float ratio=Mathf.Round(_target.ReliefTransform.x*_target.BumpMapGlobalScale);
							_target.BumpMapGlobalScale=ratio/_target.ReliefTransform.x;
							EditorUtility.SetDirty(_targetRT);
						}
					EditorGUILayout.EndHorizontal();						
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("MIP offset", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target.rtp_mipoffset_globalnorm, EditorGUILayout.IntSlider(_target.rtp_mipoffset_globalnorm, 0, 5));
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Distance start", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target.distance_start_bumpglobal, EditorGUILayout.Slider(_target.distance_start_bumpglobal, 0, 100));
					if (_target.distance_start_bumpglobal<_target.distance_start) _target.distance_start_bumpglobal=_target.distance_start;
				EditorGUILayout.EndHorizontal();
					
				EditorGUI.BeginDisabledGroup( _target.distance_start_bumpglobal>0 );
				if (_target.distance_start_bumpglobal>0) _target.rtp_perlin_start_val=0;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Starting value", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target.rtp_perlin_start_val, EditorGUILayout.Slider(_target.rtp_perlin_start_val, 0, 1.0f));
				EditorGUILayout.EndHorizontal();
				EditorGUI.EndDisabledGroup();
					
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Fade length", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target.distance_transition_bumpglobal, EditorGUILayout.Slider(_target.distance_transition_bumpglobal, 0, 300));
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField("Far normal damp", GUILayout.MinWidth(120), GUILayout.MaxWidth(120));
					checkChange(ref _target._FarNormalDamp, EditorGUILayout.Slider(_target._FarNormalDamp, 0, 1));
				EditorGUILayout.EndHorizontal();
				EditorGUILayout.EndVertical();
				EditorGUILayout.EndHorizontal();
				
				EditorGUILayout.EndVertical();
					
				GUILayout.Space(15);							
				if (GUILayout.Button("Reset perlin normal settings numeric params to default")) {
					Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
					_target.ReturnToDefaults("perlin");
					EditorUtility.SetDirty(_targetRT);
					_target.Refresh();
				}		
					
				#endregion Settings - Global normal	
			break;					
				
			case ReliefTerrainSettingsItems.Superdetail:
				#region Settings - superdetail					
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoSuperdetail),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Superdetail settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;
				
				if (SUPER_DETAIL_ENABLED_FIRST || SUPER_DETAIL_ENABLED_ADD) {
					EditorGUILayout.HelpBox("Superdetail is texture consisting of Perlin normalmap and optional 2 additional multiplicative channels. They're shared on combined texture with water mask and reflection map, so CAN NOT be used (with water/reflection) at the same time.\n\nSuperdetail normal is applied only on near distance.", MessageType.None, true);
						
					if (GUILayout.Button("Disable superdetails (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_SUPER_DETAIL_FIRST=false;
						_RTP_LODmanagerScript.RTP_SUPER_DETAIL_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}
					
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Superdetail tiling scale", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._SuperDetailTiling, EditorGUILayout.IntSlider(Mathf.RoundToInt(_target._SuperDetailTiling), 1, 16));
					EditorGUILayout.EndHorizontal();
					
					if (SUPER_DETAIL_MULTS_ENABLED_FIRST || SUPER_DETAIL_MULTS_ENABLED_ADD) {
						GUILayout.Space(8);
						EditorGUILayout.HelpBox("Superdetail multiplicative channles can be applied on both near and far distances with optional self-masking (works the way multiplicative channel masks itself using Perlin normal tiling).\n\nColor multiplication is realised classic way (color x mult_channel x 2) giving opportunity to make it lighten/darken (grey texture gives neutral effect).\n\nOn far distance selfmasking set to 0 means we've got no blending (otherwise we would see distinct superdetail patterns over large areas).", MessageType.None, true);
						EditorGUILayout.BeginHorizontal();
						Texture2D tmp_tex=_target.SuperDetailA;
						ntex=tmp_tex;
						checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.SuperDetailA, typeof(Texture2D), false, GUILayout.MinHeight(90), GUILayout.MinWidth(90), GUILayout.MaxWidth(90)));
						if (ntex!=tmp_tex) {
							Texture2D tex_prev=_target.SuperDetailA;
							_target.SuperDetailA=ntex;
							if (ntex) {
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Superdetail 1st texture ("+ntex.name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
									}
								}
							}
							if (!_targetRT.PrepareGlobalNormalsAndSuperDetails()) _target.SuperDetailA=tex_prev;
							_target.Refresh();
						}
						ColorChannels nchannel=ColorChannels.R;
						EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
						checkChange(ref nchannel, (ColorChannels)EditorGUILayout.EnumPopup(_target.SuperDetailA_channel));
						if (nchannel!=_target.SuperDetailA_channel) {
							_target.SuperDetailA_channel=nchannel;
							_targetRT.PrepareGlobalNormalsAndSuperDetails();
						}
						EditorGUILayout.EndHorizontal();
						
						EditorGUILayout.Space();
						EditorGUILayout.BeginHorizontal();
						tmp_tex=_target.SuperDetailB;
						ntex=tmp_tex;
						checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.SuperDetailB, typeof(Texture2D), false, GUILayout.MinHeight(90), GUILayout.MinWidth(90), GUILayout.MaxWidth(90)));
						if (ntex!=tmp_tex) {
							Texture2D tex_prev=_target.SuperDetailB;
							_target.SuperDetailB=ntex;
							if (ntex) {
								AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
								if (_importer) {
									TextureImporter tex_importer=(TextureImporter)_importer;
									if (!tex_importer.isReadable) {
										Debug.LogWarning("Superdetail 2st texture ("+ntex.name+") has been reimported as readable.");
										tex_importer.isReadable=true;
										AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
									}
								}
							}
							if (!_targetRT.PrepareGlobalNormalsAndSuperDetails()) _target.SuperDetailB=tex_prev;
							_target.Refresh();
						}
						EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
						checkChange(ref nchannel, (ColorChannels)EditorGUILayout.EnumPopup(_target.SuperDetailB_channel));
						if (nchannel!=_target.SuperDetailB_channel) {
							_target.SuperDetailB_channel=nchannel;
							_targetRT.PrepareGlobalNormalsAndSuperDetails();
						}
						EditorGUILayout.EndHorizontal();
					} // superdetail mults
					
					if (SUPER_DETAIL_MULTS_ENABLED_FIRST || SUPER_DETAIL_MULTS_ENABLED_ADD) {
						if (GUILayout.Button("Disable superdetails mult (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_FIRST=false;
							_RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
					} else {
						EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable superdetails mult (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_FIRST=true;
							_RTP_LODmanagerScript.RTP_SUPER_DETAIL_MULTS_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
							//_RTP_LODmanagerScript.RefreshLODlevel();
							//EditorUtility.SetDirty(_targetRT);
						}
					}		
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset superdetail settings numeric params to default")) {
						Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
						_target.ReturnToDefaults("superdetail");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh();							
					}	
						
				} else {
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable superdetails (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_SUPER_DETAIL_FIRST=true;
						_RTP_LODmanagerScript.RTP_SUPER_DETAIL_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}
				}
				
				EditorGUILayout.EndVertical();
				
				#endregion Settings - superdetail					
			break;	
			case ReliefTerrainSettingsItems.VerticalTex:
				#region Settings - Vertical texture		
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoVerticalTexture),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Vertical texturing", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;
				
				if (	RTP_VERTICAL_TEXTURE_FIRST || RTP_VERTICAL_TEXTURE_ADD) {
					EditorGUILayout.HelpBox("This texture is applied along world y axis using V coord. Pixel color is multiplied, controlled per layer (\"Layer properties\" - Vertical map strength).",MessageType.None, true);
					
					EditorGUILayout.BeginHorizontal();
					checkChange(ref _target.VerticalTexture, (Texture2D)EditorGUILayout.ObjectField(_target.VerticalTexture, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					EditorGUILayout.BeginVertical();
						EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("Tiling [m]", GUILayout.MinWidth(145), GUILayout.MaxWidth(145));
							checkChange(ref _target.VerticalTextureTiling, EditorGUILayout.FloatField(_target.VerticalTextureTiling));
						EditorGUILayout.EndHorizontal();
						EditorGUILayout.BeginHorizontal();
							EditorGUILayout.LabelField("Offset via Perlin normal", GUILayout.MinWidth(145), GUILayout.MaxWidth(145));
							checkChange(ref _target.VerticalTextureGlobalBumpInfluence, EditorGUILayout.Slider(_target.VerticalTextureGlobalBumpInfluence, 0, 0.1f));
						EditorGUILayout.EndHorizontal();
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndHorizontal();
				} // v-tex
				
				if (		RTP_VERTICAL_TEXTURE_FIRST || RTP_VERTICAL_TEXTURE_ADD) {
					if (GUILayout.Button("Disable feature (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_FIRST=false;
						_RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset vertical texture settings numeric params to default")) {
						Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
						_target.ReturnToDefaults("vertical");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh();
					}	
						
				} else {
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable feature (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_FIRST=true;
						_RTP_LODmanagerScript.RTP_VERTICAL_TEXTURE_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
						//_RTP_LODmanagerScript.RefreshLODlevel();
						//EditorUtility.SetDirty(_targetRT);
					}
				}
				
				EditorGUILayout.EndVertical();
					
				#endregion Settings - Vertical texture
			break;
				
			case ReliefTerrainSettingsItems.Snow:
				#region Settings - Snow
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoSnow),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Snow settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;
				
				if (SNOW_ENABLED_FIRST || SNOW_ENABLED_ADD) {
#if !UNITY_3_5
					EditorGUILayout.HelpBox("Snow settings are set globally and its params are visible in any shader using RTP dynamic snow feature (Bonus snow shaders). This also means that you can't use different snow settings on multiple terrains (Unity4).",MessageType.Warning, true);
#endif
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Strength", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_strength, EditorGUILayout.Slider(_target._snow_strength, 0, 1));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.HelpBox("Global color influence means the darker is global color the more snow is present.",MessageType.None, true);
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Global color influence", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._global_color_brightness_to_snow, EditorGUILayout.Slider(_target._global_color_brightness_to_snow, 0, 0.3f));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.HelpBox("Reduction by slope is factor for decreasing snow coverage on slopes.",MessageType.None, true);
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Reduction by slope", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_slope_factor, EditorGUILayout.Slider(_target._snow_slope_factor, 0, 10f));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.HelpBox("Height threshold/transition allows to put snow on choosen height only (i.e. high mountais).",MessageType.None, true);
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Height threshold [units]", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_height_treshold, EditorGUILayout.Slider(_target._snow_height_treshold, -200, 7000));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Height transition", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_height_transition, EditorGUILayout.Slider(_target._snow_height_transition, 1, 4000));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.Space ();
					
					EditorGUILayout.HelpBox("Color / spec / gloss are used for far distance.\nFor near distance you can choose a layer to get its color/normalmap as snow (refer to _RTP_LODmanager game object inspector).",MessageType.None, true);
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Color", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_color, EditorGUILayout.ColorField(_target._snow_color));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Specular", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_specular, EditorGUILayout.Slider(_target._snow_specular, 0.01f, 1f));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Gloss", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_gloss, EditorGUILayout.Slider(_target._snow_gloss, 0.01f, 1f));
					EditorGUILayout.EndHorizontal();
					EditorGUI.BeginDisabledGroup( !(REFLECTION_ENABLED_FIRST || REFLECTION_ENABLED_ADD));
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Reflection", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_reflectivness, EditorGUILayout.Slider(_target._snow_reflectivness, 0.01f, 1f));
					EditorGUILayout.EndHorizontal();
					EditorGUI.EndDisabledGroup();

					EditorGUILayout.Space ();
			
					EditorGUILayout.HelpBox("Edges definition makes snow transition smooth (snow color gradualy blends underlying surface) or sharp.",MessageType.None, true);
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Edges definition", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_edge_definition, EditorGUILayout.Slider(_target._snow_edge_definition, 0.5f, 20f));
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.Space ();
					EditorGUILayout.HelpBox("Deep factor adjusts how fast covered surface will get dedicated normals (from texture) and extrusion height canceled (in POM/PM shading).",MessageType.None, true);
					EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("Deep factor", GUILayout.MinWidth(140), GUILayout.MaxWidth(140));
						checkChange(ref _target._snow_deep_factor, EditorGUILayout.Slider(_target._snow_deep_factor, 0, 6));
					EditorGUILayout.EndHorizontal();
				
				} // snow
				EditorGUILayout.Space ();
				
				if (SNOW_ENABLED_FIRST || SNOW_ENABLED_ADD) {
					if (GUILayout.Button("Disable snow (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_SNOW_FIRST=false;
						_RTP_LODmanagerScript.RTP_SNOW_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
					}
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset snow settings numeric params to default")) {
						Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
						_target.ReturnToDefaults("snow");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh();
					}	
						
				} else {
					_target._snow_strength=1;
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable snow (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_SNOW_FIRST=true;
						_RTP_LODmanagerScript.RTP_SNOW_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
					}
				}					
				
				EditorGUILayout.EndVertical();
					
				#endregion Settings - Snow
			break;					
				
			case ReliefTerrainSettingsItems.Water:
				#region Settings - Water
				_target.paint_wetmask=true;
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoWater),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Water settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;

				if (WATER_ENABLED_FIRST || WATER_ENABLED_ADD) {
					EditorGUILayout.HelpBox("Water has 3 states due to wetness applied - diffuse color darken for initial water, then surface becomes wet, then water may accumulate in lower parts (lower in terms of heightmap applied).\n\nReflection is taken from reflection map (the same as in Reflection settings). Most params are applied per layer.",MessageType.None, true);
					checkChange(ref _target.TERRAIN_GlobalWetness, EditorGUILayout.Slider("Global wetness", _target.TERRAIN_GlobalWetness, 0, 1));
					checkChange(ref _target.TERRAIN_WaterSpecularity, EditorGUILayout.Slider("Water specularity", _target.TERRAIN_WaterSpecularity, 0.01f, 1f));
					checkChange(ref _target.TERRAIN_FlowSpeed, EditorGUILayout.Slider("Flow speed", _target.TERRAIN_FlowSpeed, 0, 2f));
					EditorGUILayout.BeginHorizontal();
						checkChange(ref _target.TERRAIN_FlowScale, EditorGUILayout.Slider("Flow tex tiling ("+(Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_FlowScale*100)/100)+")", _target.TERRAIN_FlowScale, 0.25f, 8f));
						if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
							float ratio=Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_FlowScale);
							_target.TERRAIN_FlowScale=ratio/_target.ReliefTransform.x;
							EditorUtility.SetDirty(_targetRT);
						}
					EditorGUILayout.EndHorizontal();
					checkChange(ref _target.TERRAIN_FlowMipOffset, EditorGUILayout.Slider("Flow tex filter", _target.TERRAIN_FlowMipOffset/4f, 0, 1)*4f);
					checkChange(ref _target.TERRAIN_mipoffset_flowSpeed, EditorGUILayout.Slider("Filter by flow speed", _target.TERRAIN_mipoffset_flowSpeed/4f, 0, 1)*4);
					checkChange(ref _target.TERRAIN_WetDarkening, EditorGUILayout.Slider("Water surface darkening", _target.TERRAIN_WetDarkening, 0.1f, 0.9f));
					EditorGUILayout.HelpBox("You can exclude any parts from wetness - shelter mask is put on derived/combined texture channel B together with Perlin normal (RG) and reflection map (A) (see Combined textures in RTP main inspector menu tab).\n\nWhen you don't specify texture below it will be treated black(full water).\n\nWhen you start painting the mask will be automatically made for you (with size of Special combined texture).",MessageType.None, true);

					Texture2D tmp_tex=_targetRT.TERRAIN_WetMask;
					ntex=tmp_tex;
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.BeginVertical();
					if (checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_targetRT.TERRAIN_WetMask, typeof(Texture2D), false, GUILayout.MinHeight(140), GUILayout.MinWidth(140), GUILayout.MaxWidth(140)))) {
						_targetRT.RefreshTextures();
					}
					if (SaveTexture(ref _targetRT.TERRAIN_WetMask, ref _targetRT.save_path_WetMask, "terrain_wetmask.png", 140, TextureImporterFormat.Alpha8, true)) {
						_targetRT.globalWaterModifed_flag=false;
					}
					EditorGUILayout.EndVertical();
					EditorGUILayout.BeginVertical();
						int fill_flag=0;
						if (GUILayout.Button("Dry all terrain")) {
							fill_flag=1;
							_targetRT.RefreshTextures();
						}
						if (GUILayout.Button("Fill all terrain with water")) {
							fill_flag=2;
							_targetRT.RefreshTextures();
						}
						if (fill_flag>0) {
							if (_targetRT.TERRAIN_WetMask) DestroyImmediate(_targetRT.TERRAIN_WetMask, false);
							if (_targetRT.BumpGlobalCombined) {
								_targetRT.TERRAIN_WetMask=new Texture2D(_targetRT.BumpGlobalCombined.width, _targetRT.BumpGlobalCombined.height, TextureFormat.Alpha8, false);
							} else if (_target.TERRAIN_ReflectionMap) {
								_targetRT.TERRAIN_WetMask=new Texture2D(_target.TERRAIN_ReflectionMap.width, _target.TERRAIN_ReflectionMap.height, TextureFormat.Alpha8, false);
							} else {
								_targetRT.TERRAIN_WetMask=new Texture2D(1024, 1024, TextureFormat.Alpha8, false);
							}
							Color32[] cols=new Color32[_targetRT.TERRAIN_WetMask.width*_targetRT.TERRAIN_WetMask.height];
							if (fill_flag==1) {
								for(int k=0; k<cols.Length; k++) cols[k]=Color.white;
							}
							_targetRT.TERRAIN_WetMask.SetPixels32(cols,0);
							_targetRT.TERRAIN_WetMask.Apply(true,false);
							_targetRT.globalWaterModifed_flag=true;
							_targetRT.PrepareGlobalNormalsAndSuperDetails(true,false);
						}
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndHorizontal();
					if (ntex!=tmp_tex) {
						Texture2D tex_prev=_targetRT.TERRAIN_WetMask;
						_targetRT.TERRAIN_WetMask=ntex;
						if (ntex) {
							AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								bool modified_flag=false;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Wet mask texture ("+ntex.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									modified_flag=true;
								}
								if (tex_importer.textureFormat!=TextureImporterFormat.Alpha8) {
									Debug.LogWarning("Wet mask texture ("+ntex.name+") has been reimported as Alpha8.");
									tex_importer.grayscaleToAlpha=true;
									tex_importer.textureFormat=TextureImporterFormat.Alpha8;
									modified_flag=true;
								}
								if (modified_flag) {
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
								}	
							}
						}
						if (!_targetRT.PrepareGlobalNormalsAndSuperDetails(true,false)) _targetRT.TERRAIN_WetMask=tex_prev;
						_target.Refresh();
					}
						
					//
					// paint tools
					//						
					GUILayout.Space(8);
					EditorGUILayout.BeginVertical("Box");		
					skin_color=GUI.color;
					GUI.color=new Color(1,1,0.5f,1);
					EditorGUILayout.LabelField("Wetmask paint tool", EditorStyles.boldLabel);
					GUI.color=skin_color;
						
					prev_paint_flag=_target.paint_flag;
					
					if (!_target.paint_flag) {
						Color c=GUI.color;
						GUI.color=new Color(0.9f,1, 0.9f);
						if (GUILayout.Button(new GUIContent("Begin painting (M)",icoPaintOn, "Click to turn on painting"))) {
							_target.paint_flag=true;
							_target.paint_wetmask=true;
							_target.paint_alpha_flag=true;
							if (!_targetRT.TERRAIN_WetMask) {
								if (_targetRT.BumpGlobalCombined) {
									_targetRT.TERRAIN_WetMask=new Texture2D(_targetRT.BumpGlobalCombined.width, _targetRT.BumpGlobalCombined.height, TextureFormat.Alpha8, false);
								} else if (_target.TERRAIN_ReflectionMap) {
									_targetRT.TERRAIN_WetMask=new Texture2D(_target.TERRAIN_ReflectionMap.width, _target.TERRAIN_ReflectionMap.height, TextureFormat.Alpha8, false);
								} else {
									_targetRT.TERRAIN_WetMask=new Texture2D(1024, 1024, TextureFormat.Alpha8, false);
								}
								Color32[] cols=new Color32[_targetRT.TERRAIN_WetMask.width*_targetRT.TERRAIN_WetMask.height];
								_targetRT.TERRAIN_WetMask.SetPixels32(cols,0);
								_targetRT.TERRAIN_WetMask.Apply(true,false);
							}
							if (!_targetRT.BumpGlobalCombined) {
								if (!_targetRT.PrepareGlobalNormalsAndSuperDetails(true, false)) {
									_target.paint_flag=false;
								}
							}
						}
						if (!_targetRT.collider || !_targetRT.collider.enabled) _target.paint_flag=false;
						GUI.color=c;
					} else if (_target.paint_flag) {
						Color c=GUI.color;
						GUI.color=new Color(1,0.9f,0.9f);
						if (GUILayout.Button(new GUIContent("End painting (M)",icoPaintOff, "Click to turn off painting"))) {
							_target.paint_flag=false;
						}
						GUI.color=c;
					}
					if (!prev_paint_flag && _target.paint_flag) {
						Tools.current=Tool.View;
						ReliefTerrain._SceneGUI = new SceneView.OnSceneFunc(CustomOnSceneGUI);
						SceneView.onSceneGUIDelegate += ReliefTerrain._SceneGUI;
					} else if (prev_paint_flag && !_target.paint_flag) {
						Tools.current=prev_tool;
						SceneView.onSceneGUIDelegate -= ReliefTerrain._SceneGUI;
					}
					if (prev_paint_flag!=_target.paint_flag) EditorUtility.SetDirty(target);
					if (_target.paint_flag) {
						EditorGUILayout.BeginHorizontal();
						EditorGUILayout.LabelField("", GUILayout.MaxWidth(10));
						EditorGUILayout.BeginVertical();			
						
						if (!_targetRT.collider || !_targetRT.collider.enabled) EditorGUILayout.HelpBox("Object doesn't have collider (necessary for painting).",MessageType.Error, true);
							
						EditorGUILayout.HelpBox("Hold SHIFT while painting to add water.",MessageType.Info, true);
							
						if (_targetRT.tmp_WaterMap && _targetRT.tmp_WaterMap.format!=TextureFormat.Alpha8) {
							EditorGUILayout.HelpBox("Wet mask need to be readable and uncompressed for painting.",MessageType.Error, true);
						}
						if (_targetRT.tmp_CombinedMap && _targetRT.tmp_CombinedMap.format!=TextureFormat.ARGB32) {
							EditorGUILayout.HelpBox("Special combined map need to be readable and uncompressed for painting.",MessageType.Error, true);
						}
						GUILayout.BeginHorizontal();
							GUILayout.Label ("Area size", EditorStyles.label );
							_target.paint_size = EditorGUILayout.Slider(_target.paint_size, 0.1f, 6);
						GUILayout.EndHorizontal();	
						GUILayout.BeginHorizontal();
							GUILayout.Label ("Area smoothness", EditorStyles.label );
							_target.paint_smoothness = EditorGUILayout.Slider (_target.paint_smoothness, 0.001f, 1);
						GUILayout.EndHorizontal();
						GUILayout.BeginHorizontal();
							GUILayout.Label ("Opacity", EditorStyles.label );
							_target.paint_opacity = EditorGUILayout.Slider (_target.paint_opacity, 0, 1);
						GUILayout.EndHorizontal();	
			
						EditorGUILayout.EndVertical();
						EditorGUILayout.EndHorizontal();
						GUILayout.Space(10);
					}
					EditorGUILayout.EndVertical();	
				
					EditorGUILayout.HelpBox("Below feature simulates drops on the water surface. Texture used for animation is predefined so you don't have to touch it. Ripples appears on accumulated water surface, for wet surface only when \"Rain on wet\" is positive. Ripples can be also damped on slopes via \"Water level slope damp\" layer param.",MessageType.None, true);
					if (RIPPLEMAP_ENABLED_FIRST || RIPPLEMAP_ENABLED_ADD) {
						if (GUILayout.Button("Disable droplets anim (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_FIRST=false;
							_RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_ADD=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
					} else {
						//EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable droplets anim (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_FIRST=true;
							_RTP_LODmanagerScript.RTP_WET_RIPPLE_TEXTURE_ADD=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
					}						
					EditorGUI.BeginDisabledGroup( !(RIPPLEMAP_ENABLED_FIRST || RIPPLEMAP_ENABLED_ADD));
						checkChange(ref _target.TERRAIN_RainIntensity, EditorGUILayout.Slider("Rain intensity", _target.TERRAIN_RainIntensity, 0, 1f));
						checkChange(ref _target.TERRAIN_WetDropletsStrength, EditorGUILayout.Slider("Rain on wet", _target.TERRAIN_WetDropletsStrength, 0, 1));
						checkChange(ref _target.TERRAIN_DropletsSpeed, EditorGUILayout.Slider("Anim speed", _target.TERRAIN_DropletsSpeed, 1, 30f));
						EditorGUILayout.BeginHorizontal();
							checkChange(ref _target.TERRAIN_RippleScale, EditorGUILayout.Slider("Ripple tex tiling ("+(Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_RippleScale*100)/100)+")", _target.TERRAIN_RippleScale, 0.25f, 8));
							if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
								float ratio=Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_RippleScale);
								_target.TERRAIN_RippleScale=ratio/_target.ReliefTransform.x;
								EditorUtility.SetDirty(_targetRT);
							}
						EditorGUILayout.EndHorizontal();						
						if ((RIPPLEMAP_ENABLED_FIRST || RIPPLEMAP_ENABLED_ADD) && _target.TERRAIN_RippleMap==null) {
							_target.TERRAIN_RippleMap=(Texture2D)AssetDatabase.LoadAssetAtPath("Assets/ReliefPack/Textures/ReliefTerrain/water_drops_anim.png", typeof(Texture2D));
						}
						checkChange(ref _target.TERRAIN_RippleMap, (Texture2D)EditorGUILayout.ObjectField(_target.TERRAIN_RippleMap, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
					EditorGUI.EndDisabledGroup();
				} else {
					_target.TERRAIN_GlobalWetness=1;
				}
					
				GUILayout.Space(15);
				if (WATER_ENABLED_FIRST || WATER_ENABLED_ADD) {
					if (GUILayout.Button("Disable water (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_WETNESS_FIRST=false;
						_RTP_LODmanagerScript.RTP_WETNESS_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
					}
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset water settings numeric params to default")) {
						Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
						_target.ReturnToDefaults("water");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh();
					}		
						
				} else {
					_target.TERRAIN_GlobalWetness=1;
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable water (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_WETNESS_FIRST=true;
						_RTP_LODmanagerScript.RTP_WETNESS_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
					}
				}						
				
				EditorGUILayout.EndVertical();
					
				#endregion Settings - Water
					
				#region Settings - Caustics
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoWater),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Caustics settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;

				if (CAUSTICS_ENABLED_FIRST || CAUSTICS_ENABLED_ADD) {
					checkChange(ref _target.TERRAIN_CausticsAnimSpeed, EditorGUILayout.Slider("Anim speed", _target.TERRAIN_CausticsAnimSpeed, 0, 10f));
					checkChange(ref _target.TERRAIN_CausticsColor, EditorGUILayout.ColorField("Color", _target.TERRAIN_CausticsColor));
					checkChange(ref _target.TERRAIN_CausticsWaterLevelRefObject, (GameObject)EditorGUILayout.ObjectField("Water Level Ref", _target.TERRAIN_CausticsWaterLevelRefObject, typeof(GameObject), true));
					EditorGUI.BeginDisabledGroup(_target.TERRAIN_CausticsWaterLevelRefObject);
					checkChange(ref _target.TERRAIN_CausticsWaterLevel, EditorGUILayout.FloatField("Water Level", _target.TERRAIN_CausticsWaterLevel));
					EditorGUI.EndDisabledGroup();
					checkChange(ref _target.TERRAIN_CausticsWaterLevelByAngle, EditorGUILayout.Slider("Water level by slope", _target.TERRAIN_CausticsWaterLevelByAngle, 0f, 8f));
					checkChange(ref _target.TERRAIN_CausticsWaterShallowFadeLength, EditorGUILayout.Slider("Shallow fade length", _target.TERRAIN_CausticsWaterShallowFadeLength, 0.1f, 10f));
					checkChange(ref _target.TERRAIN_CausticsWaterDeepFadeLength, EditorGUILayout.Slider("Deep fade length", _target.TERRAIN_CausticsWaterDeepFadeLength, 1f, 100f));
					EditorGUILayout.BeginHorizontal();
						checkChange(ref _target.TERRAIN_CausticsTilingScale, EditorGUILayout.Slider("Texture tiling  ("+(Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_CausticsTilingScale*100)/100)+")", _target.TERRAIN_CausticsTilingScale, 0.5f, 4f));
						if (GUILayout.Button(new GUIContent("A","Align to terrain tile"), GUILayout.Width(22), GUILayout.Height(16))) {
							float ratio=Mathf.Round(_target.ReliefTransform.x*_target.TERRAIN_CausticsTilingScale);
							_target.TERRAIN_CausticsTilingScale=ratio/_target.ReliefTransform.x;
							EditorUtility.SetDirty(_targetRT);
						}
					EditorGUILayout.EndHorizontal();						
					EditorGUILayout.LabelField("Caustics texture", EditorStyles.boldLabel);
					checkChange(ref _target.TERRAIN_CausticsTex, (Texture2D)EditorGUILayout.ObjectField(_target.TERRAIN_CausticsTex, typeof(Texture2D), false, GUILayout.MinHeight(100), GUILayout.MinWidth(100), GUILayout.MaxWidth(100)));
				}
					
				GUILayout.Space(15);
				if (CAUSTICS_ENABLED_FIRST || CAUSTICS_ENABLED_ADD) {
					if (GUILayout.Button("Disable caustics (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_CAUSTICS_FIRST=false;
						_RTP_LODmanagerScript.RTP_CAUSTICS_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
					}
					
					GUILayout.Space(15);							
					if (GUILayout.Button("Reset caustics settings numeric params to default")) {
						Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
						_target.ReturnToDefaults("caustics");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh();
					}		
						
				} else {
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable caustics (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_CAUSTICS_FIRST=true;
						_RTP_LODmanagerScript.RTP_CAUSTICS_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
					}
				}						
				
				EditorGUILayout.EndVertical();
					
				#endregion Settings - Caustics
			break;					
				
			case ReliefTerrainSettingsItems.Reflections:
				#region Settings - Reflections
				GUILayout.Space(6);

				EditorGUILayout.BeginVertical("Box");
				skin_color=GUI.color;
				EditorGUILayout.BeginHorizontal();
					EditorGUILayout.LabelField(new GUIContent(icoReflection),  EditorStyles.miniLabel, GUILayout.Width(16), GUILayout.Height(16));
					GUI.color=new Color(1,1,0.5f,1);						
					EditorGUILayout.LabelField("Reflections settings", EditorStyles.boldLabel);
				EditorGUILayout.EndHorizontal();
				GUI.color=skin_color;
				
				if (REFLECTION_ENABLED_FIRST || REFLECTION_ENABLED_ADD) {
					EditorGUILayout.HelpBox("Reflection map, realised as grayscale 2D texture (planar mapped sphere) is put on channel A of combined texture together of Perlin normal map (RG) and wetness mask (B).\n\nWhites are mapped on Reflection Color A (emission), blacks are mapped on Reflection Color B (diffuse blend depending on color alpha).\n\nAmount of reflection is set per layer, taken from view angle (Fresnel like effect), layer specularity (alpha channel of diffuse map) and water on the surface.",MessageType.None, true);
						
					EditorGUILayout.BeginHorizontal();
					Texture2D tmp_tex=_target.TERRAIN_ReflectionMap;
					ntex=tmp_tex;
					checkChange(ref ntex, (Texture2D)EditorGUILayout.ObjectField(_target.TERRAIN_ReflectionMap, typeof(Texture2D), false, GUILayout.MinHeight(90), GUILayout.MinWidth(90), GUILayout.MaxWidth(90)));
					if (ntex!=tmp_tex) {
						Texture2D tex_prev=_target.TERRAIN_ReflectionMap;
						_target.TERRAIN_ReflectionMap=ntex;
						if (ntex) {
							AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(ntex));
							if (_importer) {
								TextureImporter tex_importer=(TextureImporter)_importer;
								if (!tex_importer.isReadable) {
									Debug.LogWarning("Reflection map texture ("+ntex.name+") has been reimported as readable.");
									tex_importer.isReadable=true;
									AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(ntex),  ImportAssetOptions.ForceUpdate);
								}
							}
						}
						if (!_targetRT.PrepareGlobalNormalsAndSuperDetails(false, true)) _target.TERRAIN_ReflectionMap=tex_prev;
						_targetRT.RefreshTextures();
						_target.Refresh();
					}
					ColorChannels nchannel=ColorChannels.R;
					EditorGUILayout.LabelField("channel", GUILayout.MinWidth(60), GUILayout.MaxWidth(60));
					checkChange(ref nchannel, (ColorChannels)EditorGUILayout.EnumPopup(_target.TERRAIN_ReflectionMap_channel));
					if (nchannel!=_target.TERRAIN_ReflectionMap_channel) {
						_target.TERRAIN_ReflectionMap_channel=nchannel;
						_targetRT.PrepareGlobalNormalsAndSuperDetails(false,true);
					}
					EditorGUILayout.EndHorizontal();
						
					checkChange(ref _target.TERRAIN_ReflColorA, EditorGUILayout.ColorField("Reflection color A", _target.TERRAIN_ReflColorA));
					checkChange(ref _target.TERRAIN_ReflColorB, EditorGUILayout.ColorField("Reflection color B", _target.TERRAIN_ReflColorB));
					checkChange(ref _target.TERRAIN_ReflDistortion, EditorGUILayout.Slider("Normal based distortion", _target.TERRAIN_ReflDistortion, 0, 0.1f));
					EditorGUILayout.HelpBox("Reflection map can rotate (imitating clouds moving around), option below can be separately enabled in RTP_LODmanager.",MessageType.None, true);
					if (REFLECTION_ROTATION_ENABLED || REFLECTION_ROTATION_ENABLED) {
						if (GUILayout.Button("Disable reflection rotation (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_ROTATE_REFLECTION=false;
							if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
					} else {
						//EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
						if (GUILayout.Button("Enable reflection rotation (rebuild shaders via RTP_LODmanager)")) {
							_RTP_LODmanagerScript.RTP_ROTATE_REFLECTION=true;
							if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
								Selection.activeObject=_RTP_LODmanagerScript.gameObject;
								_RTP_LODmanagerScript.dont_sync=true;
							}
						}
					}						
					EditorGUI.BeginDisabledGroup(!REFLECTION_ROTATION_ENABLED);
					checkChange(ref _target.TERRAIN_ReflectionRotSpeed, EditorGUILayout.Slider("Rotation speed", _target.TERRAIN_ReflectionRotSpeed, 0, 2));
					EditorGUI.EndDisabledGroup();
					EditorGUILayout.Space();
					checkChange(ref _target.TERRAIN_FresnelPow, EditorGUILayout.Slider("Fresnel exponent", _target.TERRAIN_FresnelPow, 0.5f, 32f));
					checkChange(ref _target.TERRAIN_FresnelOffset, EditorGUILayout.Slider("Fresnel offset", _target.TERRAIN_FresnelOffset, 0, 0.9f));
				}
				GUILayout.Space(15);
				if (REFLECTION_ENABLED_FIRST || REFLECTION_ENABLED_ADD) {
					if (GUILayout.Button("Disable reflection (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_REFLECTION_FIRST=false;
						_RTP_LODmanagerScript.RTP_REFLECTION_ADD=false;
						if (EditorUtility.DisplayDialog("", "Go to RTP manager now (to recompile shaders) ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
					}
					
					GUILayout.Space(15);	
					if (GUILayout.Button("Reset reflection settings numeric params to default")) {
						Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
						_target.ReturnToDefaults("reflection");
						EditorUtility.SetDirty(_targetRT);
						_target.Refresh();
					}	
						
				} else {
					EditorGUILayout.HelpBox("This feature is currently disabled.",MessageType.Warning, true);
					if (GUILayout.Button("Enable reflection (rebuild shaders via RTP_LODmanager)")) {
						_RTP_LODmanagerScript.RTP_REFLECTION_FIRST=true;
						_RTP_LODmanagerScript.RTP_REFLECTION_ADD=true;
						if (EditorUtility.DisplayDialog("", "Feature is DISABLED in shader until you recompile it.\nGo to RTP manager to do it now ?","Yes","No")) {
							Selection.activeObject=_RTP_LODmanagerScript.gameObject;
							_RTP_LODmanagerScript.dont_sync=true;
						}
					}
				}	
				
				EditorGUILayout.EndVertical();
					
				#endregion Settings - Reflections
			break;					
				
			}
			
			GUILayout.Space(8);
			//Begin_Global_Indent();
			if (GUILayout.Button("Reset all numeric params to default")) {
				if (EditorUtility.DisplayDialog("Warning", "Are you sure to reset all RTP numeric values to their defaults ?","Yes","Cancel")) {
					Undo.RegisterUndo(_targetRT, "Undo relief terrain edit");
					_target.ReturnToDefaults();
					EditorUtility.SetDirty(_targetRT);
					_target.Refresh();
				}
			}	
			
			#endregion ALLSettings
		}
		
		if (dirtyFlag) {
			EditorUtility.SetDirty(_targetRT);
			_targetRT.RefreshTextures();				
			_target.Refresh();
		}

		GUILayout.Space(10);
		//DrawDefaultInspector();
		if (_target.activateObject) {
			Selection.activeObject=_target.activateObject;
			_target.activateObject=null;
		}


		Event current = Event.current;
		switch(current.type) {
			case EventType.keyDown:
				if (current.keyCode==KeyCode.M) {
					_target.paint_flag=!_target.paint_flag;
					if (!_targetRT.collider || !_targetRT.collider.enabled) _target.paint_flag=false;
					if (_target.paint_flag) {
						if (_target.submenu!=ReliefTerrainMenuItems.GeneralSettings || (_target.submenu_settings!=ReliefTerrainSettingsItems.GlobalColor && _target.submenu_settings!=ReliefTerrainSettingsItems.Water)) {
							_target.paint_flag=false;
						}
						if (_target.submenu==ReliefTerrainMenuItems.GeneralSettings) {
							if (_target.submenu_settings==ReliefTerrainSettingsItems.Water) {
								if (!_targetRT.PrepareGlobalNormalsAndSuperDetails(true, true)) {
									_target.paint_flag=false;
								}
								_target.paint_wetmask=true;
								_target.paint_alpha_flag=true;
							}
//							if (_target.submenu_settings==ReliefTerrainSettingsItems.GlobalColor) {
//								if (!_target.prepare_tmpTexture(true)) {
//									_target.paint_flag=false;
//								}
//							}							
						}
					}					
					if (_target.paint_flag) {
						Tools.current=Tool.View;
						ReliefTerrain._SceneGUI = new SceneView.OnSceneFunc(CustomOnSceneGUI);
						SceneView.onSceneGUIDelegate += ReliefTerrain._SceneGUI;
					} else {
						Tools.current=prev_tool;
						SceneView.onSceneGUIDelegate -= ReliefTerrain._SceneGUI;
					}
					EditorUtility.SetDirty(target);
				}
			break;
		}			
	}
	
	private void PrepareAtlases(int mask=3) {
		ReliefTerrain _targetRT=(ReliefTerrain)target;
		ReliefTerrainGlobalSettingsHolder _target=_targetRT.globalSettingsHolder;
			
		for(int n=0; n<_target.numLayers; n++) {
			int min_size=9999;
			for(int m=(n/4)*4; (m<((n/4)*4+4)) && (m<_target.numLayers); m++) {
				if (_target.splats[m]) { // czasem może byc błędnie wprowadzony jako null
					if (_target.splats[m].width<min_size) min_size=_target.splats[m].width;
				}
			}		
			AssetImporter _importer=AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(_target.splats[n]));
			if (_importer) {
				TextureImporter tex_importer=(TextureImporter)_importer;
				bool reimport_flag=false;
				if (!tex_importer.isReadable) {
					Debug.LogWarning("Detail texture "+n+" ("+_target.splats[n].name+") has been reimported as readable.");
					tex_importer.isReadable=true;
					reimport_flag=true;
				}
				if (_target.splats[n] && _target.splats[n].width>min_size) {
					Debug.LogWarning("Detail texture "+n+" ("+_target.splats[n].name+") has been reimported with "+min_size+" size.");
					tex_importer.maxTextureSize=min_size;
					reimport_flag=true;
				}
				if (reimport_flag) {
					AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(_target.splats[n]),  ImportAssetOptions.ForceUpdate);
				}
			}					
		}				
		
		int i;
		for(i=0; i<_target.numLayers; i++) {
			try { 
				_target.splats[i].GetPixels(0,0,4,4,0);
			} catch (Exception e) {
				Debug.LogError("Splat texture "+i+" has to be marked as isReadable...");
				Debug.LogError(e.Message);
				return;
			}
		}
		int w=_target.splats[0].width;
		for(i=1; i<_target.numLayers; i++) {
			if (_target.splats[i].width!=w) {
				Debug.LogError("For performance reasons - all splats (detail textures) should have the same size");
				Debug.LogError("Detail tex 0 size="+w+" while detail tex "+i+" size="+_target.splats[i].width);
				return;
			}
		}
				
		ResetProgress( ((mask==3)?(8+2*8):(4+1*8)), "Padding textures" );
				
		int num=_target.numLayers<=8 ? _target.numLayers : 8;
		Texture2D[] splats=new Texture2D[num<=4 ? 4:8];
		for(i=0; i<splats.Length; i++) {
			if (((i<4) && (mask&1)>0) || ((i>=4) && (mask&2)>0)) {
				if (i<num) {
					splats[i]=_target.splats[i];
					splats[i]=PadTex(splats[i], 16);
					CheckProgress();							
				} else {
					splats[i]=new Texture2D(_target.splats[num-1].width, _target.splats[num-1].width);
				}
			}
		}
		progress_description="Packing textures";
				
		if ( ((mask&1)>0) && _target.splat_atlases[0] && AssetDatabase.GetAssetPath(_target.splat_atlases[0])=="") {
			DestroyImmediate(_target.splat_atlases[0]);
		}
		if ( ((mask&2)>0) && _target.splat_atlases[1] && AssetDatabase.GetAssetPath(_target.splat_atlases[1])=="") {
			DestroyImmediate(_target.splat_atlases[1]);
		}
		
		if ((mask&1)>0) {		
			_target.splat_atlases[0]=new Texture2D(splats[0].width*2, splats[0].width*2);
			_target.splat_atlases[0].wrapMode=TextureWrapMode.Clamp;
			_target.splat_atlases[0].PackTextures( new Texture2D[4] { splats[0],splats[1],splats[2],splats[3] } , 0, _target.splat_atlases[0].width, false);
			progress_description="Blending corners";
			CheckProgress();
			//if (splats[0].width<=128) BlendMip(_target.splat_atlases[0], 3, 0.5f);
			//if (splats[0].width<=256) BlendMip(_target.splat_atlases[0], 4, 0.5f);
			//if (splats[0].width<=512) BlendMip(_target.splat_atlases[0], 5, 0.5f);
			BlendMip(_target.splat_atlases[0], 0, 0.5f, 16); BlendMip(_target.splat_atlases[0], 0, 0.5f, 15);
			CheckProgress();					
			BlendMip(_target.splat_atlases[0], 1, 0.5f, 8); BlendMip(_target.splat_atlases[0], 1, 0.5f, 7);
			CheckProgress();					
			BlendMip(_target.splat_atlases[0], 2, 0.5f, 4); BlendMip(_target.splat_atlases[0], 2, 0.5f, 3);
			CheckProgress();					
			BlendMip(_target.splat_atlases[0], 3, 0.5f, 2); BlendMip(_target.splat_atlases[0], 3, 0.5f, 1);
			CheckProgress();					
			BlendMip(_target.splat_atlases[0], 4, 0.5f, 2); BlendMip(_target.splat_atlases[0], 4, 0.5f, 1);
			CheckProgress();					
			BlendMip(_target.splat_atlases[0], 5, 0.5f, 1); BlendMip(_target.splat_atlases[0], 5, 0.5f, 0);
			CheckProgress();					
			for(i=6; i<_target.splat_atlases[0].mipmapCount-2; i++) BlendMip(_target.splat_atlases[0], i, 0.5f);
			progress_description="Packing textures";
			CheckProgress();					
			_target.splat_atlases[0].Compress(true);
			_target.splat_atlases[0].Apply(false,false);
			_target.splat_atlases[0].filterMode=FilterMode.Trilinear;
			_target.splat_atlases[0].anisoLevel=0;
		}
				
		if ( ((mask&2)>0) && (num>4)) {
			_target.splat_atlases[1]=new Texture2D(splats[4].width*2, splats[4].width*2);
			_target.splat_atlases[1].wrapMode=TextureWrapMode.Clamp;
			_target.splat_atlases[1].PackTextures( new Texture2D[4] { splats[4],splats[5],splats[6],splats[7] } , 0, _target.splat_atlases[1].width, false);
			progress_description="Blending corners";
			CheckProgress();					
//			if (splats[0].width<=128) BlendMip(_target.splat_atlases[1], 3, 0.5f);
//			if (splats[0].width<=256) BlendMip(_target.splat_atlases[1], 4, 0.5f);
//			if (splats[0].width<=512) BlendMip(_target.splat_atlases[1], 5, 0.5f);
			BlendMip(_target.splat_atlases[1], 0, 0.5f, 16); BlendMip(_target.splat_atlases[1], 0, 0.5f, 15);
			CheckProgress();
			BlendMip(_target.splat_atlases[1], 1, 0.5f, 8); BlendMip(_target.splat_atlases[1], 1, 0.5f, 7);
			CheckProgress();
			BlendMip(_target.splat_atlases[1], 2, 0.5f, 4); BlendMip(_target.splat_atlases[1], 2, 0.5f, 3);
			CheckProgress();
			BlendMip(_target.splat_atlases[1], 3, 0.5f, 2); BlendMip(_target.splat_atlases[1], 3, 0.5f, 1);
			CheckProgress();
			BlendMip(_target.splat_atlases[1], 4, 0.5f, 2); BlendMip(_target.splat_atlases[1], 4, 0.5f, 1);
			CheckProgress();
			BlendMip(_target.splat_atlases[1], 5, 0.5f, 1); BlendMip(_target.splat_atlases[1], 5, 0.5f, 0);
			CheckProgress();
			for(i=6; i<_target.splat_atlases[1].mipmapCount-2; i++) BlendMip(_target.splat_atlases[1], i, 0.5f);
			CheckProgress();
			_target.splat_atlases[1].Compress(true);
			_target.splat_atlases[1].Apply(false,false);
			_target.splat_atlases[1].filterMode=FilterMode.Trilinear;
			_target.splat_atlases[1].anisoLevel=0;
		}
		for(i=0; i<splats.Length; i++) {
			DestroyImmediate(splats[i]);
		}
		EditorUtility.ClearProgressBar();
				
	}