Freeciv21
Develop your civilization from humble roots to a global empire
cm.cpp
Go to the documentation of this file.
1 /*
2  Copyright (c) 1996-2020 Freeciv21 and Freeciv contributors. This file is
3  part of Freeciv21. Freeciv21 is free software: you can redistribute it
4  and/or modify it under the terms of the GNU General Public License as
5  published by the Free Software Foundation, either version 3 of the
6  License, or (at your option) any later version. You should have received
7  a copy of the GNU General Public License along with Freeciv21. If not,
8  see https://www.gnu.org/licenses/.
9  */
10 
11 #include <array>
12 #include <cstdlib>
13 #include <cstring>
14 
15 // Qt
16 #include <QLoggingCategory>
17 
18 // utility
19 #include "player.h"
20 #include "shared.h"
21 
22 // common
23 #include "city.h"
24 #include "game.h"
25 #include "government.h"
26 #include "map.h"
27 #include "specialist.h"
28 
29 #include "cm.h"
30 
65 /*
66  Defines, structs, globals, forward declarations
67  */
68 
69 Q_LOGGING_CATEGORY(cm_category, "freeciv.cm")
70 
71 // Maximal iterations before the search loop is stoped.
72 #define CM_MAX_LOOP 25000
73 
74 #define CPUHOG_CM_MAX_LOOP (CM_MAX_LOOP * 4)
75 
76 #ifdef FREECIV_DEBUG
77 #define GATHER_TIME_STATS
78 #endif
79 
80 /* Whether to print every query, or just at cm_free ; matters only
81  if GATHER_TIME_STATS is on */
82 #define PRINT_TIME_STATS_EVERY_QUERY
83 
84 #define LOG_TIME_STATS LOG_DEBUG
85 #define LOG_CM_STATE LOG_DEBUG
86 #define LOG_LATTICE LOG_DEBUG
87 #define LOG_REACHED_LEAF LOG_DEBUG
88 #define LOG_BETTER_LEAF LOG_DEBUG
89 #define LOG_PRUNE_BRANCH LOG_DEBUG
90 
91 #ifdef GATHER_TIME_STATS
92 struct one_perf {
93  civtimer *wall_timer;
94  int query_count;
95  int apply_count;
96  const char *name;
97 };
98 static struct {
99  one_perf greedy, opt;
100  struct one_perf *current;
101 } performance;
102 
103 static void print_performance(struct one_perf *counts);
104 #endif // GATHER_TIME_STATS
105 
106 // Fitness of a solution.
107 struct cm_fitness {
108  int weighted; // weighted sum
109  bool sufficient; // false => doesn't meet constraints
110 };
111 
112 /*
113  * We have a cyclic structure here, so we need to forward-declare the
114  * structs
115  */
116 struct cm_tile_type;
117 struct cm_tile;
118 
123 struct cm_tile {
124  const struct cm_tile_type *type;
125  int index; // city map index; only valid if !is_specialist
126 };
127 
128 // define the tile_vector as array<cm_tile>
129 #define SPECVEC_TAG tile
130 #define SPECVEC_TYPE struct cm_tile
131 #include "specvec.h"
132 
133 // define the tile_type_vector as array <cm_tile_type*>
134 #define SPECVEC_TAG tile_type
135 #define SPECVEC_TYPE struct cm_tile_type *
136 #include "specvec.h"
137 #define tile_type_vector_iterate(vector, var) \
138  { \
139  struct cm_tile_type *var; \
140  TYPED_VECTOR_ITERATE(struct cm_tile_type *, vector, var##p) \
141  { \
142  var = *var##p; \
143  {
144 #define tile_type_vector_iterate_end \
145  } \
146  } \
147  VECTOR_ITERATE_END; \
148  }
149 
162 struct cm_tile_type {
164  double estimated_fitness; // weighted sum of production
166  Specialist_type_id spec; // valid only if is_specialist
167  struct tile_vector tiles; // valid only if !is_specialist
168  struct tile_type_vector better_types;
169  struct tile_type_vector worse_types;
170  int lattice_index; // index in state->lattice
171  int lattice_depth; // depth = sum(#tiles) over all better types
172 };
173 
180  // indices for these two match the lattice indices
181  int *worker_counts; // number of workers on each type
182  int *prereqs_filled; // number of better types filled up
183 
184  int production[O_LAST]; // raw production, cached for the heuristic
185  int idle; // number of idle workers
186 };
187 
193 struct cm_state {
194  // input from the caller
195  struct cm_parameter parameter;
196  /*mutable*/ struct city *pcity;
197 
198  // the tile lattice
199  struct tile_type_vector lattice;
200  struct tile_type_vector lattice_by_prod[O_LAST];
201 
202  // the output of tiles the city works for free.
203  std::array<int, O_LAST> city_center_output = {0};
204 
205  // specialist outputs
206  std::vector<std::array<int, O_LAST>> specialist_outputs = {};
207 
208  // cached government centers to avoid looping through all cities
209  std::vector<city *> gov_centers;
210 
211  // cached waste levels to avoid recomputations
212  std::array<cached_waste, O_LAST> waste;
213 
214  // the best known solution, and its fitness
215  struct partial_solution best;
216  struct cm_fitness best_value;
217 
218  /* hard constraints on production: any solution with less production than
219  * this fails to satisfy the constraints, so we can stop investigating
220  * this branch. A solution with more production than this may still
221  * fail (for being unhappy, for instance). */
223 
224  // needed luxury to be content, this includes effects by specialists
226 
227  // the current solution we're examining.
228  struct partial_solution current;
229 
230  /*
231  * Where we are in the search. When we add a worker to the current
232  * partial solution, we also push the tile type index on the stack.
233  */
234  struct {
235  int *stack;
236  int size;
238 
239  bool *workers_map; // placement of the workers within the city map
240 };
241 
242 // return #fields + specialist types
243 static int num_types(const struct cm_state *state);
244 
245 // debugging functions
246 #ifdef FREECIV_DEBUG
247 static void real_print_tile_type(QtMsgType level, const char *file,
248  const char *function, int line,
249  const struct cm_tile_type *ptype,
250  const char *prefix);
251 #define print_tile_type(loglevel, ptype, prefix) \
252  real_print_tile_type(loglevel, __FILE__, __FUNCTION__, __FC_LINE__, \
253  ptype, prefix);
254 
255 static void real_print_lattice(QtMsgType level, const char *file,
256  const char *function, int line,
257  const struct tile_type_vector *lattice);
258 #define print_lattice(loglevel, lattice) \
259  real_print_lattice(loglevel, __FILE__, __FUNCTION__, __FC_LINE__, lattice);
260 
261 static void real_print_partial_solution(QtMsgType level, const char *file,
262  const char *function, int line,
263  const struct partial_solution *soln,
264  const struct cm_state *state);
265 #define print_partial_solution(loglevel, soln, state) \
266  real_print_partial_solution(loglevel, __FILE__, __FUNCTION__, \
267  __FC_LINE__, soln, state);
268 
269 #else
270 #define print_tile_type(loglevel, ptype, prefix)
271 #define print_lattice(loglevel, lattice)
272 #define print_partial_solution(loglevel, soln, state)
273 #endif // FREECIV_DEBUG
274 
275 static void cm_result_copy(std::unique_ptr<cm_result> &result,
276  const struct city *pcity, bool *workers_map);
277 
278 static double estimate_fitness(const struct cm_state *state,
279  const int production[]);
280 static bool choice_is_promising(struct cm_state *state, int newchoice,
281  bool negative_ok);
282 
288 void cm_init()
289 {
290  // In the B&B algorithm there's not really anything to initialize.
291 #ifdef GATHER_TIME_STATS
292  memset(&performance, 0, sizeof(performance));
293 
294  performance.greedy.wall_timer = timer_new(TIMER_USER, TIMER_ACTIVE);
295  performance.greedy.name = "greedy";
296 
297  performance.opt.wall_timer = timer_new(TIMER_USER, TIMER_ACTIVE);
298  performance.opt.name = "opt";
299 #endif // GATHER_TIME_STATS
300 }
301 
308 {
309  // In the B&B algorithm there's not really anything to initialize.
310 }
311 
315 void cm_free()
316 {
317 #ifdef GATHER_TIME_STATS
318  print_performance(&performance.greedy);
319  print_performance(&performance.opt);
320 
321  timer_destroy(performance.greedy.wall_timer);
322  timer_destroy(performance.opt.wall_timer);
323  memset(&performance, 0, sizeof(performance));
324 #endif // GATHER_TIME_STATS
325 }
326 
330 std::unique_ptr<cm_result> cm_result_new(struct city *pcity)
331 {
332  // initialise all values
333  auto result = std::make_unique<cm_result>();
334  result->city_radius_sq =
336  int tiles = city_map_tiles(result->city_radius_sq);
337  fc_assert_ret_val(tiles > 0, result);
338  result->worker_positions.resize(tiles, false);
339 
340  /* test if the city pointer is valid; the cm_result struct can be
341  * returned as it uses the maximal possible value for the size of
342  * 'worker_positions' (= city_map_tiles(CITY_MAP_MAX_RADIUS_SQ))*/
343  fc_assert_ret_val(pcity != nullptr, result);
344 
345  return result;
346 }
347 
348 /*
349  Functions of tile-types.
350  */
351 
355 static void tile_type_init(struct cm_tile_type *type)
356 {
357  memset(type, 0, sizeof(*type));
358  tile_vector_init(&type->tiles);
359  tile_type_vector_init(&type->better_types);
360  tile_type_vector_init(&type->worse_types);
361 }
362 
367 static struct cm_tile_type *tile_type_dup(const struct cm_tile_type *oldtype)
368 {
369  auto *newtype = new cm_tile_type;
370 
371  memcpy(newtype, oldtype, sizeof(*oldtype));
372  tile_vector_init(&newtype->tiles);
373  tile_type_vector_init(&newtype->better_types);
374  tile_type_vector_init(&newtype->worse_types);
375 
376  return newtype;
377 }
378 
382 static void tile_type_destroy(struct cm_tile_type *type)
383 {
384  /* The call to vector_free() will magically free all the tiles in the
385  * vector. */
386  tile_vector_free(&type->tiles);
387  tile_type_vector_free(&type->better_types);
388  tile_type_vector_free(&type->worse_types);
389 }
390 
395 static void tile_type_vector_free_all(struct tile_type_vector *vec)
396 {
397  tile_type_vector_iterate(vec, type)
398  {
399  // Destroy all data in the type, and free the type itself.
400  tile_type_destroy(type);
401  delete type;
402  }
404 
405  tile_type_vector_free(vec);
406 }
407 
413 static bool tile_type_equal(const struct cm_tile_type *a,
414  const struct cm_tile_type *b)
415 {
416  output_type_iterate(stat_index)
417  {
418  if (a->production[stat_index] != b->production[stat_index]) {
419  return false;
420  }
421  }
423 
424  return a->is_specialist == b->is_specialist;
425 }
426 
433 static bool tile_type_better(const struct cm_tile_type *a,
434  const struct cm_tile_type *b)
435 {
436  output_type_iterate(stat_index)
437  {
438  if (a->production[stat_index] < b->production[stat_index]) {
439  return false;
440  }
441  }
443 
444  if (a->is_specialist && !b->is_specialist) {
445  /* If A is a specialist and B isn't, and all of A's production is at
446  * least as good as B's, then A is better because it doesn't tie up
447  * the map tile. */
448  return true;
449  } else if (!a->is_specialist && b->is_specialist) {
450  // Vice versa.
451  return false;
452  }
453 
454  return true;
455 }
456 
463 static int
464 tile_type_vector_find_equivalent(const struct tile_type_vector *vec,
465  const struct cm_tile_type *ptype)
466 {
467  int i;
468 
469  for (i = 0; i < vec->size; i++) {
470  if (tile_type_equal(vec->p[i], ptype)) {
471  return i;
472  }
473  }
474 
475  return -1;
476 }
477 
483 static int tile_type_num_tiles(const struct cm_tile_type *type)
484 {
485  if (type->is_specialist) {
486  return FC_INFINITY;
487  } else {
488  return tile_vector_size(&type->tiles);
489  }
490 }
491 
498 static int tile_type_num_prereqs(const struct cm_tile_type *ptype)
499 {
500  return ptype->better_types.size;
501 }
502 
508 static const struct cm_tile_type *tile_type_get(const struct cm_state *state,
509  int type)
510 {
511  // Sanity check the index.
512  fc_assert_ret_val(0 <= type, nullptr);
513  fc_assert_ret_val(state->lattice.size > type, nullptr);
514 
515  return state->lattice.p[type];
516 }
517 
524 static const struct cm_tile *tile_get(const struct cm_tile_type *ptype,
525  int j)
526 {
527  fc_assert_ret_val(!ptype->is_specialist, nullptr);
528  fc_assert_ret_val(0 <= j, nullptr);
529  fc_assert_ret_val(j < ptype->tiles.size, nullptr);
530 
531  return &ptype->tiles.p[j];
532 }
533 
534 /*
535  Functions on the cm_fitness struct.
536  */
537 
541 static bool fitness_better(struct cm_fitness a, struct cm_fitness b)
542 {
543  if (a.sufficient != b.sufficient) {
544  return a.sufficient;
545  }
546  return a.weighted > b.weighted;
547 }
548 
553 static struct cm_fitness worst_fitness()
554 {
555  struct cm_fitness f;
556 
557  f.sufficient = false;
558  f.weighted = -FC_INFINITY;
559  return f;
560 }
561 
566 static struct cm_fitness
567 compute_fitness(const int surplus[], bool disorder, bool happy,
568  const struct cm_parameter *parameter)
569 {
570  struct cm_fitness fitness;
571 
572  fitness.sufficient = true;
573  fitness.weighted = 0;
574 
575  output_type_iterate(stat_index)
576  {
577  fitness.weighted += surplus[stat_index] * parameter->factor[stat_index];
578  if (surplus[stat_index] < parameter->minimal_surplus[stat_index]) {
579  fitness.sufficient = false;
580  }
581  }
583 
584  if (happy) {
585  fitness.weighted += parameter->happy_factor;
586  } else if (parameter->require_happy) {
587  fitness.sufficient = false;
588  }
589 
590  if (disorder && !parameter->allow_disorder) {
591  fitness.sufficient = false;
592  }
593 
594  return fitness;
595 }
596 
597 /*
598  Handle struct partial_solution.
599  - perform a deep copy
600  - convert to city
601  - convert to cm_result
602  */
603 
607 static void init_partial_solution(struct partial_solution *into, int ntypes,
608  int idle, bool negative_ok)
609 {
610  into->worker_counts = new int[ntypes]();
611  into->prereqs_filled = new int[ntypes]();
612 
613  if (negative_ok) {
614  output_type_iterate(otype) { into->production[otype] = -FC_INFINITY; }
616  } else {
617  memset(into->production, 0, sizeof(into->production));
618  }
619  into->idle = idle;
620 }
621 
627 {
628  delete[] into->worker_counts;
629  delete[] into->prereqs_filled;
630 }
631 
636 static void copy_partial_solution(struct partial_solution *dst,
637  const struct partial_solution *src,
638  const struct cm_state *state)
639 {
640  memcpy(dst->worker_counts, src->worker_counts,
641  sizeof(*dst->worker_counts) * num_types(state));
642  memcpy(dst->prereqs_filled, src->prereqs_filled,
643  sizeof(*dst->prereqs_filled) * num_types(state));
644  memcpy(dst->production, src->production, sizeof(dst->production));
645  dst->idle = src->idle;
646 }
647 
655 static void apply_solution(struct cm_state *state,
656  const struct partial_solution *soln)
657 {
658  struct city *pcity = state->pcity;
659  int i, citizen_count = 0;
660 
661 #ifdef GATHER_TIME_STATS
662  performance.current->apply_count++;
663 #endif
664 
665  fc_assert_ret(0 == soln->idle);
666 
667  /* Clear all specialists, and remove all workers from fields (except
668  * the city center). */
669  memset(&pcity->specialists, 0, sizeof(pcity->specialists));
670  memset(state->workers_map, 0, city_map_tiles_from_city(state->pcity));
672 
673  /* Now for each tile type, find the right number of such tiles and set them
674  * as worked. For specialists we just increase the number of specialists
675  * of that type. */
676  for (i = 0; i < num_types(state); i++) {
677  int nworkers = soln->worker_counts[i];
678  const struct cm_tile_type *type;
679 
680  if (nworkers == 0) {
681  // No citizens of this type.
682  continue;
683  }
684  citizen_count += nworkers;
685 
686  type = tile_type_get(state, i);
687 
688  if (type->is_specialist) {
689  // Just increase the number of specialists.
690  pcity->specialists[type->spec] += nworkers;
691  } else {
692  int j;
693 
694  // Place citizen workers onto the citymap tiles.
695  for (j = 0; j < nworkers; j++) {
696  const struct cm_tile *cmtile = tile_get(type, j);
697 
698  state->workers_map[cmtile->index] = true;
699  }
700  }
701  }
702 
703  // Finally we must refresh the city to reset all the precomputed fields.
704  city_refresh_from_main_map(pcity, state->workers_map, state->gov_centers,
705  &state->waste, &state->specialist_outputs);
706  fc_assert_ret(citizen_count == city_size_get(pcity));
707 }
708 
714 static void get_city_surplus(const struct city *pcity, int surplus[],
715  bool *disorder, bool *happy)
716 {
717  output_type_iterate(o) { surplus[o] = pcity->surplus[o]; }
719 
720  *disorder = city_unhappy(pcity);
721  *happy = city_happy(pcity);
722 }
723 
727 static struct cm_fitness
728 evaluate_solution(struct cm_state *state,
729  const struct partial_solution *soln)
730 {
731  struct city *pcity = state->pcity;
732  int surplus[O_LAST];
733  bool disorder, happy;
734 
735  // apply and evaluate the solution, backup is done in find_best_solution
736  apply_solution(state, soln);
737  get_city_surplus(pcity, surplus, &disorder, &happy);
738 
739  // if this solution is not content, we have an estimate on min. luxuries
740  if (disorder) {
741  /* We have to consider the influence of each specialist in this
742  solution possibly 'hiding' a potential unhappy citizen who
743  could require luxuries.
744  Since we know the city is in disorder, we can discount most
745  effects that make citizens content, since they clearly weren't
746  sufficient.
747  This may not be sufficient luxury to make the city content (due
748  to military unhappiness etc), but certainly no less will do.
749  (Specialists may also be making angry citizens content, requiring
750  additional luxuries, but we don't try to consider that here; this
751  just means we might explore some solutions unnecessarily.) */
752  int specialists_amount = city_specialists(pcity);
753  int max_content = player_content_citizens(city_owner(pcity));
754 
755  state->min_luxury =
757  + game.info.happy_cost * MAX(specialists_amount - max_content, 0)
758  + 1;
759  }
760 
761  return compute_fitness(surplus, disorder, happy, &state->parameter);
762 }
763 
768 static void convert_solution_to_result(struct cm_state *state,
769  const struct partial_solution *soln,
770  std::unique_ptr<cm_result> &result)
771 {
772  struct cm_fitness fitness;
773 
774  if (soln->idle != 0) {
775  /* If there are unplaced citizens it's not a real solution, so the
776  * result is invalid. */
777  result->found_a_valid = false;
778  return;
779  }
780 
781  // apply and evaluate the solution, backup is done in find_best_solution
782  apply_solution(state, soln);
783  cm_result_copy(result, state->pcity, state->workers_map);
784 
785  /* result->found_a_valid should be only true if it matches the
786  * parameter; figure out if it does */
787  fitness = compute_fitness(result->surplus, result->disorder, result->happy,
788  &state->parameter);
789  result->found_a_valid = fitness.sufficient;
790 }
791 
804  const struct cm_tile_type *b)
805 {
806  if (a == b) {
807  return 0;
808  }
809 
810  // Least depth first
811  if (a->lattice_depth != b->lattice_depth) {
812  return a->lattice_depth - b->lattice_depth;
813  }
814 
815  // With equal depth, break ties arbitrarily, more production first.
816  output_type_iterate(stat_index)
817  {
818  if (a->production[stat_index] != b->production[stat_index]) {
819  return b->production[stat_index] - a->production[stat_index];
820  }
821  }
823 
824  // If we get here, then we have two copies of identical types, an error
825  fc_assert(false);
826  return 0;
827 }
828 
835 static int compare_tile_type_by_fitness(const void *va, const void *vb)
836 {
837  const auto *a = static_cast<cm_tile_type *const *>(va);
838  const auto *b = static_cast<cm_tile_type *const *>(vb);
839  double diff;
840 
841  if (*a == *b) {
842  return 0;
843  }
844 
845  /* To avoid double->int roundoff problems, we call a result non-zero only
846  * if it's larger than 0.5. */
847  diff = (*b)->estimated_fitness - (*a)->estimated_fitness;
848  if (diff > 0.5) {
849  return 1; // return value is int; don't round down!
850  }
851  if (diff < -0.5) {
852  return -1;
853  }
854 
855  return compare_tile_type_by_lattice_order(*a, *b);
856 }
857 
860 
867 static int compare_tile_type_by_stat(const void *va, const void *vb)
868 {
869  const auto *a = static_cast<cm_tile_type *const *>(va);
870  const auto *b = static_cast<cm_tile_type *const *>(vb);
871 
872  if (*a == *b) {
873  return 0;
874  }
875 
876  /* consider the influence of trade on science, luxury, gold
877  for compute_max_stats_heuristic, which uses these sorted arrays,
878  it is essential, that the sorting is correct, else promising
879  branches get pruned */
880  double valuea = (*a)->production[compare_key]
881  + compare_key_trade_bonus * (*a)->production[O_TRADE];
882  double valueb = (*b)->production[compare_key]
883  + compare_key_trade_bonus * (*b)->production[O_TRADE];
884 
885  // most production of what we care about goes first
886  /* double compare is ok, both values are calculated in the same way
887  and should only be considered equal, if equal in compare_key
888  and O_TRADE */
889  if (valuea != valueb) {
890  // b-a so we sort big numbers first
891  return valueb - valuea;
892  }
893 
894  return compare_tile_type_by_lattice_order(*a, *b);
895 }
896 
905 static void compute_tile_production(const struct city *pcity,
906  const struct tile *ptile,
907  bool is_celebrating,
908  struct cm_tile_type *out)
909 {
911  {
912  out->production[o] = city_tile_output(pcity, ptile, is_celebrating, o);
913  }
915 }
916 
924 static void tile_type_lattice_add(struct tile_type_vector *lattice,
925  const struct cm_tile_type *newtype,
926  int tindex)
927 {
928  struct cm_tile_type *type;
929  int i;
930 
931  i = tile_type_vector_find_equivalent(lattice, newtype);
932  if (i >= 0) {
933  // We already have this type of tile; use it.
934  type = lattice->p[i];
935  } else {
936  // This is a new tile type; add it to the lattice.
937  type = tile_type_dup(newtype);
938 
939  // link up to the types we dominate, and those that dominate us
940  tile_type_vector_iterate(lattice, other)
941  {
942  if (tile_type_better(other, type)) {
943  tile_type_vector_append(&type->better_types, other);
944  tile_type_vector_append(&other->worse_types, type);
945  } else if (tile_type_better(type, other)) {
946  tile_type_vector_append(&other->better_types, type);
947  tile_type_vector_append(&type->worse_types, other);
948  }
949  }
951 
952  // insert into the list
953  type->lattice_index = lattice->size;
954  tile_type_vector_append(lattice, type);
955  }
956 
957  // Finally, add the tile to the tile type.
958  if (!type->is_specialist) {
959  struct cm_tile tile;
960 
961  tile.type = type;
962  tile.index = tindex;
963 
964  tile_vector_append(&type->tiles, tile);
965  }
966 }
967 
968 /*
969  * Add the specialist types to the lattice.
970  */
971 
976 static void init_specialist_lattice_nodes(struct cm_state *state,
977  const struct city *pcity)
978 {
979  struct cm_tile_type type;
980 
981  tile_type_init(&type);
982  type.is_specialist = true;
983 
984  /* for each specialist type, create a tile_type that has as production
985  * the bonus for the specialist (if the city is allowed to use it) */
987  {
988  std::array<int, O_LAST> outputs = {0};
989 
990  if (city_can_use_specialist(pcity, i)) {
991  type.spec = i;
992  output_type_iterate(output)
993  {
994  outputs[output] = get_specialist_output(pcity, i, output);
995  type.production[output] = outputs[output];
996  }
998 
999  tile_type_lattice_add(&state->lattice, &type, 0);
1000  }
1001 
1002  state->specialist_outputs.push_back(outputs);
1003  }
1005 }
1006 
1014 static void top_sort_lattice(struct tile_type_vector *lattice)
1015 {
1016  int i;
1017  std::vector<bool> marked;
1018  std::vector<bool> will_mark;
1019  marked.resize(lattice->size);
1020  will_mark.resize(lattice->size);
1021 
1022  struct tile_type_vector vectors[2];
1023  struct tile_type_vector *current, *next;
1024 
1025  tile_type_vector_init(&vectors[0]);
1026  tile_type_vector_init(&vectors[1]);
1027  current = &vectors[0];
1028  next = &vectors[1];
1029 
1030  // fill up 'next'
1031  tile_type_vector_iterate(lattice, ptype)
1032  {
1033  if (tile_type_num_prereqs(ptype) == 0) {
1034  tile_type_vector_append(next, ptype);
1035  }
1036  }
1038 
1039  /* while we have nodes to process: mark the nodes whose prereqs have
1040  * all been visited. Then, store all the new nodes on the frontier. */
1041  while (next->size != 0) {
1042  // what was the next frontier is now the current frontier
1043  struct tile_type_vector *vtmp = current;
1044 
1045  current = next;
1046  next = vtmp;
1047  next->size = 0; // clear out the contents
1048 
1049  // look over the current frontier and process everyone
1050  tile_type_vector_iterate(current, ptype)
1051  {
1052  /* see if all prereqs were marked. If so, decide to mark this guy,
1053  and put all the descendents on 'next'. */
1054  bool can_mark = true;
1055  int sumdepth = 0;
1056 
1057  if (will_mark[ptype->lattice_index]) {
1058  continue; // we've already been processed
1059  }
1060  tile_type_vector_iterate(&ptype->better_types, better)
1061  {
1062  if (!marked[better->lattice_index]) {
1063  can_mark = false;
1064  break;
1065  } else {
1066  sumdepth += tile_type_num_tiles(better);
1067  if (sumdepth >= FC_INFINITY) {
1068  /* if this is the case, then something better could
1069  always be used, and the same holds for our children */
1070  sumdepth = FC_INFINITY;
1071  can_mark = true;
1072  break;
1073  }
1074  }
1075  }
1077  if (can_mark) {
1078  // mark and put successors on the next frontier
1079  will_mark[ptype->lattice_index] = true;
1080  tile_type_vector_iterate(&ptype->worse_types, worse)
1081  {
1082  tile_type_vector_append(next, worse);
1083  }
1085 
1086  // this is what we spent all this time computing.
1087  ptype->lattice_depth = sumdepth;
1088  }
1089  }
1091 
1092  // now, actually mark everyone and get set for next loop
1093  for (i = 0; i < lattice->size; i++) {
1094  marked[i] = marked[i] || will_mark[i];
1095  will_mark[i] = false;
1096  }
1097  }
1098 
1099  tile_type_vector_free(&vectors[0]);
1100  tile_type_vector_free(&vectors[1]);
1101 }
1102 
1119 static void clean_lattice(struct tile_type_vector *lattice,
1120  const struct city *pcity)
1121 {
1122  int i, j; // i is the index we read, j is the index we write
1123  struct tile_type_vector tofree;
1124  bool forced_loop = false;
1125 
1126  /* We collect the types we want to remove and free them in one fell
1127  swoop at the end, in order to avoid memory errors. */
1128  tile_type_vector_init(&tofree);
1129 
1130  /* forced_loop is workaround for what seems like gcc optimization
1131  * bug.
1132  * This applies to -O2 optimization on some distributions. */
1133  if (lattice->size > 0) {
1134  forced_loop = true;
1135  }
1136  for (i = 0, j = 0; i < lattice->size || forced_loop; i++) {
1137  struct cm_tile_type *ptype = lattice->p[i];
1138 
1139  forced_loop = false;
1140 
1141  if (ptype->lattice_depth >= city_size_get(pcity)) {
1142  tile_type_vector_append(&tofree, ptype);
1143  } else {
1144  // Remove links to children that are being removed.
1145 
1146  int ci, cj; // 'c' for 'child'; read from ci, write to cj
1147 
1148  lattice->p[j] = ptype;
1149  lattice->p[j]->lattice_index = j;
1150  j++;
1151 
1152  for (ci = 0, cj = 0; ci < ptype->worse_types.size; ci++) {
1153  const struct cm_tile_type *ptype2 = ptype->worse_types.p[ci];
1154 
1155  if (ptype2->lattice_depth < city_size_get(pcity)) {
1156  ptype->worse_types.p[cj] = ptype->worse_types.p[ci];
1157  cj++;
1158  }
1159  }
1160  ptype->worse_types.size = cj;
1161  }
1162  }
1163  lattice->size = j;
1164 
1165  tile_type_vector_free_all(&tofree);
1166 }
1167 
1173 static void sort_lattice_by_fitness(const struct cm_state *state,
1174  struct tile_type_vector *lattice)
1175 {
1176  int i;
1177 
1178  // compute fitness
1179  tile_type_vector_iterate(lattice, ptype)
1180  {
1181  ptype->estimated_fitness = estimate_fitness(state, ptype->production);
1182  }
1184 
1185  // sort by it
1186  qsort(lattice->p, lattice->size, sizeof(*lattice->p),
1188 
1189  // fix the lattice indices
1190  for (i = 0; i < lattice->size; i++) {
1191  lattice->p[i]->lattice_index = i;
1192  }
1193 
1194  log_base(LOG_LATTICE, "sorted lattice:");
1195  print_lattice(LOG_LATTICE, lattice);
1196 }
1197 
1201 static void init_tile_lattice(struct city *pcity, struct cm_state *state)
1202 {
1203  struct cm_tile_type type;
1204  struct tile *pcenter = city_tile(pcity);
1205 
1206  // add all the fields into the lattice
1207  tile_type_init(&type); // init just once
1208 
1209  bool is_celebrating = base_city_celebrating(pcity);
1210  city_tile_iterate_index(city_map_radius_sq_get(pcity), pcenter, ptile,
1211  ctindex)
1212  {
1213  if (is_city_center(pcity, ptile)) {
1215  {
1216  state->city_center_output[o] =
1217  city_tile_output(pcity, ptile, is_celebrating, o);
1218  }
1220  continue;
1221  } else if (city_can_work_tile(pcity, ptile)) {
1222  compute_tile_production(pcity, ptile, is_celebrating,
1223  &type); // clobbers type
1224  tile_type_lattice_add(&state->lattice, &type,
1225  ctindex); // copy type if needed
1226  }
1227  }
1229 
1230  // Add all the specialists into the lattice.
1231  if (state->parameter.allow_specialists) {
1232  init_specialist_lattice_nodes(state, pcity);
1233  }
1234 
1235  // Set the lattice_depth fields, and clean up unreachable nodes.
1236  top_sort_lattice(&state->lattice);
1237  clean_lattice(&state->lattice, pcity);
1238 
1239  // All done now.
1240  print_lattice(LOG_LATTICE, &state->lattice);
1241 }
1242 
1252 static bool choice_stack_empty(struct cm_state *state)
1253 {
1254  return state->choice.size == 0;
1255 }
1256 
1260 static int last_choice(struct cm_state *state)
1261 {
1263 
1264  return state->choice.stack[state->choice.size - 1];
1265 }
1266 
1272 static int num_types(const struct cm_state *state)
1273 {
1274  return tile_type_vector_size(&state->lattice);
1275 }
1276 
1283 static void add_workers(struct partial_solution *soln, int itype, int number,
1284  const struct cm_state *state)
1285 {
1286  const struct cm_tile_type *ptype = tile_type_get(state, itype);
1287  int newcount;
1288  int old_worker_count = soln->worker_counts[itype];
1289 
1290  if (number == 0) {
1291  return;
1292  }
1293 
1294  // update the number of idle workers
1295  newcount = soln->idle - number;
1296  fc_assert_ret(newcount >= 0);
1297  fc_assert_ret(newcount <= city_size_get(state->pcity));
1298  soln->idle = newcount;
1299 
1300  // update the worker counts
1301  newcount = soln->worker_counts[itype] + number;
1302  fc_assert_ret(newcount >= 0);
1303  fc_assert_ret(newcount <= tile_type_num_tiles(ptype));
1304  soln->worker_counts[itype] = newcount;
1305 
1306  /* update prereqs array: if we are no longer full but we were,
1307  * we need to decrement the count, and vice-versa. */
1308  if (old_worker_count == tile_type_num_tiles(ptype)) {
1309  fc_assert_ret(number < 0);
1310  tile_type_vector_iterate(&ptype->worse_types, other)
1311  {
1312  soln->prereqs_filled[other->lattice_index]--;
1313  fc_assert_ret(soln->prereqs_filled[other->lattice_index] >= 0);
1314  }
1316  } else if (soln->worker_counts[itype] == tile_type_num_tiles(ptype)) {
1317  fc_assert_ret(number > 0);
1318  tile_type_vector_iterate(&ptype->worse_types, other)
1319  {
1320  soln->prereqs_filled[other->lattice_index]++;
1321  fc_assert_ret(soln->prereqs_filled[other->lattice_index]
1322  <= tile_type_num_prereqs(other));
1323  }
1325  }
1326 
1327  // update production
1328  output_type_iterate(stat_index)
1329  {
1330  newcount = soln->production[stat_index]
1331  + number * ptype->production[stat_index];
1332  soln->production[stat_index] = newcount;
1333  }
1335 }
1336 
1340 static void add_worker(struct partial_solution *soln, int itype,
1341  const struct cm_state *state)
1342 {
1343  add_workers(soln, itype, 1, state);
1344 }
1345 
1349 static void remove_worker(struct partial_solution *soln, int itype,
1350  const struct cm_state *state)
1351 {
1352  add_workers(soln, itype, -1, state);
1353 }
1354 
1359 static void pop_choice(struct cm_state *state)
1360 {
1362  remove_worker(&state->current, last_choice(state), state);
1363  state->choice.size--;
1364 }
1365 
1369 static bool prereqs_filled(const struct partial_solution *soln, int type,
1370  const struct cm_state *state)
1371 {
1372  const struct cm_tile_type *ptype = tile_type_get(state, type);
1373  int prereqs = tile_type_num_prereqs(ptype);
1374 
1375  return soln->prereqs_filled[type] == prereqs;
1376 }
1377 
1387 static int next_choice(struct cm_state *state, int oldchoice,
1388  bool negative_ok)
1389 {
1390  int newchoice;
1391 
1392  for (newchoice = oldchoice + 1; newchoice < num_types(state);
1393  newchoice++) {
1394  const struct cm_tile_type *ptype = tile_type_get(state, newchoice);
1395 
1396  if (!ptype->is_specialist
1397  && (state->current.worker_counts[newchoice]
1398  == tile_vector_size(&ptype->tiles))) {
1399  // we've already used all these tiles
1400  continue;
1401  }
1402  if (!prereqs_filled(&state->current, newchoice, state)) {
1403  // we could use a strictly better tile instead
1404  continue;
1405  }
1406  if (!choice_is_promising(state, newchoice, negative_ok)) {
1407  // heuristic says we can't beat the best going this way
1408  log_base(LOG_PRUNE_BRANCH, "--- pruning branch ---");
1410  print_tile_type(LOG_PRUNE_BRANCH, tile_type_get(state, newchoice),
1411  " + worker on ");
1412  log_base(LOG_PRUNE_BRANCH, "--- branch pruned ---");
1413  continue;
1414  }
1415  break;
1416  }
1417 
1418  // returns num_types if no next choice was available.
1419  return newchoice;
1420 }
1421 
1426 static bool take_sibling_choice(struct cm_state *state, bool negative_ok)
1427 {
1428  int oldchoice = last_choice(state);
1429  int newchoice;
1430 
1431  // need to remove first, to run the heuristic
1432  remove_worker(&state->current, oldchoice, state);
1433  newchoice = next_choice(state, oldchoice, negative_ok);
1434 
1435  if (newchoice == num_types(state)) {
1436  // add back in so the caller can then remove it again.
1437  add_worker(&state->current, oldchoice, state);
1438  return false;
1439  } else {
1440  add_worker(&state->current, newchoice, state);
1441  state->choice.stack[state->choice.size - 1] = newchoice;
1442  // choice.size is unchanged
1443  return true;
1444  }
1445 }
1446 
1454 static bool take_child_choice(struct cm_state *state, bool negative_ok)
1455 {
1456  int oldchoice, newchoice;
1457 
1458  if (state->current.idle == 0) {
1459  return false;
1460  }
1461 
1462  if (state->choice.size == 0) {
1463  oldchoice = 0;
1464  } else {
1465  oldchoice = last_choice(state);
1466  }
1467 
1468  // oldchoice-1 because we can use oldchoice again
1469  newchoice = next_choice(state, oldchoice - 1, negative_ok);
1470 
1471  // did we fail?
1472  if (newchoice == num_types(state)) {
1473  return false;
1474  }
1475 
1476  // now push the new choice on the choice stack
1477  add_worker(&state->current, newchoice, state);
1478  state->choice.stack[state->choice.size] = newchoice;
1479  state->choice.size++;
1480 
1481  return true;
1482 }
1483 
1488 static void complete_solution(struct partial_solution *soln,
1489  const struct cm_state *state,
1490  const struct tile_type_vector *lattice)
1491 {
1492  int last_worker_choice = -1;
1493  int i;
1494 
1495  if (soln->idle == 0) {
1496  return;
1497  }
1498 
1499  // find the last worker type added (-1 if none)
1500  for (i = 0; i < num_types(state); i++) {
1501  if (soln->worker_counts[i] != 0) {
1502  last_worker_choice = i;
1503  }
1504  }
1505 
1506  /* While there are idle workers, pick up the next-best kind of tile,
1507  * and assign the workers to the tiles.
1508  * Respect lexicographic order and prerequisites. */
1509  tile_type_vector_iterate(lattice, ptype)
1510  {
1511  int used = soln->worker_counts[ptype->lattice_index];
1512  int total = tile_type_num_tiles(ptype);
1513  int touse;
1514 
1515  if (ptype->lattice_index < last_worker_choice) {
1516  /* lex-order: we can't use ptype (some other branch
1517  will check this combination, or already did) */
1518  continue;
1519  }
1520  if (!prereqs_filled(soln, ptype->lattice_index, state)) {
1521  // don't bother using this tile before all better tiles are used
1522  continue;
1523  }
1524 
1525  touse = total - used;
1526  if (touse > soln->idle) {
1527  touse = soln->idle;
1528  }
1529  add_workers(soln, ptype->lattice_index, touse, state);
1530 
1531  if (soln->idle == 0) {
1532  // nothing left to do here
1533  return;
1534  }
1535  }
1537 }
1538 
1542 static int specialists_in_solution(const struct cm_state *state,
1543  const struct partial_solution *soln)
1544 {
1545  int count = 0;
1546  int i;
1547 
1548  for (i = 0; i < num_types(state); i++) {
1549  if (soln->worker_counts[i] > 0
1550  && tile_type_get(state, i)->is_specialist) {
1551  count += soln->worker_counts[i];
1552  }
1553  }
1554 
1555  return count;
1556 }
1557 
1568 static void compute_max_stats_heuristic(const struct cm_state *state,
1569  const struct partial_solution *soln,
1570  int production[], int check_choice,
1571  bool negative_ok)
1572 {
1573  struct partial_solution solnplus; // will be soln, plus some tiles
1574 
1575  /* Production is whatever the solution produces, plus the
1576  most possible of each kind of production the idle workers could
1577  produce */
1578 
1579  if (soln->idle == 1) {
1580  /* Then the total solution is soln + this new worker. So we know the
1581  production exactly, and can shortcut the later code. */
1582  const struct cm_tile_type *ptype = tile_type_get(state, check_choice);
1583 
1584  memcpy(production, soln->production, sizeof(soln->production));
1585  output_type_iterate(stat_index)
1586  {
1587  production[stat_index] += ptype->production[stat_index];
1588  }
1590 
1591  } else {
1592  // initialize solnplus here, after the shortcut check
1593  init_partial_solution(&solnplus, num_types(state),
1594  city_size_get(state->pcity), negative_ok);
1595 
1596  output_type_iterate(stat_index)
1597  {
1598  /* compute the solution that has soln, then the check_choice,
1599  then complete it with the best available tiles for the stat. */
1600  copy_partial_solution(&solnplus, soln, state);
1601  add_worker(&solnplus, check_choice, state);
1602  complete_solution(&solnplus, state,
1603  &state->lattice_by_prod[stat_index]);
1604 
1605  production[stat_index] = solnplus.production[stat_index];
1606  }
1608 
1609  destroy_partial_solution(&solnplus);
1610  }
1611 
1612  /* we found the basic production, however, bonus, taxes,
1613  free production, tithes, traderoutes are missing
1614  we add free production, and have the city.c code do the rest */
1615 
1616  struct city *pcity = state->pcity;
1617  output_type_iterate(stat_index)
1618  {
1619  pcity->citizen_base[stat_index] =
1620  production[stat_index] + state->city_center_output[stat_index];
1621  }
1623 
1624  set_city_production(pcity, state->gov_centers, &state->waste);
1625  memcpy(production, pcity->prod, sizeof(pcity->prod));
1626 }
1627 
1634 static bool choice_is_promising(struct cm_state *state, int newchoice,
1635  bool negative_ok)
1636 {
1637  int production[O_LAST];
1638  bool beats_best = false;
1639 
1640  /* this computes an upper bound (componentwise) for the current branch,
1641  if it is worse in every component than the best, or still unsufficient,
1642  then we can prune the whole branch */
1643  compute_max_stats_heuristic(state, &state->current, production, newchoice,
1644  negative_ok);
1645 
1646  output_type_iterate(stat_index)
1647  {
1648  if (production[stat_index] < state->min_production[stat_index]) {
1649  log_base(LOG_PRUNE_BRANCH, "--- pruning: insufficient %s (%d < %d)",
1650  get_output_name(stat_index), production[stat_index],
1651  state->min_production[stat_index]);
1652  return false;
1653  }
1654  if (production[stat_index] > state->best.production[stat_index]
1655  && state->parameter.factor[stat_index] > 0) {
1656  beats_best = true;
1657  /* may still fail to meet min at another production type, so
1658  * don't short-circuit */
1659  }
1660  }
1662 
1663  /* If we don't get the city content, we assume using every idle worker
1664  as specialist and the maximum producible luxury already computed.
1665  If this is less than the amount of luxury we calculated in
1666  evaluate_solution() (where min_luxury is set), when we observed the
1667  city in disorder, then this is clearly not worth pursuing.
1668  (Since we're comparing to evaluate_solution()'s calculation, we
1669  don't need to take effects, angry citizens etc into account here
1670  either.)
1671  FIXME: this heuristic will break in rulesets where specialists can
1672  influence happiness other than by direct production of luxury. */
1673  {
1674  int specialists_amount = specialists_in_solution(state, &state->current);
1675  int max_content = player_content_citizens(city_owner(state->pcity));
1676  int specialists_suppress_unhappy =
1677  MAX(specialists_amount + state->current.idle - max_content, 0);
1678  int max_luxury = production[O_LUXURY]
1679  + game.info.happy_cost * specialists_suppress_unhappy;
1680 
1681  if (max_luxury < state->min_luxury) {
1682  log_base(LOG_PRUNE_BRANCH, "--- pruning: disorder (%d + %d*%d < %d)",
1683  production[O_LUXURY], game.info.happy_cost,
1684  specialists_suppress_unhappy, state->min_luxury);
1685  return false;
1686  }
1687  }
1688  if (!beats_best) {
1690  "--- pruning: best is better in all important ways");
1691  }
1692 
1693  return beats_best;
1694 }
1695 
1699 static void init_min_production(struct cm_state *state)
1700 {
1701  struct city *pcity = state->pcity;
1702 
1704  {
1705  state->min_production[o] =
1706  pcity->usage[o] + state->parameter.minimal_surplus[o];
1707  }
1709 
1710  /* We could get a minimum on luxury if we knew how many luxuries were
1711  * needed to make us content. */
1712 }
1713 
1717 static void get_tax_rates(const struct player *pplayer, int rates[])
1718 {
1719  const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1720 
1721  if (game.info.changeable_budget) {
1722  rates[SCIENCE] = pplayer->economic.science;
1723  rates[LUXURY] = pplayer->economic.luxury;
1724  rates[TAX] = 100 - rates[SCIENCE] - rates[LUXURY];
1725  } else {
1726  rates[SCIENCE] = game.info.forced_science;
1727  rates[LUXURY] = game.info.forced_luxury;
1728  rates[TAX] = game.info.forced_gold;
1729  }
1730 
1731  // ANARCHY
1733  rates[SCIENCE] = 0;
1734  rates[LUXURY] = 100;
1735  rates[TAX] = 0;
1736  }
1737 }
1738 
1747 static double estimate_fitness(const struct cm_state *state,
1748  const int production[])
1749 {
1750  const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1751  const struct city *pcity = state->pcity;
1752  const struct player *pplayer = city_owner(pcity);
1753  int rates[3];
1754  double estimates[O_LAST];
1755  double sum = 0;
1756  int trade;
1757 
1758  output_type_iterate(stat_index)
1759  {
1760  estimates[stat_index] = production[stat_index];
1761  }
1763 
1764  // bonus to trade is applied before calculating taxes, see city.c
1765  trade = estimates[O_TRADE] * pcity->bonus[O_TRADE] / 100.0;
1766 
1767  get_tax_rates(pplayer, rates);
1768 
1769  /* sci/lux/gold get benefit from the national budget (in percentage) */
1770  estimates[O_SCIENCE] += rates[SCIENCE] * trade / 100.0;
1771  estimates[O_LUXURY] += rates[LUXURY] * trade / 100.0;
1772  estimates[O_GOLD] += rates[TAX] * trade / 100.0;
1773 
1774  // now add in the bonuses from building effects (in percentage)
1775  output_type_iterate(stat_index)
1776  {
1777  estimates[stat_index] *= pcity->bonus[stat_index] / 100.0;
1778  }
1780 
1781  /* finally, sum it all up, weighted by the parameter, but give additional
1782  * weight to luxuries to take account of disorder/happy constraints */
1783  output_type_iterate(stat_index)
1784  {
1785  sum += estimates[stat_index] * state->parameter.factor[stat_index];
1786  }
1788  sum += estimates[O_LUXURY];
1789 
1790  return sum;
1791 }
1792 
1805 static bool bb_next(struct cm_state *state, bool negative_ok)
1806 {
1807  // if no idle workers, then look at our solution.
1808  if (state->current.idle == 0) {
1809  struct cm_fitness value = evaluate_solution(state, &state->current);
1810 
1812  if (fitness_better(value, state->best_value)) {
1813  log_base(LOG_BETTER_LEAF, "-> replaces previous best");
1814  copy_partial_solution(&state->best, &state->current, state);
1815  state->best_value = value;
1816  }
1817  }
1818 
1819  /* try to move to a child branch, if we can. If not (including if we're
1820  at a leaf), then move to a sibling. */
1821  if (!take_child_choice(state, negative_ok)) {
1822  /* keep trying to move to a sibling branch, or popping out a level if
1823  we're stuck (fully examined the current branch) */
1824  while ((!choice_stack_empty(state))
1825  && !take_sibling_choice(state, negative_ok)) {
1826  pop_choice(state);
1827  }
1828 
1829  // if we popped out all the way, we're done
1830  if (choice_stack_empty(state)) {
1831  return true;
1832  }
1833  }
1834 
1835  // if we didn't detect that we were done, we aren't
1836  return false;
1837 }
1838 
1842 static struct cm_state *cm_state_init(struct city *pcity,
1843  const cm_parameter *param,
1844  bool negative_ok)
1845 {
1846  const int SCIENCE = 0, TAX = 1, LUXURY = 2;
1847  const struct player *pplayer = city_owner(pcity);
1848  int numtypes;
1849  auto *state = new cm_state;
1850  state->parameter = *param;
1851 
1852  int rates[3];
1853 
1854  log_base(LOG_CM_STATE, "creating cm_state for %s (size %d)",
1855  city_name_get(pcity), city_size_get(pcity));
1856 
1857  // copy the arguments
1858  state->pcity = pcity;
1859 
1860  // create the lattice
1861  tile_type_vector_init(&state->lattice);
1862  init_tile_lattice(pcity, state);
1863  numtypes = tile_type_vector_size(&state->lattice);
1864 
1865  get_tax_rates(pplayer, rates);
1866 
1867  // cache government centers
1868  state->gov_centers = player_gov_centers(pplayer);
1869 
1870  // cache waste levels
1872  {
1873  state->waste[o].level =
1874  get_city_output_bonus(pcity, get_output_type(o), EFT_OUTPUT_WASTE);
1875  state->waste[o].relative = get_city_output_bonus(
1876  pcity, get_output_type(o), EFT_OUTPUT_WASTE_PCT);
1877  state->waste[o].by_distance = get_city_output_bonus(
1878  pcity, get_output_type(o), EFT_OUTPUT_WASTE_BY_DISTANCE);
1879  state->waste[o].by_rel_distance = get_city_output_bonus(
1880  pcity, get_output_type(o), EFT_OUTPUT_WASTE_BY_REL_DISTANCE);
1881  }
1883 
1884  // For the heuristic, make sorted copies of the lattice
1885  output_type_iterate(stat_index)
1886  {
1887  tile_type_vector_init(&state->lattice_by_prod[stat_index]);
1888  tile_type_vector_copy(&state->lattice_by_prod[stat_index],
1889  &state->lattice);
1890  compare_key = stat_index;
1891  // calculate effect of 1 trade production on interesting production
1892  switch (stat_index) {
1893  case O_SCIENCE:
1895  rates[SCIENCE] * pcity->bonus[O_TRADE] / 100.0;
1896  break;
1897  case O_LUXURY:
1899  rates[LUXURY] * pcity->bonus[O_TRADE] / 100.0;
1900  break;
1901  case O_GOLD:
1902  compare_key_trade_bonus = rates[TAX] * pcity->bonus[O_TRADE] / 100.0;
1903  break;
1904  default:
1906  break;
1907  }
1908  qsort(state->lattice_by_prod[stat_index].p,
1909  state->lattice_by_prod[stat_index].size,
1910  sizeof(*state->lattice_by_prod[stat_index].p),
1912  }
1914 
1915  state->min_luxury = -FC_INFINITY;
1916 
1917  // We have no best solution yet, so its value is the worst possible.
1918  init_partial_solution(&state->best, numtypes, city_size_get(pcity),
1919  negative_ok);
1920  state->best_value = worst_fitness();
1921 
1922  // Initialize the current solution and choice stack to empty
1923  init_partial_solution(&state->current, numtypes, city_size_get(pcity),
1924  negative_ok);
1925  state->choice.stack = new int[city_size_get(pcity)];
1926  state->choice.size = 0;
1927 
1928  // Initialize workers map
1929  state->workers_map = new bool[city_map_tiles_from_city(state->pcity)]();
1930 
1931  return state;
1932 }
1933 
1939 {
1940  struct city *pcity = state->pcity;
1942  citizens city_size = city_size_get(pcity);
1943  int max_surplus = -game.info.food_cost * city_size;
1944  bool is_celebrating = base_city_celebrating(pcity);
1945  citizens workers = city_size;
1946  int food_needed = city_granary_size(city_size) - pcity->food_stock;
1947  int min_turns;
1948 
1950  {
1951  struct tile *ptile = city_map_to_tile(pcity->tile, city_radius_sq, x, y);
1952  if (!ptile || !city_can_work_tile(pcity, ptile)) {
1953  continue;
1954  }
1955  max_surplus += city_tile_output(pcity, ptile, is_celebrating, O_FOOD);
1956  }
1958 
1959  if (max_surplus <= 0) {
1960  return max_surplus;
1961  }
1962 
1963  if (food_needed <= 0) {
1964  return 0;
1965  }
1966 
1968  {
1969  int num = tile_vector_size(&ptype->tiles);
1970 
1971  if (ptype->is_specialist || workers < num) {
1972  max_surplus += workers * ptype->production[O_FOOD];
1973  break;
1974  }
1975  max_surplus += num * ptype->production[O_FOOD];
1976  workers -= num;
1977  }
1979 
1980  /* min_turns will always be positive because if food_needed or
1981  * max_surplus are non-positive, this function returns earlier. */
1982  min_turns = (food_needed + max_surplus - 1) / max_surplus;
1983 
1984  return (food_needed + min_turns - 1) / min_turns;
1985 }
1986 
1991 static void begin_search(struct cm_state *state,
1992  const struct cm_parameter *parameter,
1993  bool negative_ok)
1994 {
1995 #ifdef GATHER_TIME_STATS
1996  timer_start(performance.current->wall_timer);
1997  performance.current->query_count++;
1998 #endif // GATHER_TIME_STATS
1999 
2000  // copy the parameter and sort the main lattice by it
2001  cm_copy_parameter(&state->parameter, parameter);
2002 
2003  if (parameter->max_growth) {
2004  state->parameter.minimal_surplus[O_FOOD] =
2006  state->parameter.factor[O_FOOD] = 0;
2007  }
2008 
2009  sort_lattice_by_fitness(state, &state->lattice);
2010  init_min_production(state);
2011 
2012  // clear out the old solution
2013  state->best_value = worst_fitness();
2015  init_partial_solution(&state->current, num_types(state),
2016  city_size_get(state->pcity), negative_ok);
2017  state->choice.size = 0;
2018 }
2019 
2024 static void end_search(struct cm_state *state)
2025 {
2026  Q_UNUSED(state)
2027 #ifdef GATHER_TIME_STATS
2028  timer_stop(performance.current->wall_timer);
2029 
2030 #ifdef PRINT_TIME_STATS_EVERY_QUERY
2031  print_performance(performance.current);
2032 #endif // PRINT_TIME_STATS_EVERY_QUERY
2033 
2034  performance.current = nullptr;
2035 #endif // GATHER_TIME_STATS
2036 }
2037 
2041 static void cm_state_free(struct cm_state *state)
2042 {
2044  output_type_iterate(stat_index)
2045  {
2046  tile_type_vector_free(&state->lattice_by_prod[stat_index]);
2047  }
2049  destroy_partial_solution(&state->best);
2051 
2052  delete[] state->choice.stack;
2053  delete[] state->workers_map;
2054  state->choice.stack = nullptr;
2055  state->workers_map = nullptr;
2056  delete state;
2057  state = nullptr;
2058 }
2059 
2063 static void cm_find_best_solution(struct cm_state *state,
2064  const struct cm_parameter *const parameter,
2065  std::unique_ptr<cm_result> &result,
2066  bool negative_ok)
2067 {
2068  int loop_count = 0;
2069  int max_count;
2070  struct city backup;
2071 
2072 #ifdef GATHER_TIME_STATS
2073  performance.current = &performance.opt;
2074 #endif
2075 
2076  begin_search(state, parameter, negative_ok);
2077 
2078  // make a backup of the city to restore at the very end
2079  memcpy(&backup, state->pcity, sizeof(backup));
2080 
2081  if (player_is_cpuhog(city_owner(state->pcity))) {
2082  max_count = CPUHOG_CM_MAX_LOOP;
2083  } else {
2084  max_count = CM_MAX_LOOP;
2085  }
2086 
2087  result->aborted = false;
2088 
2089  // search until we find a feasible solution
2090  while (!bb_next(state, negative_ok)) {
2091  // Limit the number of loops.
2092  loop_count++;
2093 
2094  if (loop_count > max_count) {
2095  qCWarning(cm_category,
2096  "Did not find a cm solution in %d iterations for %s.",
2097  max_count, city_name_get(state->pcity));
2098  result->aborted = true;
2099  break;
2100  }
2101  }
2102 
2103  // convert to the caller's format
2104  convert_solution_to_result(state, &state->best, result);
2105 
2106  memcpy(state->pcity, &backup, sizeof(backup));
2107 
2108  end_search(state);
2109 }
2110 
2115 void cm_query_result(struct city *pcity, const struct cm_parameter *param,
2116  std::unique_ptr<cm_result> &result, bool negative_ok)
2117 {
2118  struct cm_state *state = cm_state_init(pcity, param, negative_ok);
2119 
2120  /* Refresh the city. Otherwise the CM can give wrong results or just be
2121  * slower than necessary. Note that cities are often passed in in an
2122  * unrefreshed state (which should probably be fixed). */
2123  city_refresh_from_main_map(pcity, nullptr, state->gov_centers);
2124 
2125  cm_find_best_solution(state, param, result, negative_ok);
2126  cm_state_free(state);
2127 }
2128 
2129 bool operator==(const struct cm_parameter &p1, const struct cm_parameter &p2)
2130 {
2132  {
2133  if (p1.minimal_surplus[i] != p2.minimal_surplus[i]) {
2134  return false;
2135  }
2136  if (p1.factor[i] != p2.factor[i]) {
2137  return false;
2138  }
2139  }
2141  if (p1.max_growth != p2.max_growth) {
2142  return false;
2143  }
2144  if (p1.require_happy != p2.require_happy) {
2145  return false;
2146  }
2147  if (p1.allow_disorder != p2.allow_disorder) {
2148  return false;
2149  }
2150  if (p1.allow_specialists != p2.allow_specialists) {
2151  return false;
2152  }
2153  if (p1.happy_factor != p2.happy_factor) {
2154  return false;
2155  }
2156 
2157  return true;
2158 }
2159 
2164  const struct cm_parameter *const src)
2165 {
2166  *dest = *src;
2167 }
2168 
2173 {
2174  output_type_iterate(stat_index)
2175  {
2176  dest->minimal_surplus[stat_index] = 0;
2177  dest->factor[stat_index] = 1;
2178  }
2180 
2181  dest->happy_factor = 1;
2182  dest->require_happy = false;
2183  dest->allow_disorder = false;
2184  dest->allow_specialists = true;
2185  dest->max_growth = false;
2186 }
2187 
2193 {
2194  output_type_iterate(stat_index)
2195  {
2196  dest->minimal_surplus[stat_index] = -FC_INFINITY;
2197  dest->factor[stat_index] = 1;
2198  }
2200 
2201  dest->happy_factor = 1;
2202  dest->require_happy = false;
2203  dest->allow_disorder = true;
2204  dest->allow_specialists = true;
2205  dest->max_growth = false;
2206 }
2207 
2211 int cm_result_workers(const std::unique_ptr<cm_result> &result)
2212 {
2213  int count = 0;
2214 
2215  city_map_iterate(result->city_radius_sq, cindex, x, y)
2216  {
2217  if (is_city_center_index(cindex)) {
2218  continue;
2219  }
2220 
2221  if (result->worker_positions[cindex]) {
2222  count++;
2223  }
2224  }
2226 
2227  return count;
2228 }
2229 
2233 int cm_result_specialists(const std::unique_ptr<cm_result> &result)
2234 {
2235  int count = 0;
2236 
2237  specialist_type_iterate(spec) { count += result->specialists[spec]; }
2239 
2240  return count;
2241 }
2242 
2246 int cm_result_citizens(const std::unique_ptr<cm_result> &result)
2247 {
2248  return cm_result_workers(result) + cm_result_specialists(result);
2249 }
2250 
2255 void cm_result_from_main_map(std::unique_ptr<cm_result> &result,
2256  const struct city *pcity)
2257 {
2258  cm_result_copy(result, pcity, nullptr);
2259 }
2260 
2266 static void cm_result_copy(std::unique_ptr<cm_result> &result,
2267  const struct city *pcity, bool *workers_map)
2268 {
2269  struct tile *pcenter = city_tile(pcity);
2270 
2271  // clear worker positions
2272  for (auto position : result->worker_positions) {
2273  position = false;
2274  }
2275 
2276  city_tile_iterate_index(result->city_radius_sq, pcenter, ptile, ctindex)
2277  {
2278  if (workers_map == nullptr) {
2279  // use the main map
2280  struct city *pwork = tile_worked(ptile);
2281 
2282  result->worker_positions[ctindex] =
2283  (nullptr != pwork && pwork == pcity);
2284  } else {
2285  result->worker_positions[ctindex] = workers_map[ctindex];
2286  }
2287  }
2289 
2290  // copy the specialist counts
2292  {
2293  result->specialists[spec] = pcity->specialists[spec];
2294  }
2296 
2297  // find the surplus production numbers
2298  get_city_surplus(pcity, result->surplus, &result->disorder,
2299  &result->happy);
2300 
2301  // this is a valid result, in a sense
2302  result->found_a_valid = true;
2303 }
2304 
2308 #ifdef FREECIV_DEBUG
2309 static void snprint_production(char *buffer, size_t bufsz,
2310  const int production[])
2311 {
2312  fc_snprintf(buffer, bufsz, "[%d %d %d %d %d %d]", production[O_FOOD],
2315 }
2316 
2320 static void real_print_tile_type(QtMsgType level, const char *file,
2321  const char *function, int line,
2322  const struct cm_tile_type *ptype,
2323  const char *prefix)
2324 {
2325  Q_UNUSED(level)
2326  Q_UNUSED(line)
2327  Q_UNUSED(function)
2328  Q_UNUSED(file)
2329  char prodstr[256];
2330 
2331  snprint_production(prodstr, sizeof(prodstr), ptype->production);
2332  qCDebug(cm_category, "%s%s fitness %g depth %d, idx %d; %d tiles", prefix,
2333  prodstr, ptype->estimated_fitness, ptype->lattice_depth,
2334  ptype->lattice_index, tile_type_num_tiles(ptype));
2335 }
2336 
2340 static void real_print_lattice(QtMsgType level, const char *file,
2341  const char *function, int line,
2342  const struct tile_type_vector *lattice)
2343 {
2344  qCDebug(cm_category, "lattice has %u terrain types",
2345  (unsigned) lattice->size);
2346  tile_type_vector_iterate(lattice, ptype)
2347  {
2348  real_print_tile_type(level, file, function, line, ptype, " ");
2349  }
2351 }
2352 
2356 static void real_print_partial_solution(QtMsgType level, const char *file,
2357  const char *function, int line,
2358  const struct partial_solution *soln,
2359  const struct cm_state *state)
2360 {
2361  int i;
2362  int last_type = 0;
2363  char buf[256];
2364 
2365  if (soln->idle != 0) {
2366  qCDebug(cm_category, "** partial solution has %d idle workers",
2367  soln->idle);
2368  } else {
2369  qCDebug(cm_category, "** completed solution:");
2370  }
2371 
2372  snprint_production(buf, sizeof(buf), soln->production);
2373  qCDebug(cm_category, "production: %s", buf);
2374 
2375  qCDebug(cm_category, "tiles used:");
2376  for (i = 0; i < num_types(state); i++) {
2377  if (soln->worker_counts[i] != 0) {
2378  fc_snprintf(buf, sizeof(buf), " %d tiles of type ",
2379  soln->worker_counts[i]);
2380  real_print_tile_type(level, file, function, line,
2381  tile_type_get(state, i), buf);
2382  }
2383  }
2384 
2385  for (i = 0; i < num_types(state); i++) {
2386  if (soln->worker_counts[i] != 0) {
2387  last_type = i;
2388  }
2389  }
2390 
2391  qCDebug(cm_category, "tiles available:");
2392  for (i = last_type; i < num_types(state); i++) {
2393  const struct cm_tile_type *ptype = tile_type_get(state, i);
2394 
2395  if (soln->prereqs_filled[i] == tile_type_num_prereqs(ptype)
2396  && soln->worker_counts[i] < tile_type_num_tiles(ptype)) {
2397  real_print_tile_type(level, file, function, line,
2398  tile_type_get(state, i), " ");
2399  }
2400  }
2401 }
2402 
2403 #endif // FREECIV_DEBUG
2404 
2405 #ifdef GATHER_TIME_STATS
2409 static void print_performance(struct one_perf *counts)
2410 {
2411  double s, ms;
2412  double q;
2413  int queries, applies;
2414 
2415  s = timer_read_seconds(counts->wall_timer);
2416  ms = 1000.0 * s;
2417 
2418  queries = counts->query_count;
2419  q = queries;
2420 
2421  applies = counts->apply_count;
2422 
2423  qCDebug(timers_category,
2424  "CM-%s: overall=%fs queries=%d %fms / query, %d applies",
2425  counts->name, s, queries, ms / q, applies);
2426 }
2427 #endif // GATHER_TIME_STATS
2428 
2432 void cm_print_city(const struct city *pcity)
2433 {
2434  struct tile *pcenter = city_tile(pcity);
2435 
2436  log_test("cm_print_city(city %d=\"%s\")", pcity->id, city_name_get(pcity));
2437  log_test(" size=%d, specialists=%s", city_size_get(pcity),
2439 
2440  log_test(" workers at:");
2441  city_tile_iterate_index(city_map_radius_sq_get(pcity), pcenter, ptile,
2442  cindex)
2443  {
2444  struct city *pwork = tile_worked(ptile);
2445 
2446  if (nullptr != pwork && pwork == pcity) {
2447  int cx, cy;
2448 
2449  if (city_tile_index_to_xy(&cx, &cy, cindex,
2450  city_map_radius_sq_get(pcity))) {
2451  log_test(" {%2d,%2d} (%4d,%4d)", cx, cy, TILE_XY(ptile));
2452  }
2453  }
2454  }
2456 
2457  log_test(" food = %3d (%+3d)", pcity->prod[O_FOOD],
2458  pcity->surplus[O_FOOD]);
2459  log_test(" shield = %3d (%+3d)", pcity->prod[O_SHIELD],
2460  pcity->surplus[O_SHIELD]);
2461  log_test(" trade = %3d", pcity->surplus[O_TRADE]);
2462 
2463  log_test(" gold = %3d (%+3d)", pcity->prod[O_GOLD],
2464  pcity->surplus[O_GOLD]);
2465  log_test(" luxury = %3d", pcity->prod[O_LUXURY]);
2466  log_test(" science = %3d", pcity->prod[O_SCIENCE]);
2467 }
2468 
2472 void cm_print_result(const std::unique_ptr<cm_result> &result)
2473 {
2474  int *city_map_data = new int[city_map_tiles(result->city_radius_sq)]();
2475 
2476  log_test("cm_print_result(result=%p)", (void *) result.get());
2477  log_test(" found_a_valid=%d disorder=%d happy=%d", result->found_a_valid,
2478  result->disorder, result->happy);
2479 
2480  city_map_iterate(result->city_radius_sq, cindex, x, y)
2481  {
2482  if (is_city_center_index(cindex)) {
2483  city_map_data[cindex] = 2;
2484  } else if (result->worker_positions[cindex]) {
2485  city_map_data[cindex] = 1;
2486  } else {
2487  city_map_data[cindex] = 0;
2488  }
2489  }
2491  log_test("workers map (2: free worked; 1: worker; 0: not used):");
2492  citylog_map_data(LOG_TEST, result->city_radius_sq, city_map_data);
2493  delete[] city_map_data;
2494 
2495  log_test(" (workers/specialists) %d/%s", cm_result_workers(result),
2496  specialists_string(result->specialists));
2497 
2499  {
2500  log_test(" %10s surplus=%d", get_output_name(i), result->surplus[i]);
2501  }
2503 }
bool base_city_celebrating(const struct city *pcity)
Return TRUE if the city was celebrating at the start of the turn, and it still has sufficient size to...
Definition: city.cpp:1555
struct output_type * get_output_type(Output_type_id output)
Return the output type for this index.
Definition: city.cpp:611
int city_granary_size(int city_size)
Generalized formula used to calculate granary size.
Definition: city.cpp:2034
struct player * city_owner(const struct city *pcity)
Return the owner of the city.
Definition: city.cpp:1083
void set_city_production(struct city *pcity, const std::vector< city * > &gov_centers, const std::array< cached_waste, O_LAST > *pcwaste)
Set food, trade and shields production in a city.
Definition: city.cpp:2830
struct tile * city_tile(const struct city *pcity)
Return the tile location of the city.
Definition: city.cpp:1095
bool city_can_use_specialist(const struct city *pcity, Specialist_type_id type)
Returns TRUE iff the given city can use this kind of specialist.
Definition: city.cpp:1005
struct tile * city_map_to_tile(const struct tile *city_center, int city_radius_sq, int city_map_x, int city_map_y)
Finds the map position for a given city map coordinate of a certain city.
Definition: city.cpp:298
bool city_tile_index_to_xy(int *city_map_x, int *city_map_y, int city_tile_index, int city_radius_sq)
Returns the coordinates for the given city tile index taking into account the squared city radius.
Definition: city.cpp:95
citizens player_content_citizens(const struct player *pplayer)
Give base number of content citizens in any city owned by pplayer.
Definition: city.cpp:2088
const char * city_name_get(const struct city *pcity)
Return the name of the city.
Definition: city.cpp:1077
bool city_unhappy(const struct city *pcity)
Return TRUE iff the city is unhappy.
Definition: city.cpp:1544
void citylog_map_data(QtMsgType level, int radius_sq, int *map_data)
Display 'map_data' on a city map with the given radius 'radius_sq' for the requested log level.
Definition: city.cpp:404
bool city_happy(const struct city *pcity)
Return TRUE iff the city is happy.
Definition: city.cpp:1531
int city_map_radius_sq_get(const struct city *pcity)
Returns the current squared radius of the city.
Definition: city.cpp:130
citizens city_specialists(const struct city *pcity)
Give the number of specialists in a city.
Definition: city.cpp:3228
int city_tile_output(const struct city *pcity, const struct tile *ptile, bool is_celebrating, Output_type_id otype)
Calculate the output for the tile.
Definition: city.cpp:1230
void city_refresh_from_main_map(struct city *pcity, bool *workers_map, const std::vector< city * > &gov_centers, const std::array< cached_waste, O_LAST > *pcwaste, const std::vector< std::array< int, O_LAST >> *pcsoutputs)
Refreshes the internal cached data in the city structure.
Definition: city.cpp:3052
int city_map_tiles(int city_radius_sq)
Return the number of tiles for the given city radius.
Definition: city.cpp:164
bool is_city_center(const struct city *pcity, const struct tile *ptile)
Return TRUE if the city is centered at the given tile.
Definition: city.cpp:3497
bool city_can_work_tile(const struct city *pcity, const struct tile *ptile)
Returns TRUE when a tile is available to be worked, or the city itself is currently working the tile ...
Definition: city.cpp:1392
const char * get_output_name(Output_type_id output)
Return a translated name for the output type.
Definition: city.cpp:602
citizens city_size_get(const struct city *pcity)
Get the city size.
Definition: city.cpp:1101
#define CITY_MAP_MAX_RADIUS_SQ
Definition: city.h:59
#define city_tile_iterate_index_end
Definition: city.h:177
#define output_type_iterate(output)
Definition: city.h:764
#define city_map_iterate_end
Definition: city.h:148
#define is_city_center_index(city_tile_index)
Definition: city.h:778
#define city_map_iterate(_radius_sq, _index, _x, _y)
Definition: city.h:144
#define CITY_MAP_CENTER_TILE_INDEX
Definition: city.h:64
#define city_tile_iterate_index(_radius_sq, _city_tile, _tile, _index)
Definition: city.h:169
#define city_map_tiles_from_city(_pcity)
Definition: city.h:100
#define city_map_iterate_without_index(_radius_sq, _x, _y)
Definition: city.h:150
#define output_type_iterate_end
Definition: city.h:771
static void sort_lattice_by_fitness(const struct cm_state *state, struct tile_type_vector *lattice)
Determine the estimated_fitness fields, and sort by that.
Definition: cm.cpp:1173
static double estimate_fitness(const struct cm_state *state, const int production[])
Estimate the fitness of a tile.
Definition: cm.cpp:1747
void cm_init()
Initialize the CM data at the start of each game.
Definition: cm.cpp:288
static void get_tax_rates(const struct player *pplayer, int rates[])
Get the national budget, see city.c.
Definition: cm.cpp:1717
static void init_tile_lattice(struct city *pcity, struct cm_state *state)
Create the lattice.
Definition: cm.cpp:1201
static int specialists_in_solution(const struct cm_state *state, const struct partial_solution *soln)
Return number of specialists used in partial solution.
Definition: cm.cpp:1542
static void begin_search(struct cm_state *state, const struct cm_parameter *parameter, bool negative_ok)
Set the parameter for the state.
Definition: cm.cpp:1991
static int min_food_surplus_for_fastest_growth(struct cm_state *state)
Find the minimum food surplus needed to grow in the fewest number of turns.
Definition: cm.cpp:1938
static int next_choice(struct cm_state *state, int oldchoice, bool negative_ok)
Return the next choice to make after oldchoice.
Definition: cm.cpp:1387
static void tile_type_destroy(struct cm_tile_type *type)
Free all the storage in the tile type (but don't free the type itself).
Definition: cm.cpp:382
static struct cm_state * cm_state_init(struct city *pcity, const cm_parameter *param, bool negative_ok)
Initialize the state for the branch-and-bound algorithm.
Definition: cm.cpp:1842
static struct cm_fitness compute_fitness(const int surplus[], bool disorder, bool happy, const struct cm_parameter *parameter)
Compute the fitness of the given surplus (and disorder/happy status) according to the weights and min...
Definition: cm.cpp:567
static void init_partial_solution(struct partial_solution *into, int ntypes, int idle, bool negative_ok)
Allocate and initialize an empty solution.
Definition: cm.cpp:607
static void complete_solution(struct partial_solution *soln, const struct cm_state *state, const struct tile_type_vector *lattice)
Complete the solution by choosing tiles in order off the given tile lattice.
Definition: cm.cpp:1488
static bool take_child_choice(struct cm_state *state, bool negative_ok)
Go down from the current branch, if we can.
Definition: cm.cpp:1454
static bool tile_type_better(const struct cm_tile_type *a, const struct cm_tile_type *b)
Return TRUE if tile a is better or equal to tile b in all categories.
Definition: cm.cpp:433
#define LOG_LATTICE
Definition: cm.cpp:86
static const struct cm_tile_type * tile_type_get(const struct cm_state *state, int type)
Retrieve a tile type by index.
Definition: cm.cpp:508
static Output_type_id compare_key
Definition: cm.cpp:858
static struct cm_fitness evaluate_solution(struct cm_state *state, const struct partial_solution *soln)
Compute the fitness of the solution.
Definition: cm.cpp:728
static int tile_type_vector_find_equivalent(const struct tile_type_vector *vec, const struct cm_tile_type *ptype)
If there is a tile type in the vector that is equivalent to the given type, return its index.
Definition: cm.cpp:464
void cm_copy_parameter(struct cm_parameter *dest, const struct cm_parameter *const src)
Copy the parameter from the source to the destination field.
Definition: cm.cpp:2163
static void cm_find_best_solution(struct cm_state *state, const struct cm_parameter *const parameter, std::unique_ptr< cm_result > &result, bool negative_ok)
Run B&B until we find the best solution.
Definition: cm.cpp:2063
static bool choice_stack_empty(struct cm_state *state)
Handling the choice stack for the bb algorithm.
Definition: cm.cpp:1252
void cm_free()
Called at the end of a game to free any CM data.
Definition: cm.cpp:315
static void tile_type_vector_free_all(struct tile_type_vector *vec)
Destroy and free all types in the vector, and the vector itself.
Definition: cm.cpp:395
static bool prereqs_filled(const struct partial_solution *soln, int type, const struct cm_state *state)
True if all tiles better than this type have been used.
Definition: cm.cpp:1369
static void clean_lattice(struct tile_type_vector *lattice, const struct city *pcity)
Remove unreachable lattice nodes to speed up processing later.
Definition: cm.cpp:1119
void cm_init_parameter(struct cm_parameter *dest)
Initialize the parameter to sane default values.
Definition: cm.cpp:2172
static int tile_type_num_prereqs(const struct cm_tile_type *ptype)
Return the number of tile types that are better than this type.
Definition: cm.cpp:498
void cm_query_result(struct city *pcity, const struct cm_parameter *param, std::unique_ptr< cm_result > &result, bool negative_ok)
Wrapper that actually runs the branch & bound, and returns the best solution.
Definition: cm.cpp:2115
static void copy_partial_solution(struct partial_solution *dst, const struct partial_solution *src, const struct cm_state *state)
Copy the source solution into the destination one (the destination solution must already be allocated...
Definition: cm.cpp:636
static void cm_state_free(struct cm_state *state)
Release all the memory allocated by the state.
Definition: cm.cpp:2041
static void init_specialist_lattice_nodes(struct cm_state *state, const struct city *pcity)
Create lattice nodes for each type of specialist.
Definition: cm.cpp:976
static int compare_tile_type_by_fitness(const void *va, const void *vb)
Sort by fitness.
Definition: cm.cpp:835
static void destroy_partial_solution(struct partial_solution *into)
Free all storage associated with the solution.
Definition: cm.cpp:626
static void convert_solution_to_result(struct cm_state *state, const struct partial_solution *soln, std::unique_ptr< cm_result > &result)
Convert the solution into a cm_result.
Definition: cm.cpp:768
#define print_partial_solution(loglevel, soln, state)
Definition: cm.cpp:272
int cm_result_citizens(const std::unique_ptr< cm_result > &result)
Count the total number of citizens in the result.
Definition: cm.cpp:2246
#define print_lattice(loglevel, lattice)
Definition: cm.cpp:271
static bool tile_type_equal(const struct cm_tile_type *a, const struct cm_tile_type *b)
Return TRUE iff all categories of the two types are equal.
Definition: cm.cpp:413
static void tile_type_init(struct cm_tile_type *type)
Set all production to zero and initialize the vectors for this tile type.
Definition: cm.cpp:355
#define tile_type_vector_iterate(vector, var)
Definition: cm.cpp:137
#define LOG_REACHED_LEAF
Definition: cm.cpp:87
bool operator==(const struct cm_parameter &p1, const struct cm_parameter &p2)
Definition: cm.cpp:2129
static void add_worker(struct partial_solution *soln, int itype, const struct cm_state *state)
Add just one worker to the solution.
Definition: cm.cpp:1340
static bool choice_is_promising(struct cm_state *state, int newchoice, bool negative_ok)
A choice is unpromising if isn't better than the best in at least one way.
Definition: cm.cpp:1634
static struct cm_fitness worst_fitness()
Return a fitness struct that is the worst possible result we can represent.
Definition: cm.cpp:553
static double compare_key_trade_bonus
Definition: cm.cpp:859
static bool take_sibling_choice(struct cm_state *state, bool negative_ok)
Pick a sibling choice to the last choice.
Definition: cm.cpp:1426
void cm_result_from_main_map(std::unique_ptr< cm_result > &result, const struct city *pcity)
Copy the city's current setup into the cm result structure.
Definition: cm.cpp:2255
static void apply_solution(struct cm_state *state, const struct partial_solution *soln)
Evaluating a completed solution.
Definition: cm.cpp:655
static void init_min_production(struct cm_state *state)
Initialize minimal production needed to be sufficient.
Definition: cm.cpp:1699
void cm_init_citymap()
Initialize the CM citymap data.
Definition: cm.cpp:307
static void end_search(struct cm_state *state)
Clean up after a search.
Definition: cm.cpp:2024
static void compute_tile_production(const struct city *pcity, const struct tile *ptile, bool is_celebrating, struct cm_tile_type *out)
Compute the tile-type lattice.
Definition: cm.cpp:905
static int compare_tile_type_by_stat(const void *va, const void *vb)
Compare by the production of type compare_key.
Definition: cm.cpp:867
static int tile_type_num_tiles(const struct cm_tile_type *type)
Return the number of tiles of this type that can be worked.
Definition: cm.cpp:483
static bool fitness_better(struct cm_fitness a, struct cm_fitness b)
Return TRUE iff fitness A is strictly better than fitness B.
Definition: cm.cpp:541
static bool bb_next(struct cm_state *state, bool negative_ok)
The high-level algorithm is:
Definition: cm.cpp:1805
static void top_sort_lattice(struct tile_type_vector *lattice)
Topologically sort the lattice.
Definition: cm.cpp:1014
static void get_city_surplus(const struct city *pcity, int surplus[], bool *disorder, bool *happy)
Convert the city's surplus numbers into an array.
Definition: cm.cpp:714
#define LOG_BETTER_LEAF
Definition: cm.cpp:88
static const struct cm_tile * tile_get(const struct cm_tile_type *ptype, int j)
Retrieve a tile of a particular type by index.
Definition: cm.cpp:524
int cm_result_workers(const std::unique_ptr< cm_result > &result)
Count the total number of workers in the result.
Definition: cm.cpp:2211
static void compute_max_stats_heuristic(const struct cm_state *state, const struct partial_solution *soln, int production[], int check_choice, bool negative_ok)
The heuristic: A partial solution cannot produce more food than the amount of food it currently gener...
Definition: cm.cpp:1568
std::unique_ptr< cm_result > cm_result_new(struct city *pcity)
Create a new cm_result.
Definition: cm.cpp:330
static int last_choice(struct cm_state *state)
Return the last choice in the stack.
Definition: cm.cpp:1260
#define print_tile_type(loglevel, ptype, prefix)
Definition: cm.cpp:270
static int compare_tile_type_by_lattice_order(const struct cm_tile_type *a, const struct cm_tile_type *b)
Compare functions to allow sorting lattice vectors.
Definition: cm.cpp:803
static void remove_worker(struct partial_solution *soln, int itype, const struct cm_state *state)
Remove just one worker from the solution.
Definition: cm.cpp:1349
static void cm_result_copy(std::unique_ptr< cm_result > &result, const struct city *pcity, bool *workers_map)
Copy the city's current setup into the cm result structure.
Definition: cm.cpp:2266
#define CPUHOG_CM_MAX_LOOP
Definition: cm.cpp:74
static void add_workers(struct partial_solution *soln, int itype, int number, const struct cm_state *state)
Update the solution to assign 'number' more workers on to tiles of the given type.
Definition: cm.cpp:1283
static void tile_type_lattice_add(struct tile_type_vector *lattice, const struct cm_tile_type *newtype, int tindex)
Add the tile [x,y], with production indicated by type, to the tile-type lattice.
Definition: cm.cpp:924
void cm_init_emergency_parameter(struct cm_parameter *dest)
Initialize the parameter to sane default values that will always produce a result.
Definition: cm.cpp:2192
static void pop_choice(struct cm_state *state)
Remove a worker from the current solution, and pop once off the choice stack.
Definition: cm.cpp:1359
#define LOG_PRUNE_BRANCH
Definition: cm.cpp:89
static int num_types(const struct cm_state *state)
Return the number of different tile types.
Definition: cm.cpp:1272
#define tile_type_vector_iterate_end
Definition: cm.cpp:144
#define LOG_CM_STATE
Definition: cm.cpp:85
void cm_print_result(const std::unique_ptr< cm_result > &result)
Print debugging information about a full CM result.
Definition: cm.cpp:2472
#define CM_MAX_LOOP
Definition: cm.cpp:72
void cm_print_city(const struct city *pcity)
Debugging routines.
Definition: cm.cpp:2432
static struct cm_tile_type * tile_type_dup(const struct cm_tile_type *oldtype)
Duplicate a tile type, except for the vectors - the vectors of the new tile type will be empty.
Definition: cm.cpp:367
int cm_result_specialists(const std::unique_ptr< cm_result > &result)
Count the total number of specialists in the result.
Definition: cm.cpp:2233
int get_city_output_bonus(const struct city *pcity, const struct output_type *poutput, enum effect_type effect_type)
Returns the player effect bonus of an output.
Definition: effects.cpp:800
unsigned char citizens
Definition: fc_types.h:305
int Specialist_type_id
Definition: fc_types.h:292
@ O_SHIELD
Definition: fc_types.h:86
@ O_FOOD
Definition: fc_types.h:85
@ O_TRADE
Definition: fc_types.h:87
@ O_SCIENCE
Definition: fc_types.h:90
@ O_LUXURY
Definition: fc_types.h:89
@ O_GOLD
Definition: fc_types.h:88
@ O_LAST
Definition: fc_types.h:91
enum output_type_id Output_type_id
Definition: fc_types.h:295
struct civ_game game
Definition: game.cpp:47
struct government * government_of_player(const struct player *pplayer)
Return the government of a player.
Definition: government.cpp:107
const char * name
Definition: inputfile.cpp:118
#define fc_assert_ret(condition)
Definition: log.h:112
#define log_test
Definition: log.h:71
#define fc_assert(condition)
Definition: log.h:89
#define LOG_TEST
Definition: log.h:74
#define fc_assert_ret_val(condition, val)
Definition: log.h:114
#define log_base(level, message,...)
Definition: log.h:41
std::vector< city * > player_gov_centers(const struct player *pplayer)
Locate the player's government centers.
Definition: player.cpp:1264
static bool player_is_cpuhog(const struct player *pplayer)
Definition: player.h:558
struct setting_list * level[OLEVELS_NUM]
Definition: settings.cpp:167
#define FC_INFINITY
Definition: shared.h:32
#define MAX(x, y)
Definition: shared.h:48
const char * specialists_string(const citizens *specialist_list)
Return a string showing the number of specialists in the array.
Definition: specialist.cpp:198
int get_specialist_output(const struct city *pcity, Specialist_type_id sp, Output_type_id otype)
Return the output for the specialist type with this output type.
Definition: specialist.cpp:218
#define specialist_type_iterate_end
Definition: specialist.h:73
#define specialist_type_iterate(sp)
Definition: specialist.h:67
Definition: city.h:291
int surplus[O_LAST]
Definition: city.h:324
int food_stock
Definition: city.h:338
int id
Definition: city.h:296
int city_radius_sq
Definition: city.h:346
int citizen_base[O_LAST]
Definition: city.h:328
int usage[O_LAST]
Definition: city.h:329
struct universal production
Definition: city.h:368
bool happy
Definition: city.h:437
int bonus[O_LAST]
Definition: city.h:335
citizens specialists[SP_MAX]
Definition: city.h:305
struct tile * tile
Definition: city.h:293
int prod[O_LAST]
Definition: city.h:327
struct packet_game_info info
Definition: game.h:80
struct government * government_during_revolution
Definition: game.h:85
int weighted
Definition: cm.cpp:108
bool sufficient
Definition: cm.cpp:109
bool allow_disorder
Definition: cm.h:20
int factor[O_LAST]
Definition: cm.h:23
bool max_growth
Definition: cm.h:18
bool allow_specialists
Definition: cm.h:21
bool require_happy
Definition: cm.h:19
int minimal_surplus[O_LAST]
Definition: cm.h:17
int happy_factor
Definition: cm.h:24
State of the search.
Definition: cm.cpp:193
int size
Definition: cm.cpp:236
struct partial_solution best
Definition: cm.cpp:215
struct cm_parameter parameter
Definition: cm.cpp:195
std::array< cached_waste, O_LAST > waste
Definition: cm.cpp:212
std::vector< std::array< int, O_LAST > > specialist_outputs
Definition: cm.cpp:206
int min_production[O_LAST]
Definition: cm.cpp:222
struct tile_type_vector lattice
Definition: cm.cpp:199
std::array< int, O_LAST > city_center_output
Definition: cm.cpp:203
struct partial_solution current
Definition: cm.cpp:228
struct tile_type_vector lattice_by_prod[O_LAST]
Definition: cm.cpp:200
std::vector< city * > gov_centers
Definition: cm.cpp:209
struct cm_fitness best_value
Definition: cm.cpp:216
bool * workers_map
Definition: cm.cpp:239
struct cm_state::@13 choice
int min_luxury
Definition: cm.cpp:225
struct city * pcity
Definition: cm.cpp:196
int * stack
Definition: cm.cpp:235
A tile type.
Definition: cm.cpp:162
int production[O_LAST]
Definition: cm.cpp:163
Specialist_type_id spec
Definition: cm.cpp:166
struct tile_type_vector better_types
Definition: cm.cpp:168
struct tile_vector tiles
Definition: cm.cpp:167
bool is_specialist
Definition: cm.cpp:165
int lattice_depth
Definition: cm.cpp:171
int lattice_index
Definition: cm.cpp:170
struct tile_type_vector worse_types
Definition: cm.cpp:169
double estimated_fitness
Definition: cm.cpp:164
A tile.
Definition: cm.cpp:123
const struct cm_tile_type * type
Definition: cm.cpp:124
int index
Definition: cm.cpp:125
A partial solution.
Definition: cm.cpp:179
int production[O_LAST]
Definition: cm.cpp:184
int * worker_counts
Definition: cm.cpp:181
int * prereqs_filled
Definition: cm.cpp:182
Definition: player.h:231
struct player_economic economic
Definition: player.h:266
Definition: tile.h:42
int index
Definition: tile.h:43
int fc_snprintf(char *str, size_t n, const char *format,...)
See also fc_utf8_snprintf_trunc(), fc_utf8_snprintf_rep().
Definition: support.cpp:537
#define tile_worked(_tile)
Definition: tile.h:97
#define TILE_XY(ptile)
Definition: tile.h:36
Q_LOGGING_CATEGORY(tileset_category, "freeciv.tileset")
Functions for handling the tilespec files which describe the files and contents of tilesets.
void timer_destroy(civtimer *t)
Deletes timer.
Definition: timing.cpp:66
double timer_read_seconds(civtimer *t)
Read value from timer.
Definition: timing.cpp:137
civtimer * timer_new(enum timer_timetype type, enum timer_use use)
Allocate a new timer with specified "type" and "use".
Definition: timing.cpp:43
void timer_start(civtimer *t)
Start timing, adding to previous accumulated time if timer has not been cleared.
Definition: timing.cpp:95
void timer_stop(civtimer *t)
Stop timing, and accumulate time so far.
Definition: timing.cpp:116
@ TIMER_ACTIVE
Definition: timing.h:25
@ TIMER_USER
Definition: timing.h:21