Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / newgrf_object.cpp
blobe69787c0ce94d63bd8de40b60f87faf99568b659
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file newgrf_object.cpp Handling of object NewGRFs. */
10 #include "stdafx.h"
11 #include "company_base.h"
12 #include "company_func.h"
13 #include "debug.h"
14 #include "genworld.h"
15 #include "newgrf_class_func.h"
16 #include "newgrf_object.h"
17 #include "newgrf_sound.h"
18 #include "object_base.h"
19 #include "object_map.h"
20 #include "tile_cmd.h"
21 #include "town.h"
22 #include "water.h"
23 #include "newgrf_animation_base.h"
25 #include "safeguards.h"
27 /** The override manager for our objects. */
28 ObjectOverrideManager _object_mngr(NEW_OBJECT_OFFSET, NUM_OBJECTS, INVALID_OBJECT_TYPE);
30 extern const ObjectSpec _original_objects[NEW_OBJECT_OFFSET];
31 /** All the object specifications. */
32 ObjectSpec _object_specs[NUM_OBJECTS];
34 /**
35 * Get the specification associated with a specific ObjectType.
36 * @param index The object type to fetch.
37 * @return The specification.
39 /* static */ const ObjectSpec *ObjectSpec::Get(ObjectType index)
41 assert(index < NUM_OBJECTS);
42 return &_object_specs[index];
45 /**
46 * Get the specification associated with a tile.
47 * @param tile The tile to fetch the data for.
48 * @return The specification.
50 /* static */ const ObjectSpec *ObjectSpec::GetByTile(TileIndex tile)
52 return ObjectSpec::Get(GetObjectType(tile));
55 /**
56 * Check whether the object might be available at some point in this game with the current game mode.
57 * @return true if it might be available.
59 bool ObjectSpec::IsEverAvailable() const
61 return this->enabled && HasBit(this->climate, _settings_game.game_creation.landscape) &&
62 (this->flags & ((_game_mode != GM_EDITOR && !_generating_world) ? OBJECT_FLAG_ONLY_IN_SCENEDIT : OBJECT_FLAG_ONLY_IN_GAME)) == 0;
65 /**
66 * Check whether the object was available at some point in the past or present in this game with the current game mode.
67 * @return true if it was ever or is available.
69 bool ObjectSpec::WasEverAvailable() const
71 return this->IsEverAvailable() && _date > this->introduction_date;
74 /**
75 * Check whether the object is available at this time.
76 * @return true if it is available.
78 bool ObjectSpec::IsAvailable() const
80 return this->WasEverAvailable() &&
81 (_date < this->end_of_life_date || this->end_of_life_date < this->introduction_date + 365);
84 /**
85 * Gets the index of this spec.
86 * @return The index.
88 uint ObjectSpec::Index() const
90 return this - _object_specs;
93 /** This function initialize the spec arrays of objects. */
94 void ResetObjects()
96 /* Clean the pool. */
97 for (uint16 i = 0; i < NUM_OBJECTS; i++) {
98 _object_specs[i] = {};
101 /* And add our originals. */
102 MemCpyT(_object_specs, _original_objects, lengthof(_original_objects));
104 for (uint16 i = 0; i < lengthof(_original_objects); i++) {
105 _object_specs[i].grf_prop.local_id = i;
109 template <typename Tspec, typename Tid, Tid Tmax>
110 /* static */ void NewGRFClass<Tspec, Tid, Tmax>::InsertDefaults()
112 ObjectClassID cls = ObjectClass::Allocate('LTHS');
113 ObjectClass::Get(cls)->name = STR_OBJECT_CLASS_LTHS;
114 _object_specs[OBJECT_LIGHTHOUSE].cls_id = cls;
115 ObjectClass::Assign(&_object_specs[OBJECT_LIGHTHOUSE]);
117 cls = ObjectClass::Allocate('TRNS');
118 ObjectClass::Get(cls)->name = STR_OBJECT_CLASS_TRNS;
119 _object_specs[OBJECT_TRANSMITTER].cls_id = cls;
120 ObjectClass::Assign(&_object_specs[OBJECT_TRANSMITTER]);
123 template <typename Tspec, typename Tid, Tid Tmax>
124 bool NewGRFClass<Tspec, Tid, Tmax>::IsUIAvailable(uint index) const
126 return this->GetSpec(index)->IsEverAvailable();
129 INSTANTIATE_NEWGRF_CLASS_METHODS(ObjectClass, ObjectSpec, ObjectClassID, OBJECT_CLASS_MAX)
131 /* virtual */ uint32 ObjectScopeResolver::GetRandomBits() const
133 return IsValidTile(this->tile) && IsTileType(this->tile, MP_OBJECT) ? GetObjectRandomBits(this->tile) : 0;
137 * Make an analysis of a tile and get the object type.
138 * @param tile TileIndex of the tile to query
139 * @param cur_grfid GRFID of the current callback chain
140 * @return value encoded as per NFO specs
142 static uint32 GetObjectIDAtOffset(TileIndex tile, uint32 cur_grfid)
144 if (!IsTileType(tile, MP_OBJECT)) {
145 return 0xFFFF;
148 const Object *o = Object::GetByTile(tile);
149 const ObjectSpec *spec = ObjectSpec::Get(o->type);
151 /* Default objects have no associated NewGRF file */
152 if (spec->grf_prop.grffile == nullptr) {
153 return 0xFFFE; // Defined in another grf file
156 if (spec->grf_prop.grffile->grfid == cur_grfid) { // same object, same grf ?
157 return spec->grf_prop.local_id | o->view << 16;
160 return 0xFFFE; // Defined in another grf file
164 * Based on newhouses equivalent, but adapted for newobjects
165 * @param parameter from callback. It's in fact a pair of coordinates
166 * @param tile TileIndex from which the callback was initiated
167 * @param index of the object been queried for
168 * @param grf_version8 True, if we are dealing with a new NewGRF which uses GRF version >= 8.
169 * @return a construction of bits obeying the newgrf format
171 static uint32 GetNearbyObjectTileInformation(byte parameter, TileIndex tile, ObjectID index, bool grf_version8)
173 if (parameter != 0) tile = GetNearbyTile(parameter, tile); // only perform if it is required
174 bool is_same_object = (IsTileType(tile, MP_OBJECT) && GetObjectIndex(tile) == index);
176 return GetNearbyTileInformation(tile, grf_version8) | (is_same_object ? 1 : 0) << 8;
180 * Get the closest object of a given type.
181 * @param tile The tile to start searching from.
182 * @param type The type of the object to search for.
183 * @param current The current object (to ignore).
184 * @return The distance to the closest object.
186 static uint32 GetClosestObject(TileIndex tile, ObjectType type, const Object *current)
188 uint32 best_dist = UINT32_MAX;
189 for (const Object *o : Object::Iterate()) {
190 if (o->type != type || o == current) continue;
192 best_dist = std::min(best_dist, DistanceManhattan(tile, o->location.tile));
195 return best_dist;
199 * Implementation of var 65
200 * @param local_id Parameter given to the callback, which is the set id, or the local id, in our terminology.
201 * @param grfid The object's GRFID.
202 * @param tile The tile to look from.
203 * @param current Object for which the inquiry is made
204 * @return The formatted answer to the callback : rr(reserved) cc(count) dddd(manhattan distance of closest sister)
206 static uint32 GetCountAndDistanceOfClosestInstance(byte local_id, uint32 grfid, TileIndex tile, const Object *current)
208 uint32 grf_id = GetRegister(0x100); // Get the GRFID of the definition to look for in register 100h
209 uint32 idx;
211 /* Determine what will be the object type to look for */
212 switch (grf_id) {
213 case 0: // this is a default object type
214 idx = local_id;
215 break;
217 case 0xFFFFFFFF: // current grf
218 grf_id = grfid;
219 FALLTHROUGH;
221 default: // use the grfid specified in register 100h
222 idx = _object_mngr.GetID(local_id, grf_id);
223 break;
226 /* If the object type is invalid, there is none and the closest is far away. */
227 if (idx >= NUM_OBJECTS) return 0 | 0xFFFF;
229 return Object::GetTypeCount(idx) << 16 | std::min(GetClosestObject(tile, idx, current), 0xFFFFu);
232 /** Used by the resolver to get values for feature 0F deterministic spritegroups. */
233 /* virtual */ uint32 ObjectScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
235 /* We get the town from the object, or we calculate the closest
236 * town if we need to when there's no object. */
237 const Town *t = nullptr;
239 if (this->obj == nullptr) {
240 switch (variable) {
241 /* Allow these when there's no object. */
242 case 0x41:
243 case 0x60:
244 case 0x61:
245 case 0x62:
246 case 0x64:
247 break;
249 /* Allow these, but find the closest town. */
250 case 0x45:
251 case 0x46:
252 if (!IsValidTile(this->tile)) goto unhandled;
253 t = ClosestTownFromTile(this->tile, UINT_MAX);
254 break;
256 /* Construction date */
257 case 0x42: return _date;
259 /* Object founder information */
260 case 0x44: return _current_company;
262 /* Object view */
263 case 0x48: return this->view;
266 * Disallow the rest:
267 * 0x40: Relative position is passed as parameter during construction.
268 * 0x43: Animation counter is only for actual tiles.
269 * 0x47: Object colour is only valid when its built.
270 * 0x63: Animation counter of nearby tile, see above.
272 default:
273 goto unhandled;
276 /* If there's an invalid tile, then we don't have enough information at all. */
277 if (!IsValidTile(this->tile)) goto unhandled;
278 } else {
279 t = this->obj->town;
282 switch (variable) {
283 /* Relative position. */
284 case 0x40: {
285 uint offset = this->tile - this->obj->location.tile;
286 uint offset_x = TileX(offset);
287 uint offset_y = TileY(offset);
288 return offset_y << 20 | offset_x << 16 | offset_y << 8 | offset_x;
291 /* Tile information. */
292 case 0x41: return GetTileSlope(this->tile) << 8 | GetTerrainType(this->tile);
294 /* Construction date */
295 case 0x42: return this->obj->build_date;
297 /* Animation counter */
298 case 0x43: return GetAnimationFrame(this->tile);
300 /* Object founder information */
301 case 0x44: return GetTileOwner(this->tile);
303 /* Get town zone and Manhattan distance of closest town */
304 case 0x45: return GetTownRadiusGroup(t, this->tile) << 16 | std::min(DistanceManhattan(this->tile, t->xy), 0xFFFFu);
306 /* Get square of Euclidian distance of closest town */
307 case 0x46: return DistanceSquare(this->tile, t->xy);
309 /* Object colour */
310 case 0x47: return this->obj->colour;
312 /* Object view */
313 case 0x48: return this->obj->view;
315 /* Get object ID at offset param */
316 case 0x60: return GetObjectIDAtOffset(GetNearbyTile(parameter, this->tile), this->ro.grffile->grfid);
318 /* Get random tile bits at offset param */
319 case 0x61: {
320 TileIndex tile = GetNearbyTile(parameter, this->tile);
321 return (IsTileType(tile, MP_OBJECT) && Object::GetByTile(tile) == this->obj) ? GetObjectRandomBits(tile) : 0;
324 /* Land info of nearby tiles */
325 case 0x62: return GetNearbyObjectTileInformation(parameter, this->tile, this->obj == nullptr ? INVALID_OBJECT : this->obj->index, this->ro.grffile->grf_version >= 8);
327 /* Animation counter of nearby tile */
328 case 0x63: {
329 TileIndex tile = GetNearbyTile(parameter, this->tile);
330 return (IsTileType(tile, MP_OBJECT) && Object::GetByTile(tile) == this->obj) ? GetAnimationFrame(tile) : 0;
333 /* Count of object, distance of closest instance */
334 case 0x64: return GetCountAndDistanceOfClosestInstance(parameter, this->ro.grffile->grfid, this->tile, this->obj);
337 unhandled:
338 Debug(grf, 1, "Unhandled object variable 0x{:X}", variable);
340 *available = false;
341 return UINT_MAX;
345 * Constructor of the object resolver.
346 * @param obj Object being resolved.
347 * @param tile %Tile of the object.
348 * @param view View of the object.
349 * @param callback Callback ID.
350 * @param param1 First parameter (var 10) of the callback.
351 * @param param2 Second parameter (var 18) of the callback.
353 ObjectResolverObject::ObjectResolverObject(const ObjectSpec *spec, Object *obj, TileIndex tile, uint8 view,
354 CallbackID callback, uint32 param1, uint32 param2)
355 : ResolverObject(spec->grf_prop.grffile, callback, param1, param2), object_scope(*this, obj, spec, tile, view)
357 this->town_scope = nullptr;
358 this->root_spritegroup = (obj == nullptr && spec->grf_prop.spritegroup[CT_PURCHASE_OBJECT] != nullptr) ?
359 spec->grf_prop.spritegroup[CT_PURCHASE_OBJECT] : spec->grf_prop.spritegroup[0];
362 ObjectResolverObject::~ObjectResolverObject()
364 delete this->town_scope;
368 * Get the town resolver scope that belongs to this object resolver.
369 * On the first call, the town scope is created (if possible).
370 * @return Town scope, if available.
372 TownScopeResolver *ObjectResolverObject::GetTown()
374 if (this->town_scope == nullptr) {
375 Town *t;
376 if (this->object_scope.obj != nullptr) {
377 t = this->object_scope.obj->town;
378 } else {
379 t = ClosestTownFromTile(this->object_scope.tile, UINT_MAX);
381 if (t == nullptr) return nullptr;
382 this->town_scope = new TownScopeResolver(*this, t, this->object_scope.obj == nullptr);
384 return this->town_scope;
387 GrfSpecFeature ObjectResolverObject::GetFeature() const
389 return GSF_OBJECTS;
392 uint32 ObjectResolverObject::GetDebugID() const
394 return this->object_scope.spec->grf_prop.local_id;
398 * Perform a callback for an object.
399 * @param callback The callback to perform.
400 * @param param1 The first parameter to pass to the NewGRF.
401 * @param param2 The second parameter to pass to the NewGRF.
402 * @param spec The specification of the object / the entry point.
403 * @param o The object to call the callback for.
404 * @param tile The tile the callback is called for.
405 * @param view The view of the object (only used when o == nullptr).
406 * @return The result of the callback.
408 uint16 GetObjectCallback(CallbackID callback, uint32 param1, uint32 param2, const ObjectSpec *spec, Object *o, TileIndex tile, uint8 view)
410 ObjectResolverObject object(spec, o, tile, view, callback, param1, param2);
411 return object.ResolveCallback();
415 * Draw an group of sprites on the map.
416 * @param ti Information about the tile to draw on.
417 * @param group The group of sprites to draw.
418 * @param spec Object spec to draw.
420 static void DrawTileLayout(const TileInfo *ti, const TileLayoutSpriteGroup *group, const ObjectSpec *spec)
422 const DrawTileSprites *dts = group->ProcessRegisters(nullptr);
423 PaletteID palette = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? SPR_2CCMAP_BASE : PALETTE_RECOLOUR_START) + Object::GetByTile(ti->tile)->colour;
425 SpriteID image = dts->ground.sprite;
426 PaletteID pal = dts->ground.pal;
428 if (GB(image, 0, SPRITE_WIDTH) != 0) {
429 /* If the ground sprite is the default flat water sprite, draw also canal/river borders
430 * Do not do this if the tile's WaterClass is 'land'. */
431 if ((image == SPR_FLAT_WATER_TILE || spec->flags & OBJECT_FLAG_DRAW_WATER) && IsTileOnWater(ti->tile)) {
432 DrawWaterClassGround(ti);
433 } else {
434 DrawGroundSprite(image, GroundSpritePaletteTransform(image, pal, palette));
438 DrawNewGRFTileSeq(ti, dts, TO_STRUCTURES, 0, palette);
442 * Draw an object on the map.
443 * @param ti Information about the tile to draw on.
444 * @param spec Object spec to draw.
446 void DrawNewObjectTile(TileInfo *ti, const ObjectSpec *spec)
448 Object *o = Object::GetByTile(ti->tile);
449 ObjectResolverObject object(spec, o, ti->tile);
451 const SpriteGroup *group = object.Resolve();
452 if (group == nullptr || group->type != SGT_TILELAYOUT) return;
454 DrawTileLayout(ti, (const TileLayoutSpriteGroup *)group, spec);
458 * Draw representation of an object (tile) for GUI purposes.
459 * @param x Position x of image.
460 * @param y Position y of image.
461 * @param spec Object spec to draw.
462 * @param view The object's view.
464 void DrawNewObjectTileInGUI(int x, int y, const ObjectSpec *spec, uint8 view)
466 ObjectResolverObject object(spec, nullptr, INVALID_TILE, view);
467 const SpriteGroup *group = object.Resolve();
468 if (group == nullptr || group->type != SGT_TILELAYOUT) return;
470 const DrawTileSprites *dts = ((const TileLayoutSpriteGroup *)group)->ProcessRegisters(nullptr);
472 PaletteID palette;
473 if (Company::IsValidID(_local_company)) {
474 /* Get the colours of our company! */
475 if (spec->flags & OBJECT_FLAG_2CC_COLOUR) {
476 const Livery *l = Company::Get(_local_company)->livery;
477 palette = SPR_2CCMAP_BASE + l->colour1 + l->colour2 * 16;
478 } else {
479 palette = COMPANY_SPRITE_COLOUR(_local_company);
481 } else {
482 /* There's no company, so just take the base palette. */
483 palette = (spec->flags & OBJECT_FLAG_2CC_COLOUR) ? SPR_2CCMAP_BASE : PALETTE_RECOLOUR_START;
486 SpriteID image = dts->ground.sprite;
487 PaletteID pal = dts->ground.pal;
489 if (GB(image, 0, SPRITE_WIDTH) != 0) {
490 DrawSprite(image, GroundSpritePaletteTransform(image, pal, palette), x, y);
493 DrawNewGRFTileSeqInGUI(x, y, dts, 0, palette);
497 * Perform a callback for an object.
498 * @param callback The callback to perform.
499 * @param param1 The first parameter to pass to the NewGRF.
500 * @param param2 The second parameter to pass to the NewGRF.
501 * @param spec The specification of the object / the entry point.
502 * @param o The object to call the callback for.
503 * @param tile The tile the callback is called for.
504 * @param extra_data Ignored.
505 * @return The result of the callback.
507 uint16 StubGetObjectCallback(CallbackID callback, uint32 param1, uint32 param2, const ObjectSpec *spec, Object *o, TileIndex tile, int extra_data)
509 return GetObjectCallback(callback, param1, param2, spec, o, tile);
512 /** Helper class for animation control. */
513 struct ObjectAnimationBase : public AnimationBase<ObjectAnimationBase, ObjectSpec, Object, int, StubGetObjectCallback> {
514 static const CallbackID cb_animation_speed = CBID_OBJECT_ANIMATION_SPEED;
515 static const CallbackID cb_animation_next_frame = CBID_OBJECT_ANIMATION_NEXT_FRAME;
517 static const ObjectCallbackMask cbm_animation_speed = CBM_OBJ_ANIMATION_SPEED;
518 static const ObjectCallbackMask cbm_animation_next_frame = CBM_OBJ_ANIMATION_NEXT_FRAME;
522 * Handle the animation of the object tile.
523 * @param tile The tile to animate.
525 void AnimateNewObjectTile(TileIndex tile)
527 const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
528 if (spec == nullptr || !(spec->flags & OBJECT_FLAG_ANIMATION)) return;
530 ObjectAnimationBase::AnimateTile(spec, Object::GetByTile(tile), tile, (spec->flags & OBJECT_FLAG_ANIM_RANDOM_BITS) != 0);
534 * Trigger the update of animation on a single tile.
535 * @param o The object that got triggered.
536 * @param tile The location of the triggered tile.
537 * @param trigger The trigger that is triggered.
538 * @param spec The spec associated with the object.
540 void TriggerObjectTileAnimation(Object *o, TileIndex tile, ObjectAnimationTrigger trigger, const ObjectSpec *spec)
542 if (!HasBit(spec->animation.triggers, trigger)) return;
544 ObjectAnimationBase::ChangeAnimationFrame(CBID_OBJECT_ANIMATION_START_STOP, spec, o, tile, Random(), trigger);
548 * Trigger the update of animation on a whole object.
549 * @param o The object that got triggered.
550 * @param trigger The trigger that is triggered.
551 * @param spec The spec associated with the object.
553 void TriggerObjectAnimation(Object *o, ObjectAnimationTrigger trigger, const ObjectSpec *spec)
555 if (!HasBit(spec->animation.triggers, trigger)) return;
557 for (TileIndex tile : o->location) {
558 TriggerObjectTileAnimation(o, tile, trigger, spec);