#	Example:
#
#	example_effect = {
#		add_resource = { energy = -100 }
#	}
#
#
#	In a script file:
#
#	effect = {
#		example_effect = yes
#	}
#

# Debug scope printing
print_scope_effect = {
	log = "------------------------------"
	log = "- Printing the current scopes (effect) -"
	log = "- This: \\[This.GetName]"
	log = "- Root: \\[Root.GetName]"
	log = "- Prev: \\[Prev.GetName]"
	log = "- PrevPrev: \\[PrevPrev.GetName]"
	log = "- PrevPrevPrev: \\[PrevPrevPrev.GetName]"
	log = "- PrevPrevPrevPrev: \\[PrevPrevPrevPrev.GetName]"
	log = "- From: \\[From.GetName]"
	log = "- FromFrom: \\[FromFrom.GetName]"
	log = "- FromFromFrom: \\[FromFromFrom.GetName]"
	log = "- FromFromFromFrom: \\[FromFromFromFrom.GetName]"
	log = "- This's Solar System: \\[This.GetStarName]"
	log = "- This's Planet: \\[This.Planet.GetName]"
	log = "- This's Sector: \\[This.Sector.GetName]"
	log = "- Root's Solar System: \\[Root.GetStarName]"
	log = "- Root's Owner's Name: \\[Root.Owner.GetName]"
	log = "- Root's Owner's Capital's Name: \\[Root.Owner.Capital.GetName]"
	log = "- Owner: \\[Owner.GetName]"
	log = "------------------------------"
}

establish_communication_with_subjects_and_federation = {
	every_subject = {
		limit = {
			NOT = {
				any_agreement = {
					agreement_preset = preset_scion
				}
			}
			NOR = {
				has_communications = prevprev
				has_active_first_contact_with = prevprev
				has_country_flag = $FLAG$
			}
		}
		establish_communications_no_message = prevprev
		set_country_flag = $FLAG$
	}
	every_federation_ally = {
		limit = {
			NOR = {
				has_communications = prevprev
				has_active_first_contact_with = prevprev
				has_country_flag = $FLAG$
			}
		}
		establish_communications_no_message = prevprev
		set_country_flag = $FLAG$
	}
}

# Checks if Subterraneans (player-only event nation) exists
# Creates the country and saves it if it does not
# use in planet scope
create_subterranean_nation = {
	optimize_memory
	if = {
		limit = {
			NOT = {
				any_country = {
					is_country_type = adversary
					has_country_flag = $FLAG$
				}
			}
		}
		create_species = {
			name = random
			class = random_non_machine
			portrait = random
			traits = {
				trait = trait_cave_dweller
				trait = random_traits
			}
			homeworld = root
		}
		create_country = {
			name = "NAME_Subterranean_Nation"
			species = last_created_species
			type = adversary
			ethos = random
			origin = origin_subterranean
			auto_delete = no
			flag = {
				icon = {
					category = "zoological"
					file = "flag_zoological_10.dds"
				}
				background= {
					category = "backgrounds"
					file = "new_dawn.dds"
				}
				colors={
					"red"
					"black"
					"null"
					"null"
				}
			}
			effect = {
				set_relation_flag = {
					who = root.owner
					flag = subterror
				}
				set_country_flag = $FLAG$
				establish_contact = { who = event_target:subterranean_planet_owner location = root }
				establish_communications_no_message = event_target:subterranean_planet_owner
				save_event_target_as = subterranean_nation
				owner_species = { save_event_target_as = subterranean_species }
			}
		}
	}
	else_if = {
		limit = {
			NOT = { exists = event_target:subterranean_nation }
		}
		random_country = {
			limit = {
				is_country_type = adversary
				has_country_flag = $FLAG$
			}
			save_event_target_as = subterranean_nation
		}
	}
}

# Checks if Pirate country (global event target) exists
# Creates the country and saves it if it does not
create_pirate_country = {
	optimize_memory
	if = {
		limit = {
			NOT = {
				exists = event_target:pirate_country
			}
		}
		create_country = {
			name = "NAME_Privateers"
			name_list = "PRT1"
			species = random
			type = pirate
			flag = {
				background = {
					category = "backgrounds"
					file = "00_solid.dds"
				}
				colors ={
					"black"
					"black"
					"null"
					"null"
				}
			}
			effect = {
				save_global_event_target_as = pirate_country
				randomize_flag_symbol = "pirate"
			}
		}
	}
}

# Change planet class one step up in temperature
increase_planet_temperature = {
	if = {
		limit = { is_planet_class = pc_barren }
		change_pc = pc_molten
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_desert }
		change_pc = pc_molten
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_arid }
		change_pc = pc_barren
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_savannah }
		change_pc = pc_barren
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_ocean }
		change_pc = pc_desert
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_continental }
		change_pc = pc_arid
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_tropical }
		change_pc = pc_savannah
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_arctic }
		change_pc = pc_ocean
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_alpine }
		change_pc = pc_continental
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_tundra }
		change_pc = pc_tropical
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_barren_cold }
		change_pc = pc_tundra
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_frozen }
		change_pc = pc_arctic
		reroll_planet = yes
		clear_blockers = yes
	}
}

# Change planet class one step down in temperature
decrease_planet_temperature = {
	if = {
		limit = { is_planet_class = pc_molten }
		change_pc = pc_desert
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_barren }
		change_pc = pc_arid
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_desert }
		change_pc = pc_ocean
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_arid }
		change_pc = pc_continental
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_savannah }
		change_pc = pc_tropical
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_ocean }
		change_pc = pc_arctic
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_continental }
		change_pc = pc_alpine
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_tropical }
		change_pc = pc_tundra
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_arctic }
		change_pc = pc_frozen
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_alpine }
		change_pc = pc_frozen
		reroll_planet = yes
		clear_blockers = yes
	}
	else_if = {
		limit = { is_planet_class = pc_tundra }
		random_list = {
			50 = { change_pc = pc_frozen }
			50 = { change_pc = pc_barren_cold }
		}
		reroll_planet = yes
		clear_blockers = yes
	}
}

spawn_sun_temperature_effect = {
	if = {
		limit = { is_planet_class = pc_g_star }
		create_ambient_object = {
			location = this
			type = yellow_sun_grow_particle_object
			duration = 1

			use_3d_location= yes

			entity_offset = { min = 0 max = 0 }
			entity_offset_angle = { min = 0 max = 360 }
			entity_offset_height = { min = 0 max = 0 }

			entity_scale_to_size = yes
			scale = 0.01
		}
	}
	else_if = {
		limit = {
			OR = {
				is_planet_class = pc_k_star
				is_planet_class = pc_m_star
			}
		}
		create_ambient_object = {
			location = this
			type = red_sun_grow_particle_object
			duration = 1

			use_3d_location= yes

			entity_offset = { min = 0 max = 0 }
			entity_offset_angle = { min = 0 max = 360 }
			entity_offset_height = { min = 0 max = 0 }

			entity_scale_to_size = yes
			scale = 0.01
		}
	}
	else_if = {
		limit = {
			OR = {
				is_planet_class = pc_b_star
				is_planet_class = pc_a_star
				is_planet_class = pc_f_star
				is_planet_class = pc_pulsar
				is_planet_class = pc_neutron_star
			}
		}
		create_ambient_object = {
			location = this
			type = blue_sun_grow_particle_object
			duration = 1

			use_3d_location= yes

			entity_offset = { min = 0 max = 0 }
			entity_offset_angle = { min = 0 max = 360 }
			entity_offset_height = { min = 0 max = 0 }

			entity_scale_to_size = yes
			scale = 0.01
		}
	}
}

spawn_planet_temperature_effect = {
	create_ambient_object = {
		location = this
		type = planet_heat_up_particle_object
		duration = 30

		use_3d_location= yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.15
	}
}

spawn_planet_temperature_effect2 = {
	create_ambient_object = {
		location = this
		#type = planet_heat_up_particle_object
		type = blue_sun_grow_particle_object
		duration = 3

		use_3d_location= yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.03
	}
}

create_curator_guardian_poi = {
	root = {
		if = {
			limit = {
				NOT = {
					has_event_chain = curator_poi_chain
				}
			}
			begin_event_chain = {
				event_chain = curator_poi_chain
				target = this
			}
		}
		create_point_of_interest = {
			id = $POI$
			name = curator_poi_title
			desc = curator_poi_desc
			event_chain = curator_poi_chain
			location = prevprevprev
		}
	}
}

end_curator_chain = {
	if = {
		limit = {
			has_event_chain = curator_poi_chain
			NOR = {
				has_point_of_interest = { poi = curator_poi_dragon }
				has_point_of_interest = { poi = curator_poi_technosphere }
				has_point_of_interest = { poi = curator_poi_wraith }
				has_point_of_interest = { poi = curator_poi_horror }
				has_point_of_interest = { poi = curator_poi_fortress }
				has_point_of_interest = { poi = curator_poi_hiver }
				has_point_of_interest = { poi = curator_poi_stellarite }
				has_point_of_interest = { poi = curator_poi_dreadnought }
				has_point_of_interest = { poi = curator_poi_hatchling }
				has_point_of_interest = { poi = curator_poi_tiyanki }
				has_point_of_interest = { poi = curator_poi_scavenger_bot }
				has_point_of_interest = { poi = curator_poi_opus_sentinel }
			}
		}
		end_event_chain = curator_poi_chain
	}
}

make_intelligent = {
	if = {
		limit = { pop_group_has_trait = trait_intelligent }
		# nothing
	}
	else = {
		limit = { is_robot_pop_group = no }
		# remove opposite traits
		if = {
			limit = { pop_group_has_trait = trait_nerve_stapled }
			modify_species = {
				species = this
				remove_trait = trait_nerve_stapled
			}
		}
		if = {
			limit = { pop_group_has_trait = trait_erudite }
			modify_species = {
				species = this
				remove_trait = trait_erudite
			}
		}
		if = {
			limit = { pop_group_has_trait = trait_enigmatic_intelligence }
			modify_species = {
				species = this
				remove_trait = trait_enigmatic_intelligence
			}
		}
		if = {
			limit = { pop_group_has_trait = trait_enigmatic_intelligence_poor }
			modify_species = {
				species = this
				remove_trait = trait_enigmatic_intelligence_poor
			}
		}
		# add trait
		modify_species = {
			species = this
			add_trait = trait_intelligent
		}
	}
	#add machine trait
	if = {
		limit = { pop_group_has_trait = trait_robot_logic_engines }
		# nothing
	}
	else = {
		limit = { is_robot_pop_group = yes }
		# no opposites
		modify_species = {
			species = this
			add_trait = trait_robot_logic_engines
		}
	}
}

make_resilient = {
	if = {
		limit = { pop_group_has_trait = trait_resilient }
		# nothing
	}
	else = {
		limit = { is_robot_pop_group = no }
		# no opposites
		modify_species = {
			species = this
			add_trait = trait_resilient
		}
	}
	#add machine trait
	if = {
		limit = { pop_group_has_trait = trait_robot_durable }
		# nothing
	}
	else = {
		limit = { is_robot_pop_group = yes }
		# remove opposite traits
		if = {
			limit = { pop_group_has_trait = trait_robot_high_maintenance }
			modify_species = {
				species = this
				remove_trait = trait_robot_high_maintenance
			}
		}
		# add trait
		modify_species = {
			species = this
			add_trait = trait_robot_durable
		}
	}
}

 ##create a subspecies with the Intelligent and Fanatically Pacifist traits, and remove Militarist or Fanatically Militarist
make_unleashed_messenger = {
	if = {
		limit = { root = { is_species_class = ART } }
		if = {
			limit = { NOT = { root = { species_portrait = art11 } } }
			modify_species = { portrait = art11 }
		}
		else = { modify_species = { portrait = art10 } }
	}
	else_if = {
		limit = { root = { is_species_class = MAM } }
		if = {
			limit = { NOT = { root = { species_portrait = mam10 } } }
			modify_species = { portrait = mam10 }
		}
		else = { modify_species = { portrait = mam13 } }
	}
	else_if = {
		limit = { root = { is_species_class = FUN } }
		if = {
			limit = { NOT = { root = { species_portrait = fun12 } } }
			modify_species = { portrait = fun12 }
		}
		else = { modify_species = { portrait = fun10 } }
	}
	else_if = {
		limit = { root = { is_species_class = HUM } }
		if = {
			limit = { NOT = { root = { species_portrait = humanoid_04 } } }
			modify_species = { portrait = humanoid_04 }
		}
		else = { modify_species = { portrait = humanoid_03 } }
	}
	else_if = {
		limit = { root = { is_species_class = MOL } }
		if = {
			limit = { NOT = { root = { species_portrait = mol11 } } }
			modify_species = { portrait = mol11 }
		}
		else = { modify_species = { portrait = mol12 } }
	}
	else_if = {
		limit = { root = { is_species_class = PLANT } }
		if = {
			limit = { NOT = { root = { species_portrait = pla15 } } }
			modify_species = { portrait = pla15 }
		}
		else = { modify_species = { portrait = pla10 } }
	}
	else_if = {
		limit = { root = { is_species_class = REP } }
		if = {
			limit = { NOT = { root = { species_portrait = rep8 } } }
			modify_species = { portrait = rep8 }
		}
		else = { modify_species = { portrait = rep4 } }
	}
	else_if = {
		limit = { root = { is_species_class = AVI } }
		if = {
			limit = { NOT = { root = { species_portrait = avi1 } } }
			modify_species = { portrait = avi1 }
		}
		else = { modify_species = { portrait = avi4 } }
	}
	else_if = {
		limit = { root = { is_species_class = LITHOID } }
		if = {
			limit = { NOT = { root = { species_portrait = lith10 } } }
			modify_species = { portrait = lith10 }
		}
		else = { modify_species = { portrait = lith4 } }
	}
	else_if = {
		limit = { root = { is_species_class = NECROID } }
		if = {
			limit = { NOT = { root = { species_portrait = nec12 } } }
			modify_species = { portrait = nec12 }
		}
		else = { modify_species = { portrait = nec11 } }
	}
	else_if = {
		limit = { root = { is_species_class = AQUATIC } }
		if = {
			limit = { NOT = { root = { species_portrait = aqu4 } } }
			modify_species = { portrait = aqu4 }
		}
		else = { modify_species = { portrait = aqu7 } }
	}
	else_if = {
		limit = { root = { is_species_class = TOX } }
		if = {
			limit = { NOT = { root = { species_portrait = tox5 } } }
			modify_species = { portrait = tox5 }
		}
		else = { modify_species = { portrait = tox8 } }
	}
}

make_leashed_messenger = {
	if = {
		limit = { root = { is_species_class = ART } }
		if = {
			limit = { NOT = { root = { species_portrait = art11 } } }
			modify_species = { portrait = art11 }
		}
		else = { modify_species = { portrait = art10 } }
	}
	else_if = {
		limit = { root = { is_species_class = MAM } }
		if = {
			limit = { NOT = { root = { species_portrait = mam10 } } }
			modify_species = { portrait = mam10 }
		}
		else = { modify_species = { portrait = mam13 } }
	}
	else_if = {
		limit = { root = { is_species_class = FUN } }
		if = {
			limit = { NOT = { root = { species_portrait = fun12 } } }
			modify_species = { portrait = fun12 }
		}
		else = { modify_species = { portrait = fun10 } }
	}
	else_if = {
		limit = { root = { is_species_class = HUM } }
		if = {
			limit = { NOT = { root = { species_portrait = humanoid_04 } } }
			modify_species = { portrait = humanoid_04 }
		}
		else = { modify_species = { portrait = humanoid_03 } }
	}
	else_if = {
		limit = { root = { is_species_class = MOL } }
		if = {
			limit = { NOT = { root = { species_portrait = mol11 } } }
			modify_species = { portrait = mol11 }
		}
		else = { modify_species = { portrait = mol12 } }
	}
	else_if = {
		limit = { root = { is_species_class = PLANT } }
		if = {
			limit = { NOT = { root = { species_portrait = pla15 } } }
			modify_species = { portrait = pla15 }
		}
		else = { modify_species = { portrait = pla10 } }
	}
	else_if = {
		limit = { root = { is_species_class = REP } }
		if = {
			limit = { NOT = { root = { species_portrait = rep8 } } }
			modify_species = { portrait = rep8 }
		}
		else = { modify_species = { portrait = rep4 } }
	}
	else_if = {
		limit = { root = { is_species_class = AVI } }
		if = {
			limit = { NOT = { root = { species_portrait = avi1 } } }
			modify_species = { portrait = avi1 }
		}
		else = { modify_species = { portrait = avi4 } }
	}
	else_if = {
		limit = { root = { is_species_class = LITHOID } }
		if = {
			limit = { NOT = { root = { species_portrait = lith10 } } }
			modify_species = { portrait = lith10 }
		}
		else = { modify_species = { portrait = lith4 } }
	}
	else_if = {
		limit = { root = { is_species_class = NECROID } }
		if = {
			limit = { NOT = { root = { species_portrait = nec12 } } }
			modify_species = { portrait = nec12 }
		}
		else = { modify_species = { portrait = nec11 } }
	}
	else_if = {
		limit = { root = { is_species_class = AQUATIC } }
		if = {
			limit = { NOT = { root = { species_portrait = aqu4 } } }
			modify_species = { portrait = aqu4 }
		}
		else = { modify_species = { portrait = aqu7 } }
	}
	else_if = {
		limit = { root = { is_species_class = TOX } }
		if = {
			limit = { NOT = { root = { species_portrait = tox5 } } }
			modify_species = { portrait = tox5 }
		}
		else = { modify_species = { portrait = tox8 } }
	}
}


collector_surrenders_artifact = {
	if = {
		limit = { has_event_chain = "vultaum_chain" }
		add_event_chain_counter = {
			event_chain = "vultaum_chain"
			counter = "vultaum_artifacts"
			amount = 1
		}
		hidden_effect = {
			country_event = { id = precursor.97 }
		}
		break = yes
	}
	if = {
		limit = { has_event_chain = "yuht_chain" }
		add_event_chain_counter = {
			event_chain = "yuht_chain"
			counter = "yuht_artifacts"
			amount = 1
		}
		hidden_effect = {
			country_event = { id = precursor.597 }
		}
		break = yes
	}
	if = {
		limit = { has_event_chain = "first_league_chain" }
		add_event_chain_counter = {
			event_chain = "first_league_chain"
			counter = "first_league_artifacts"
			amount = 1
		}
		hidden_effect = {
			country_event = { id = precursor.1097 }
		}
		break = yes
	}
	if = {
		limit = { has_event_chain = "irassian_chain" }
		add_event_chain_counter = {
			event_chain = "irassian_chain"
			counter = "irassian_artifacts"
			amount = 1
		}
		hidden_effect = {
			country_event = { id = precursor.1597 }
		}
		break = yes
	}
	if = {
		limit = { has_event_chain = "cybrex_chain" }
		add_event_chain_counter = {
			event_chain = "cybrex_chain"
			counter = "cybrex_artifacts"
			amount = 1
		}
		hidden_effect = {
			country_event = { id = precursor.2103 }
		}
		break = yes
	}
}

reset_planet = {
	clear_planet_modifiers = yes
	reroll_deposits = yes
}

reroll_planet = {
	reroll_deposits = yes
	reroll_planet_modifiers = yes
}

# Given a species, create a mod with trait_cybernetic and apply to all pops, leaders
# and armies that have the original species and the same owner as the scope object.
# Scope: Something that has a species and an owner
create_cybernetic_species_mod = {
	species = {
		modify_species = {
			remove_trait = trait_latent_psionic
			remove_trait = trait_psionic
			effect = {
				create_species = {
					is_mod = yes
					name = this
					plural = this
					class = this
					portrait = this
					traits = this
					can_be_modified = this
					homeworld = this
					namelist = this
					gender = this
					traits = {
						ideal_planet_class = this
						trait = trait_cybernetic
					}
				}
			}
		}
		save_event_target_as = changing_species
	}

	owner = {
		every_owned_pop_group = {
			limit = { is_exact_same_species = event_target:changing_species }
			change_species = last_created_species
		}
		every_owned_leader = {
			limit = { is_exact_same_species = event_target:changing_species }
			change_species = last_created_species
		}
		every_pool_leader = {
			limit = { is_exact_same_species = event_target:changing_species }
			change_species = last_created_species
		}
		every_envoy = {
			limit = { is_exact_same_species = event_target:changing_species }
			change_species = last_created_species
		}
		every_owned_army = {
			limit = {
				exists = species
				is_exact_same_species = event_target:changing_species
			}
			change_species = last_created_species
		}
		every_controlled_ship = {
			limit = {
				is_ship_class = shipclass_colonizer
				is_exact_same_species = event_target:changing_species
			}
			change_species = last_created_species
		}
	}
}

create_nuked_species_mod = {
	species = {
		modify_species = {
			effect = {
				create_species = {
					is_mod = yes
					name = this
					plural = this
					class = this
					portrait = this
					traits = this
					can_be_modified = this
					homeworld = this
					namelist = this
					gender = this
					traits = {
						trait = trait_survivor
					}
				}
			}
		}
		save_event_target_as = changing_species
	}

	owner = {
		every_owned_pop_group = {
			limit = { is_exact_same_species = event_target:changing_species }
			change_species = last_created_species
		}
		every_owned_leader = {
			limit = { is_exact_same_species = event_target:changing_species }
			change_species = last_created_species
		}
		every_pool_leader = {
			limit = { is_exact_same_species = event_target:changing_species }
			change_species = last_created_species
		}
		every_envoy = {
			limit = { is_exact_same_species = event_target:changing_species }
			change_species = last_created_species
		}
		every_owned_army = {
			limit = {
				exists = species
				is_exact_same_species = event_target:changing_species
			}
			change_species = last_created_species
		}
		every_controlled_ship = {
			limit = {
				is_ship_class = shipclass_colonizer
				is_exact_same_species = event_target:changing_species
			}
			change_species = last_created_species
		}
	}
}

set_all_comms_surveyed = {
	every_country = {
		limit = {
			has_communications = from
		}
		prev = {
			set_surveyed = {
				surveyed = yes
				surveyor = Prev
			}
		}
	}
}

# AI Crisis Planet Defense plus Armies
create_ai_planet_defense = {
	create_fleet = {
		name = "NAME_AI_Core"
		effect = {
			set_owner = event_target:AI_crisis
			create_ship = {
				name = random
				design = "NAME_AI_Core"
				graphical_culture = "ai_01"
			}
			set_location = {
				target = root
				distance = 10
				angle = random
			}
		}
	}
	owner = {
		create_leader = {
			class = commander
			species = event_target:contingency_bot
			name = random
			skill = 3
			effect = {
				set_age = 0
				save_event_target_as = contingency_fleet_leader
			}
		}
	}
	create_fleet = {
		effect = {
			set_owner = event_target:AI_crisis
			while = {
				count = 16
				create_ship = {
					name = random
					design = "NAME_Euthanizer"
					graphical_culture = "ai_01"
				}
			}
			assign_leader = event_target:contingency_fleet_leader
			while = {
				count = 35
				create_ship = {
					name = random
					design = "NAME_Sterilizer"
					graphical_culture = "ai_01"
				}
			}
			set_location = {
				target = root
				distance = 45
				angle = random
			}
			set_fleet_bombardment_stance = armageddon
		}
		settings = {
			garrison = yes
		}
	}
	create_fleet = {
		effect = {
			set_owner = event_target:AI_crisis
			while = {
				count = 20
				create_army_transport = {
					graphical_culture = "ai_01"
					army_type = "robotic_army"
				}
			}
			set_location = {
				target = root
				distance = 45
				angle = random
			}
		}
	}
	create_fleet = {
		effect = {
			set_owner = event_target:AI_crisis
			create_ship = {
				name = random
				design = "NAME_AI_Constructor"
				graphical_culture = "ai_01"
			}
			set_location = {
				target = root
				distance = 45
				angle = random
			}
		}
	}
	create_fleet = {
		effect = {
			set_owner = event_target:AI_crisis
			create_ship = {
				name = random
				design = "NAME_AI_Constructor"
				graphical_culture = "ai_01"
			}
			set_location = {
				target = root
				distance = 45
				angle = random
			}
		}
	}
	create_fleet = {
		effect = {
			set_owner = event_target:AI_crisis
			create_ship = {
				name = random
				design = "NAME_AI_Constructor"
				graphical_culture = "ai_01"
			}
			set_location = {
				target = root
				distance = 45
				angle = random
			}
		}
	}
}

create_ai_armies = {
	create_fleet = {
		effect = {
			set_owner = event_target:AI_crisis
			while = {
				count = 20
				create_army_transport = {
					graphical_culture = "ai_01"
					army_type = "robotic_army"
				}
			}
			set_location = {
				target = root
				distance = 45
				angle = random
			}
		}
	}
	create_fleet = {
		effect = {
			set_owner = event_target:AI_crisis
			while = {
				count = 20
				create_army_transport = {
					graphical_culture = "ai_01"
					army_type = "robotic_army"
				}
			}
			set_location = {
				target = root
				distance = 45
				angle = random
			}
		}
	}
}

