File: MissionAction.cpp

package info (click to toggle)
endless-sky 0.10.16-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 414,608 kB
  • sloc: cpp: 73,435; python: 893; xml: 666; sh: 271; makefile: 28
file content (501 lines) | stat: -rw-r--r-- 15,069 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/* MissionAction.cpp
Copyright (c) 2014 by Michael Zahniser

Endless Sky is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later version.

Endless Sky is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program. If not, see <https://www.gnu.org/licenses/>.
*/

#include "MissionAction.h"

#include "CargoHold.h"
#include "ConversationPanel.h"
#include "DataNode.h"
#include "DataWriter.h"
#include "Dialog.h"
#include "text/Format.h"
#include "GameData.h"
#include "GameEvent.h"
#include "Outfit.h"
#include "PlayerInfo.h"
#include "Ship.h"
#include "TextReplacements.h"
#include "UI.h"

using namespace std;

namespace {
	int CountInCargo(const Outfit *outfit, const PlayerInfo &player)
	{
		int available = 0;
		// If landed, all cargo from available ships is pooled together.
		if(player.GetPlanet())
			available += player.Cargo().Get(outfit);
		// Otherwise only count outfits in the cargo holds of in-system ships.
		else
		{
			const System *here = player.GetSystem();
			for(const auto &ship : player.Ships())
			{
				if(ship->IsDisabled() || ship->IsParked())
					continue;
				if(ship->GetSystem() == here || (ship->CanBeCarried()
						&& !ship->GetSystem() && ship->GetParent()->GetSystem() == here))
					available += ship->Cargo().Get(outfit);
			}
		}
		return available;
	}
}



MissionAction::MissionDialog::MissionDialog(const ExclusiveItem<Phrase> &phrase):
	dialogPhrase(phrase)
{
}



MissionAction::MissionDialog::MissionDialog(const string &text):
	dialogText(text)
{
}



MissionAction::MissionDialog::MissionDialog(const DataNode &node, const ConditionsStore *playerConditions)
{
	const string &key = node.Token(0);
	// Handle anonymous phrases
	//    phrase
	//       ...
	if(node.Size() == 1 && key == "phrase")
	{
		dialogPhrase = ExclusiveItem<Phrase>(Phrase(node));
		// Anonymous phrases do not support "to display"
		return;
	}

	// Handle named phrases
	//    phrase "A Phrase Name"
	if(node.Size() == 2 && key == "phrase")
		dialogPhrase = ExclusiveItem<Phrase>(GameData::Phrases().Get(node.Token(1)));

	// Handle regular dialog text
	//    "Some thrilling dialog that truly moves the player."
	else
	{
		if(node.Size() > 1)
			node.PrintTrace("Ignoring extra tokens.");
		dialogText = key;

		// Prevent a corner case that breaks assumptions. Dialog text cannot be empty (that indicates a phrase).
		if(dialogText.empty())
			dialogText = '\t';
	}

	// Search for "to display" lines.
	for(auto &child : node)
	{
		if(child.Size() != 2 || child.Token(0) != "to" || child.Token(1) != "display" || !child.HasChildren())
			node.PrintTrace("Ignoring unrecognized dialog token");
		else
			condition.Load(child, playerConditions);
	}
}



// Construct and Load() at the same time.
MissionAction::MissionAction(const DataNode &node, const ConditionsStore *playerConditions,
	const set<const System *> *visitedSystems, const set<const Planet *> *visitedPlanets)
{
	Load(node, playerConditions, visitedSystems, visitedPlanets);
}



void MissionAction::Load(const DataNode &node, const ConditionsStore *playerConditions,
	const set<const System *> *visitedSystems, const set<const Planet *> *visitedPlanets)
{
	if(node.Size() >= 2)
		trigger = node.Token(1);
	if(node.Size() >= 3)
		system = node.Token(2);

	for(const DataNode &child : node)
		LoadSingle(child, playerConditions, visitedSystems, visitedPlanets);

	// Collapse pure-text dialog (no phrases). This is necessary to handle saved missions.
	// It is also an optimization for the most common case in game data files.
	dialogText = CollapseDialog(nullptr);
	if(!dialogText.empty())
		dialog.clear();
}



