]> git.mxchange.org Git - city.git/blob - application/city/classes/database/frontend/city_entities/sections/class_CitySectionsDatabaseWrapper.php
604cf46b9bf406a42ed59f314332a45be2a7b070
[city.git] / application / city / classes / database / frontend / city_entities / sections / class_CitySectionsDatabaseWrapper.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\City\Database\Frontend\Sections;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
7
8 /**
9  * A database wrapper for city sections. Sections are the smalles entity of a
10  * city. They can be connected with each other and form a lot. Therefore only
11  * sections of same type (and sub type) can be linked combined, else you will
12  * something really strange, a residential building with some industry parts
13  * for example is not possible in real world.
14  *
15  * Sure you can have a small shop (commercial) on ground level and some
16  * residentials on higher levels. This city simulation does support such
17  * creations as the levels (Z axis) is different.
18  *
19  * @author              Roland Haeder <webmaster@shipsimu.org>
20  * @version             0.0.0
21  * @copyright   Copyright (c) 2015, 2016 City Developer Team
22  * @license             GNU GPL 3.0 or any newer version
23  * @link                http://www.shipsimu.org
24  *
25  * This program is free software: you can redistribute it and/or modify
26  * it under the terms of the GNU General Public License as published by
27  * the Free Software Foundation, either version 3 of the License, or
28  * (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program. If not, see <http://www.gnu.org/licenses/>.
37  */
38 class CitySectionsDatabaseWrapper extends BaseDatabaseWrapper implements CitySectionsWrapper, Registerable {
39         // Constants for database table names
40         const DB_TABLE_CITY_SECTIONS = 'city_sections';
41
42         // Entry id
43         const DB_COLUMN_ENTRY_ID               = 'entry_id';
44
45         // Section id, an referenced city id and lot id
46         const DB_COLUMN_SECTION_ID             = 'city_section_id';
47         const DB_COLUMN_CITY_ID                = 'city_id';
48
49         /*
50          * Lot id, the lot id is only set if the player has "aquired" the sections
51          * and has created a lot based on these sections.
52          */
53         const DB_COLUMN_LOT_ID                 = 'lot_id';
54
55         // Section and sub type (e.g. residential, hut)
56         const DB_COLUMN_SECTION_TYPE           = 'section_type';
57         const DB_COLUMN_SECTION_SUB_TYPE       = 'section_sub_type';
58
59         // X-Y-Z position
60         const DB_COLUMN_SECTION_POSITION_X     = 'section_position_x';
61         const DB_COLUMN_SECTION_POSITION_Y     = 'section_position_y';
62         const DB_COLUMN_SECTION_POSITION_Z     = 'section_position_z';
63
64         // Connected neigbouring sections
65         const DB_COLUMN_SECTION_NEIGHBOUR_WEST_ID  = 'section_neighbour_west_id';
66         const DB_COLUMN_SECTION_NEIGHBOUR_EAST_ID  = 'section_neighbour_east_id';
67         const DB_COLUMN_SECTION_NEIGHBOUR_NORTH_ID = 'section_neighbour_north_id';
68         const DB_COLUMN_SECTION_NEIGHBOUR_SOUTH_ID = 'section_neighbour_south_id';
69         const DB_COLUMN_SECTION_NEIGHBOUR_UP_ID    = 'section_neighbour_up_id';
70         const DB_COLUMN_SECTION_NEIGHBOUR_DOWN_ID  = 'section_neighbour_down_id';
71
72         // Other settings:
73         // Reserved section (see documentation)
74         const DB_COLUMN_SECTION_RESERVED       = 'section_reserved';
75
76         // Section types
77         // @TODO "water" is not yet supported and may end up in a very random land.
78         const SECTION_TYPE_WATER      = 'water';
79         const SECTION_TYPE_EMPTY_LAND = 'land';
80         const SECTION_TYPE_AIR        = 'air';
81
82         // Sub sections
83         // @TODO All types of water are not supported yet.
84         const SECTION_SUB_TYPE_GRASS = 'grass';
85         const SECTION_SUB_TYPE_AIR   = 'air';
86
87         // Reserved flag
88         const IS_NOT_RESERVED = 0;
89         const IS_RESERVED     = 1;
90
91         /**
92          * Protected constructor
93          *
94          * @return      void
95          */
96         protected function __construct () {
97                 // Call parent constructor
98                 parent::__construct(__CLASS__);
99         }
100
101         /**
102          * Creates an instance of this database wrapper by a provided user class
103          *
104          * @return      $wrapperInstance        An instance of the created wrapper class
105          */
106         public static final function createCitySectionsDatabaseWrapper () {
107                 // Get a new instance
108                 $wrapperInstance = new CitySectionsDatabaseWrapper();
109
110                 // Set (primary!) table name
111                 $wrapperInstance->setTableName(self::DB_TABLE_CITY_SECTIONS);
112
113                 // Return the instance
114                 return $wrapperInstance;
115         }
116
117         /**
118          * Checks if the given city id is found in sections table
119          *
120          * @param       $cityId         City id to check
121          * @return      $isFound        Whether the city id is found
122          */
123         public function ifCityHasSections ($cityId) {
124                 // Get search instance
125                 $searchInstance = ObjectFactory::createObjectByConfiguredName('search_criteria_class');
126
127                 // Search for 'city_id'
128                 $searchInstance->addCriteria(self::DB_COLUMN_CITY_ID, $cityId);
129
130                 /*
131                  * Only one entry is enough to find, else this query could run very
132                  * long on large maps.
133                  */
134                 $searchInstance->setLimit(1);
135
136                 // Execute it on database instance
137                 $resultInstance = $this->doSelectByCriteria($searchInstance);
138
139                 // Check if there is one entry
140                 $isFound = $resultInstance->next();
141
142                 // Return result
143                 return $isFound;
144         }
145
146         /**
147          * Expands the sections table with initial data for given city id
148          *
149          * @param       $cityId         City id to check
150          * @return      $ids            Sections ids from initial expansion
151          * @todo        Add handling of water types to make a more cooler map
152          */
153         public function doInitialCityExpansion ($cityId) {
154                 // Make sure this city has no sections
155                 assert(!$this->ifCityHasSections($cityId));
156
157                 /*
158                  * "Cache" max "radius" for initial city expansion. It is not a real
159                  * radius but more a max expansion area (expand +- half of "radius"
160                  * from 0/0). The "zero point" is always calculated in.
161                  *
162                  * This gives a maxium initial area calculated as follows:
163                  *
164                  * totalInitialSections = (radius + 1) * (radius + 1)
165                  */
166                 $radius = $this->getConfigInstance()->getConfigEntry('city_max_initial_xy_expansion_radius');
167
168                 // Max up and down ...
169                 $maxUp   = $this->getConfigInstance()->getConfigEntry('city_max_initial_up_expansion');
170                 $maxDown = $this->getConfigInstance()->getConfigEntry('city_max_initial_down_expansion');
171
172                 // Calculate total sections
173                 $totalSections = (($radius + 1) * ($radius + 1) * $maxUp * ($maxDown + 1));
174
175                 // Debug message:
176                 /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: radius=' . $radius . ',maxUp=' . $maxUp . ',maxDown=' . $maxDown . ',totalSections=' . $totalSections);
177
178                 // Get data set instance
179                 $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria_class', array(self::DB_TABLE_CITY_SECTIONS));
180
181                 // Add values for "zero point"
182                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_ID                , 1);
183                 $dataSetInstance->addCriteria(self::DB_COLUMN_CITY_ID                   , $cityId);
184                 $dataSetInstance->addCriteria(self::DB_COLUMN_LOT_ID                    , 0);
185                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_TYPE              , self::SECTION_TYPE_AIR);
186                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_SUB_TYPE          , self::SECTION_SUB_TYPE_AIR);
187                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_POSITION_X        , 0);
188                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_POSITION_Y        , 0);
189                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_POSITION_Z        , 0);
190                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_NORTH_ID, 0);
191                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_SOUTH_ID, 0);
192                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_WEST_ID , 0);
193                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_EAST_ID , 0);
194                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_UP_ID   , 0);
195                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_NEIGHBOUR_DOWN_ID , 0);
196                 $dataSetInstance->addCriteria(self::DB_COLUMN_SECTION_RESERVED          , self::IS_NOT_RESERVED);
197
198                 // Set primary key to 'city_id'/'section_id'
199                 $dataSetInstance->setPrimaryKeyCombined(array(self::DB_COLUMN_CITY_ID, self::DB_COLUMN_SECTION_ID));
200
201                 // Entry id for counting each entry
202                 $dataSetInstance->setUniqueKey(self::DB_COLUMN_ENTRY_ID);
203
204                 // Add "zero point"
205                 $this->queryInsertDataSet($dataSetInstance);
206
207                 // Set section id to 2 as 1 is already initialized + init array
208                 $sections = array();
209
210                 // Output message to ask for user's patience ...
211                 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: Writing ' . $totalSections . ' sections for city ' . $cityId . ' ... (this may takes some time)');
212
213                 // Expand half of it to north/south (north=positive, south=negative)
214                 for ($north = 1; $north < round($radius / 2); $north++) {
215                         // Expand half of it to west/east (west=positive, east=negative)
216                         for ($west = 1; $west < round($radius / 2); $west++) {
217                                 // Expand up/down (including "zero point")
218                                 for ($z = $maxDown; $z < ($maxUp + 1); $z++) {
219                                         // Debug message
220                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: north=' . $north . ',west=' . $west . ',z=' . $z);
221
222                                         // Fill array up with south/east/down ids
223                                         $sections[($north * -1)][($west * -1)][$z]['type'] = self::SECTION_TYPE_EMPTY_LAND;
224                                         $sections[($north * -1)][($west * -1)][$z]['sub']  = self::SECTION_SUB_TYPE_GRASS;
225
226                                         // Fill up array with north/west/up ids (only air)
227                                         $sections[$north][$west][$z]['type'] = self::SECTION_TYPE_AIR;
228                                         $sections[$north][$west][$z]['sub']  = self::SECTION_SUB_TYPE_AIR;
229                                 } // END - for
230                         } // END - for
231                 } // END - for
232
233                 // Init section id with 2 as 1 is the "zero point"
234                 $sectionId = 2;
235
236                 // Loop through whole array again for writing it to database: north/south
237                 foreach ($sections as $x => $sectionX) {
238                         // Loop through west/east values
239                         foreach ($sectionX as $y => $sectionY) {
240                                 // Loop through up/down values
241                                 foreach ($sectionY as $z => $sectionData) {
242                                         // Debug message
243                                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: x=' . $x . ',y=' . $y . ',z=' . $z . ',sectionId=' . $sectionId);
244
245                                         // Set all coordinates for positive directions
246                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_ID        , $sectionId);
247                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_POSITION_X, $x);
248                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_POSITION_Y, $y);
249                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_POSITION_Z, $z);
250                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_TYPE      , $sectionData['type']);
251                                         $dataSetInstance->setCriteria(self::DB_COLUMN_SECTION_SUB_TYPE  , $sectionData['sub']);
252
253                                         // Add value to database
254                                         $this->queryInsertDataSet($dataSetInstance);
255
256                                         // Count id up
257                                         $sectionId++;
258                                 } // END - foreach
259
260                                 // Debug message
261                                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: x=' . $x . ',y=' . $y . ' has been written.');
262                         } // END - foreach
263
264                         // Debug message
265                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: x=' . $x . ' has been written.');
266                 } // END - foreach
267
268                 // Thank you for waiting! :-)
269                 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: A total of ' . $totalSections . ' sections has been written for city id ' . $cityId . '.');
270         }
271 }