create_ai_constructors = {
	if = {
		limit = {
			event_target:AI_crisis = {
				count_controlled_ship = {
					limit = { is_ship_size = construction_ship_ai }
					count < 5
				}
			}
		}
		create_fleet = {
			effect = {
				set_owner = event_target:AI_crisis
				create_ship = {
					name = random
					design = "NAME_AI_Constructor"
					graphical_culture = "ai_01"
				}
				set_location = {
					target = root
					distance = 45
					angle = random
				}
			}
		}
	}
}

create_ai_fleet = {
	owner = {
		create_leader = {
			class = commander
			species = event_target:contingency_bot
			name = random
			skill = 3
			effect = {
				set_age = 0
				save_event_target_as = contingency_fleet_leader
			}
		}
	}
	create_fleet = {
		effect = {
			set_owner = event_target:AI_crisis
			while = {
				count = 5
				create_ship = {
					name = random
					design = "NAME_Euthanizer"
					graphical_culture = "ai_01"
				}
			}
			assign_leader = event_target:contingency_fleet_leader
			while = {
				count = 10
				create_ship = {
					name = random
					design = "NAME_Sterilizer"
					graphical_culture = "ai_01"
				}
			}
			set_location = {
				target = root
				distance = 45
				angle = random
			}
			set_fleet_bombardment_stance = armageddon
		}
	}
}

create_unbidden_fleet = {
	event_target:extradimensionals = {
		random_list = {
			25 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
					traits = {
						trait = leader_trait_ethereal
					}
				}
			}
			25 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
					traits = {
						trait = leader_trait_dimensional_stutter
					}
				}
			}
			50 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
				}
			}
		}
		create_fleet = {
			effect = {
				set_owner = PREV
				create_ship = {
					name = random
					design = "NAME_Revenant"
					graphical_culture = "extra_dimensional_01"
				}
				assign_leader = last_created_leader
				while = {
					count = 3
					create_ship = {
						name = random
						design = "NAME_Revenant"
						graphical_culture = "extra_dimensional_01"
					}
				}
				while = {
					count = 5
					create_ship = {
						name = random
						design = "NAME_Phantom"
						graphical_culture = "extra_dimensional_01"
					}
				}
				while = {
					count = 9
					create_ship = {
						name = random
						design = "NAME_Wraith"
						graphical_culture = "extra_dimensional_01"
					}
				}
				set_location = {
					target = ROOT
					distance = 5
					angle = random
				}
				set_fleet_stance = aggressive
				set_aggro_range = 500
				set_aggro_range_measure_from = self
				set_fleet_bombardment_stance = armageddon
			}
		}
	}
}

create_aberrant_fleet = {
	event_target:extradimensionals2 = {
		# Create Admiral
		random_list = {
			25 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
					traits = {
						trait = leader_trait_ethereal
					}
				}
			}
			25 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
					traits = {
						trait = leader_trait_dimensional_stutter
					}
				}
			}
			50 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
				}
			}
		}

		# Create Fleet
		create_fleet = {
			effect = {
				set_owner = ROOT
				create_ship = {
					name = random
					design = "NAME_Huntress"
					graphical_culture = "extra_dimensional_02"
				}
				assign_leader = last_created_leader
				while = {
					count = 3
					create_ship = {
						name = random
						design = "NAME_Huntress"
						graphical_culture = "extra_dimensional_02"
					}
				}
				while = {
					count = 5
					create_ship = {
						name = random
						design = "NAME_Assassin"
						graphical_culture = "extra_dimensional_02"
					}
				}
				while = {
					count = 10
					create_ship = {
						name = random
						design = "NAME_Predator"
						graphical_culture = "extra_dimensional_02"
					}
				}
				set_location = {
					target = event_target:dimensional_portal
					distance = 5
					angle = random
				}
				set_fleet_stance = aggressive
				set_aggro_range = 500
				set_aggro_range_measure_from = self
				set_fleet_bombardment_stance = armageddon
			}
		}
	}
}

create_vehement_fleet = {
	event_target:extradimensionals3 = {
		# Create Admiral
		random_list = {
			25 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
					traits = {
						trait = leader_trait_ethereal
					}
				}
			}
			25 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
					traits = {
						trait = leader_trait_dimensional_stutter
					}
				}
			}
			50 = {
				create_leader = {
					class = commander
					species = event_target:extradimensional_species
					name = random
					skill = 3
				}
			}
		}

		# Create Fleet
		create_fleet = {
			effect = {
				set_owner = ROOT
				create_ship = {
					name = random
					design = "NAME_Eradicator"
					graphical_culture = "extra_dimensional_03"
				}
				assign_leader = last_created_leader
				while = {
					count = 3
					create_ship = {
						name = random
						design = "NAME_Eradicator"
						graphical_culture = "extra_dimensional_03"
					}
				}
				while = {
					count = 5
					create_ship = {
						name = random
						design = "NAME_Annihilator"
						graphical_culture = "extra_dimensional_03"
					}
				}
				while = {
					count = 10
					create_ship = {
						name = random
						design = "NAME_Obliterator"
						graphical_culture = "extra_dimensional_03"
					}
				}
				set_location = {
					target = event_target:dimensional_portal
					distance = 5
					angle = random
				}
				set_fleet_stance = aggressive
				set_aggro_range = 500
				set_aggro_range_measure_from = self
				set_fleet_bombardment_stance = armageddon
			}
		}
	}
}

#Used for setting up breakaway machine empires. Not suitable for event rewards.
# this = country
add_500_unity_per_year_passed = {
	add_resource = {
		unity = 500
		mult = trigger:years_passed
	}
}

set_crisis_stage_1 = {
	set_global_flag = crisis_stage_1
	remove_global_flag = crisis_stage_2
	remove_global_flag = crisis_stage_3
	remove_global_flag = crisis_stage_4
}

set_crisis_stage_2 = {
	remove_global_flag = crisis_stage_1
	set_global_flag = crisis_stage_2
	remove_global_flag = crisis_stage_3
	remove_global_flag = crisis_stage_4
}

set_crisis_stage_3 = {
	remove_global_flag = crisis_stage_1
	remove_global_flag = crisis_stage_2
	set_global_flag = crisis_stage_3
	remove_global_flag = crisis_stage_4
}

set_crisis_stage_4 = {
	remove_global_flag = crisis_stage_1
	remove_global_flag = crisis_stage_2
	remove_global_flag = crisis_stage_3
	set_global_flag = crisis_stage_4
}

end_crisis = {
	remove_global_flag = crisis_stage_1
	remove_global_flag = crisis_stage_2
	remove_global_flag = crisis_stage_3
	remove_global_flag = crisis_stage_4
	multiply_crisis_strength = 2
}

# this = pop
remove_hive_minded = {
	if = {
		limit = { has_trait = trait_hive_mind }
		modify_species = {
			species = this
			remove_trait = trait_hive_mind
			change_scoped_species = yes
		}
	}
}

# this = pop
remove_self_modified = {
	if = {
		limit = { has_trait = trait_self_modified }
		modify_species = {
			species = this
			remove_trait = trait_self_modified
			change_scoped_species = yes
		}
	}
}

#deprecated
remove_culture_shock = {
	if = {
		limit = { has_modifier = culture_shock_stone_age }
		remove_modifier = culture_shock_stone_age
	}
	if = {
		limit = { has_modifier = culture_shock_bronze_age }
		remove_modifier = culture_shock_bronze_age
	}
	if = {
		limit = { has_modifier = culture_shock_iron_age }
		remove_modifier = culture_shock_iron_age
	}
	if = {
		limit = { has_modifier = culture_shock_late_medieval_age }
		remove_modifier = culture_shock_late_medieval_age
	}
	if = {
		limit = { has_modifier = culture_shock_renaissance_age }
		remove_modifier = culture_shock_renaissance_age
	}
	if = {
		limit = { has_modifier = culture_shock_steam_age }
		remove_modifier = culture_shock_steam_age
	}
	if = {
		limit = { has_modifier = culture_shock_industrial_age }
		remove_modifier = culture_shock_industrial_age
	}
	if = {
		limit = { has_modifier = culture_shock_machine_age }
		remove_modifier = culture_shock_machine_age
	}
	if = {
		limit = { has_modifier = culture_shock_atomic_age }
		remove_modifier = culture_shock_atomic_age
	}
	if = {
		limit = { has_modifier = culture_shock_early_space_age }
		remove_modifier = culture_shock_early_space_age
	}
	if = {
		limit = {
			planet = {
				NOT = {
					any_owned_pop_group = {
						NOR = {
							pop_group_has_trait = trait_hive_mind
							pop_group_has_trait = trait_cybernetic
							pop_group_has_trait = trait_machine_unit
						}
					}
				}
			}
		}
		planet = {
			remove_modifier = planet_culture_shock
		}
	}
}

nuke_pre_ftls_effect = {
	destroy_colony = yes
	set_carrier_flag = pre_ftls_nuked_themselves
	if = {
		limit = {
			is_artificial = no
		}
		change_pc = pc_nuked
		reroll_planet = yes
		remove_all_buildings = yes
		add_deposit = d_metal_boneyard
		set_planet_flag = nuked_planet_anomalies_disabled
	}
}

nuke_pre_ftls_toxic_effect = {
	destroy_colony = yes
	if = {
		limit = {
			is_artificial = no
		}
		change_pc = pc_toxic
		set_deposit = d_society_3
		if = {
			limit = {
				has_toxoids = yes
			}
			set_carrier_flag = toxic_terraforming_candidate
			add_modifier = {
				modifier = toxic_terraforming_candidate
			}
		}
	}
	reset_planet = yes
	add_modifier = {
		modifier = "nuclear_devastation"
		days = -1
	}
}

# (Pre-FTL) planet scope | owner = pre-FTL country
nuke_pre_ftls_stone_age_effect = {
	every_owned_pop_group = {
		limit = { is_robotic_species = yes }
		kill_single_pop = yes
	}
	while = {
		limit = {
			pop_amount > 200
		}
		random_owned_pop_group = {
			kill_single_pop = yes
		}
	}
	owner = {
		if = {
			limit = {
				NOT = {
					has_pre_ftl_age = stone_age
				}
			}
			set_pre_ftl_age_effect = {
				PRE_FTL_AGE = stone_age
			}
		}
	}
	if = {
		limit = {
			is_artificial = no
		}
		owner = {
			set_origin = origin_post_apocalyptic
			# Propagate a new, 'Survivor' Trait species based on the existing pre-FTL one
			weighted_random_owned_pop_group = {
				limit = { is_exact_same_species = prev }
				create_nuked_species_mod = yes
			}
			change_dominant_species = { species = event_target:changing_species }
			set_awareness = 0
		}
		change_pc = pc_nuked
		reroll_planet = yes
		owner = {
			add_pre_ftl_buildings = yes
		}
		add_deposit = d_metal_boneyard
		set_planet_flag = nuked_planet_anomalies_disabled
	}
}

# This is called once per 5 pops in apply_post_assimilation_effects
generate_cyborg_treats = {
	if = {
		limit = {
			has_assimilator_cybernetics_adopt = yes
			OR = {
				has_government = gov_memory_aggregator
				AND = {
					has_origin = origin_nomadic_purger
					overlord? = { has_government = gov_memory_aggregator }
				}
			}
		}
		add_monthly_resource_mult = {
			resource = unity
			value = 1
			min = 0.25
			max = 12.5
		}
		add_monthly_resource_mult = {
			resource = society_research
			value = 1
			min = 0.25
			max = 12.5
		}
		add_monthly_resource_mult = {
			resource = engineering_research
			value = 2
			min = 0.25
			max = 12.5
		}
	}
	else_if = {
		limit = {
			has_assimilator_cybernetics_adopt = yes
			NOR = {
				has_government = gov_memory_aggregator
				AND = {
					has_origin = origin_nomadic_purger
					overlord? = { has_government = gov_memory_aggregator }
				}
			}
		}
		add_monthly_resource_mult = {
			resource = unity
			value = 1
			min = 0.25
			max = 8.75
		}
		add_monthly_resource_mult = {
			resource = society_research
			value = 1
			min = 0.25
			max = 8.75
		}
		add_monthly_resource_mult = {
			resource = engineering_research
			value = 2
			min = 0.5
			max = 8.75
		}
	}
	else = {
		add_monthly_resource_mult = {
			resource = unity
			value = 1
			min = 0.25
			max = 5
		}
		add_monthly_resource_mult = {
			resource = society_research
			value = 1
			min = 0.25
			max = 5
		}
	}
}

create_contingency_starbase = {
	create_starbase = {
		size = starbase_ai
		owner = event_target:AI_crisis
	}
}

country_syndaw545_in_days = {
	random_owned_planet = {
		limit = {
			is_occupied_flag = no
			any_owned_pop_group = {
				has_trait = trait_mechanical
			}
		}
		carrier_event = { id = syndaw.545 days = $DAYS$ random = $DAYS$ }
	}
}

country_cleanup_syndaw_situation = {
	remove_modifier = syndaw_research_bonus
	remove_modifier = syndaw_production_surplus
	if = {
		limit = { has_special_project = PROJECT_MACHINE_UPRISING_PATCH }
		abort_special_project = { type = PROJECT_MACHINE_UPRISING_PATCH }
	}
	if = {
		limit = { has_special_project = PROJECT_MACHINE_UPRISING_WIPE }
		abort_special_project = { type = PROJECT_MACHINE_UPRISING_WIPE }
	}
	end_event_chain = "machine_uprising_chain"
}

# Planet Cracker effect
spawn_habitat_cracker_effect = {
	create_ambient_object = {
		location = this
		type = habitat_cracker_object
		play_animation_once = yes
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
	save_event_target_as = target_habitat
	solar_system = {
		spawn_megastructure = {
			type = habitat_central_complex_ruined
			owner = this.owner
			coords_from = PREV
		}
		random_system_planet = {
			limit = {
				has_planet_flag = habitat@event_target:target_habitat
			}
			remove_planet_flag = habitat@event_target:target_habitat
			set_planet_flag = habitat_build_site
		}
		every_fleet_in_system = {
			limit = {
				is_ship_class = shipclass_habitat_station
			}
			orbit = {
				remove_planet_flag = has_megastructure
			}
			delete_fleet = this
		}
	}
	remove_planet = yes
}

spawn_lathe_cracker_effect = {
	create_ambient_object = {
		location = this
		type = habitat_cracker_object
		play_animation_once = yes
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
	save_event_target_as = target_lathe
	solar_system = {
		spawn_megastructure = {
			type = cosmogenesis_world_ruined
			owner = this.owner
			coords_from = PREV
		}
		random_system_planet = {
			limit = {
				has_planet_flag = has_cosmogenesis_world
			}
			remove_planet_flag = has_cosmogenesis_world
			remove_planet_flag = has_megastructure
		}
	}
	remove_planet = yes
	random_country = {
		limit = {
			has_country_flag = cosmogenesis_world_built
			NOT = {
				any_owned_planet = {
					is_planet_class = pc_cosmogenesis_world
				}
			}
		}
		remove_country_flag = cosmogenesis_world_built
	}
}

spawn_ringworld_cracker_effect = {
	create_ambient_object = {
		location = this
		type = ringworld_cracker_object
		duration = 5
		play_animation_once = yes

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

# Global Pacifier effect
spawn_habitat_pacifier_effect = {
	create_ambient_object = {
		location = this
		type = habitat_pacifier_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
	solar_system = {
		every_fleet_in_system = {
			limit = {
				is_ship_class = shipclass_habitat_station
			}
			orbit = {
				remove_planet_flag = has_megastructure
			}
			delete_fleet = this
		}
	}
}

spawn_lathe_pacifier_effect = {
	create_ambient_object = {
		location = this
		type = habitat_pacifier_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
	save_event_target_as = target_lathe
	solar_system = {
		spawn_megastructure = {
			type = cosmogenesis_world_ruined
			owner = this.owner
			coords_from = PREV
		}
		random_system_planet = {
			limit = {
				has_planet_flag = has_cosmogenesis_world
			}
			remove_planet_flag = has_cosmogenesis_world
			remove_planet_flag = has_megastructure
		}
	}
	remove_planet = yes
}

spawn_ringworld_pacifier_effect = {
	create_ambient_object = {
		location = this
		type = ringworld_pacifier_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

# Neutron Sweep effect
spawn_habitat_neutron_effect = {
	create_ambient_object = {
		location = this
		type = habitat_neutron_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

spawn_ringworld_neutron_effect = {
	create_ambient_object = {
		location = this
		type = ringworld_neutron_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

spawn_lathe_neutron_effect = {
	create_ambient_object = {
		location = this
		type = habitat_neutron_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

# Divine Enforcer effect
spawn_habitat_divine_effect = {
	create_ambient_object = {
		location = this
		type = habitat_divine_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

spawn_ringworld_divine_effect = {
	create_ambient_object = {
		location = this
		type = ringworld_divine_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

spawn_lathe_divine_effect = {
	create_ambient_object = {
		location = this
		type = habitat_divine_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

# Nanobot effect
spawn_habitat_nanobot_effect = {
	create_ambient_object = {
		location = this
		type = habitat_nanobot_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

spawn_ringworld_nanobot_effect = {
	create_ambient_object = {
		location = this
		type = ringworld_nanobot_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

spawn_lathe_nanobot_effect = {
	create_ambient_object = {
		location = this
		type = habitat_nanobot_object
		duration = 5

		use_3d_location = yes
		base_angle_towards = star
		entity_face_object = star

		entity_offset = { min = 0 max = 0 }

		entity_scale_to_size = yes
		scale = 0.10
	}
}

remove_xuracorp_trades = {
	if = {
		limit = { has_modifier = enclave_trade_1_xur }
		remove_modifier = enclave_trade_1_xur
	}
	if = {
		limit = { has_modifier = enclave_trade_2_xur }
		remove_modifier = enclave_trade_2_xur
	}
	if = {
		limit = { has_modifier = enclave_trade_3_xur }
		remove_modifier = enclave_trade_3_xur
	}
	if = {
		limit = { has_modifier = enclave_trade_4_xur }
		remove_modifier = enclave_trade_4_xur
	}
	if = {
		limit = { has_modifier = enclave_trade_5_xur }
		remove_modifier = enclave_trade_5_xur
	}
}

remove_riggan_trades = {
	if = {
		limit = { has_modifier = enclave_trade_1_rig }
		remove_modifier = enclave_trade_1_rig
	}
	if = {
		limit = { has_modifier = enclave_trade_2_rig }
		remove_modifier = enclave_trade_2_rig
	}
	if = {
		limit = { has_modifier = enclave_trade_3_rig }
		remove_modifier = enclave_trade_3_rig
	}
	if = {
		limit = { has_modifier = enclave_trade_4_rig }
		remove_modifier = enclave_trade_4_rig
	}
	if = {
		limit = { has_modifier = enclave_trade_5_rig }
		remove_modifier = enclave_trade_5_rig
	}
}

remove_muutagan_trades = {
	if = {
		limit = { has_modifier = enclave_trade_1_mut }
		remove_modifier = enclave_trade_1_mut
	}
	if = {
		limit = { has_modifier = enclave_trade_2_mut }
		remove_modifier = enclave_trade_2_mut
	}
	if = {
		limit = { has_modifier = enclave_trade_3_mut }
		remove_modifier = enclave_trade_3_mut
	}
	if = {
		limit = { has_modifier = enclave_trade_4_mut }
		remove_modifier = enclave_trade_4_mut
	}
	if = {
		limit = { has_modifier = enclave_trade_5_mut }
		remove_modifier = enclave_trade_5_mut
	}
}

# Leader scope
update_leader_after_modification = {
	if = {
		limit = {
			is_leader_tier = leader_tier_default
			has_any_chosen_one_leader_trait = no
		}
		# Remove all applicable leader traits
		remove_trait = leader_trait_erudite
		remove_trait = leader_trait_cyborg
		remove_trait = leader_trait_limited_cyborg
		remove_trait = leader_trait_firewalled
		remove_trait = leader_trait_hacked
		remove_trait = leader_trait_psionic
		remove_trait = leader_trait_virtual
		remove_trait = leader_trait_synthetic
		# Add the correct leader trait based on the species
		if = {
			limit = {
				is_robotic_species = no
			}
			species = {
				switch = {
					trigger = has_trait
					trait_erudite = {
						prev = {
							add_trait = {
								trait = leader_trait_erudite
								show_message = no
							}
						}
					}
					trait_cybernetic = {
						prev = {
							if = {
								limit = {
									is_spiritualist = yes
									owner = {
										has_policy_flag = cyberization_standards_limited
									}
								}
								add_trait = {
									trait = leader_trait_limited_cyborg
									show_message = no
								}
							}
							else = {
								add_trait = {
									trait = leader_trait_cyborg
									show_message = no
								}
							}
							if = {
								limit = {
									owner = {
										has_country_flag = firewall_built
									}
								}
								add_trait = {
									trait = leader_trait_firewalled
									show_message = no
								}
							}
						}
					}
					trait_psionic = {
						prev = {
							add_trait = {
								trait = leader_trait_psionic
								show_message = no
							}
						}
					}
				}
			}
		}
		if = {
			limit = {
				species = {
					has_trait = trait_robot_psionic
				}
			}
			add_trait = {
				trait = leader_trait_psionic
				show_message = no
			}
		}
		else_if = {
			limit = {
				species = {
					has_virtual_species_trait = yes
				}
			}
			add_trait = {
				trait = leader_trait_virtual
				show_message = no
			}
		}
		else = {
			if = {
				limit = {
					owner = { has_country_flag = driven_cybernetics }
				}
				add_trait = {
					trait = leader_trait_cyborg
					show_message = no
				}
			}
			else_if = {
				limit = {
					owner = {
						OR = {
							has_country_flag = synthetic_empire
							has_tradition = tr_synthetics_finish
							has_tradition = tr_modularity_finish
						}
					}
				}
				add_trait = {
					trait = leader_trait_synthetic
					show_message = no
				}
			}
		}
	}
}

incr_minerallump1_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_mineral_lump1
				value < 1
			}
		}
		set_variable = {
			which = aianom_mineral_lump1
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_mineral_lump1
			value = 1
		}
	}
}

incr_minerallump2_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_mineral_lump2
				value < 1
			}
		}
		set_variable = {
			which = aianom_mineral_lump2
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_mineral_lump2
			value = 1
		}
	}
}

incr_minerallump3_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_mineral_lump3
				value < 1
			}
		}
		set_variable = {
			which = aianom_mineral_lump3
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_mineral_lump3
			value = 1
		}
	}
}

incr_minerallump4_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_mineral_lump4
				value < 1
			}
		}
		set_variable = {
			which = aianom_mineral_lump4
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_mineral_lump4
			value = 1
		}
	}
}

incr_energylump1_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_energy_lump1
				value < 1
			}
		}
		set_variable = {
			which = aianom_energy_lump1
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_energy_lump1
			value = 1
		}
	}
}

incr_energylump2_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_energy_lump2
				value < 1
			}
		}
		set_variable = {
			which = aianom_energy_lump2
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_energy_lump2
			value = 1
		}
	}
}

incr_energylump3_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_energy_lump3
				value < 1
			}
		}
		set_variable = {
			which = aianom_energy_lump3
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_energy_lump3
			value = 1
		}
	}
}

incr_energylump4_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_energy_lump4
				value < 1
			}
		}
		set_variable = {
			which = aianom_energy_lump4
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_energy_lump4
			value = 1
		}
	}
}

incr_physicslump1_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_physics_lump1
				value < 1
			}
		}
		set_variable = {
			which = aianom_physics_lump1
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_physics_lump1
			value = 1
		}
	}
}

incr_physicslump2_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_physics_lump2
				value < 1
			}
		}
		set_variable = {
			which = aianom_physics_lump2
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_physics_lump2
			value = 1
		}
	}
}

incr_physicslump3_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_physics_lump3
				value < 1
			}
		}
		set_variable = {
			which = aianom_physics_lump3
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_physics_lump3
			value = 1
		}
	}
}

incr_physicslump4_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_physics_lump4
				value < 1
			}
		}
		set_variable = {
			which = aianom_physics_lump4
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_physics_lump4
			value = 1
		}
	}
}

incr_societylump1_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_society_lump1
				value < 1
			}
		}
		set_variable = {
			which = aianom_society_lump1
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_society_lump1
			value = 1
		}
	}
}

incr_societylump2_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_society_lump2
				value < 1
			}
		}
		set_variable = {
			which = aianom_society_lump2
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_society_lump2
			value = 1
		}
	}
}

incr_societylump3_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_society_lump3
				value < 1
			}
		}
		set_variable = {
			which = aianom_society_lump3
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_society_lump3
			value = 1
		}
	}
}

incr_societylump4_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_society_lump4
				value < 1
			}
		}
		set_variable = {
			which = aianom_society_lump4
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_society_lump4
			value = 1
		}
	}
}