void MissionAction::LoadSingle(const DataNode &child, const ConditionsStore *playerConditions,
	const set<const System *> *visitedSystems, const set<const Planet *> *visitedPlanets)
{
	const string &key = child.Token(0);
	bool hasValue = child.Size() >= 2;

	if(key == "dialog")
	{
		// Parse the "dialog phrase whatever" and "dialog whatever" lines:
		if(child.Size() == 3 && child.Token(1) == "phrase")
			dialog.emplace_back(ExclusiveItem<Phrase>(GameData::Phrases().Get(child.Token(2))));
		else if(hasValue)
			dialog.emplace_back(child.Token(1));
		// Parse embedded child dialog
		for(const auto &grand : child)
			dialog.emplace_back(grand, playerConditions);
	}
	else if(key == "conversation" && child.HasChildren())
		conversation = ExclusiveItem<Conversation>(Conversation(child, playerConditions));
	else if(key == "conversation" && hasValue)
		conversation = ExclusiveItem<Conversation>(GameData::Conversations().Get(child.Token(1)));
	else if(key == "require" && hasValue)
	{
		int count = (child.Size() < 3 ? 1 : static_cast<int>(child.Value(2)));
		if(count >= 0)
			requiredOutfits[GameData::Outfits().Get(child.Token(1))] = count;
		else
			child.PrintTrace("Error: Skipping invalid \"require\" count:");
	}
	// The legacy syntax "outfit <outfit> 0" means "the player must have this outfit installed."
	else if(key == "outfit" && child.Size() >= 3 && child.Token(2) == "0")
	{
		child.PrintTrace("Warning: Deprecated use of \"outfit\" with count of 0. Use \"require <outfit>\" instead:");
		requiredOutfits[GameData::Outfits().Get(child.Token(1))] = 1;
	}
	else if(key == "system")
	{
		if(system.empty() && child.HasChildren())
			systemFilter.Load(child, visitedSystems, visitedPlanets);
		else
			child.PrintTrace("Error: Unsupported use of \"system\" LocationFilter:");
	}
	else if(key == "can trigger after failure")
		runsWhenFailed = true;
	else
		action.LoadSingle(child, playerConditions);
}



// Note: the Save() function can assume this is an instantiated mission, not
// a template, so it only has to save a subset of the data.
void MissionAction::Save(DataWriter &out) const
{
	if(system.empty())
		out.Write("on", trigger);
	else
		out.Write("on", trigger, system);
	out.BeginChild();
	{
		SaveBody(out);
	}
	out.EndChild();
}



void MissionAction::SaveBody(DataWriter &out) const
{
	if(!systemFilter.IsEmpty())
	{
		out.Write("system");
		// LocationFilter indentation is handled by its Save method.
		systemFilter.Save(out);
	}
	if(runsWhenFailed)
		out.Write("can trigger after failure");
	if(!dialogText.empty())
	{
		out.Write("dialog");
		out.BeginChild();
		{
			// Break the text up into paragraphs.
			for(const string &line : Format::Split(dialogText, "\n\t"))
				out.Write(line);
		}
		out.EndChild();
	}
	if(!conversation->IsEmpty())
		conversation->Save(out);
	for(const auto &it : requiredOutfits)
		out.Write("require", it.first->TrueName(), it.second);

	action.Save(out);
}