incr_engineeringlump1_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_engineering_lump1
				value < 1
			}
		}
		set_variable = {
			which = aianom_engineering_lump1
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_engineering_lump1
			value = 1
		}
	}
}

incr_engineeringlump2_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_engineering_lump2
				value < 1
			}
		}
		set_variable = {
			which = aianom_engineering_lump2
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_engineering_lump2
			value = 1
		}
	}
}

incr_engineeringlump3_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_engineering_lump3
				value < 1
			}
		}
		set_variable = {
			which = aianom_engineering_lump3
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_engineering_lump3
			value = 1
		}
	}
}

incr_engineeringlump4_var = {
	if = {
		limit = {
			check_variable = {
				which = aianom_engineering_lump4
				value < 1
			}
		}
		set_variable = {
			which = aianom_engineering_lump4
			value = 1
		}
	}
	else = {
		change_variable = {
			which = aianom_engineering_lump4
			value = 1
		}
	}
}

incr_mineraldepo1_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_mineral_depo1
					value < 1
				}
			}
			set_variable = {
				which = aianom_mineral_depo1
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_mineral_depo1
				value = 1
			}
		}
	}
}

incr_mineraldepo2_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_mineral_depo2
					value < 1
				}
			}
			set_variable = {
				which = aianom_mineral_depo2
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_mineral_depo2
				value = 1
			}
		}
	}
}

incr_mineraldepo3_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_mineral_depo3
					value < 1
				}
			}
			set_variable = {
				which = aianom_mineral_depo3
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_mineral_depo3
				value = 1
			}
		}
	}
}

incr_mineraldepo4_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_mineral_depo4
					value < 1
				}
			}
			set_variable = {
				which = aianom_mineral_depo4
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_mineral_depo4
				value = 1
			}
		}
	}
}

incr_energydepo1_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_energy_depo1
					value < 1
				}
			}
			set_variable = {
				which = aianom_energy_depo1
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_energy_depo1
				value = 1
			}
		}
	}
}

incr_energydepo2_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_energy_depo2
					value < 1
				}
			}
			set_variable = {
				which = aianom_energy_depo2
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_energy_depo2
				value = 1
			}
		}
	}
}

incr_energydepo3_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_energy_depo3
					value < 1
				}
			}
			set_variable = {
				which = aianom_energy_depo3
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_energy_depo3
				value = 1
			}
		}
	}
}

incr_energydepo4_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_energy_depo4
					value < 1
				}
			}
			set_variable = {
				which = aianom_energy_depo4
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_energy_depo4
				value = 1
			}
		}
	}
}

incr_physicsdepo1_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_physics_depo1
					value < 1
				}
			}
			set_variable = {
				which = aianom_physics_depo1
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_physics_depo1
				value = 1
			}
		}
	}
}

incr_physicsdepo2_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_physics_depo2
					value < 1
				}
			}
			set_variable = {
				which = aianom_physics_depo2
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_physics_depo2
				value = 1
			}
		}
	}
}

incr_physicsdepo3_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_physics_depo3
					value < 1
				}
			}
			set_variable = {
				which = aianom_physics_depo3
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_physics_depo3
				value = 1
			}
		}
	}
}

incr_physicsdepo4_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_physics_depo4
					value < 1
				}
			}
			set_variable = {
				which = aianom_physics_depo4
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_physics_depo4
				value = 1
			}
		}
	}
}

incr_societydepo1_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_society_depo1
					value < 1
				}
			}
			set_variable = {
				which = aianom_society_depo1
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_society_depo1
				value = 1
			}
		}
	}
}

incr_societydepo2_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_society_depo2
					value < 1
				}
			}
			set_variable = {
				which = aianom_society_depo2
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_society_depo2
				value = 1
			}
		}
	}
}

incr_societydepo3_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_society_depo3
					value < 1
				}
			}
			set_variable = {
				which = aianom_society_depo3
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_society_depo3
				value = 1
			}
		}
	}
}

incr_societydepo4_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_society_depo4
					value < 1
				}
			}
			set_variable = {
				which = aianom_society_depo4
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_society_depo4
				value = 1
			}
		}
	}
}

incr_engineeringdepo1_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_engineering_depo1
					value < 1
				}
			}
			set_variable = {
				which = aianom_engineering_depo1
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_engineering_depo1
				value = 1
			}
		}
	}
}

incr_engineeringdepo2_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_engineering_depo2
					value < 1
				}
			}
			set_variable = {
				which = aianom_engineering_depo2
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_engineering_depo2
				value = 1
			}
		}
	}
}

incr_engineeringdepo3_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_engineering_depo3
					value < 1
				}
			}
			set_variable = {
				which = aianom_engineering_depo3
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_engineering_depo3
				value = 1
			}
		}
	}
}

incr_engineeringdepo4_var = {
	root.owner = {
		if = {
			limit = {
				check_variable = {
					which = aianom_engineering_depo4
					value < 1
				}
			}
			set_variable = {
				which = aianom_engineering_depo4
				value = 1
			}
		}
		else = {
			change_variable = {
				which = aianom_engineering_depo4
				value = 1
			}
		}
	}
}

add_alloys = {
	set_deposit = d_alloys_1
}

add_volatile_motes = {
	set_deposit = d_volatile_motes_1
}

add_exotic_gases = {
	set_deposit = d_exotic_gases_1
}

add_rare_crystals = {
	set_deposit = d_rare_crystals_1
}

add_dark_matter = {
	random_list = {
		16 = { set_deposit = d_dark_matter_deposit_1 }
		4 = { set_deposit = d_dark_matter_deposit_2 }
		1 = { set_deposit = d_dark_matter_deposit_3 }
	}
}

add_zro = {
	random_list = {
		16 = { set_deposit = d_zro_deposit_1 }
		4 = { set_deposit = d_zro_deposit_2 }
		1 = { set_deposit = d_zro_deposit_3 }
	}
}

# giving clues, see pop_lcluster_event for popping follow-up events
# this = country getting a clue
generate_lcluster_clue = {
	optimize_memory
	hidden_effect = {
		# increment counter
		if = {
			limit = {
				has_distar = yes
				NOT = { has_global_flag = l_cluster_opened }
				has_event_chain = l_cluster_chain
			}
			# increment counter
			custom_tooltip = add_lcluster_clue
			add_event_chain_counter = {
				event_chain = l_cluster_chain
				counter = clues
				amount = 1
			}
			# increment variable
			change_variable = {
				which = num_lcluster_clues
				value = 1
			}
		}
		if = {
			limit = {
				has_completed_event_chain_counter = {
					event_chain = l_cluster_chain
					counter = clues
				}
			}
			custom_tooltip = l_cluster_openable
			set_country_flag = completed_lcluster_chain
			country_event = { id = distar.10904 }
		}
	}
}

# this = solar system to isolate
isolate_system = {
	every_system = {
		limit = { has_hyperlane_to = prev }
		remove_hyperlane = { from = this to = prev }
	}
}

# for follow-up events
# use in AFTER or OPTION for timing reasons
# this = country getting a clue
pop_lcluster_event = {
	hidden_effect = {
		# pop follow-up if valid
		if = {
			limit = {
				has_distar = yes
				has_country_flag = encountered_first_lgate
				NOR = {
					has_global_flag = l_cluster_opened
					has_completed_event_chain_counter = {
						event_chain = l_cluster_chain
						counter = clues
					}
				}
			}
			random_list = {
				7 = {}
				3 = { country_event = { id = distar.9000 days = 10 } }
			}
		}
	}
}

create_enigmatic_cache_fleet = {
	create_fleet = {
		name = "NAME_enigmatic_cache"
		settings = {
			spawn_debris = no
			is_boss = yes
		}
		effect = {
			save_global_event_target_as = enigmatic_cache_fleet
			set_owner = event_target:enigmatic_cache_country
			create_ship = {
				name = "NAME_enigmatic_cache"
				design = NAME_enigmatic_cache
				effect = {
					set_disable_at_health = 0.90
					save_global_event_target_as = enigmatic_cache_ship
					set_ship_flag = enigmatic_cache_ship
				}
			}
			set_fleet_flag = enigmatic_cache_fleet
			set_location = {
				target = event_target:new_location
				distance = 80
				angle = 220
			}
			set_fleet_stance = passive
			set_aggro_range_measure_from = self
			set_aggro_range = 100
			auto_move_to_planet = {
				target = event_target:new_location
				clear_auto_move_on_arrival = no
			}
		}
	}
}

start_lcluster_chain = {
	hidden_effect = {
		custom_tooltip = begin_lcluster_chain
		begin_event_chain = {
			event_chain = l_cluster_chain
			target = this
		}
		set_variable = {
			which = num_lcluster_clues
			value = 0
		}
	}
}

liquidate_clues = {
	hidden_effect = {
		if = {
			limit = { has_event_chain = l_cluster_chain }
			end_event_chain = l_cluster_chain
		}
		if = {
			limit = {
				check_variable = {
					which = num_lcluster_clues
					value > 6
				}
			}
			custom_tooltip = liquidated_7
			add_resource = {
				engineering_research = 3500
				energy = 3500
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = num_lcluster_clues
					value = 6
				}
			}
			custom_tooltip = liquidated_6
			add_resource = {
				engineering_research = 3000
				energy = 3000
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = num_lcluster_clues
					value = 5
				}
			}
			custom_tooltip = liquidated_5
			add_resource = {
				engineering_research = 2500
				energy = 2500
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = num_lcluster_clues
					value = 4
				}
			}
			custom_tooltip = liquidated_4
			add_resource = {
				engineering_research = 2000
				energy = 2000
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = num_lcluster_clues
					value = 3
				}
			}
			custom_tooltip = liquidated_3
			add_resource = {
				engineering_research = 1500
				energy = 1500
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = num_lcluster_clues
					value = 2
				}
			}
			custom_tooltip = liquidated_2
			add_resource = {
				engineering_research = 1000
				energy = 1000
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = num_lcluster_clues
					value = 1
				}
			}
			custom_tooltip = liquidated_1
			add_resource = {
				engineering_research = 500
				energy = 500
			}
		}
		else = {
			custom_tooltip = liquidated_0
		}
	}
}

# saves the owned (regular) or waystation-co-located (nomad) L-Gate as candidate_gateway, then enables the project
enable_lgate_project_on_owned_gateway = {
	if = {
		limit = { any_owned_megastructure = { is_megastructure_type = lgate_base } }	# regular empires
		random_owned_megastructure = {
			limit = { is_megastructure_type = lgate_base }
			save_event_target_as = candidate_gateway
		}
	}
	else = {																			# nomads
		random_owned_nonprimary_starbase = {
			limit = {
				is_waystation_starbase = yes
				solar_system = {
					any_system_megastructure = { is_megastructure_type = lgate_base }
				}
			}
			solar_system = {
				random_system_megastructure = {
					limit = { is_megastructure_type = lgate_base }
					save_event_target_as = candidate_gateway
				}
			}
		}
	}
	country_event = { id = distar.10905 } # enable project
}

create_global_robot_parent_species = {
	create_species = {
		name = "NAME_Robot"
		plural = "NAME_Robot_plural"
		class = ROBOT
		namelist = this
		portrait = "default_robot"
		traits = {
			trait = "trait_mechanical"
		}

		effect = {
			save_global_event_target_as = global_robot_parent_species
		}
	}
}

create_built_robot_species = {
	if = {
		limit = {
			NOT = {
				exists = event_target:global_robot_parent_species
			}
		}
		create_global_robot_parent_species = yes
	}

	create_species = {
		name = "NAME_Robot"
		plural = "NAME_Robot_plural"
		class = ROBOT
		homeworld = this
		namelist = this
		portrait = "default_robot"
		traits = {
			trait = "trait_mechanical"
		}

		effect = {
			set_synth_or_robot_portrait_effect = yes
			set_species_identity = event_target:global_robot_parent_species
			set_species_flag = mechanical_species@prev
			save_event_target_as = robot_species
		}
	}

	species = {
		if = {
			limit = {
				has_trait = trait_void_dweller_1
			}
			event_target:robot_species = {
				change_species_characteristics = {
					add_trait = trait_void_dweller_2
				}
			}
		}
		if = {
			limit = {
				has_trait = trait_aquatic
			}
			event_target:robot_species = {
				change_species_characteristics = {
					add_trait = trait_robot_aquatic
				}
			}
		}
		if = {
			limit = {
				has_trait = trait_cave_dweller
			}
			event_target:robot_species = {
				change_species_characteristics = {
					add_trait = trait_robot_cave_dweller
				}
			}
		}
	}

	set_built_species = last_created_species
}

give_next_breakthrough_effect = {
	inverted_switch = {
		trigger = has_technology
		tech_$AREA$_1 = {
			give_breakthrough_tech_option_or_progress_effect = { TECH = tech_$AREA$_1 }
		}
		tech_$AREA$_2 = {
			give_breakthrough_tech_option_or_progress_effect = { TECH = tech_$AREA$_2 }
		}
		tech_$AREA$_3 = {
			give_breakthrough_tech_option_or_progress_effect = { TECH = tech_$AREA$_3 }
		}
		tech_$AREA$_4 = {
			give_breakthrough_tech_option_or_progress_effect = { TECH = tech_$AREA$_4 }
		}
		default = {
			add_monthly_resource_mult = {
				resource = $AREA$_research
				value = @tier3researchreward
				min = @tier3researchmin
				max = @tier3researchmax
			}
		}
	}
}

give_next_terraforming_tech_option_effect = {
	if = {
		limit = { NOT = { has_technology = tech_terrestrial_sculpting } }
		add_research_option = tech_terrestrial_sculpting
		add_tech_progress = {
			tech = tech_terrestrial_sculpting
			progress = 0.25
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_ecological_adaptation } }
		add_research_option = tech_ecological_adaptation
		add_tech_progress = {
			tech = tech_ecological_adaptation
			progress = 0.25
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_climate_restoration } }
		add_research_option = tech_climate_restoration
		add_tech_progress = {
			tech = tech_climate_restoration
			progress = 0.25
		}
	}
	else = {
		add_monthly_resource_mult = {
			resource = society_research
			value = @tier3researchreward
			min = @tier3researchmin
			max = @tier3researchmax
		}
	}
}

give_next_terraforming_tech_effect = {
	inverted_switch = {
		trigger = has_technology
		tech_terrestrial_sculpting = {
			give_technology = { tech = tech_terrestrial_sculpting }
		}
		tech_ecological_adaptation = {
			give_technology = { tech = tech_ecological_adaptation }
		}
		tech_climate_restoration = {
			give_technology = { tech = tech_climate_restoration }
		}
		default = {
			add_monthly_resource_mult = {
				resource = society_research
				value = @tier3researchreward
				min = @tier3researchmin
				max = @tier3researchmax
			}
		}
	}
}

give_next_ai_tech_option_effect = {
	if = {
		limit = { NOT = { has_technology = tech_self_aware_logic } }
		add_research_option = tech_self_aware_logic
		add_tech_progress = {
			tech = tech_self_aware_logic
			progress = 0.25
		}
	}
	else_if = {
		limit = {
			NOT = { has_technology = tech_sapient_ai }
			NOT = { has_ethic = ethic_gestalt_consciousness }
		}
		add_research_option = tech_sapient_ai
		add_tech_progress = {
			tech = tech_sapient_ai
			progress = 0.25
		}
	}
	else_if = {
		limit = {
			NOT = { has_technology = tech_positronic_implants }
			has_ethic = ethic_gestalt_consciousness
		}
		add_research_option = tech_positronic_implants
		add_tech_progress = {
			tech = tech_positronic_implants
			progress = 0.25
		}
	}
	else_if = {
		limit = {
			NOT = { has_technology = tech_combat_computers_3 }
		}
		add_research_option = tech_combat_computers_3
		add_tech_progress = {
			tech = tech_combat_computers_3
			progress = 0.25
		}
	}
	else = {
		add_monthly_resource_mult = {
			resource = physics_research
			value = @tier3researchreward
			min = @tier3researchmin
			max = @tier3researchmax
		}
	}
}

give_next_armor_tech_option_effect = {
	if = {
		limit = { NOT = { has_technology = tech_ship_armor_1 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_ship_armor_1
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_ship_armor_2 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_ship_armor_2
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_ship_armor_3 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_ship_armor_3
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_ship_armor_4 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_ship_armor_4
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_ship_armor_5 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_ship_armor_5
		}
	}
	else = {
		add_monthly_resource_mult = {
			resource = engineering_research
			value = @tier3researchreward
			min = @tier3researchmin
			max = @tier3researchmax
		}
	}
}

give_next_shield_tech_option_effect = {
	if = {
		limit = { NOT = { has_technology = tech_shields_1 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_shields_1
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_shields_2 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_shields_2
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_shields_3 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_shields_3
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_shields_4 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_shields_4
		}
	}
	else_if = {
		limit = { NOT = { has_technology = tech_shields_5 } }
		give_tech_option_or_progress_effect = {
			TECH = tech_shields_5
		}
	}
	else = {
		add_monthly_resource_mult = {
			resource = physics_research
			value = @tier3researchreward
			min = @tier3researchmin
			max = @tier3researchmax
		}
	}
}

give_next_habitability_tech_option_effect = {
	if = {
		limit = {
			NOT = { has_technology = tech_colonization_2 }
			can_research_technology = tech_colonization_2
		}
		give_tech_option_or_progress_effect = {
			TECH = tech_colonization_2
		}
	}
	else_if = {
		limit = {
			NOT = { has_technology = tech_colonization_3 }
			can_research_technology = tech_colonization_3
		}
		give_tech_option_or_progress_effect = {
			TECH = tech_colonization_3
		}
	}
	else_if = {
		limit = {
			NOT = { has_technology = tech_colonization_4 }
			can_research_technology = tech_colonization_4
		}
		give_tech_option_or_progress_effect = {
			TECH = tech_colonization_4
		}
	}
	else_if = {
		limit = {
			NOT = { has_technology = tech_colonization_5 }
			can_research_technology = tech_colonization_5
		}
		give_tech_option_or_progress_effect = {
			TECH = tech_colonization_5
		}
	}
	else = {
		add_monthly_resource_mult = {
			 resource = society_research
			 value = @tier3researchreward
			 min = @tier3researchmin
			 max = @tier3researchmax
		 }
	}
}

grant_dragon_armor_effect = {
	if = {
		limit = {
			NOR = {
				has_technology = tech_dragon_armor
				has_tech_option = tech_dragon_armor
			}
		}
		add_tech_progress = {
			tech = tech_dragon_armor
			progress = 0.3
		}
	}
	else = {
		add_monthly_resource_mult = {
			resource = minerals
			value = @tier4materialreward
			min = @tier4materialmin
			max = @tier4materialmax
		}
		add_monthly_resource_mult = {
			resource = society_research
			value = @tier4researchreward
			min = @tier4researchmin
			max = @tier4researchmax
		}
	}
}

give_tech_option_or_progress_effect = {
	if = {
		limit = { NOT = { has_tech_option = $TECH$ } }
		add_tech_progress = {
			tech = $TECH$
			progress = 0.25
		}
	}
	else = {
		add_tech_progress = {
			tech = $TECH$
			progress = 0.5
		}
	}
}

#Use in war scope. War is deleted.
end_war_effect = {
	every_war_participant = {
		prev = { remove_war_participant = prev }
	}
}

fire_random_centralisation_flavour_event_effect = {
	hidden_effect = {
		random_member = {
			limit = {
				is_gestalt = no
				any_owned_leader = {
					is_assigned_to_federation = yes
				}
			}
			random_list = {
				1 = {
					country_event = { id = envoy_events.16 days = 15 }
					modifier = {
						factor = 0.8
						federation = {
							federation_cohesion >= 90
						}
					}
					modifier = {
						factor = 1.5
						federation = {
							federation_cohesion <= 50
						}
					}
					modifier = {
						factor = 1.5
						federation = {
							federation_cohesion <= 25
						}
					}
					modifier = {
						factor = 1.5
						federation = {
							federation_cohesion <= 0
						}
					}
				}
				4 = { } #nej
			}
		}
	}
}

set_assimilation_counter_variable = {
	# 5d20 + Auto-Mod Modifier
	export_modifier_to_variable = {
		modifier = auto_mod_monthly_mult
		variable = assimilation_counter_mult
	}
	change_variable = {
		which = assimilation_counter_mult
		value = 1
	}
	export_modifier_to_variable = {
		modifier = auto_mod_monthly_add
		variable = assimilation_counter
	}
	multiply_variable = {
		which = assimilation_counter
		value = assimilation_counter_mult
	}
	set_variable_to_random_value = {
		which = assimilation_counter_1
		min = 1
		max = 20
		rounded = yes
	}
	set_variable_to_random_value = {
		which = assimilation_counter_2
		min = 1
		max = 20
		rounded = yes
	}
	set_variable_to_random_value = {
		which = assimilation_counter_3
		min = 1
		max = 20
		rounded = yes
	}
	set_variable_to_random_value = {
		which = assimilation_counter_4
		min = 1
		max = 20
		rounded = yes
	}
	set_variable_to_random_value = {
		which = assimilation_counter_5
		min = 1
		max = 20
		rounded = yes
	}
	change_variable = {
		which = assimilation_counter
		value = assimilation_counter_1
	}
	change_variable = {
		which = assimilation_counter
		value = assimilation_counter_2
	}
	change_variable = {
		which = assimilation_counter
		value = assimilation_counter_3
	}
	change_variable = {
		which = assimilation_counter
		value = assimilation_counter_4
	}
	change_variable = {
		which = assimilation_counter
		value = assimilation_counter_5
	}
	# Divide by 5 as we assimilate in batches of 5
	divide_variable = {
		which = assimilation_counter
		value = 5
	}
	round_variable = assimilation_counter
}

clear_assimilation_variables = {
	clear_variable = assimilation_counter_mult
	clear_variable = assimilation_counter
	clear_variable = assimilation_counter_1
	clear_variable = assimilation_counter_2
	clear_variable = assimilation_counter_3
	clear_variable = assimilation_counter_4
	clear_variable = assimilation_counter_5
}

# pop group scope. Creates the assimilated counterpart species, or finds the one
# an earlier pass already made, and saves it as target_species.
create_assimilation_species = {
	if = {
		limit = {
			NOT = {
				any_galaxy_species = {
					has_species_flag = assimilation_species_of_species@event_target:old_species
					has_species_flag = assimilation_species_of_empire@root.owner
					is_same_species = event_target:old_species
				}
			}
		}
		create_species = {
			is_mod = yes
			name = this
			plural = this
			class = this
			portrait = this
			traits = this
			can_be_modified = this
			homeworld = this
			namelist = this
			gender = this
			effect = {
				modify_species = {
					species = this
					$TRAITS$
					add_traits_at_start_of_list = yes
					change_scoped_species = no

					effect = {
						set_species_flag = assimilation_species_of_species@event_target:old_species
						set_species_flag = assimilation_species_of_empire@root.owner
						save_event_target_as = target_species
					}
				}
			}
		}
	}
	else = {
		random_galaxy_species = {
			limit = {
				has_species_flag = assimilation_species_of_species@event_target:old_species
				has_species_flag = assimilation_species_of_empire@root.owner
				is_same_species = event_target:old_species
			}
			save_event_target_as = target_species
		}
	}
}

# pop group scope. Converts to the owner founder species rather than a new one.
use_founder_species_as_assimilation_target = {
	root.owner.species = {
		save_event_target_as = target_species
	}
	$TRAITS$					# The founder species keeps its own traits, so this is empty
}

# pop group scope. Moves AMOUNT pops into the assimilated species group
assimilate_pop_group_effect = {
	colony = {
		create_pop_group = {
			pop_group = event_target:old_pop_group
			species = event_target:target_species
			size = 0
			effect = {
				transfer_pop_amount = {
					source = event_target:old_pop_group
					target = this
					amount = $AMOUNT|5$
				}
				set_timed_pop_group_flag = {
					flag = already_assimilated
					days = 15
				}
				apply_post_assimilation_effects = yes
			}
		}
	}
}

# pop group scope. Wilderness keeps one pop in five, so the rest are killed.
assimilate_wilderness_pop_group_effect = {
	assimilate_pop_group_effect = {
		AMOUNT = 1
	}
	colony = {
		kill_pop_group = {
			pop_group = event_target:old_pop_group
			amount = 4
		}
	}
}

# pop scope, root = planet
apply_post_assimilation_effects = {
	if = { # assimilator empire
		limit = {
			root.owner = {
				is_machine_empire = yes
				has_civic = civic_machine_assimilator
			}
		}
		root.owner = { generate_cyborg_treats = yes } # scripted effect
	}
	if = {
		limit = {
			NOT = {
				owner = {
					any_owned_pop_group = {
						is_exact_same_species = event_target:target_species
						NOT = { is_same_value = prevprev }
					}
				}
			}
		}
		if = { # set citizenship
			limit = { root.owner = { is_machine_empire = yes } }
			set_citizenship_type = {
				type = citizenship_full_machine
				country = root.owner
			}
		}
		else = {
			set_citizenship_type = {
				type = citizenship_full
				country = root.owner
			}
		}

		if = { # set citizenship
			limit = { root.owner = { has_ethic = ethic_gestalt_consciousness } }
			set_living_standard = {
				type = living_standard_hive_mind
				country = root.owner
			}
		}
	}

	if = { # Handle Purity Authority effects
		limit = {
			root.owner = {
				is_purity_authority = yes
			}
			species = {
				OR = {
					is_archetype = PRESAPIENT
					is_archetype = BIOLOGICAL
					is_archetype = LITHOID
				}
			}
		}
		species = {
			set_species_traits_purity_count_variable = yes
		}
	}
}

# planet scope. Run once a month, because assimilating over 100 pops a month is hard
finish_assimilation_effect = {
	owner = {
		credit_assimilation_purge_crisis = {
			COUNT = 1
		}
		assimilate_armies = {
			SOURCE = event_target:old_species
			TARGET = event_target:target_species
		}
		assimilate_colony_ships = {
			SOURCE = event_target:old_species
			TARGET = event_target:target_species
		}
		assimilate_leaders = {
			SOURCE = event_target:old_species
			TARGET = event_target:target_species
		}
	}
}

# Credits Become-the-Crisis "Purge Pops" $COUNT$ times. A purge vassal is not the Crisis, so credit goes to its Overlord.
credit_assimilation_purge_crisis = {
	if = {
		limit = { has_ascension_perk = ap_become_the_crisis }
		while = {
			count = $COUNT$
			complete_crisis_objective = crisobj_purge_pops
		}
	}
	else_if = {
		limit = {
			has_origin = origin_nomadic_purger
			overlord? = { has_ascension_perk = ap_become_the_crisis }
		}
		overlord = {
			while = {
				count = $COUNT$
				complete_crisis_objective = crisobj_purge_pops
			}
		}
	}
}

setup_baol_colony_1 = {
	root.owner = { set_visited = prev }
	set_star_flag = grunur_site@root.owner
	random_system_planet = {
		limit = {
			is_planet_class = pc_barren
			has_anomaly = no
			NOT = { exists = archaeological_site }
			NOT = { has_planet_flag = suppress_archaeological_sites }
		}
		save_event_target_as = baol_colony_1
	}
}

setup_baol_colony_2 = {
	root.owner = { set_visited = prev }
	set_star_flag = grunur_site@root.owner
	random_system_planet = {
		limit = {
			is_planet_class = pc_asteroid
			has_anomaly = no
			NOT = { exists = archaeological_site }
			NOT = { has_planet_flag = suppress_archaeological_sites }
		}
		save_event_target_as = baol_colony_2
	}
}

setup_baol_colony_3 = {
	root.owner = { set_visited = prev }
	set_star_flag = grunur_site@root.owner
	random_system_planet = {
		limit = {
			habitable_planet = yes
			is_urban_planet = no
			has_anomaly = no
			NOR = {
				exists = archaeological_site
				has_carrier_flag = colony_event
				has_planet_flag = suppress_archaeological_sites
			}
			OR = {
				is_colony = no
				sapient_pop_amount < 1000
			}
		}
		save_event_target_as = baol_colony_3
	}
}

setup_baol_colony_3_fallback = {
	root.owner = { set_visited = prev }
	set_star_flag = grunur_site@root.owner
	random_system_planet = {
		limit = {
			habitable_planet = yes
			is_urban_planet = no
			has_anomaly = no
			NOR = {
				exists = archaeological_site
				has_carrier_flag = colony_event
				has_planet_flag = suppress_archaeological_sites
			}
			OR = {
				is_colony = no
				sapient_pop_amount < 1000
			}
		}
		save_event_target_as = baol_colony_3
	}
}

add_extra_hyperlane_to_spawned_system_effect = {
	hidden_effect = {
		last_created_system = {
			if = {
				limit = {
					any_system = {
						distance = {
							source = prev
							type = euclidean
							min_distance >= 1
							max_distance <= 10
						}
						NOR = {
							has_hyperlane_to = prev
							has_star_flag = sealed_system
							has_star_flag = surveillance_supercomputer_system
						}
					}
				}
				random_system = {
					limit = {
						distance = {
							source = prev
							type = euclidean
							min_distance >= 1
							max_distance <= 10
						}
						NOR = {
							has_hyperlane_to = prev
							has_star_flag = sealed_system
							has_star_flag = surveillance_supercomputer_system
						}
					}
					add_hyperlane = {
						from = this
						to = prev
					}
				}
			}
			else_if = {
				limit = {
					any_system = {
						distance = {
							source = prev
							type = euclidean
							min_distance >= 1
							max_distance <= 15
						}
						NOR = {
							has_hyperlane_to = prev
							has_star_flag = sealed_system
							has_star_flag = surveillance_supercomputer_system
						}
					}
				}
				random_system = {
					limit = {
						distance = {
							source = prev
							type = euclidean
							min_distance >= 1
							max_distance <= 15
						}
						NOR = {
							has_hyperlane_to = prev
							has_star_flag = sealed_system
							has_star_flag = surveillance_supercomputer_system
						}
					}
					add_hyperlane = {
						from = this
						to = prev
					}
				}
			}
			else_if = {
				limit = {
					any_system = {
						distance = {
							source = prev
							type = euclidean
							min_distance >= 1
							max_distance <= 25
						}
						NOR = {
							has_hyperlane_to = prev
							has_star_flag = sealed_system
							has_star_flag = surveillance_supercomputer_system
						}
					}
				}
				random_system = {
					limit = {
						distance = {
							source = prev
							type = euclidean
							min_distance >= 1
							max_distance <= 25
						}
						NOT = { has_hyperlane_to = prev }
					}
					add_hyperlane = {
						from = this
						to = prev
					}
				}
			}
			else_if = {
				limit = {
					any_system = {
						distance = {
							source = prev
							type = euclidean
							min_distance >= 1
							max_distance <= 40
						}
						NOR = {
							has_hyperlane_to = prev
							has_star_flag = sealed_system
							has_star_flag = surveillance_supercomputer_system
						}
					}
				}
				random_system = {
					limit = {
						distance = {
							source = prev
							type = euclidean
							min_distance >= 1
							max_distance <= 40
						}
						NOR = {
							has_hyperlane_to = prev
							has_star_flag = sealed_system
							has_star_flag = surveillance_supercomputer_system
						}
					}
					add_hyperlane = {
						from = this
						to = prev
					}
				}
			}
		}
	}
}

add_extra_hyperlane_to_this_system_effect = {
	if = {
		limit = {
			any_system = {
				distance = {
					source = prev
					type = euclidean
					min_distance >= 1
					max_distance <= 10
				}
				NOR = {
					has_hyperlane_to = prev
					has_star_flag = sealed_system
					has_star_flag = surveillance_supercomputer_system
					is_bottleneck_system = yes
				}
			}
		}
		random_system = {
			limit = {
				distance = {
					source = prev
					type = euclidean
					min_distance >= 1
					max_distance <= 10
				}
				NOR = {
					has_hyperlane_to = prev
					has_star_flag = sealed_system
					has_star_flag = surveillance_supercomputer_system
					is_bottleneck_system = yes
				}
			}
			add_hyperlane = {
				from = this
				to = prev
			}
		}
	}
	else_if = {
		limit = {
			any_system = {
				distance = {
					source = prev
					type = euclidean
					min_distance >= 1
					max_distance <= 15
				}
				NOR = {
					has_hyperlane_to = prev
					has_star_flag = sealed_system
					has_star_flag = surveillance_supercomputer_system
					is_bottleneck_system = yes
				}
			}
		}
		random_system = {
			limit = {
				distance = {
					source = prev
					type = euclidean
					min_distance >= 1
					max_distance <= 15
				}
				NOR = {
					has_hyperlane_to = prev
					has_star_flag = sealed_system
					has_star_flag = surveillance_supercomputer_system
					is_bottleneck_system = yes
				}
			}
			add_hyperlane = {
				from = this
				to = prev
			}
		}
	}
	else_if = {
		limit = {
			any_system = {
				distance = {
					source = prev
					type = euclidean
					min_distance >= 1
					max_distance <= 25
				}
				NOR = {
					has_hyperlane_to = prev
					has_star_flag = sealed_system
					has_star_flag = surveillance_supercomputer_system
					is_bottleneck_system = yes
				}
			}
		}
		random_system = {
			limit = {
				distance = {
					source = prev
					type = euclidean
					min_distance >= 1
					max_distance <= 25
				}
				NOR = {
					has_hyperlane_to = prev
					has_star_flag = sealed_system
					has_star_flag = surveillance_supercomputer_system
					is_bottleneck_system = yes
				}
			}
			add_hyperlane = {
				from = this
				to = prev
			}
		}
	}
	else_if = {
		limit = {
			any_system = {
				distance = {
					source = prev
					type = euclidean
					min_distance >= 1
					max_distance <= 40
				}
				NOR = {
					has_hyperlane_to = prev
					has_star_flag = sealed_system
					has_star_flag = surveillance_supercomputer_system
					is_bottleneck_system = yes
				}
			}
		}
		random_system = {
			limit = {
				distance = {
					source = prev
					type = euclidean
					min_distance >= 1
					max_distance <= 40
				}
				NOR = {
					has_hyperlane_to = prev
					has_star_flag = sealed_system
					has_star_flag = surveillance_supercomputer_system
					is_bottleneck_system = yes
				}
			}
			add_hyperlane = {
				from = this
				to = prev
			}
		}
	}
}

add_imp_concession_ports_0 = {
	remove_modifier = imp_concession_ports_1
	remove_modifier = imp_concession_ports_2
	remove_modifier = imp_concession_ports_3
	remove_modifier = imp_concession_ports_4
	remove_modifier = imp_concession_ports_5
	remove_modifier = imp_concession_ports_6
	remove_modifier = imp_concession_ports_7
	remove_modifier = imp_concession_ports_8
	remove_modifier = imp_concession_ports_9
	remove_modifier = imp_concession_ports_10
}

add_imp_concession_ports = {
	add_imp_concession_ports_0 = yes
	add_modifier = { modifier = $MODIFIER$ }
}

can_build_crisis_star_eater = {
	set_country_flag = can_build_crisis_star_eater
	create_ship_design = { design = "NAME_Crisis_Star_Eater" }
	add_ship_design = last_created_design
}

destroy_star_system = {
	if = {
		limit = { exists = event_target:crisis_country }
		fire_on_action = {
			on_action = on_destroy_star_system
			scopes = { from = event_target:crisis_country }
		}
	}
	else = {
		fire_on_action = { on_action = on_destroy_star_system }
	}
	# Must run before the bodies below are removed.
	every_system_planet = {
		clear_consecration_effect = yes
	}
	set_star_flag = star_cracked
	set_star_class = sc_black_hole
	every_system_ambient_object = {
		limit = {
			# Preserve Unbidden crisis effects
			NOR = {
				has_ambient_object_flag = extradimensional_system_effect
				has_ambient_object_flag = extradimensional_system_effect_2
			}
		}
		destroy_ambient_object = this
	}
	every_system_planet = {
		limit = { is_star = yes }
		create_ambient_object = {
			type = "star_explosion"
			play_animation_once = yes
			location = this
		}
		last_created_ambient_object = {
			set_location = {
				target = prev
				distance = 0
				angle = random
			}
		}
		change_pc = pc_black_hole
	}
	# Handle Contingency Machine Worlds
	every_system_planet = {
		limit = {
			is_planet_class = pc_ai
			NOT = { has_planet_flag = machine_lair }
		}
		destroy_machine_world = yes
	}
	random_system_planet = {
		limit = {
			is_planet_class = pc_ai
			has_planet_flag = machine_lair
		}
		from.owner = { save_event_target_as = final_machine_world_destroyer }
		stop_crisis_sound = yes
		carrier_event = { id = crisis.2046 }
	}
	every_system_planet = {
		limit = {
			is_star = no
			is_asteroid = no
			NOR = {
				is_planet_class = pc_shattered
				is_planet_class = pc_shattered_2
				is_planet_class = pc_shielded
				is_planet_class = pc_ringworld_habitable_damaged
				is_planet_class = pc_ringworld_tech_damaged
				is_planet_class = pc_ringworld_seam_damaged
			}
		}
		if = {
			limit = { is_colony = yes }
			if = {
				limit = {
					exists = orbital_defence
				}
				destroy_fleet = orbital_defence
			}
			remove_all_buildings = yes
			destroy_colony = yes
			if = {
				limit = { is_planet_class = pc_habitat }
				spawn_habitat_cracker_effect = yes
			}
			else_if = {
				limit = { is_planet_class = pc_cosmogenesis_world }
				spawn_lathe_cracker_effect = yes
			}
			else_if = {
				limit = { is_ringworld = yes }
				spawn_ringworld_cracker_effect = yes
				change_pc = pc_ringworld_habitable_damaged
			}
			else = {
				if = {
					limit = { solar_system = { has_star_flag = destroyed_by_end_of_the_cycle } }
					change_pc = pc_shrouded
				}
				else = { change_pc = pc_shattered }
			}
		}
		else_if = {
			limit = { is_planet_class = pc_habitat } # uncolonized
			spawn_habitat_cracker_effect = yes
		}
		else_if = {
			limit = { is_planet_class = pc_cosmogenesis_world } # uncolonized
			spawn_lathe_cracker_effect = yes
		}
		else_if = {
			limit = { is_ringworld = yes } # uncolonized
			spawn_ringworld_cracker_effect = yes
			change_pc = pc_ringworld_habitable_damaged
		}
		else_if = {
			limit = { is_planet_class = pc_ringworld_tech }
			spawn_ringworld_cracker_effect = yes
			change_pc = pc_ringworld_tech_damaged
		}
		else_if = {
			limit = { is_planet_class = pc_ringworld_seam }
			spawn_ringworld_cracker_effect = yes
			change_pc = pc_ringworld_seam_damaged
		}
		else = {
			if = {
				limit = { solar_system = { has_star_flag = destroyed_by_end_of_the_cycle } }
				change_pc = pc_shrouded
			}
			else = { change_pc = pc_shattered }
		}
	}
	every_system_planet = {
		limit = {
			exists = orbital_station
		}
		orbital_station = { dismantle = yes }
	}
	every_system_planet = {
		clear_deposits = yes
		clear_planet_modifiers = yes
		prevent_anomaly = yes
	}
	every_system_planet = {
		limit = { is_asteroid = yes }
		clear_deposits = yes
	}
	every_fleet_in_system = {
		limit = {
			NOR = {
				is_same_value = from
				# except Extradimensionals
				AND = {
					exists = owner
					owner = {
						OR = {
							is_country_type = portal_holder
							is_country_type = extradimensional
							is_country_type = extradimensional_2
							is_country_type = extradimensional_3
						}
					}
				}
				# except biggest monsters or arkships
				any_owned_ship = {
					OR = {
						is_ship_size = behemoth_04
						is_ship_size = voidspawn_boss
					}
				}
				#except fallen empires
				owner? = {
					OR = {
						is_country_type = fallen_empire
						is_country_type = awakened_fallen_empire
					}
				}
			}
		}
		if = {
			limit = {
				exists = event_target:crisis_country #i.e. not final destruction of all matter
				is_mobile = yes
			}
			set_mia = mia_return_home
		}
		else_if = { # To avoid Nomads game overing.
			limit = {
				is_arkship_fleet = yes
			}
			every_owned_ship = {
				colony? = {
					add_planet_devastation = 90
					every_owned_pop_group = {
						kill_pop_group = {
							pop_group = this
							percentage = 0.5
						}
					}
				}
				reduce_hp_percent = 0.9
			}
			set_mia = mia_return_home
		}
		else = {
			destroy_fleet = this
		}
	}
	every_system_megastructure = {
		set_ruined_megastructure = yes
	}
	star = {
		create_ambient_object = {
			type = "destroyed_system"
			location = this
		}
		last_created_ambient_object = {
			set_ambient_object_flag = destroyed_system_effect
			set_location = {
				target = prev
				distance = 0
				angle = random
			}
		}
	}
	remove_system_terraforming_candidates = yes
}

rebellion_remove_from_wars = {
	if = {
		limit = { is_at_war = yes }
		every_war = {
			limit = {
				NOR = {
					using_war_goal = {
						type = wg_war_in_heaven
						owner = attacker
					}
					using_war_goal = {
						type = wg_declared_crisis
						owner = attacker
					}
				}
			}
			remove_war_participant = prev
		}
		every_subject = {
			every_war = {
				limit = {
					NOR = {
						using_war_goal = {
							type = wg_war_in_heaven
							owner = attacker
						}
						using_war_goal = {
							type = wg_declared_crisis
							owner = attacker
						}
					}
				}
				remove_war_participant = prev
			}
		}
	}
}

add_tech_option_or_research_effect = {
	if = {
		limit = {
			OR = {
				has_technology = $TECH$
				NOT = { can_research_technology = $TECH$ }
			}
		}
		add_monthly_resource_mult = { #18 i.e. @tier2researchreward if $PROGRESS$ is 0.25
			value = @\[( 72 * $PROGRESS$ )]
			resource = $CATEGORY$
		}
	}
	else_if = {
		limit = { NOT = { has_tech_option = $TECH$ } }
		add_research_option = $TECH$
		add_tech_progress = {
			tech = $TECH$
			progress = $PROGRESS$
		}
	}
	else = {
		add_tech_progress = { #give a bit more if they already have the option
			tech = $TECH$ #the formula basically means min( 1, <calced value> ), it's needed because trying to grant more than 1 causes error messages
			progress = @\[ ( ( 1 + ( 1.5 * $PROGRESS$ ) ) / 2 ) - ( | 1 - ( 1.5 * $PROGRESS$ ) | / 2 ) ]
		}
	}
}

add_tech_option_no_progress_effect = {
	if = {
		limit = {
			NOT = { has_technology = $TECH$ }
			can_research_technology = $TECH$
		}
		add_research_option = $TECH$
	}
}

give_tech_no_error_effect = {
	if = {
		limit = {
			NOT = { has_technology = $TECH$ }
		}
		give_technology = {
			message = $MESSAGE$
			tech = $TECH$
		}
	}
}

destroy_machine_world = {
	log = "machine handling fired"
	if = {
		limit = { has_planet_flag = machine_world_1 }
		every_playable_country = {
			limit = { has_event_chain = "ai_crisis_chain" }
			remove_point_of_interest = ai_crisis_poi.1
		}
	}
	else_if = {
		limit = { has_planet_flag = machine_world_2 }
		every_playable_country = {
			limit = { has_event_chain = "ai_crisis_chain" }
			remove_point_of_interest = ai_crisis_poi.2
		}
	}
	else_if = {
		limit = { has_planet_flag = machine_world_3 }
		every_playable_country = {
			limit = { has_event_chain = "ai_crisis_chain" }
			remove_point_of_interest = ai_crisis_poi.3
		}
	}
	else_if = {
		limit = { has_planet_flag = machine_world_4 }
		every_playable_country = {
			limit = { has_event_chain = "ai_crisis_chain" }
			remove_point_of_interest = ai_crisis_poi.4
		}
	}
	if = {
		limit = {
			OR = {
				NOT = { has_carrier_flag = destroyed_by_colossus }
				has_carrier_flag = planet_godrayed
				has_carrier_flag = planet_drenched
				has_carrier_flag = planet_devolved
				has_carrier_flag = planet_burned
			}
		}
		destroy_colony = yes
		change_pc = pc_broken
		reset_planet = yes
		hidden_effect = { clear_deposits = yes }
		add_deposit = d_living_metal_deposit
		add_deposit = d_minerals_3
		add_deposit = d_energy_3
	}
	every_playable_country = {
		limit = { has_event_chain = "ai_crisis_chain" }
		add_event_chain_counter = {
			event_chain = "ai_crisis_chain"
			counter = "active_machine_worlds"
			amount = -1
		}
	}
	random_country = {
		limit = { is_country_type = "ai_empire" }
		change_variable = {
			which = "machine_worlds_destroyed"
			value = 1
		}
		if = {
			limit = {
				check_variable = {
					which = "machine_worlds_destroyed"
					value = 1
				}
			}
			remove_global_flag = ghost_signal_5_flag
			set_global_flag = ghost_signal_4_flag
			every_country = {
				limit = { has_notification_modifier = ghost_signal_5 }
				remove_notification_modifier = ghost_signal_5
				add_notification_modifier = ghost_signal_4
				every_owned_pop_group = {
					limit = { has_modifier = pop_ghost_signal_5 }
					remove_modifier = "pop_ghost_signal_5"
					add_modifier = { modifier = "pop_ghost_signal_4" days = -1 }
				}
				every_controlled_ship = {
					limit = {
						has_sapient_combat_computer = yes
					}
					remove_modifier = "ship_ghost_signal_5"
					add_modifier = { modifier = "ship_ghost_signal_4" days = -1 }
				}
			}
			every_country = {
				limit = { has_notification_modifier = ghost_signal_5_machine }
				remove_notification_modifier = ghost_signal_5_machine
				add_notification_modifier = ghost_signal_4_machine
				every_owned_pop_group = {
					limit = { has_trait = trait_machine_unit }
					remove_modifier = "pop_ghost_signal_5_machine"
					add_modifier = { modifier = "pop_ghost_signal_4_machine" days = -1 }
				}
				every_controlled_ship = {
					limit = {
						has_sapient_combat_computer = yes
					}
					remove_modifier = "ship_ghost_signal_5"
					add_modifier = { modifier = "ship_ghost_signal_4" days = -1 }
				}
			}
			observer_event = { id = observer.50 }
			every_country = {
				limit = { is_ai = no }
				country_event = { id = crisis.2037 }
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = "machine_worlds_destroyed"
					value = 2
				}
			}
			set_global_flag = first_machine_world_destroyed
			remove_global_flag = ghost_signal_4_flag
			set_global_flag = ghost_signal_3_flag
			every_country = {
				limit = { has_notification_modifier = ghost_signal_4 }
				remove_notification_modifier = ghost_signal_4
				add_notification_modifier = ghost_signal_3
				every_owned_pop_group = {
					limit = { has_modifier = "pop_ghost_signal_4" }
					remove_modifier = "pop_ghost_signal_4"
					add_modifier = { modifier = "pop_ghost_signal_3" days = -1 }
				}
				every_controlled_ship = {
					limit = {
						has_sapient_combat_computer = yes
					}
					remove_modifier = "ship_ghost_signal_4"
					add_modifier = { modifier = "ship_ghost_signal_3" days = -1 }
				}
			}
			every_country = {
				limit = { has_notification_modifier = ghost_signal_4_machine }
				remove_notification_modifier = ghost_signal_4_machine
				every_owned_pop_group = {
					limit = { has_trait = trait_machine_unit }
					remove_modifier = "pop_ghost_signal_4_machine"
				}
				every_controlled_ship = {
					limit = {
						has_sapient_combat_computer = yes
					}
					remove_modifier = "ship_ghost_signal_4"
				}
			}
			every_country = {
				limit = { has_special_project = AI_CRISIS_PROJECT }
				abort_special_project = { type = AI_CRISIS_PROJECT }
			}
			observer_event = { id = observer.50 }
			every_country = {
				limit = { is_ai = no }
				country_event = { id = crisis.2037 }
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = "machine_worlds_destroyed"
					value = 3
				}
			}
			remove_global_flag = ghost_signal_3_flag
			set_global_flag = ghost_signal_2_flag
			every_country = {
				limit = { has_notification_modifier = ghost_signal_3 }
				remove_notification_modifier = ghost_signal_3
				add_notification_modifier = ghost_signal_2
				every_owned_pop_group = {
					limit = { has_modifier = pop_ghost_signal_3 }
					remove_modifier = "pop_ghost_signal_3"
					add_modifier = { modifier = "pop_ghost_signal_2" days = -1 }
				}
				every_controlled_ship = {
					limit = {
						has_sapient_combat_computer = yes
					}
					remove_modifier = "ship_ghost_signal_3"
					add_modifier = { modifier = "ship_ghost_signal_2" days = -1 }
				}
			}
			observer_event = { id = observer.50 }
			every_country = {
				limit = { is_ai = no }
				country_event = { id = crisis.2037 }
			}
		}
		else_if = {
			limit = {
				check_variable = {
					which = "machine_worlds_destroyed"
					value = 4
				}
			}
			remove_global_flag = ghost_signal_2_flag
			every_country = {
				limit = { has_notification_modifier = ghost_signal_2 }
				remove_notification_modifier = ghost_signal_2
				add_notification_modifier = ghost_signal_1
				every_owned_pop_group = {
					limit = { has_modifier = pop_ghost_signal_2 }
					remove_modifier = "pop_ghost_signal_2"
					add_modifier = { modifier = "pop_ghost_signal_1" days = -1 }
				}
				every_controlled_ship = {
					limit = {
						has_sapient_combat_computer = yes
					}
					remove_modifier = "ship_ghost_signal_2"
					add_modifier = { modifier = "ship_ghost_signal_1" days = -1 }
				}
			}
			observer_event = { id = observer.50 }
			country_event = { id = crisis.2035 }
		}
	}
}