// Check this template or instantiated MissionAction to see if any used content
// is not fully defined (e.g. plugin removal, typos in names, etc.).
string MissionAction::Validate() const
{
	// Any filter used to control where this action triggers must be valid.
	if(!systemFilter.IsValid())
		return "system location filter";

	// Stock conversations must be defined.
	if(conversation.IsStock() && conversation->IsEmpty())
		return "stock conversation";

	// Conversations must have valid actions.
	string reason = conversation->Validate();
	if(!reason.empty())
		return reason;

	// Required content must be defined & valid.
	for(auto &&outfit : requiredOutfits)
		if(!outfit.first->IsDefined())
			return "required outfit \"" + outfit.first->TrueName() + "\"";

	return action.Validate();
}



const string &MissionAction::DialogText() const
{
	return dialogText;
}



// Check if this action can be completed right now. It cannot be completed
// if it takes away money or outfits that the player does not have.
bool MissionAction::CanBeDone(const PlayerInfo &player, bool isFailed, const shared_ptr<Ship> &boardingShip) const
{
	if(isFailed && !runsWhenFailed && trigger != "fail")
		return false;
	if(player.Accounts().Credits() < -Payment())
		return false;

	const Ship *flagship = player.Flagship();
	for(auto &&it : action.Outfits())
	{
		// If this outfit is being given, the player doesn't need to have it.
		if(it.second > 0)
			continue;

		// Outfits may always be taken from the flagship. If landed, they may also be taken from
		// the collective cargo hold of any in-system, non-disabled escorts (player.Cargo()). If
		// boarding, consider only the flagship's cargo hold. If in-flight, show mission status
		// by checking the cargo holds of ships that would contribute to player.Cargo if landed.
		int available = flagship ? flagship->OutfitCount(it.first) : 0;
		available += boardingShip ? flagship->Cargo().Get(it.first)
				: CountInCargo(it.first, player);

		if(available < -it.second)
			return false;
	}

	for(auto &&it : action.Ships())
		if(!it.CanBeDone(player))
			return false;

	for(auto &&it : requiredOutfits)
	{
		// Maps are not normal outfits; they represent the player's spatial awareness.
		int mapSize = it.first->Get("map");
		if(mapSize > 0)
		{
			bool needsUnmapped = it.second == 0;
			// This action can't be done if it requires an unmapped region, but the region is
			// mapped, or if it requires a mapped region but the region is not mapped.
			if(needsUnmapped == player.HasMapped(mapSize, false))
				return false;
			continue;
		}

		// Requiring the player to have 0 of this outfit means all ships and all cargo holds
		// must be checked, even if the ship is disabled, parked, or out-of-system.
		if(!it.second)
		{
			// When landed, ships pool their cargo into the player's cargo.
			if(player.GetPlanet() && player.Cargo().Get(it.first))
				return false;

			for(const auto &ship : player.Ships())
				if(!ship->IsDestroyed())
					if(ship->OutfitCount(it.first) || ship->Cargo().Get(it.first))
						return false;
		}
		else
		{
			// Required outfits must be present on the player's flagship or
			// in the cargo holds of able ships at the player's location.
			int available = flagship ? flagship->OutfitCount(it.first) : 0;
			available += boardingShip ? flagship->Cargo().Get(it.first)
					: CountInCargo(it.first, player);

			if(available < it.second)
				return false;
		}
	}

	// An `on enter` MissionAction may have defined a LocationFilter that
	// specifies the systems in which it can occur.
	if(!systemFilter.IsEmpty() && !systemFilter.Matches(player.GetSystem()))
		return false;
	return true;
}



bool MissionAction::RequiresGiftedShip(const string &shipId) const
{
	for(auto &&it : action.Ships())
		if(it.Id() == shipId)
			return true;
	return false;
}