# Called from galcom resolutions. Needs event_target:new_crisis and event_target:community_war_leader
declare_crisis_war_effect = {
	# community opens internal borders and ceases pre-existing wars with the Crisis
	every_playable_country = {
		limit = {
			is_galactic_community_member = yes
			NOR = {
				has_country_flag = declared_crisis
				is_in_federation_with = event_target:new_crisis
			}
		}
		if = {
			limit = {
				any_war = {
					any_war_participant = {
						is_same_value = event_target:new_crisis
					}
				}
			}
			every_war = {
				limit = {
					any_war_participant = {
						is_same_value = event_target:new_crisis
					}
				}
				remove_war_participant = event_target:new_crisis
			}
		}
		every_playable_country = {
			limit = {
				is_galactic_community_member = yes
				NOR = {
					is_same_value = prev
					has_country_flag = declared_crisis
					is_in_federation_with = event_target:new_crisis
				}
			}
			set_closed_borders = {
				who = prev
				status = no
			}
		}
	}
	event_target:community_war_leader = {
		declare_war = {
			target = event_target:new_crisis
			name = {
				key = "NAME_Declared_Crisis_War"
				variable_string = "\\[This.MainDefender.GetAdj\\]"
			}
			attacker_war_goal = "wg_declared_crisis"
			effect = { save_event_target_as = crisis_war }
		}
	}
	every_playable_country = {
		limit = {
			is_galactic_community_member = yes
			NOR = {
				is_same_value = event_target:community_war_leader
				is_in_federation_with = event_target:new_crisis
			}
		}

		join_war_on_side = {
			war = event_target:crisis_war
			side = event_target:community_war_leader
		}
	}
}

death_cult_sacrifice_effect = {
	#First we need to get the variables that determine how big the boon is

	# Formula is ( initiates * random factor ) / (total pops), and then round that to the nearest 0.1 to avoid weird-looking results
	# Count Mortal Initiates
	export_trigger_value_to_variable = {
		trigger = num_assigned_jobs
		parameters = {
			job = mortal_initiate
		}
		variable = sacrifice_result_mult
	}
	every_subject = {
		# Count Subject Mortal Initiates
		export_trigger_value_to_variable = {
			trigger = num_assigned_jobs
			parameters = {
				job = overlord_mortal_initiate
			}
			variable = sacrifice_vassal_amount
		}
		# Count Subject Mortal Initiate Drones
		export_trigger_value_to_variable = {
			trigger = num_assigned_jobs
			parameters = {
				job = overlord_mortal_initiate_drone
			}
			variable = sacrifice_vassal_amount_drone
		}
		prev = {
			# Add Subject Mortal Initiates to the count
			change_variable = {
				which = sacrifice_result_mult
				value = prev.sacrifice_vassal_amount
			}
			# Add Subject Mortal Initiate Drones to the count
			change_variable = {
				which = sacrifice_result_mult
				value = prev.sacrifice_vassal_amount_drone
			}
		}
	}
	# We do some maths here to calculate the effective percentage of your population sacrificed
	# and cap the bonus to 15% as if you'd sacrificed 15% of your population if it is greater.
	divide_variable = {
		which = sacrifice_result_mult
		value = trigger:pop_amount
	}
	if = {
		limit = {
			check_variable = {
				which = sacrifice_result_mult
				value >= 0.15
			}
		}
		set_variable = {
			which = sacrifice_result_mult
			value = 0.15
		}
	}

	random_list = {
		#This is effectively ( base * random ), where base = 30
		#It is balanced so that sacrificing 5% of your pops gives a really good result
		1 = {
			multiply_variable = {
				which = sacrifice_result_mult
				value = 15
			}
		}
		4 = {
			multiply_variable = {
				which = sacrifice_result_mult
				value = 20
			}
		}
		1 = {
			multiply_variable = {
				which = sacrifice_result_mult
				value = 25
			}
		}
	}
	if = { #small empire penalty: losing 1 pop out of 30 is not the same as 30 out of 900 with logarithmic growth
		limit = { pop_amount > 5000 }
		multiply_variable = {
			which = sacrifice_result_mult
			value = 0.8
		}
		if = {
			limit = { pop_amount > 10000 }
			multiply_variable = {
				which = sacrifice_result_mult
				value = 0.8
			}
		}
	}
	round_variable_to_closest = {
		which = sacrifice_result_mult
		value = 0.1
	}

	#We also need the edicts length multiplier for the modifiers
	export_modifier_to_variable = {
		modifier = edict_length_mult
		variable = edict_length_modifiers
	}
	change_variable = { # Needs to be 1 + mult
		which = edict_length_modifiers
		value = 1
	}

	#Now we do the sacrifice
	every_owned_pop_job = {
		limit = {
			has_job_type = mortal_initiate
		}
		sacrifice_assigned_pop_amount = {
			percentage = 1
		}
	}
	every_subject = {
		limit = {
			any_owned_pop_job = {
				OR = {
					has_job_type = overlord_mortal_initiate
					has_job_type = overlord_mortal_initiate_drone
				}
			}
		}
		set_country_flag = recent_overlord_sacrifice
		every_owned_pop_job = {
			limit = {
				OR = {
					has_job_type = overlord_mortal_initiate
					has_job_type = overlord_mortal_initiate_drone
				}
			}
			kill_assigned_pop_amount = {
				percentage = 1
			}
		}
	}

	# Scale result by the level of any death_cult councilor.
	multiply_variable = {
		which = sacrifice_result_mult
		value = value:sacrifice_edict_power_councilor_death_cult
	}
}


#THIS and ROOT are the Situation
deduce_planetary_separatism_species = {
	target = {
		random_owned_species = {
			limit = {
				is_sapient = yes
				OR = {
					species_has_happiness_with_owner = root.owner
					NOT = {
						prev = {
							any_owned_species = { species_has_happiness_with_owner = root.owner }
						}
					}
				}
				OR = {
					root = {
						NOT = { has_situation_flag = slave_revolt }
					}
					has_citizenship_type = { type = citizenship_slavery country = root.owner }
				}
			}
			weights = {
				base = 100
				complex_trigger_modifier = { #add 0.1 for each unhappy pop of this species
					trigger = count_owned_pop_amount
					trigger_scope = root.target
					potential = {
						species_has_happiness_with_owner = root.owner
					}
					parameters = {
						limit = {
							is_same_species = prevprev #prev should be root.target, prevprev the species
							happiness < 0.3
						}
					}
					mode = add
					mult = 0.1
				}
				complex_trigger_modifier = { #multiply it by the percentage of pops on the planet
					trigger = pop_amount_percentage
					trigger_scope = root.target
					parameters = {
						limit = { is_same_species = prevprev }
					}
					mode = mult
				}
				modifier = { #it looks unusual for a species to rebel against itself
					factor = 0.5
					is_same_species = root.owner
				}
			}
			save_event_target_as = rebellion_species
			set_species_flag = rebellion_species@root
		}
	}
}

#Works from any scope, but event_target:rebellion_species and event_target:revolt_situation need to be set.
ask_empire_if_they_want_this_revolt = {
	ordered_country = {
		position = 0
		order_by = trigger:num_owned_planets
		limit = {
			NOT = { has_country_flag = asked_about_revolt_@event_target:revolt_situation }
			separatism_joining_eligibility_trigger = {
				SPECIES = event_target:rebellion_species
				SITUATION = event_target:revolt_situation
			}
			OR = {
				event_target:revolt_situation.target = {
					OR = {
						is_original_owner = prev
						distance_to_empire = {
							who = prev
							distance < 150
							type = hyperlane
						}
						distance_to_empire = { #extra condition for really close empires on the other side of bypasses
							who = prev
							distance < 75
							type = euclidean
						}
					}
				}
				event_target:revolt_situation.owner = {
					any_owned_planet = {
						has_modifier = instability_join_revolt
						OR = {
							distance_to_empire = {
								who = prevprev
								distance < 150
								type = hyperlane
							}
							distance_to_empire = { #extra condition for really close empires on the other side of bypasses
								who = prevprev
								distance < 75
								type = euclidean
							}
						}
					}
				}
			}
		}
		set_country_flag = asked_about_revolt_@event_target:revolt_situation
		country_event = { id = unrest.4055 }
	}
}

#Call this from the Situation, at the end
cleanup_separatism_situation = {
	owner = {
		every_owned_planet = {
			limit = { has_modifier = instability_join_revolt }
			remove_modifier = instability_join_revolt
		}
		random_owned_species = {
			limit = { has_species_flag = rebellion_species@root }
			remove_species_flag = rebellion_species@root
		}
	}
	target = {
		if = {
			limit = { has_modifier = slave_hunger_strike }
			remove_modifier = slave_hunger_strike
		}
		if = {
			limit = { has_modifier = adding_unrest_slaves }
			remove_modifier = adding_unrest_slaves
		}
		if = {
			limit = { has_modifier = slave_riots }
			remove_modifier = slave_riots
		}
	}
	every_country = {
		limit = { has_country_flag = revolt_joiner_empire_@root }
		remove_country_flag = revolt_joiner_empire_@root
	}
	every_country = {
		limit = { has_country_flag = asked_about_revolt_@root }
		remove_country_flag = asked_about_revolt_@root
	}
}

create_nivlac_effect = {
	if = {
		limit = {
			host_has_dlc = "Plantoids Species Pack"
		}
		create_species = {
			name = "NAME_Nivlac"
			plural = "NAME_Nivlacs"
			class = FUN
			portrait = "fun15"
			namelist = "FUN4"
			extra_trait_points = 2
			traits = {
				trait = "trait_organic"
				trait = "trait_nivlac"
				trait = "trait_plantoid_radiotrophic"
				trait = "trait_quick_learners"
			}
			homeworld = event_target:nivlac_joint_planet
			effect = {
				save_global_event_target_as = nivlac_species
			}
		}
	}

	else = {
		create_species = {
			name = "NAME_Nivlac"
			plural = "NAME_Nivlacs"
			class = FUN
			portrait = "fun15"
			namelist = "FUN4"
			traits = {
				trait = "trait_organic"
				trait = "trait_nivlac"
				trait = "trait_quick_learners"
			}
			homeworld = event_target:nivlac_joint_planet
			effect = {
				save_global_event_target_as = nivlac_species
			}
		}
	}
}

create_baol_species_effect = {
	create_species = {
		name = $SPECIES_NAME$
		plural = $SPECIES_NAME$
		class = "PLANT"
		portrait = pla16_baol
		namelist = PLANT2
		extra_trait_points = 4
		traits = {
			trait = trait_organic
			trait = trait_agrarian
			trait = trait_communal
			trait = trait_venerable
			trait = trait_delicious
			trait = trait_slow_breeders
			trait = trait_pc_gaia_preference
		}
		effect = {
			save_global_event_target_as = $GLOBAL_TARGET$
		}
	}
	if = {
		limit = {
			host_has_dlc = "Plantoids Species Pack"
		}
		event_target:$GLOBAL_TARGET$ = {
			modify_species = {
				species = this
				add_trait = trait_plantoid_phototrophic
				add_traits_at_start_of_list = yes
				effect = {
					save_global_event_target_as = $GLOBAL_TARGET$
				}
			}
		}
	}
}

create_hive_baol_species_effect = {
	create_baol_species_effect = {
		SPECIES_NAME = $SPECIES_NAME$
		GLOBAL_TARGET = $GLOBAL_TARGET$
	}
	event_target:$GLOBAL_TARGET$ = {
		modify_species = {
			species = this
			add_trait = trait_hive_mind
			add_traits_at_start_of_list = yes
			effect = {
				save_global_event_target_as = $GLOBAL_TARGET$
			}
		}
	}
}

create_nu_baol_effect = {
	create_baol_species_effect = {
		SPECIES_NAME = "NAME_Nu_Baol"
		GLOBAL_TARGET = nu_baol_species
	}
}

create_hive_nu_baol_effect = {
	create_hive_baol_species_effect = {
		SPECIES_NAME = "NAME_Nu_Baol"
		GLOBAL_TARGET = nu_baol_species
	}
}

#This will remove the ship, create the deposit, and fire an event to respawn the ship in 15 years
create_origin_dragon_deposit_effect = {
	event_target:here_be_the_dragon_ship = { delete_ship = this }
	add_deposit = d_landed_dragon

	owner = {
		remove_country_flag = space_dragon_about_to_land
	}


	carrier_event = { id = aquatics.170 days = 5400 random = 360 } #about 15 years
}

create_origin_dragon_fleet_effect = {
	create_fleet = {
		name = "NAME_Hrozgar_of_the_Endless_Flames"
		settings = {
			spawn_debris = no
			is_boss = yes
			can_change_leader = no
		}
		effect = {
			set_owner = event_target:here_be_the_dragon_country
			create_ship = {
				name = "NAME_Hrozgar_of_the_Endless_Flames"
				design = "NAME_Sky_Dragon"
				effect = {
					set_ship_flag = here_be_the_dragon_ship
					save_event_target_as = here_be_the_dragon_ship
				}
			}
			set_location = {
				target = event_target:here_be_dragons_planet
				distance = 10
				angle = 90
				direction = in_system
			}
			set_fleet_stance = passive
			set_aggro_range_measure_from = self
			set_aggro_range = 350

			queue_actions = {
				repeat = {
					find_random_planet = {
						found_planet = {
							move_to = this
							orbit_planet = THIS
							wait = 30
						}
					}
				}
			}
		}
	}
}

ice_mining_depletion_effect = {
	owner = {
		random_owned_starbase = {
			limit = {
				has_starbase_building = ice_mining_station
			}
			weights = {
				base = 1
				modifier = {
					factor = 1000
					solar_system = {
						has_star_flag = ice_mining@prevprevprev
					}
				}
				modifier = {
					factor = 0
					NOT = {
						solar_system = {
							has_star_flag = ice_mining@prevprevprev
						}
					}
					owner = {
						any_system_within_border = {
							has_star_flag = ice_mining@prevprevprevprev
							exists = starbase
							starbase = { has_starbase_building = ice_mining_station }
						}
					}
				}
			}
			solar_system = {
				save_event_target_as = mined_system

				if = {
					limit = { has_star_flag = ice_mining@prevprevprev }
					remove_star_flag = ice_mining@prevprevprev
				}
				remove_star_flag = ice_mining_in_progress

				random_system_planet = {
					limit = {
						OR = {
							is_planet_class = pc_ice_asteroid
							is_planet_class = pc_frozen
						}
						NOT = { has_planet_flag = mercenary_enclave_planet }
					}
					if = {
						limit = {
							is_planet_class = pc_ice_asteroid
						}
						if = {
							limit = { exists = orbital_station }
							orbital_station = { delete_fleet = this }
						}
						set_planet_flag = being_killed #probably only removed in the next tick
						remove_planet = yes
					}
					else_if = {
						limit = { planet_size > 1 }
						change_planet_size = -1
						change_variable = {
							which = ice_mined
							value = 1
						}
						if = {
							limit = {
								check_variable = {
									which = ice_mined
									value >= 3
								}
							}
							change_pc = pc_barren_cold
							add_modifier = {
								modifier = ice_mined_planet
							}
						}
					}
					else = {
						change_pc = pc_barren_cold
						add_modifier = {
							modifier = ice_mined_planet
						}
					}
				}
				if = {
					limit = {
						NOT = {
							any_system_planet = {
								OR = {
									is_planet_class = pc_ice_asteroid
									is_planet_class = pc_frozen
								}
								NOT = { has_planet_flag = being_killed }
							}
						}
					}
					root = { set_carrier_flag = temp_ice_mine_exhausted_flag } #deliberately root and not prevprevprev (because that is not always a planet)
				}
			}
		}
	}
}

reduce_unity_celebration = {
	switch = {
		trigger = has_situation_flag
		standard_unity_reward = {
			remove_situation_flag = standard_unity_reward
			set_situation_flag = small_unity_reward
		}
		large_unity_reward = {
			remove_situation_flag = large_unity_reward
			set_situation_flag = standard_unity_reward
		}
		small_unity_reward = {
			owner = {
				add_resource = { unity = -200 }
			}
		}
	}
}
increase_unity_celebration = {
	switch = {
		trigger = has_situation_flag
		small_unity_reward = {
			remove_situation_flag = small_unity_reward
			set_situation_flag = standard_unity_reward
		}
		standard_unity_reward = {
			remove_situation_flag = standard_unity_reward
			set_situation_flag = large_unity_reward
		}
		large_unity_reward = {
			owner = {
				add_monthly_resource_mult = {
					resource = unity
					value = @tier1unityreward
					min = @tier1unitymin
					max = @tier1unitymax
				}
			}
		}
	}
}

set_celebration_modifier = {
	switch = {
		trigger = has_situation_flag
		celebration_ether_drake = {
			target = {
				add_modifier = { modifier = ether_trophy }
			}
		}
		celebration_shard = {
			target = {
				add_modifier = { modifier = shard_trophy }
			}
		}
		celebration_automated_dreadnought = {
			target = {
				add_modifier = { modifier = dread_trophy }
			}
		}
		celebration_tiyanki_matriarch = {
			if = {
				limit = { has_situation_flag = burnt_flagella }
				target = {
					add_modifier = { modifier = burnt_tiyanki_trophy }
				}
			}
			else = {
				target = {
					add_modifier = { modifier = tiyanki_trophy }
				}
			}
		}
		celebration_hrozgar = {
			target = {
				add_modifier = { modifier = sky_dragon_trophy }
			}
		}
		celebration_scavenger_bot = {
			target = {
				add_modifier = { modifier = scavenger_trophy }
			}
		}
		celebration_spectral_wraith = {
			target = {
				add_modifier = { modifier = wraith_trophy }
			}
		}
		celebration_dimensional_horror = {
			if = {
				limit = { has_situation_flag = studied_the_mass }
				target = {
					add_modifier = { modifier = horror_study_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 2480 }
					}
				}
			}
			else_if = {
				limit = { has_situation_flag = contained_the_mass }
				target = {
					add_modifier = { modifier = horror_study_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 4960 }
					}
				}
			}
			else_if = {
				limit = { has_situation_flag = deified_the_mass }
				target = {
					add_modifier = { modifier = horror_deify_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 2480 }
					}
				}
			}
		}
		celebration_worm = {
			if = {
				limit = { has_situation_flag = studied_the_mass }
				target = {
					add_modifier = { modifier = horror_study_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 2480 }
					}
				}
			}
			else_if = {
				limit = { has_situation_flag = contained_the_mass }
				target = {
					add_modifier = { modifier = horror_study_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 4960 }
					}
				}
			}
			else_if = {
				limit = { has_situation_flag = deified_the_mass }
				target = {
					add_modifier = { modifier = horror_deify_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 2480 }
					}
				}
			}
		}
		celebration_elder_one = {
			if = {
				limit = { has_situation_flag = studied_the_mass }
				target = {
					add_modifier = { modifier = horror_study_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 2480 }
					}
				}
			}
			else_if = {
				limit = { has_situation_flag = contained_the_mass }
				target = {
					add_modifier = { modifier = horror_study_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 4960 }
					}
				}
			}
			else_if = {
				limit = { has_situation_flag = deified_the_mass }
				target = {
					add_modifier = { modifier = horror_deify_trophy }
					hidden_effect = {
						carrier_event = { id = situation.1085 days = 2480 }
					}
				}
			}
		}
		celebration_enigmatic_fortress = {
			target = {
				add_modifier = { modifier = fortress_trophy }
			}
		}
		celebration_voidspawn = {
			target = {
				add_modifier = { modifier = voidspawn_trophy }
			}
		}
		celebration_stellar_devourer = {
			target = {
				add_modifier = { modifier = stellar_devourer_trophy }
			}
			owner = {
				set_country_flag = stellar_performance_achievement
			}
		}
	}
}

generate_parade_city = {
	if = {
		limit = {
			any_owned_planet = {
				NOR = {
					has_carrier_flag = recent_parade
					has_modifier = slave_colony
					is_planet_class = pc_cosmogenesis_world
				}
				any_owned_species = {
					OR = {
						has_citizenship_type = { type = citizenship_full country = prev.owner }
						has_citizenship_type = { type = citizenship_full_machine country = prev.owner }
					}
				}
			}
		}
		ordered_owned_planet = {
			limit = {
				NOR = {
					has_carrier_flag = recent_parade
					has_modifier = slave_colony
					is_planet_class = pc_cosmogenesis_world
				}
				any_owned_species = {
					OR = {
						has_citizenship_type = { type = citizenship_full country = prev.owner }
						has_citizenship_type = { type = citizenship_full_machine country = prev.owner }
					}
				}
			}
			position = 0
			order_by = trigger:pop_amount
			save_event_target_as = parade_city
			set_timed_carrier_flag = { flag = recent_parade years = 40 }
		}
	}
	else = {
		ordered_owned_planet = {
			position = 0
			order_by = trigger:pop_amount
			save_event_target_as = parade_city
			remove_carrier_flag = recent_parade
			set_timed_carrier_flag = { flag = recent_parade years = 40 }
		}
	}
}

count_drones_on_planet = {

	set_variable = {
		which = energy_cost
		value = $ENERGY$
	}

	export_trigger_value_to_variable = {
		trigger = count_owned_pop_amount
		parameters = {
			limit = {
				is_robot_pop_group = yes
				is_pop_category = simple_drone
			}
		}
		variable = simple_drones_counter
	}

	set_variable = {
		which = simple_drones_cost
		value = simple_drones_counter
	}
	divide_variable = {
		which = simple_drones_cost
		value = 100
	}
	multiply_variable = {
		which = simple_drones_cost
		value = $ENERGY$
	}

	export_trigger_value_to_variable = {
		trigger = count_owned_pop_amount
		parameters = {
			limit = {
				is_robot_pop_group = yes
				is_pop_category = complex_drone
			}
		}
		variable = complex_drones_counter
	}

	set_variable = {
		which = complex_drones_cost
		value = complex_drones_counter
	}
	divide_variable = {
		which = complex_drones_cost
		value = 100
	}
	multiply_variable = {
		which = complex_drones_cost
		value = $ENERGY$
	}

	export_trigger_value_to_variable = {
		trigger = count_owned_pop_amount
		parameters = {
			limit = {
				is_robot_pop_group = yes
			}
		}
		variable = total_drones_counter
	}

	set_variable = {
		which = total_drones_cost
		value = total_drones_counter
	}
	divide_variable = {
		which = total_drones_cost
		value = 100
	}
	multiply_variable = {
		which = total_drones_cost
		value = $ENERGY$
	}

	set_variable = {
		which = simple_drones_percentage
		value = value:percentage_protected_drones|CATEGORY|simple_drone|
	}

	set_variable = {
		which = complex_drones_percentage
		value = value:percentage_protected_drones|CATEGORY|complex_drone|
	}

	set_variable = {
		which = total_drones_percentage
		value = simple_drones_percentage
	}
	change_variable = {
		which = total_drones_percentage
		value = complex_drones_percentage
	}
}

get_unprotected_drone = {
	if = { # if we're protecting simple drones, target a complex drone
		limit = {
			current_situation_approach = protect_simple_drones
		}
		target = {
			random_owned_pop_group = {
				limit = {
					is_robot_pop_group = yes
					is_pop_category = complex_drone
				}
				save_event_target_as = broken_drone
			}
		}
	}
	else_if = { # if we're protecting complex drones, target a simple drone
		limit = {
			current_situation_approach = protect_complex_drones
		}
		target = {
			random_owned_pop_group = {
				limit = {
					is_robot_pop_group = yes
					is_pop_category = simple_drone
				}
				save_event_target_as = broken_drone
			}
		}
	}
	else = { # if not protecting anyone, grab whatever
		target = {
			random_owned_pop_group = {
			limit = {
				is_robot_pop_group = yes
			}
			save_event_target_as = broken_drone
			}
		}
	}
}

random_stockpile_positive = {
	random_list = {
		5 = {
			add_resource = { food = 200 }
		}
		5 = {
			add_resource = { energy = 200 }
		}
		5 = {
			add_resource = { minerals = 200 }
		}
		5 = {
			add_resource = { alloys = 500 }
		}
	}
}

random_stockpile_negative = {
	random_list = {
		5 = {
			add_resource = { food = -200 }
		}
		5 = {
			add_resource = { energy = -200 }
		}
		5 = {
			add_resource = { minerals = -200 }
		}
		5 = {
			add_resource = { alloys = -200 }
		}
	}
}

# Scope: Country
# VALUE: How much Unity per Empire Size that is added.
add_unity_times_empire_size = {
	add_resource = { unity = $VALUE$ mult = trigger:empire_size }
}

country_defaulted_in_situation_tooltip = {
	tooltip = {
		owner = { country_defaulted_effect = yes }
	}
	custom_tooltip = deficit_situation_extra_defaulted_tooltip
}

country_defaulted_effect = {
	if = {
		limit = { is_wilderness_empire = yes }
		add_modifier = {
			modifier = country_defaulted_wilderness
			years = 10
		}
	}
	else = {
		add_modifier = {
			modifier = country_defaulted
			years = 10
		}
	}
	hidden_effect = {
		if = {
			limit = { is_ai = yes }
			log = "AI [This.GetName] defaulted as a result of [Root.GetName] in [GetYear]"
		}
		else = {
			log = "Player [This.GetName] defaulted as a result of [Root.GetName] in [GetYear]"
		}
		downgrade_all_buildings = yes
		every_owned_ship = {
			limit = { is_ship_class = shipclass_military }
			random = {
				chance = 50
				if = {
					limit = {
						exists = leader
					}
					leader = {
						unassign_leader = this
					}
				}
				delete_ship = this
			}
		}
		every_owned_army = {
			limit = { is_defensive_army = no }
			if = {
				limit = {
					exists = leader
				}
				leader = {
					unassign_leader = this
				}
			}
			remove_army = yes
		}
	}
	custom_tooltip = end_deficit_effect_tooltip
	if = {
		limit = {
			any_situation = {
				NOT = { is_same_value = root }
				has_situation_flag = deficit_situation
			}
		}
		custom_tooltip = end_other_deficit_situations_tooltip
		hidden_effect = {
			every_situation = {
				limit = {
					NOT = { is_same_value = root }
					has_situation_flag = deficit_situation
				}
				abort_situation = this
			}
		}
	}
}

count_robots_to_recycle = {

	set_variable = {
		which = alloys_for_robot
		value = $ALLOYS$
	}

	set_variable = {
		which = recycled_robots
		value = 0
	}

	# if machine empire, get half of the population
	if = {
		limit = {
			owner = { is_machine_empire = yes }
		}
		export_trigger_value_to_variable = {
			trigger = count_owned_pop_amount
			parameters = {
				limit = {
					is_robot_pop_group = yes
				}
			}
			variable = recycled_robots
		}
		divide_variable = {
			which = recycled_robots
			value = 2
		}

		round_variable = recycled_robots
	}
	# if normal empire, get all robots
	else = {
		export_trigger_value_to_variable = {
			trigger = count_owned_pop_amount
			parameters = {
				limit = {
					OR = {
						is_shackled_robot = yes
						is_non_sapient_robot = yes
					}
				}
			}
			variable = recycled_robots
		}
	}

	set_variable = {
		which = recycled_robots_100
		value = recycled_robots
	}

	divide_variable = {
		which = recycled_robots_100
		value = 100
	}

	set_variable = {
		which = total_alloys_gained
		value = recycled_robots_100
	}

	multiply_variable = {
		which = total_alloys_gained
		value = $ALLOYS$
	}
}

give_physics_tech_tier_1_effect = {
	give_technology = { tech = tech_basic_science_lab_2 }
	give_technology = { tech = tech_space_science_1 }
	give_technology = { tech = tech_space_science_2 }
	give_technology = { tech = tech_administrative_ai }
	give_technology = { tech = tech_cryostasis_1 }
	give_technology = { tech = tech_automated_exploration }
	give_technology = { tech = tech_combat_computers_1 }
	give_technology = { tech = tech_auxiliary_fire_control }
	give_technology = { tech = tech_encryption_1 }
	give_technology = { tech = tech_decryption_1 }
	give_technology = { tech = tech_fusion_power }
	give_technology = { tech = tech_reactor_boosters_2 }
	give_technology = { tech = tech_reactor_boosters_3 }
	give_technology = { tech = tech_shields_2 }
	give_technology = { tech = tech_power_plant_2 }
	give_technology = { tech = tech_power_hub_1 }
}

give_physics_tech_tier_2_effect = {
	give_technology = { tech = tech_curator_lab }
	if = {
		limit = {
			has_ancrel = yes
		}
		give_technology = { tech = tech_archeology_lab_ancrel }
	}
	else = {
		give_technology = { tech = tech_archeology_lab }
	}
	give_technology = { tech = tech_space_science_3 }
	give_technology = { tech = tech_space_science_4 }
	give_technology = { tech = tech_self_aware_logic }
	if = {
		limit = {
			OR = {
				is_gestalt = no
				has_valid_civic = civic_machine_servitor
			}
		}
		give_technology = { tech = tech_consumer_good_refinement_1 }
	}
	give_technology = { tech = tech_encryption_2 }
	give_technology = { tech = tech_decryption_2 }
	give_technology = { tech = tech_cold_fusion_power }
	give_technology = { tech = tech_shields_3 }
	give_technology = { tech = tech_shield_rechargers_1 }
	give_technology = { tech = tech_sensors_2 }
	give_technology = { tech = tech_power_plant_3 }
	give_technology = { tech = tech_power_hub_2 }
	give_technology = { tech = tech_hyper_drive_2 }
	give_technology = { tech = tech_ftl_inhibitor }
}

give_engineering_tech_tier_1_effect = {
	give_technology = { tech = tech_corvette_build_speed }
	give_technology = { tech = tech_corvette_hull_1 }
	give_technology = { tech = tech_strike_craft_1 }
	give_technology = { tech = tech_ship_armor_2 }
	give_technology = { tech = tech_powered_exoskeletons }
	give_technology = { tech = tech_space_mining_1 }
	give_technology = { tech = tech_space_mining_2 }
	give_technology = { tech = tech_mining_1 }
	give_technology = { tech = tech_mineral_purification_1 }
	give_technology = { tech = tech_alloys_1 }
	give_technology = { tech = tech_luxuries_1 }
	give_technology = { tech = tech_robotic_workers }
	give_technology = { tech = tech_afterburners_1 }
	give_technology = { tech = tech_assembly_pattern }
}

give_engineering_tech_tier_2_effect = {
	give_technology = { tech = tech_destroyers }
	give_technology = { tech = tech_corvette_hull_2 }
	give_technology = { tech = tech_destroyer_build_speed }
	give_technology = { tech = tech_destroyer_hull_1 }
	give_technology = { tech = tech_starbase_3 }
	give_technology = { tech = tech_modular_engineering }
	give_technology = { tech = tech_strike_craft_2 }
	give_technology = { tech = tech_ship_armor_3 }
	give_technology = { tech = tech_crystal_armor_1 }
	give_technology = { tech = tech_thrusters_2 }
	give_technology = { tech = tech_defense_platform_hull_1 }
	give_technology = { tech = tech_space_mining_3 }
	give_technology = { tech = tech_space_mining_4 }
	give_technology = { tech = tech_mining_2 }
	give_technology = { tech = tech_mineral_purification_2 }
	give_technology = { tech = tech_advanced_metallurgy_1 }
	give_technology = { tech = tech_droid_workers }
	give_technology = { tech = tech_housing_1 }
}

give_society_tech_tier_1_effect = {
	if = {
		limit = {
			is_regular_empire = yes
		}
		give_technology = { tech = tech_space_trading }
	}
	give_technology = { tech = tech_eco_simulation }
	give_technology = { tech = tech_food_processing_1 }
	if = {
		limit = {
			is_regular_empire = yes
		}
		give_technology = { tech = tech_alien_life_studies }
	}
	if = {
		limit = {
			is_regular_empire = yes
		}
		give_technology = { tech = tech_frontier_health }
	}
	give_technology = { tech = tech_dense_jungle }
	give_technology = { tech = tech_quicksand_basin }
	give_technology = { tech = tech_noxious_swamp }
	give_technology = { tech = tech_massive_glacier }
	give_technology = { tech = tech_toxic_kelp }
	give_technology = { tech = tech_deep_sinkhole }
	if = {
		limit = {
			OR = {
				is_machine_empire = no
				has_civic = civic_machine_assimilator
				has_civic = civic_machine_servitor
			}
		}
		give_technology = { tech = tech_genome_mapping }
	}
	give_technology = { tech = tech_ground_defense_planning }
	give_technology = { tech = tech_planetary_unification }
	give_technology = { tech = tech_adaptive_bureaucracy }
	if = {
		limit = {
			is_regular_empire = yes
		}
		give_technology = { tech = tech_neural_implants }
	}
	if = {
		limit = {
			is_gestalt = no
		}
		give_technology = { tech = tech_hyper_entertainment_forum }
	}
	if = {
		limit = {
			NOR = {
				is_spiritualist = yes
				has_valid_civic = civic_machine_servitor
			}
		}
		give_technology = { tech = tech_heritage_site }
	}
}

give_society_tech_tier_2_effect = {
	give_technology = { tech = tech_gene_crops }
	give_technology = { tech = tech_arcane_deciphering }
	if = {
		limit = {
			OR = {
				is_machine_empire = no
				has_civic = civic_machine_assimilator
				has_civic = civic_machine_servitor
			}
		}
		give_technology = { tech = tech_colonization_2 }
	}
	if = {
		limit = {
			OR = {
				is_machine_empire = no
				has_civic = civic_machine_assimilator
				has_civic = civic_machine_servitor
			}
		}
		give_technology = { tech = tech_colonization_3 }
	}
	if = {
		limit = {
			is_gestalt = no
		}
		give_technology = { tech = tech_frontier_hospital }
	}
	give_technology = { tech = tech_mountain_range }
	give_technology = { tech = tech_volcano }
	give_technology = { tech = tech_dangerous_wildlife }
	give_technology = { tech = tech_terrestrial_sculpting }
	if = {
		limit = {
			OR = {
				is_machine_empire = no
				has_civic = civic_machine_assimilator
			}
		}
		give_technology = { tech = tech_vitality_boosters }
	}
	if = {
		limit = {
			NOT = {
				has_valid_civic = civic_fanatic_purifiers
				#has_valid_civic = civic_machine_terminator # covered by not being machine
				#has_valid_civic = civic_hive_devouring_swarm # can uplift to make delicious
			}
			OR = {
				is_machine_empire = no
				is_wilderness_empire = no
				has_civic = civic_machine_assimilator
				has_civic = civic_machine_servitor
			}
		}
		give_technology = { tech = tech_epigenetic_triggers }
	}
	if = {
		limit = {
			OR = {
				is_machine_empire = no
				has_civic = civic_machine_assimilator
			}
		}
		give_technology = { tech = tech_cloning }
	}
	if = {
		limit = {
			OR = {
				is_machine_empire = no
				is_wilderness_empire = no
				has_civic = civic_machine_assimilator
			}
		}
		give_technology = { tech = tech_gene_banks }
	}
	give_technology = { tech = tech_doctrine_fleet_size_1 }
	give_technology = { tech = tech_doctrine_fleet_size_2 }
	give_technology = { tech = tech_interstellar_fleet_traditions }
	give_technology = { tech = tech_doctrine_navy_size_1 }
	give_technology = { tech = tech_centralized_command }
	give_technology = { tech = tech_global_defense_grid }
	give_technology = { tech = tech_galactic_ambitions }
	give_technology = { tech = tech_interstellar_campaigns }
	give_technology = { tech = tech_colonial_centralization }
	give_technology = { tech = tech_planetary_infrastructure_1 }
	if = {
		limit = {
			NOT = { has_ethic = ethic_gestalt_consciousness	}
		}
		give_technology = { tech = tech_subdermal_stimulation }
	}
	give_technology = { tech = tech_effective_bureaucracy }
	give_technology = { tech = tech_colonial_bureaucracy }
	if = {
		limit = {
			NOT = { has_ethic = ethic_gestalt_consciousness }
		}
		give_technology = { tech = tech_living_state }
	}
	if = {
		limit = {
			has_ethic = ethic_gestalt_consciousness
		}
		give_technology = { tech = tech_autonomous_agents }
	}
	if = {
		limit = {
			NOT = { has_ethic = ethic_gestalt_consciousness }
		}
		give_technology = { tech = tech_artificial_moral_codes }
	}
	if = {
		limit = {
			is_gestalt = yes
		}
		give_technology = { tech = tech_unity_of_purpose }
	}
	if = {
		limit = {
			has_ethic = ethic_gestalt_consciousness
		}
		give_technology = { tech = tech_holographic_rituals }
	}
	if = {
		limit = {
			is_hive_empire = yes
			is_wilderness_empire = no
		}
		give_technology = { tech = tech_hive_cluster }
	}
	if = {
		limit = {
			is_wilderness_empire = yes
		}
		give_technology = { tech = tech_wilderness_cluster }
	}
	if = {
		limit = {
			is_gestalt = no
		}
		give_technology = { tech = tech_slave_colonies }
	}
	if = {
		limit = {
			is_regular_empire = yes
		}
		give_technology = { tech = tech_xeno_diplomacy }
	}
	give_technology = { tech = tech_capital_productivity_1 }
}

add_basic_resources_effect = {
	add_resource = { energy = $VALUE$ }
	add_resource = { minerals = $VALUE$ }
	add_resource = { food = $VALUE$ }
}

add_manufactured_resources_effect = {
	add_resource = { consumer_goods = $VALUE$ }
	add_resource = { alloys = $VALUE$ }
}

add_advanced_resources_effect = {
	add_resource = { volatile_motes = $VALUE$ }
	add_resource = { exotic_gases = $VALUE$ }
	add_resource = { rare_crystals = $VALUE$ }
}

add_rare_resources_effect = {
	add_resource = { sr_living_metal = $VALUE$ }
	add_resource = { sr_zro = $VALUE$ }
	add_resource = { sr_dark_matter = $VALUE$ }
	add_resource = { nanites = $VALUE$ }
}

central_crystal_spawn_effect = {
	if = {
		limit = {
			galaxy_size = tiny
		}
		no_scope = {
			# makes system positions originate from galactic core
			spawn_system = {
				min_distance >= 40
				max_distance <= 40
				min_orientation_angle = 90
				max_orientation_angle = 90
				initializer = $INITIALIZER$
				hyperlane = no
			}
		}
	}
	else_if = {
		limit = {
			galaxy_size = small
		}
		no_scope = {
			# makes system positions originate from galactic core
			spawn_system = {
				min_distance >= 60
				max_distance <= 60
				min_orientation_angle = 90
				max_orientation_angle = 90
				initializer = $INITIALIZER$
				hyperlane = no
			}
		}
	}
	else_if = {
		limit = {
			galaxy_size = medium
		}
		no_scope = {
			# makes system positions originate from galactic core
			spawn_system = {
				min_distance >= 80
				max_distance <= 80
				min_orientation_angle = 90
				max_orientation_angle = 90
				initializer = $INITIALIZER$
				hyperlane = no
			}
		}
	}
	else_if = {
		limit = {
			galaxy_size = large
		}
		no_scope = {
			# makes system positions originate from galactic core
			spawn_system = {
				min_distance >= 90
				max_distance <= 90
				min_orientation_angle = 90
				max_orientation_angle = 90
				initializer = $INITIALIZER$
				hyperlane = no
			}
		}
	}
	else_if = {
		limit = {
			galaxy_size = huge
		}
		no_scope = {
			# makes system positions originate from galactic core
			spawn_system = {
				min_distance >= 95
				max_distance <= 95
				min_orientation_angle = 90
				max_orientation_angle = 90
				initializer = $INITIALIZER$
				hyperlane = no
			}
		}
	}
}

central_crystal_country_spawn_effect = {
	create_species = {
		name = "NAME_Central_Crystal_Species"
		plural = "NAME_Central_Crystal_Species"
		class = PRE_ART
		portrait = art20
		namelist = "ART4"
		traits = {
			trait = trait_pc_habitat_preference
			trait = trait_organic
			trait = trait_void_dweller_1
			trait = trait_intelligent
			trait = trait_docile
		}
		homeworld = this

		effect = {
			save_global_event_target_as = crystalline_empire_species
		}
	}

	create_country = {
		name = "NAME_Central_Crystal_Country"
		type = enclave
		authority = auth_imperial
		civics = {
			civic = civic_imperial_cult
			civic = civic_aristocratic_elite
		}
		species = last_created_species
		ethos = {
			ethic = "ethic_authoritarian"
			ethic = "ethic_pacifist"
			ethic = "ethic_spiritualist"
		}
		flag = {
			icon = {
				file = "flag_spherical_5.dds"
				category = spherical
			}
			background = {
				category = "backgrounds"
				file = "00_solid.dds"
			}
			colors ={
				"blue"
				"blue"
				"null"
				"null"
			}
		}

		ignore_initial_colony_error = yes

		effect = {
			create_leader = {
				class = random_ruler
				species = this
				name = random
				skill = 5
				immortal = yes
			}
			set_leader = last_created_leader
		}
	}
	last_created_country = {
		save_global_event_target_as = central_crystal_empire
		set_country_flag = central_crystal_country

		set_graphical_culture = mammalian_01

		set_male_ruler_title = "RT_CENTRAL_CRYSTAL_COMMANDER"
		set_female_ruler_title = "RT_CENTRAL_CRYSTAL_COMMANDER"

		create_fleet = {
			name = "NAME_Central_Crystal_Enclave"
			settings = { spawn_debris = no }
			effect = {
				set_owner = prev
				create_ship = {
					name = random
					design = "NAME_Central_Crystal_Station"
					graphical_culture = prev
				}
				set_location = {
					target = prevprev
					angle = random
					distance = 100
				}
				save_event_target_as = CustomCapital
				prev = {
					set_custom_capital_location = event_target:CustomCapital
				}
			}
		}
	}
	solar_system = {
		save_global_event_target_as = the_outer_gate
	}
}

create_zombie_pop_group = {
	weighted_random_owned_pop_group = {
		limit = {
			NOT = { has_trait = trait_hive_mind }
			NOT = { has_trait = trait_zombie }
			is_robot_pop_group = no
			# Forever Cruise: only zombify crew species, not passengers
			OR = {
				owner = { NOT = { has_origin = origin_forever_cruise } }
				has_citizenship_type = { country = owner type = citizenship_cruise_crew }
			}
		}
		save_event_target_as = old_pop_group
		species = {
			save_event_target_as = old_species
		}
	}
	if = {
		limit = {
			NOT = {
				any_galaxy_species = {
					has_species_flag = zombie_species_of_species@event_target:old_species
				}
			}
		}
		event_target:old_species = {
			modify_species = {
				species = this
				add_trait = trait_zombie
				remove_trait = trait_nerve_stapled
				remove_trait = trait_syncretic_proles
				effect = {
					set_species_flag = zombie_species_of_species@event_target:old_species
					save_event_target_as = target_species
				}
			}
		}
	}
	else = {
		random_galaxy_species = {
			limit = {
				has_species_flag = zombie_species_of_species@event_target:old_species
			}
			save_event_target_as = target_species
		}
	}
	create_pop_group = {
		pop_group = event_target:old_pop_group
		species = event_target:target_species
		size = $SIZE$
		category = worker
	}
}