void MissionAction::Do(PlayerInfo &player, UI *ui, const Mission *caller, const System *destination,
	const shared_ptr<Ship> &ship, const bool isUnique) const
{
	bool isOffer = (trigger == "offer");
	if(!conversation->IsEmpty() && ui)
	{
		// Conversations offered while boarding or assisting reference a ship,
		// which may be destroyed depending on the player's choices.
		ConversationPanel *panel = new ConversationPanel(player, *conversation, caller, destination, ship, isOffer);
		if(isOffer)
			panel->SetCallback(&player, &PlayerInfo::MissionCallback);
		// Use a basic callback to handle forced departure outside of `on offer`
		// conversations.
		else
			panel->SetCallback(&player, &PlayerInfo::BasicCallback);
		ui->Push(panel);
	}
	else if(!dialogText.empty() && ui)
	{
		map<string, string> subs;
		GameData::GetTextReplacements().Substitutions(subs);
		player.AddPlayerSubstitutions(subs);
		string text = Format::Replace(dialogText, subs);

		// Don't push the dialog text if this is a visit action on a nonunique
		// mission; on visit, nonunique dialogs are handled by PlayerInfo as to
		// avoid the player being spammed by dialogs if they have multiple
		// missions active with the same destination (e.g. in the case of
		// stacking bounty jobs).
		if(isOffer)
			ui->Push(new Dialog(text, player, destination));
		else if(isUnique || trigger != "visit")
			ui->Push(new Dialog(text));
	}
	else if(isOffer && ui)
		player.MissionCallback(Conversation::ACCEPT);

	action.Do(player, ui, caller);
}



// Convert this validated template into a populated action.
MissionAction MissionAction::Instantiate(map<string, string> &subs, const System *origin,
	int jumps, int64_t payload) const
{
	MissionAction result;
	result.trigger = trigger;
	result.system = system;
	// Convert any "distance" specifiers into "near <system>" specifiers.
	result.systemFilter = systemFilter.SetOrigin(origin);

	result.requiredOutfits = requiredOutfits;

	string previousPayment = subs["<payment>"];
	string previousFine = subs["<fine>"];
	result.action = action.Instantiate(subs, jumps, payload);

	// Create any associated dialog text from phrases, or use the directly specified text.
	result.dialogText = CollapseDialog(&subs);

	if(!conversation->IsEmpty())
		result.conversation = ExclusiveItem<Conversation>(conversation->Instantiate(subs, jumps, payload));

	// Restore the "<payment>" and "<fine>" values from the "on complete" condition, for
	// use in other parts of this mission.
	if(result.Payment() && (trigger != "complete" || !previousPayment.empty()))
		subs["<payment>"] = previousPayment;
	if(result.action.Fine() && trigger != "complete")
		subs["<fine>"] = previousFine;

	return result;
}



int64_t MissionAction::Payment() const noexcept
{
	return action.Payment();
}



string MissionAction::CollapseDialog(const map<string, string> *subs) const
{
	// No subs means we're determining whether the dialog is pure text.
	// This is done at load time.

	// Result is already cached for dialogs that are pure text at Load() time.
	if(!dialogText.empty())
	{
		if(!subs)
			return dialogText;
		else
			return Format::Replace(Phrase::ExpandPhrases(dialogText), *subs);
	}

	string resultText;
	for(auto &item : dialog)
	{
		// When checking for a pure-text dialog, reject a dialog with conditions or phrases,
		// An empty string return value tells the caller that this dialog isn't pure text.
		if(!subs && (!item.condition.IsEmpty() || item.dialogText.empty()))
			return string();

		// Skip text that is disabled.
		if(!item.condition.IsEmpty() && !item.condition.Test())
			continue;

		// Evaluate the phrase if we have one, otherwise copy the prepared text.
		string content;
		if(!item.dialogText.empty())
			content = item.dialogText;
		else if(item.dialogPhrase.IsStock() && item.dialogPhrase->IsEmpty())
			content = "stock phrase";
		else
			content = item.dialogPhrase->Get();

		// Expand any ${phrases} and <substitutions>
		if(subs)
			content = Format::Replace(Phrase::ExpandPhrases(content), *subs);

		// Concatenated lines should start with a tab and be preceded by end-of-line.
		if(!resultText.empty())
		{
			resultText += '\n';
			if(!content.empty() && content[0] != '\t')
				resultText += '\t';
		}
		resultText += content;
	}
	return resultText;
}