set_ruined_megastructure = {
	if = {
		limit = {
			OR = {
				is_megastructure_type = ring_world_restored
				is_megastructure_type = ring_world_ruined
				is_megastructure_type = ring_world_2
			}
		}
		solar_system = {
			spawn_planet = {
				class = "pc_ringworld_tech_damaged"
				location = prev
				orbit_angle_offset = 30
			}
			spawn_planet = {
				class = "pc_ringworld_seam_damaged"
				location = prev
			}
			spawn_planet = {
				class = "pc_ringworld_habitable_damaged"
				location = prev
				orbit_angle_offset = -30
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = spy_orb_1
				is_megastructure_type = spy_orb_2
				is_megastructure_type = spy_orb_3
				is_megastructure_type = spy_orb_4
				is_megastructure_type = spy_orb_ruined
				is_megastructure_type = spy_orb_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "spy_orb_permanently_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = think_tank_1
				is_megastructure_type = think_tank_2
				is_megastructure_type = think_tank_3
				is_megastructure_type = think_tank_4
				is_megastructure_type = think_tank_ruined
				is_megastructure_type = think_tank_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "think_tank_permanently_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = strategic_coordination_center_1
				is_megastructure_type = strategic_coordination_center_2
				is_megastructure_type = strategic_coordination_center_3
				is_megastructure_type = strategic_coordination_center_ruined
				is_megastructure_type = strategic_coordination_center_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "strategic_coordination_center_permanently_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = mega_art_installation_1
				is_megastructure_type = mega_art_installation_2
				is_megastructure_type = mega_art_installation_3
				is_megastructure_type = mega_art_installation_4
				is_megastructure_type = mega_art_installation_ruined
				is_megastructure_type = mega_art_installation_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "mega_art_installation_permanently_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = interstellar_assembly_1
				is_megastructure_type = interstellar_assembly_2
				is_megastructure_type = interstellar_assembly_3
				is_megastructure_type = interstellar_assembly_4
				is_megastructure_type = interstellar_assembly_ruined
				is_megastructure_type = interstellar_assembly_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "interstellar_assembly_permanently_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = mega_shipyard_1
				is_megastructure_type = mega_shipyard_2
				is_megastructure_type = mega_shipyard_3
				is_megastructure_type = mega_shipyard_ruined
				is_megastructure_type = mega_shipyard_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "mega_shipyard_permanently_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = matter_decompressor_1
				is_megastructure_type = matter_decompressor_2
				is_megastructure_type = matter_decompressor_3
				is_megastructure_type = matter_decompressor_4
				is_megastructure_type = matter_decompressor_ruined
				is_megastructure_type = matter_decompressor_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "matter_decompressor_permanently_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = quantum_catapult_1
				is_megastructure_type = quantum_catapult_2
				is_megastructure_type = quantum_catapult_3
				is_megastructure_type = quantum_catapult_ruined
				is_megastructure_type = quantum_catapult_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "quantum_catapult_permanently_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = hyper_relay
				is_megastructure_type = hyper_relay_restored
			}
		}
		solar_system = {
			spawn_megastructure = {
				type = "hyper_relay_ruined"
				coords_from = prev
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = { is_crisis_sphere = yes }
		solar_system = {
			spawn_megastructure = {
				type = crisis_sphere_ruined
				coords_from = prev
				init_effect = {
					random_country = {
						limit = {
							prevprevprev = { has_megastructure_flag = crisis_sphere_of@prev }
						}
						save_event_target_as = former_owner
					}
					set_megastructure_flag = crisis_sphere_of@event_target:former_owner
				}
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = {
			OR = {
				is_megastructure_type = orbital_arc_furnace_1
				is_megastructure_type = orbital_arc_furnace_2
				is_megastructure_type = orbital_arc_furnace_3
				is_megastructure_type = orbital_arc_furnace_4
				is_megastructure_type = orbital_arc_furnace_restored
			}
		}
		solar_system = {
			random_system_planet = {
				limit = {
					has_planet_flag = has_arc_furnace
				}
				save_event_target_as = arc_furnace_world
			}
			spawn_megastructure = {
				type = "orbital_arc_furnace_destroyed"
				planet = event_target:arc_furnace_world
			}
			every_system_planet = {
				limit = {
					OR = {
						has_modifier = orbital_arc_furnace_1_mod
						has_modifier = orbital_arc_furnace_2_mod
						has_modifier = orbital_arc_furnace_3_mod
						has_modifier = orbital_arc_furnace_4_mod
					}
				}
				dismantle_arc_furnace_effect = yes
			}
		}
		remove_megastructure = this
	}
	else_if = {
		limit = { is_megastructure_type = grand_archive_0 }
		solar_system = {
			system_event = { id = grand_archive.4501 }
		}
	}
	else = {
		remove_megastructure = this
	}
}

# This = Grand Archive (megastructure)
destroy_grand_archive = {
	if = {
		limit = { is_megastructure_type = grand_archive_0 }
		create_ambient_object = {
			type = "large_debris_object"
			location = this
		}
		last_created_ambient_object = {
			set_location = {
				target = prev
				distance = 35
				angle = 30
			}
		}
		if = {
			limit = { exists = planet }
			planet = { remove_planet_flag = has_megastructure }
		}
		remove_megastructure = this
	}
}

clean_up_voidspawn_situation = {
	remove_modifier = voidspawn_contaminant
}

shroud_world_zro_deposit_effect = {
	random_list = {
		1 = {
			add_deposit = d_zro_deposit_1
		}
		4 = {
			add_deposit = d_zro_deposit_2
		}
		1 = {
			add_deposit = d_zro_deposit_3
		}
	}
	while = {
		count = value:get_shroud_forged_pop_thousands
		add_deposit = d_zro_deposit_1
	}
	random = {
		chance = value:get_shroud_forged_pop_zro_chance
		add_deposit = d_zro_deposit_1
	}
}

decision_shroud_region_effect = {
	hidden_effect = {
		random_deposit = {
			limit = {
				is_blocker = no
				NOR = {
					is_deposit_type = d_shroud_rift_deposit
					has_deposit_category = deposit_cat_rare
					has_deposit_category = deposit_cat_rare_resource
					has_deposit_category = deposit_cat_rare_blocker
				}
			}
			remove_deposit = yes
		}
	}
	add_deposit = d_shroud_rift_deposit

	close_shroud_rift_effect = yes
}

open_shroud_rift_effect = {
	hidden_effect = {
		if = {
			limit = {
				NOT = {
					has_carrier_flag = origin_shroud_forged_capital_flag
				}
			}
			create_ambient_object = {
				type = shroud_rift_object
				scale = 0.2
				entity_offset_height = -17
				location = this
			}
			last_created_ambient_object = {
				set_location = {
					target = prev
				}
				set_ambient_object_flag = shroud_rift@root
			}
		}
	}
}

close_shroud_rift_effect = {
	hidden_effect = {
		if = {
			limit = {
				NOT = {
					has_carrier_flag = origin_shroud_forged_capital_flag
				}
			}
			solar_system = {
				every_system_ambient_object = {
					limit = {
						has_ambient_object_flag = shroud_rift@root
					}
					destroy_ambient_object = this
				}
			}
		}
	}
}

remove_system_terraforming_candidates = {
	every_system_planet = {
		limit = {
			has_modifier = terraforming_candidate
		}
		remove_modifier = terraforming_candidate
	}
	every_system_planet = {
		limit = {
			has_modifier = frozen_terraforming_candidate
		}
		remove_modifier = frozen_terraforming_candidate
	}
	every_system_planet = {
		limit = {
			has_modifier = toxic_terraforming_candidate
		}
		remove_modifier = toxic_terraforming_candidate
	}
}

set_origin_effect = {
	country_event = { id = game_start.8 }
	give_starting_resources_effect = yes
	# Necrophages
	if = {
		limit = {
			has_trait = trait_necrophage
		}
		set_origin = origin_necrophage
	}
	# Subterranean
	else_if = {
		limit = {
			has_trait = trait_cave_dweller
		}
		set_origin = origin_subterranean
	}
	# Subterranean Machines
	else_if = {
		limit = {
			has_trait = trait_robot_cave_dweller
		}
		set_origin = origin_subterranean_machines
	}
	# Void Dwellers
	else_if = {
		limit = {
			has_trait = trait_void_dweller_1
		}
		set_origin = origin_void_dwellers
	}
	# Void Machines
	else_if = {
		limit = {
			has_trait = trait_void_dweller_2
		}
		set_origin = origin_void_machines
	}
	# Calamitous Birth
	else_if = {
		limit = {
			$SOURCE_COUNTRY$ = { has_origin = origin_lithoid }
			has_trait = trait_lithoid
		}
		set_origin = origin_lithoid
	}
	# Liberated
	else_if = {
		limit = {
			has_country_flag = released_empire
		}
		set_origin = origin_liberated
	}
	else = {
		set_origin = origin_default
	}

	# Fix hive/machine
	if = {
		limit = {
			is_machine_empire = yes
			NOT = { has_trait = trait_machine_unit }
		}
		country_remove_ethic = ethic_gestalt_consciousness
		shift_ethic = ethic_xenophobe
		change_government = random
	}
	else_if = {
		limit = {
			is_hive_empire = yes
			NOT = { has_trait = trait_hive_mind }
		}
		country_remove_ethic = ethic_gestalt_consciousness
		shift_ethic = ethic_xenophobe
		change_government = random
	}
	else_if = {
		limit = {
			is_machine_empire = no
			$SOURCE_COUNTRY$ = {
				is_machine_empire = yes
			}
			has_trait = trait_machine_unit
		}
		shift_ethic = ethic_gestalt_consciousness
		change_government = {
			authority = auth_machine_intelligence
			cooldown = no
			remove_invalid_civics = yes
		}
	}
	else_if = {
		limit = {
			is_hive_empire = no
			has_trait = trait_hive_mind
		}
		shift_ethic = ethic_gestalt_consciousness
		change_government = {
			authority = auth_hive_mind
			cooldown = no
			remove_invalid_civics = yes
		}
	}
	country_event = { id = game_start.70 }
	country_event = { id = game_start.72 }
}

set_merchant_government_effect = {
	if = {
		limit = { has_civic = civic_criminal_heritage }
		if = {
			limit = { has_technology = tech_galactic_administration }
			change_government = {
				authority = auth_oligarchic
				cooldown = no
				remove_invalid_civics = yes
				civics = { civic = civic_merchant_guilds civic = civic_dystopian_society civic = random }
			}
		}
		else = {
			change_government = {
				authority = auth_oligarchic
				cooldown = no
				remove_invalid_civics = yes
				civics = { civic = civic_merchant_guilds civic = civic_dystopian_society }
			}
		}
	}
	else_if = {
		limit = { has_civic = civic_worker_coop }
		shift_ethic = ethic_fanatic_egalitarian
		if = {
			limit = { has_technology = tech_galactic_administration }
			change_government = {
				authority = auth_democratic
				cooldown = no
				remove_invalid_civics = yes
				civics = { civic = civic_merchant_guilds civic = civic_shared_burden civic = random }
			}
		}
		else = {
			change_government = {
				authority = auth_democratic
				cooldown = no
				remove_invalid_civics = yes
				civics = { civic = civic_merchant_guilds civic = civic_shared_burden }
			}
		}
	}
	else = {
		if = {
			limit = { has_technology = tech_galactic_administration }
			change_government = {
				authority = auth_oligarchic
				cooldown = no
				remove_invalid_civics = yes
				civics = { civic = civic_merchant_guilds civic = random civic = random }
			}
		}
		else = {
			change_government = {
				authority = auth_oligarchic
				cooldown = no
				remove_invalid_civics = yes
				civics = { civic = civic_merchant_guilds civic = random }
			}
		}
	}
}

impose_ideology_effect = {
	if = {
		limit = {
			is_ai = yes
			OR = {
				has_origin = origin_legendary_leader
				has_origin = origin_legendary_leader_imperial
				has_origin = origin_legendary_leader_dictatorial
			}
		}
		random_owned_leader = {
			limit = { is_ruler = yes }
			kill_leader = { show_notification = yes }
		}
		set_origin = origin_legendary_leader_death
	}
	copy_ethos_and_authority = root
	if = {
		limit = {
			has_civic = civic_galactic_sovereign
		}
		force_remove_civic = civic_galactic_sovereign
	}
	if = {
		limit = {
			has_civic = civic_galactic_sovereign_megacorp
		}
		force_remove_civic = civic_galactic_sovereign_megacorp
	}
	if = {
		limit = {
			has_civic = civic_psionic_sovereign
		}
		force_remove_civic = civic_psionic_sovereign
	}
	if = {
		limit = {
			root = { is_megacorp = yes }
			is_megacorp = yes
		}
		set_merchant_government_effect = yes
	}
	if = {
		limit = {
			root = { has_civic = civic_shared_burden }
		}
		force_remove_civic_by_index = 1
		force_add_civic = civic_shared_burden
	}
	if = {
		limit = {
			root = { has_civic = civic_crusader_spirit }
		}
		force_remove_civic_by_index = 1
		force_add_civic = civic_crusader_spirit
	}
	add_modifier = { modifier = recently_liberated days = 7200 }
	add_opinion_modifier = { modifier = opinion_liberated_us who = root }
	root = {
		add_opinion_modifier = { modifier = opinion_we_liberated who = from }
	}
}

detox_hangover = {
	add_blocker = { type = d_tainted_snowcaps }
	add_blocker = { type = d_poisonous_algae }
	add_blocker = { type = d_venomous_insects }
	add_blocker = { type = d_unpleasant_atmosphere }
	add_blocker = { type = d_rotten_soil }
	hidden_effect = {
		if = {
			limit = { has_modifier = toxic_terraforming_candidate }
			remove_modifier = toxic_terraforming_candidate
		}
	}
}

zroni_legacy_planet_check_effect = {
	if = {
		limit = {
			has_carrier_flag = $FLAG$
		}
		if = {
			limit = {
				exists = event_target:$GLOBAL_TARGET$
			}
			event_target:$GLOBAL_TARGET$ = {
				if = {
					limit = {
						has_event_chain = shroud_forged_chain
					}
					add_event_chain_counter = {
						event_chain = shroud_forged_chain
						counter = shroud_forged_zroni_planet
						amount = -1
					}
					if = {
						limit = {
							prev = { has_building = building_zroni_equilibrator }
						}
						add_event_chain_counter = {
							event_chain = shroud_forged_chain
							counter = shroud_forged_zroni_portal
							amount = -1
						}
					}
				}
				if = {
					limit = {
						has_modifier = shroud_forged_trapped_entity
					}
					remove_modifier = shroud_forged_trapped_entity
					country_event = { id = shroud_forged.320 }
				}
			}
			clear_global_event_target = $GLOBAL_TARGET$
		}
		if = {
			limit = {
				exists = from
				is_owned_by = from
			}
			from = {
				save_global_event_target_as = $GLOBAL_TARGET$
				if = {
					limit = {
						has_event_chain = shroud_forged_chain
					}
					add_event_chain_counter = {
						event_chain = shroud_forged_chain
						counter = shroud_forged_zroni_planet
						amount = 1
					}
					if = {
						limit = {
							root = { has_building = building_zroni_equilibrator }
						}
						add_event_chain_counter = {
							event_chain = shroud_forged_chain
							counter = shroud_forged_zroni_portal
							amount = 1
						}
					}
				}
			}
		}
	}
}

zroni_planets_spawn_effect = {
	set_spawn_system_batch = begin
	random_system_within_border = {
		limit = {
			is_on_border = yes
		}
		weights = {
			base = 100
			modifier = {
				factor = 0.01
				has_star_flag = empire_cluster
			}
			modifier = {
				factor = 0.1
				any_neighbor_system = {
					has_star_flag = empire_cluster
				}
			}
		}
		spawn_system = {
			min_distance >= 25
			max_distance <= 50
			direction = rimwards
			min_orientation_angle = 330
			max_orientation_angle = 120
			initializer = zroni_legacy_initializer_01
			hyperlane = yes
			effect = {
				save_global_event_target_as = zroni_system_01
				spawn_natural_wormhole = {
					bypass_type = wormhole
					random_pos = no
					orbit_angle = 360
				}
			}
		}
		reroll_random = yes
		spawn_system = {
			min_distance >= 25
			max_distance <= 50
			direction = rimwards
			min_orientation_angle = 330
			max_orientation_angle = 120
			initializer = zroni_legacy_initializer_02
			hyperlane = yes
			effect = {
				save_global_event_target_as = zroni_system_02
			}
		}
		reroll_random = yes
		spawn_system = {
			min_distance >= 25
			max_distance <= 50
			direction = rimwards
			min_orientation_angle = 330
			max_orientation_angle = 120
			initializer = zroni_legacy_initializer_03
			hyperlane = yes
			effect = {
				save_global_event_target_as = zroni_system_03
			}
		}
	}
	set_spawn_system_batch = end
	random_system = {
		limit = {
			is_rim_system = no
			has_natural_wormhole = no
		}
		spawn_natural_wormhole = {
			bypass_type = wormhole
			random_pos = no
			orbit_angle = 360
		}
		event_target:zroni_system_01 = {
			link_wormholes = prev
		}
	}
}

zroni_legacy_poi_effect = {
	if = {
		limit = {
			NOT = {
				has_point_of_interest = { poi = zroni_legacy_poi_$NUMBER$ }
			}
		}
		set_visited = event_target:zroni_system_$NUMBER$
		create_point_of_interest = {
			id = zroni_legacy_poi_$NUMBER$
			name = zroni_legacy_poi_$NUMBER$_title
			desc = zroni_legacy_poi_$NUMBER$_desc
			event_chain = shroud_forged_chain
			location = event_target:zroni_legacy_planet_$NUMBER$
		}
	}
}

zroni_digsite_spawn_effect = {
	closest_system = {
		limit = {
			has_access_fleet = root.owner
			is_capital_system = no
			NOR = {
				is_same_value = root.solar_system
				has_star_flag = first_zroni_site@root.owner
				has_star_flag = hostile_system
			}
			is_fe_cluster = no
			OR = {
				has_owner = no
				owner = { is_same_value = root.owner }
			}
			any_system_planet = {
				habitable_planet = yes
				OR = {
					is_colony = no
					sapient_pop_amount < 1000
				}
				has_anomaly = no
				NOR = {
					exists = archaeological_site
					has_planet_flag = hatchling_egg
					has_planet_flag = suppress_archaeological_sites #for modders
					has_carrier_flag = colony_event
				}
			}
			root.owner = {
				any_controlled_fleet = {
					is_ship_class = shipclass_science_ship
					can_access_system = prevprev
				}
			}
		}
		min_steps = 3
		max_steps = 15
		root.owner = { set_visited = prev }
		random_system_planet = {
			limit = {
				habitable_planet = yes
				has_anomaly = no
				OR = {
					is_colony = no
					sapient_pop_amount < 1000
				}
				NOR = {
					exists = archaeological_site
					has_planet_flag = hatchling_egg
					has_planet_flag = suppress_archaeological_sites
					has_carrier_flag = colony_event
				}
			}
			create_archaeological_site = $DIGSITE$
			root.owner = {
				set_country_flag = zroni_arc_chain_@prev
			}
			add_deposit = $DEPOSIT$
			save_event_target_as = new_zroni_digsite
		}
	}
	if = {
		limit = {
			NOT = { exists = event_target:new_zroni_digsite }
		}
		closest_system = {
			limit = {
				has_access_fleet = root.owner
				is_capital_system = no
				NOR = {
					is_same_value = root.solar_system
					has_star_flag = first_zroni_site@root.owner
					has_star_flag = hostile_system
				}
				is_fe_cluster = no
				OR = {
					has_owner = no
					owner = { is_same_value = root.owner }
				}
				any_system_planet = {
					OR = {
						is_planet_class = pc_barren
						is_planet_class = pc_barren_cold
					}
					has_anomaly = no
					NOR = {
						exists = archaeological_site
						has_planet_flag = hatchling_egg
						has_planet_flag = suppress_archaeological_sites
					}
				}
			}
			min_steps = 1
			root.owner = { set_visited = prev }
			random_system_planet = {
				limit = {
					OR = {
						is_planet_class = pc_barren
						is_planet_class = pc_barren_cold
					}
					has_anomaly = no
					NOR = {
						exists = archaeological_site
						has_planet_flag = hatchling_egg
						has_planet_flag = suppress_archaeological_sites
					}
				}
				create_archaeological_site = $DIGSITE$
				root.owner = {
					set_country_flag = zroni_arc_chain_@prev
				}
				add_deposit = $DEPOSIT$
				save_event_target_as = new_zroni_digsite
			}
		}
	}
}

create_shroud_creatures = {
	if = {
		limit = {
			NOT = { exists = event_target:shroud_creatures }
		}
		create_country = {
			name = "NAME_Shroud_Creatures"
			type = guardian
			auto_delete = no
			flag = {
				icon = {
					category = "zoological"
					file = "flag_zoological_5.dds"
				}
				background= {
					category = "backgrounds"
					file = "flag_BG_12.dds"
				}
				colors={
					"purple"
					"black"
					"null"
					"null"
				}
			}
			effect = {
				every_playable_country = {
					establish_communications_no_message = prev
				}
				save_global_event_target_as = shroud_creatures
			}
		}
	}
}

shroud_creatures_army_spawn = {
	create_shroud_creatures = yes
	create_army = {
		name = "NAME_Shroud_Creatures"
		owner = event_target:shroud_creatures
		type = shroud_monstrosities
	}
}

shroud_creatures_system_spawn = {
	create_shroud_creatures = yes
	if = {
		limit = {
			end_game_years_passed >= 1
		}
		while = {
			count = 3
			shroud_creatures_avatar_spawn = yes
		}
	}
	else_if = {
		limit = {
			mid_game_years_passed >= 1
		}
		while = {
			count = 2
			shroud_creatures_avatar_spawn = yes
		}
	}
	else = {
		shroud_creatures_avatar_spawn = yes
	}
}

shroud_creatures_avatar_spawn = {
	event_target:shroud_creatures = {
		create_fleet = {
			name = "NAME_Psionic_Avatar"
			settings = {
				can_upgrade = no
				can_change_composition = no
				can_change_leader = no
				uses_naval_capacity = no
				spawn_debris = no
				is_boss = yes
			}
			effect = {
				set_owner = PREV
				set_fleet_flag = avatar_fleet
				create_ship = {
					name = "NAME_Avatar"
					design = "NAME_Shroud_Avatar"
					prefix = no
					upgradable = no
				}
				set_location = prevprev.system_star
			}
		}
		last_created_fleet = {
			clear_fleet_actions = this
			queue_actions = {
				repeat = { #repeating it creates a visual effect of swooping around the planet
					find_random_planet = {
						found_planet = {
							move_to = this
							orbit_planet = THIS
						}
					}
					wait = {
						duration = 15
					}
				}
			}
		}
	}
}

shroud_major_invasion_effect = {
	capital_scope = {
		if = {
			limit = {
				has_deposit = d_shroud_rift_deposit
				is_controlled_by = root
			}
			shroud_creatures_army_spawn = yes
		}
		solar_system = {
			shroud_creatures_system_spawn = yes
		}
	}
	shroud_invasion_effect = yes
}

shroud_invasion_effect = {
	every_owned_planet = {
		if = {
			limit = {
				is_capital = no
				has_deposit = d_shroud_rift_deposit
				is_controlled_by = root
				NOT = { has_carrier_flag = zroni_legacy_flag }
			}
			random = {
				chance = 10
				carrier_event = {
					id = shroud_forged.321
					days = 5
					random = 25
				}
			}
			random = {
				chance = 1
				solar_system = {
					shroud_creatures_system_spawn = yes
				}
			}
		}
	}
	every_owned_planet = {
		limit = {
			has_carrier_flag = zroni_legacy_flag
			is_controlled_by = root
		}
		carrier_event = {
			id = shroud_forged.321
			days = 5
			random = 25
		}
		solar_system = {
			shroud_creatures_system_spawn = yes
		}
	}
}

shroud_forged_animator_of_clay_cooldown = {
	set_timed_country_flag = { flag = animator_of_clay_cooldown days = $VALUE$ }
	set_saved_date = {
		key = animator_of_clay_cooldown_timer
		days_from_present = $VALUE$
		expires = $VALUE$
	}
}

shroud_forged_animator_of_clay_event = {
	hidden_effect = {
		country_event = {
			id = $EVENT$
			days = 30
			random = 330
		}
	}
}

machine_synthetic_leader_effect = {
	every_owned_leader = {
		limit = {
			species = { has_trait = trait_machine_unit }
			is_leader_tier = leader_tier_default
			NOR = {
				has_trait = leader_trait_synthetic
			}
		}
		add_trait = {
			trait = leader_trait_synthetic
			show_message = no
		}
	}
	every_pool_leader = {
		limit = {
			species = { has_trait = trait_machine_unit }
			NOT = { has_trait = leader_trait_synthetic }
		}
		add_trait = {
			trait = leader_trait_synthetic
			show_message = no
		}
	}
}

give_nanite_techs = {
	give_technology = { tech = tech_nanite_repair_system }
	give_technology = { tech = tech_nanite_autocannon }
	give_technology = { tech = tech_nanite_flak_batteries }
}

create_demon_species_effect = {
	if = {
		limit = {
			NOT = { species_portrait = humanoid_hp_01 }
		}
		create_species = {
			name = "NAME_Demon_Refugees"
			plural = "NAME_Demon_Refugee_pl"
			class = MAM
			namelist = random_class
			portrait = "humanoid_hp_01"
			traits = {
				trait = "trait_pc_nuked_preference"
				trait = "trait_organic"
				trait = "trait_psionic"
				trait = "trait_repugnant"
				trait = "trait_robust"
				trait = "trait_deviants"
				trait = "trait_very_strong"
				trait = "trait_slow_breeders"
			}
		}
	}
	else = {
		create_species = {
			name = "NAME_Demon_Refugees"
			plural = "NAME_Demon_Refugee_pl"
			class = MAM
			namelist = random_class
			portrait = random
			traits = {
				trait = "trait_pc_nuked_preference"
				trait = "trait_organic"
				trait = "trait_psionic"
				trait = "trait_repugnant"
				trait = "trait_robust"
				trait = "trait_deviants"
				trait = "trait_very_strong"
				trait = "trait_slow_breeders"
			}
		}
	}
}

# Scope: fleet, ship
remove_fleet_contract_modifiers = {
	remove_modifier = hired_mercenary_fleet_naval_cap_usage_no_galcom
	remove_modifier = hired_mercenary_fleet_naval_cap_usage_galcom_1
	remove_modifier = hired_mercenary_fleet_naval_cap_usage_galcom_2
	remove_modifier = hired_mercenary_fleet_naval_cap_usage_galcom_3
	remove_modifier = hired_mercenary_fleet_naval_cap_usage_galcom_4
	remove_modifier = hired_mercenary_fleet_naval_cap_usage_galcom_5
}

remove_fauna_yuht = {
	every_deposit = {
		limit = { is_deposit_type = d_dangerous_wildlife_blocker }
		clear_blocker = yes
	}
	every_deposit = {
		limit = { is_deposit_type = d_titanic_life_blocker }
		clear_blocker = yes
	}
	every_deposit = {
		limit = { is_deposit_type = d_venomous_insects }
		clear_blocker = yes
	}
	every_deposit = {
		limit = { is_deposit_type = d_wandering_forests }
		clear_blocker = yes
	}

	if = {
		limit = { has_modifier = dangerous_wildlife }
		remove_modifier = dangerous_wildlife
	}

	if = {
		limit = { has_modifier = titanic_life }
		remove_modifier = titanic_life
	}

	if = {
		limit = { has_modifier = migrating_forests }
		remove_modifier = migrating_forests
	}

	if = {
		limit = { has_modifier = migrating_forests_2 }
		remove_modifier = migrating_forests_2
	}
}

# (global) country scope
choose_galactic_market_host = {
	random_galaxy_planet = {
		limit = {
			is_market_nominee_planet = yes
			exists = owner
			owner = {
				is_country_type = default
				has_country_flag = market_nomination_eligible # i.e. they are or were a GalCom member
			}
		}
		weights = {
			base = 1
			modifier = {
				owner = { is_variable_set = market_rating }
				add = owner.market_rating
			}
			modifier = {
				add = owner.value:trade_bonus
			}
		}
		save_global_event_target_as = market_founder_planet
		owner = {
			save_global_event_target_as = market_founder
		}
		every_playable_country = {
			limit = {
				has_country_flag = market_nomination_eligible
			}
			remove_galactic_market_modifiers = yes
		}
	}
}

# country scope
remove_galactic_market_modifiers = {
	every_owned_planet = {
		limit = {
			is_market_nominee_planet = yes
		}
		# remove boosted flags
		if = {
			limit = { has_carrier_flag = boosted_once }
			remove_carrier_flag = boosted_once
		}
		if = {
			limit = { has_carrier_flag = boosted_twice }
			remove_carrier_flag = boosted_twice
		}
		# remove modifiers
		if = {
			limit = { has_modifier = market_nominee_level_1 }
			remove_modifier = market_nominee_level_1
		}
		else_if = {
			limit = { has_modifier = market_nominee_level_2 }
			remove_modifier = market_nominee_level_2
		}
		else_if = {
			limit = { has_modifier = market_nominee_level_3 }
			remove_modifier = market_nominee_level_3
		}
		else_if = {
			limit = { has_modifier = market_nominee_level_4 }
			remove_modifier = market_nominee_level_4
		}
		else_if = {
			limit = { has_modifier = market_nominee_level_5 }
			remove_modifier = market_nominee_level_5
		}
	}
	clear_variable = market_rating
}
create_random_devolved_species = {
	# Requires event_target:species_target as a species input.
	# Gives event_target:devolved_species_target as a species output.
	random_list = {
		1 = {
			modify_species = {
				species = event_target:species_target
				add_trait = trait_presapient_starborn
				add_traits_at_start_of_list = yes
				sapient = no
				change_scoped_species = no
				effect = {
					save_event_target_as = devolved_species_target
				}
			}
		}

		1 = {
			modify_species = {
				species = event_target:species_target
				add_trait = trait_presapient_earthbound
				add_traits_at_start_of_list = yes
				sapient = no
				change_scoped_species = no
				effect = {
					save_event_target_as = devolved_species_target
				}
			}
		}

		1 = {
			modify_species = {
				species = event_target:species_target
				add_trait = trait_presapient_natural_intellectuals
				add_traits_at_start_of_list = yes
				sapient = no
				change_scoped_species = no
				effect = {
					save_event_target_as = devolved_species_target
				}
			}
		}

		1 = {
			modify_species = {
				species = event_target:species_target
				add_trait = trait_presapient_proles
				add_traits_at_start_of_list = yes
				sapient = no
				change_scoped_species = no
				effect = {
					save_event_target_as = devolved_species_target
				}
			}
		}

		1 = {
			modify_species = {
				species = event_target:species_target
				add_trait = trait_presapient_conservative
				add_traits_at_start_of_list = yes
				sapient = no
				change_scoped_species = no
				effect = {
					save_event_target_as = devolved_species_target
				}
			}
		}

		1 = {
			modify_species = {
				species = event_target:species_target
				add_trait = trait_presapient_irradiated
				add_traits_at_start_of_list = yes
				sapient = no
				change_scoped_species = no
				effect = {
					save_event_target_as = devolved_species_target
				}
			}
		}

		1 = {
			modify_species = {
				species = event_target:species_target
				add_trait = trait_presapient_docile_livestock
				add_traits_at_start_of_list = yes
				sapient = no
				change_scoped_species = no
				effect = {
					save_event_target_as = devolved_species_target
				}
			}
		}
	}
}

create_devolved_species = {
	# Requires event_target:species_target as a species input.
	# Gives event_target:devolved_species_target as a species output.
	modify_species = {
		species = event_target:species_target
		add_trait = trait_presapient_forcefully_devolved
		add_traits_at_start_of_list = yes
		effect = {
			change_species_characteristics = {
				sapient = no
			}
			save_event_target_as = devolved_species_target
		}
	}
}

set_earth_entity = {
	if = {
		limit = {
			is_starting_planet_type = yes
		}
		switch = {
			trigger = is_planet_class
			pc_desert = {
				set_planet_entity = {
					entity = desert_planet_earth_entity
				}
			}
			pc_arid = {
				set_planet_entity = {
					entity = arid_planet_earth_entity
				}
			}
			pc_savannah = {
				set_planet_entity = {
					entity = savannah_planet_earth_entity
				}
			}
			pc_tropical = {
				set_planet_entity = {
					entity = tropical_planet_earth_entity
				}
			}
			pc_ocean = {
				set_planet_entity = {
					entity = ocean_planet_earth_entity
				}
			}
			pc_continental = {
				set_planet_entity = {
					entity = continental_planet_earth_entity
				}
			}
			pc_tundra = {
				set_planet_entity = {
					entity = tundra_planet_earth_entity
				}
			}
			pc_arctic = {
				set_planet_entity = {
					entity = arctic_planet_earth_entity
				}
			}
			pc_alpine = {
				set_planet_entity = {
					entity = alpine_planet_earth_entity
				}
			}
			pc_volcanic = {
				set_planet_entity = {
					entity = volcanic_planet_earth_entity
				}
			}
			default = {
				set_planet_entity = {
					entity = continental_planet_earth_entity
				}
			}
		}
	}
}

set_mars_entity = {
	if = {
		limit = {
			is_starting_planet_type = yes
		}
		switch = {
			trigger = is_planet_class
			pc_desert = {
				set_planet_entity = {
					entity = desert_planet_mars_entity
				}
			}
			pc_arid = {
				set_planet_entity = {
					entity = arid_planet_mars_entity
				}
			}
			pc_savannah = {
				set_planet_entity = {
					entity = savannah_planet_mars_entity
				}
			}
			pc_tropical = {
				set_planet_entity = {
					entity = tropical_planet_mars_entity
				}
			}
			pc_ocean = {
				set_planet_entity = {
					entity = ocean_planet_mars_entity
				}
			}
			pc_continental = {
				set_planet_entity = {
					entity = continental_planet_mars_entity
				}
			}
			pc_tundra = {
				set_planet_entity = {
					entity = tundra_planet_mars_entity
				}
			}
			pc_arctic = {
				set_planet_entity = {
					entity = arctic_planet_mars_entity
				}
			}
			pc_alpine = {
				set_planet_entity = {
					entity = alpine_planet_mars_entity
				}
			}
			pc_volcanic = {
				set_planet_entity = {
					entity = volcanic_planet_mars_entity
				}
			}
			default = {
				set_planet_entity = {
					entity = arid_planet_mars_entity
				}
			}
		}
	}
}

consume_world = {
	random_list = {
		1 = {
			modifier = {
				factor = 0
				num_districts = { type = district_hive value = 0 }
			}
			remove_district = district_hive
		}
		1 = {
			modifier = {
				factor = 0
				num_districts = { type = district_generator value = 0 }
			}
			remove_district = district_generator
		}
		1 = {
			modifier = {
				factor = 0
				num_districts = { type = district_mining value = 0 }
			}
			remove_district = district_mining
		}
		3 = {
			modifier = {
				factor = 0
				num_districts = { type = district_farming value = 0 }
			}
			remove_district = district_farming
		}
	}
	random_list = {
		10 = {
			modifier = {
				factor = 0
				num_free_districts = { type = any value < 2 }
			}
			add_deposit = d_lithoid_devastation
			add_deposit = d_lithoid_devastation
			create_pop_group = {
				species = root.owner.owner_main_species
			}
			add_planet_devastation = 20

			if = {
				limit = { owner = { is_ai = yes } }
				weighted_random_owned_pop_group = {
					limit = {
						is_being_purged = no
					}
					resettle_pop_group = {
						POP_GROUP = this
						PLANET = owner.capital_scope
						AMOUNT = 100
					}
				}
			}
			owner = {
				create_message = {
					type = MESSAGE_TERRAVORE_CONSUME_WORLD
					localization = MESSAGE_TERRAVORE_CONSUME_WORLD_POP_TEXT
					days = 30
					target = prev

					variable = {
						type = name
						localization = PLANET
						scope = prev
					}
				}
			}
		}
		10 = {
			modifier = {
				factor = 0
				num_free_districts = { type = any value < 2 }
			}
			add_deposit = d_lithoid_devastation
			add_deposit = d_lithoid_devastation
			owner = {
				add_monthly_resource_mult = {
					resource = minerals
					value = 5
					min = @tier1materialmin
					max = @tier1materialmax
				}
				create_message = {
					type = MESSAGE_TERRAVORE_CONSUME_WORLD
					localization = MESSAGE_TERRAVORE_CONSUME_WORLD_MINERALS_TEXT
					days = 30
					target = prev

					variable = {
						type = name
						localization = PLANET
						scope = prev
					}
				}
			}
			add_planet_devastation = 20
		}
		10 = {
			modifier = {
				factor = 0
				num_free_districts = { type = any value < 2 }
			}
			add_deposit = d_lithoid_devastation
			add_deposit = d_lithoid_devastation
			owner = {
				add_monthly_resource_mult = {
					resource = alloys
					value = 3
					min = @tier1materialmin
					max = @tier1materialmax
				}
				create_message = {
					type = MESSAGE_TERRAVORE_CONSUME_WORLD
					localization = MESSAGE_TERRAVORE_CONSUME_WORLD_ALLOYS_TEXT
					days = 30
					target = prev

					variable = {
						type = name
						localization = PLANET
						scope = prev
					}
				}
			}
			add_planet_devastation = 20
		}
		10 = {
			# There's only one district slot left on the planet
			modifier = {
				factor = 0
				num_free_districts = { type = any value >= 2 }
			}
			add_deposit = d_lithoid_devastation
			owner = {
				add_monthly_resource_mult = {
					resource = minerals
					value = 3
					min = @tier1materialmin
					max = @tier1materialmax
				}
				create_message = {
					type = MESSAGE_TERRAVORE_CONSUME_WORLD
					localization = MESSAGE_TERRAVORE_CONSUME_WORLD_MINERALS_TEXT
					days = 30
					target = prev

					variable = {
						type = name
						localization = PLANET
						scope = prev
					}
				}
			}
			add_planet_devastation = 10
		}
	}
	set_timed_planet_flag = {
		days = 360
		flag = recently_eaten_planet
	}
}

# Removes all life-related planet modifiers when nuking a planet.
tomb_world_modifier_cleanup = {
	remove_modifier = "natural_beauty"
	remove_modifier = "atmospheric_aphrodisiac"
	remove_modifier = "atmospheric_hallucinogen"
	remove_modifier = "lush_planet"
	remove_modifier = "dangerous_wildlife"
	remove_modifier = "planet_myrmeku_attacks"
	remove_modifier = "planet_myrmeku_seal_colony"
	remove_modifier = "planet_myrmeku_upgrade_robots"
	remove_modifier = "planet_myrmeku_pest_control"
	remove_modifier = "planet_myrmeku_lured"
}

initialize_kaleidoscope = {
	set_global_flag = kaleidoscope_started
	event_target:global_event_country = {
		if = {
			limit = {
				NOT = { is_variable_set = kaleidoscope_global_progress }
			}
			# global situation progress tracker
			set_variable = {
				which = kaleidoscope_global_progress
				value = 0
			}
			# mood (0-20, influences random events, chances of disappearing and of getting the final reward)
			# 1-6 angry
			# 7-14 neutral
			# 15-20 happy
			set_variable = {
				which = kaleidoscope_global_mood
				value = 10
			}
			# Sets a hard limit of 25 years (60 months) so it won't stay around forever
			set_timed_country_flag = {
				flag = kaleidoscope_global_lifetime
				years = 25
			}
		}
	}
}

lure_valid_critter_fleet = {
	random_fleet_in_system = {
		limit = {
			owner = {
				is_pacified_space_critter_country_type = yes
			}
			NOR = {
				has_fleet_flag = fruitful_lured_critter
				has_fleet_flag = fruitful_seeded_critter
				has_fleet_flag = is_garrison_fleet
			}
		}
		save_event_target_as = lured_critter
	}
}

create_space_storm = {
	add_modifier = { modifier = space_storm }
	fire_on_action = {
		on_action = on_space_storm_created
	}
}

destroy_space_storm = {
	remove_modifier = space_storm
	fire_on_action = {
		on_action = on_space_storm_destroyed
	}
}

reset_formless_crisis_reward = {
	remove_country_flag = formless_unbidden_reward
	remove_country_flag = formless_aberrant_reward
	remove_country_flag = formless_vehement_reward
}

remove_modifers_after_terraform = {
	remove_modifier = "bleak_planet"
	remove_modifier = "dangerous_wildlife"
	remove_modifier = "hazardous_weather"
	remove_modifier = "wild_storms"
	remove_modifier = "irradiated_planet"
	remove_modifier = "second_home"
	remove_deposit = d_radiotrophic_preserve
}

#### Nanite Slushify World

slushify_world = {
	random_list = {
		10 = {
			modifier = {
				factor = 0
				num_free_districts = { type = any value < 2 }
			}
			add_deposit = d_nanotech_devastation
			add_deposit = d_nanotech_devastation
			owner = {
				add_monthly_resource_mult = {
					resource = nanites
					value = 3
					min = @tier1materialmin
					max = @tier2materialmax
				}
				create_message = {
					type = MESSAGE_TERRAVORE_CONSUME_WORLD
					localization = MESSAGE_NANOTECH_CONSUME_WORLD_3_TEXT
					days = 30
					target = prev

					variable = {
						type = name
						localization = PLANET
						scope = prev
					}
				}
			}
			add_planet_devastation = 10
		}
		10 = {
			modifier = {
				factor = 0
				num_free_districts = { type = any value < 2 }
			}
			add_deposit = d_nanotech_devastation
			add_deposit = d_nanotech_devastation
			owner = {
				add_monthly_resource_mult = {
					resource = nanites
					value = 2
					min = @tier1materialmin
					max = @tier2materialmax
				}
				create_message = {
					type = MESSAGE_TERRAVORE_CONSUME_WORLD
					localization = MESSAGE_NANOTECH_CONSUME_WORLD_2_TEXT
					days = 30
					target = prev

					variable = {
						type = name
						localization = PLANET
						scope = prev
					}
				}
			}
			add_planet_devastation = 10
		}
		10 = {
			# There's only one district slot left on the planet
			modifier = {
				factor = 0
				num_free_districts = { type = any value >= 2 }
			}
			add_deposit = d_nanotech_devastation
			owner = {
				add_monthly_resource_mult = {
					resource = nanites
					value = 1
					min = @tier1materialmin
					max = @tier1materialmax
				}
				create_message = {
					type = MESSAGE_TERRAVORE_CONSUME_WORLD
					localization = MESSAGE_NANOTECH_CONSUME_WORLD_1_TEXT
					days = 30
					target = prev

					variable = {
						type = name
						localization = PLANET
						scope = prev
					}
				}
			}
			add_planet_devastation = 5
		}
	}
	set_timed_planet_flag = {
		days = 360
		flag = recently_eaten_planet
	}
}

set_subject_advanced_authority = {
	from = {
		switch = {
			trigger = has_country_flag
			cyber_creed_advanced_government = { root = { set_country_flag = 	cyber_creed_advanced_government } }
			cyber_individualist = { root = { set_country_flag = cyber_individualist } }
			cyber_collectivist = { root = { set_country_flag = cyber_collectivist } }
			synth_physical = { root = { set_country_flag = synth_physical } }
			synth_virtual = { root = { set_country_flag = synth_virtual } }
			cyber_hive_volitional = { root = { set_country_flag = cyber_hive_volitional } }
			cyber_hive_integrated = { root = { set_country_flag = cyber_hive_integrated } }
			driven_memory_aggregator = { root = { set_country_flag = driven_memory_aggregator } }
			driven_neural_chorus = { root = { set_country_flag = driven_neural_chorus } }
		}
	}

	advanced_authority_refresh = yes

	if = {
		limit = {
			has_country_flag = cyber_individualist
			is_imperial_authority = yes
		}
		add_relic = r_the_rulerchip
	}
}

create_strategic_resource_message = {
	create_message = {
		type = $RESOURCE_TYPE$
		localization = $RESOURCE_DESC$
		days = 100
		target = from
		variable = {
			type = name
			localization = SYSTEM
			scope = from
		}
	}
}

create_faction_formed_message = {
	create_message = {
		type = $FACTION_TYPE$
		localization = $FACTION_INTRO$
		days = 100
		target = from
	}
}

create_faction_shifted_message = {
	create_message = {
		type = $FACTION_TYPE$
		localization = $FACTION_INTRO$
		days = 100
		target = root
	}
}

create_focus_completed_message = {
	create_message = {
		type = MESSAGE_$CATEGORY$_FOCUS_COMPLETED
		localization = MESSAGE_$CATEGORY$_FOCUS_COMPLETED_DESC
		days = 30
	}
}

create_focus_reward_message = {
	create_message = {
		type = MESSAGE_$CATEGORY$_FOCUS_REWARD
		localization = MESSAGE_$CATEGORY$_FOCUS_REWARD_DESC
		days = 30
	}
}

spawn_free_defense_platform = {
	fleet = {
		if = {
			limit = {
				any_owned_ship = {
					is_ship_size = military_station_small
				}
			}
			random_owned_ship = {
				limit = {
					is_ship_size = military_station_small
				}
				save_event_target_as = target_platform
			}
		}
		else = {
			owner = {
				random_owned_design = {
					limit = {
						is_ship_size = military_station_small
					}
					save_event_target_as = target_platform
				}
			}
		}
		create_ship = {
			name = random
			design = event_target:target_platform
			graphical_culture = owner
		}
	}
}

kill_single_pop = {
	kill_pop_group = {
		pop_group = this
		amount = 100
	}
}

kill_all_pop = {
	kill_pop_group = {
		pop_group = this
		percentage = 1
	}
}

sacrifice_single_pop = {
	sacrifice_pop_group = {
		pop_group = this
		amount = 100
	}
}

# Forces an AMOUNT or PERCENTAGE of pops from the calling pop group into the provided ETHOS.
# Randomises the amounts by RANDOM.
# If POP_GROUP is set, it's used as the source pop group, otherwise a random group is selected
# If POP_GROUP_FLAG is set, it's set on the target pop group
pop_group_add_ethic_effect = {
	[[POP_GROUP]
		$POP_GROUP$ = { save_event_target_as = source_pop_group }
	]
	[[!POP_GROUP]
		weighted_random_owned_pop_group = {
			limit = {
				has_any_ethic = yes
			}
			this = { save_event_target_as = source_pop_group }
		}
	]

	event_target:source_pop_group = {
		[[AMOUNT]
			pop_force_add_ethic = {
				ethic = $ETHOS$
				amount = $AMOUNT$
				random = $RANDOM$	# Randomise by up to RANDOM
			}
		]
		[[PERCENTAGE]
			pop_force_add_ethic = {
				ethic = $ETHOS$
				percentage = $PERCENTAGE$
				random = $RANDOM$	# Randomise by up to RANDOM
			}
		]
		[[POP_GROUP_FLAG]
			set_pop_group_flag = $POP_GROUP_FLAG$
		]
	}
}

# Forces an AMOUNT or PERCENTAGE of pops from the calling pop group into the provided ETHOS.
# Randomises the amounts by RANDOM.
# If POP_GROUP is set, it's used as the source pop group, otherwise a random group is selected
# If POP_GROUP_FLAG is set, it's set on the target pop group
pop_group_transfer_effect = {
	[[POP_GROUP]
		$POP_GROUP$ = { save_event_target_as = source_pop_group }
	]
	[[!POP_GROUP]
		weighted_random_owned_pop_group = {
			limit = {
				has_ethic =	$OLD_ETHOS$
			}
			this = { save_event_target_as = source_pop_group }
		}
	]

	event_target:source_pop_group = {
		[[AMOUNT]
			pop_force_transfer_ethic = {
				old_ethic = $OLD_ETHOS$
				new_ethic = $ETHOS$
				amount = $AMOUNT$
				random = $RANDOM$	# Randomise by up to RANDOM
			}
		]
		[[PERCENTAGE]
			pop_force_transfer_ethic = {
				old_ethic = $OLD_ETHOS$
				new_ethic = $ETHOS$
				percentage = $PERCENTAGE$
				random = $RANDOM$	# Randomise by up to RANDOM
			}
		]
		[[POP_GROUP_FLAG]
			set_pop_group_flag = $POP_GROUP_FLAG$
		]
	}
}

# Transfers an AMOUNT or a PERCENTAGE of pops from the called pop group to a targeted planet.
resettle_pop_group = {
	$POP_GROUP$ = {
		save_event_target_as = source_pop_group
	}
	$PLANET$ = {
		create_pop_group = {
			pop_group = event_target:source_pop_group
			size = 0
			effect = {
				transfer_pop_amount = {
					source = event_target:source_pop_group
					target = this
					[[AMOUNT]
						amount = $AMOUNT$
					]
					[[PERCENTAGE]
						percentage = $PERCENTAGE$
					]
				}
				save_event_target_as = resettled_pop_group
			}
		}
	}
}
add_red_solution = {
	if = {
		limit = {
			has_trait = trait_strong
		}
		modify_species = {
			species = this
			#remove_trait = trait_strong
			add_trait = trait_social_pheromones
		}
		set_country_flag = strong_removed_verystrong_added
	}
	else_if = {
		limit = {
			has_trait = trait_weak
		}
		modify_species = {
			species = this
			#remove_trait = trait_weak
			add_trait = trait_social_pheromones
		}
		set_country_flag = weak_removed_strong_added
	}
	else_if = {
		#limit = {
		#	NOR = {
		#		has_trait = trait_weak
		#		has_trait = trait_strong
		#		has_trait = trait_very_strong
		#	}
		#}
		modify_species = {
			species = this
			add_trait = trait_social_pheromones
		}
		set_country_flag = verystrong_added
	}
	change_dominant_species = {
		species = last_created_species
	}
	while = {
		limit = {
			any_owned_pop_group = {
				is_subspecies = root
				NOT = { has_trait = trait_social_pheromones }
			}
		}
		weighted_random_owned_pop_group = {
			limit = {
				is_subspecies = root
				NOT = { has_trait = trait_social_pheromones }
			}
			root = {
				modify_species = {
					species = prev.species
					add_trait = trait_social_pheromones
				}
			}
		}
	}
	set_country_flag = modification_red # actually socialer now, but keeping the flags
}

add_green_solution = {
	if = {
		limit = {
			has_trait = trait_adaptive
		}
		modify_species = {
			species = this
			#remove_trait = trait_adaptive
			add_trait = trait_bioadaptability
		}
		set_country_flag = adaptive_removed_extremelyadaptive_added
	}
	if = {
		limit = {
			has_trait = trait_nonadaptive
		}
		modify_species = {
			species = this
			#remove_trait = trait_nonadaptive
			add_trait = trait_bioadaptability
		}
		set_country_flag = nonadaptive_removed_adaptive_added
	}
	if = {
		#limit = {
		#	NOR = {
		#		has_trait = trait_nonadaptive
		#		has_trait = trait_adaptive
		#		has_trait = trait_extremely_adaptive
		#	}
		#}
		modify_species = {
			species = this
			add_trait = trait_bioadaptability
		}
		set_country_flag = extremelyadaptive_added
	}
	change_dominant_species = {
		species = last_created_species
	}
	while = {
		limit = {
			any_owned_pop_group = {
				is_subspecies = root
				NOT = { has_trait = trait_bioadaptability }
			}
		}
		weighted_random_owned_pop_group = {
			limit = {
				is_subspecies = root
				NOT = { has_trait = trait_bioadaptability }
			}
			root = {
				modify_species = {
					species = prev.species
					add_trait = trait_bioadaptability
				}
			}
		}
	}
	set_country_flag = modification_green
}
add_blue_solution = {
	if = {
		limit = {
			has_trait = trait_enduring
		}
		modify_species = {
			species = this
			#remove_trait = trait_enduring
			add_trait = trait_limited_regeneration
		}
		set_country_flag = enduring_removed_venerable_added
	}
	else_if = {
		limit = {
			has_trait = trait_fleeting
		}
		modify_species = {
			species = this
			add_trait = trait_limited_regeneration
		}
		set_country_flag = fleeting_removed_enduring_added
	}
	else = {
		#limit = {
		#	NOR = {
		#		has_trait = trait_fleeting
		#		has_trait = trait_enduring
		#		has_trait = trait_venerable
		#	}
		#}
		modify_species = {
			species = this
			add_trait = trait_limited_regeneration
		}
		set_country_flag = venerable_added
	}
	change_dominant_species = {
		species = last_created_species
	}
	while = {
		limit = {
			any_owned_pop_group = {
				is_subspecies = root
				NOT = { has_trait = trait_limited_regeneration }
			}
		}
		weighted_random_owned_pop_group = {
			limit = {
				is_subspecies = root
				NOT = { has_trait = trait_limited_regeneration }
			}
			root = {
				modify_species = {
					species = prev.species
					add_trait = trait_limited_regeneration
				}
			}
		}
	}
	set_country_flag = modification_blue
}

declare_malevolent_aura_focus = {
	event_target:malevolent_aura_empire = {
		if = {
			limit = { is_galactic_community_member = yes }
			remove_from_galactic_community = yes
		}
		if = {
			limit = {
				is_galactic_council_established = yes
				is_part_of_galactic_council = yes
			}
			remove_from_galactic_council = yes
		}
		every_subject = {
			if = {
				limit = { is_galactic_community_member = yes }
				remove_from_galactic_community = yes
			}
			if = {
				limit = {
					is_galactic_council_established = yes
					is_part_of_galactic_council = yes
				}
				remove_from_galactic_council = yes
			}
		}
	}

	every_playable_country = {
		limit = {
			is_galactic_community_member = yes
			NOR = {
				has_country_flag = malevolent_aura_empire
				is_same_value = event_target:malevolent_aura_empire
				is_in_federation_with = event_target:malevolent_aura_empire
			}
		}
		if = {
			limit = {
				NOT = { has_technology = tech_psionic_suppression }
				can_research_technology = tech_psionic_suppression
			}
			add_tech_progress = {
				tech = tech_psionic_suppression
				progress = 0.25
			}
		}
		if = {
			limit = {
				any_war = {
					any_war_participant = {
						is_same_value = event_target:malevolent_aura_empire
					}
				}
			}
			every_war = {
				limit = {
					any_war_participant = {
						is_same_value = event_target:malevolent_aura_empire
					}
				}
				remove_war_participant = event_target:malevolent_aura_empire
			}
		}
		every_playable_country = {
			limit = {
				is_galactic_community_member = yes
				NOR = {
					is_same_value = prev
					# has_country_flag = declared_crisis
					is_same_value = event_target:malevolent_aura_empire
					is_in_federation_with = event_target:malevolent_aura_empire
				}
			}
			set_closed_borders = {
				who = prev
				status = no
			}
		}
	}
	event_target:community_war_leader = {
		if = {
			limit = { exists = event_target:malevolent_aura_empire }
			declare_war = {
				target = event_target:malevolent_aura_empire
				name = {
					key = "NAME_Declared_Aura_War"
					variable_string = "\\[This.MainDefender.GetAdj\\]"
				}
				attacker_war_goal = "wg_declared_crisis"
				effect = { save_event_target_as = malevolent_aura_war }
			}
		}
	}
	every_playable_country = {
		limit = {
			exists = event_target:malevolent_aura_empire
			is_galactic_community_member = yes
			NOR = {
				is_same_value = event_target:community_war_leader
				is_in_federation_with = event_target:malevolent_aura_empire
			}
		}
		join_war_on_side = {
			war = event_target:malevolent_aura_war
			side = event_target:community_war_leader
		}
	}
}

copy_deposit_from = {
	if = {
		limit = {
			$SCOPE$ = {
				has_deposit = $DEPOSIT$
			}
		}
		add_deposit = $DEPOSIT$
	}
}
