industry_gui.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "gui.h"
00014 #include "sound_func.h"
00015 #include "window_func.h"
00016 #include "textbuf_gui.h"
00017 #include "command_func.h"
00018 #include "viewport_func.h"
00019 #include "gfx_func.h"
00020 #include "industry.h"
00021 #include "town.h"
00022 #include "cheat_type.h"
00023 #include "newgrf_industries.h"
00024 #include "newgrf_text.h"
00025 #include "newgrf_debug.h"
00026 #include "strings_func.h"
00027 #include "company_func.h"
00028 #include "tilehighlight_func.h"
00029 #include "string_func.h"
00030 #include "sortlist_type.h"
00031 #include "widgets/dropdown_func.h"
00032 #include "company_base.h"
00033 #include "core/geometry_func.hpp"
00034 #include "core/random_func.hpp"
00035 #include "core/backup_type.hpp"
00036 #include "genworld.h"
00037 #include "smallmap_gui.h"
00038 #include "cargodest_gui.h"
00039 
00040 #include "table/strings.h"
00041 #include "table/sprites.h"
00042 
00043 bool _ignore_restrictions;
00044 uint64 _displayed_industries; 
00045 
00046 assert_compile(NUM_INDUSTRYTYPES <= 64); // Make sure all industry types fit in _displayed_industries.
00047 
00049 enum CargoSuffixType {
00050   CST_FUND,  
00051   CST_VIEW,  
00052   CST_DIR,   
00053 };
00054 
00055 static void ShowIndustryCargoesWindow(IndustryType id);
00056 
00072 static void GetCargoSuffix(uint cargo, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, char *suffix, const char *suffix_last)
00073 {
00074   suffix[0] = '\0';
00075   if (HasBit(indspec->callback_mask, CBM_IND_CARGO_SUFFIX)) {
00076     uint16 callback = GetIndustryCallback(CBID_INDUSTRY_CARGO_SUFFIX, 0, (cst << 8) | cargo, const_cast<Industry *>(ind), ind_type, (cst != CST_FUND) ? ind->location.tile : INVALID_TILE);
00077     if (GB(callback, 0, 8) != 0xFF) {
00078       PrepareTextRefStackUsage(6);
00079       GetString(suffix, GetGRFStringID(indspec->grf_prop.grffile->grfid, 0xD000 + callback), suffix_last);
00080       StopTextRefStackUsage();
00081     }
00082   }
00083 }
00084 
00095 template <typename TC, typename TS>
00096 static inline void GetAllCargoSuffixes(uint cb_offset, CargoSuffixType cst, const Industry *ind, IndustryType ind_type, const IndustrySpec *indspec, const TC &cargos, TS &suffixes)
00097 {
00098   assert_compile(lengthof(cargos) <= lengthof(suffixes));
00099   for (uint j = 0; j < lengthof(cargos); j++) {
00100     if (cargos[j] != CT_INVALID) {
00101       GetCargoSuffix(cb_offset + j, cst, ind, ind_type, indspec, suffixes[j], lastof(suffixes[j]));
00102     } else {
00103       suffixes[j][0] = '\0';
00104     }
00105   }
00106 }
00107 
00108 IndustryType _sorted_industry_types[NUM_INDUSTRYTYPES];
00109 
00111 static int CDECL IndustryTypeNameSorter(const IndustryType *a, const IndustryType *b)
00112 {
00113   static char industry_name[2][64];
00114 
00115   const IndustrySpec *indsp1 = GetIndustrySpec(*a);
00116   SetDParam(0, indsp1->name);
00117   GetString(industry_name[0], STR_JUST_STRING, lastof(industry_name[0]));
00118 
00119   const IndustrySpec *indsp2 = GetIndustrySpec(*b);
00120   SetDParam(0, indsp2->name);
00121   GetString(industry_name[1], STR_JUST_STRING, lastof(industry_name[1]));
00122 
00123   int r = strnatcmp(industry_name[0], industry_name[1]); // Sort by name (natural sorting).
00124 
00125   /* If the names are equal, sort by industry type. */
00126   return (r != 0) ? r : (*a - *b);
00127 }
00128 
00132 void SortIndustryTypes()
00133 {
00134   /* Add each industry type to the list. */
00135   for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
00136     _sorted_industry_types[i] = i;
00137   }
00138 
00139   /* Sort industry types by name. */
00140   QSortT(_sorted_industry_types, NUM_INDUSTRYTYPES, &IndustryTypeNameSorter);
00141 }
00142 
00150 void CcBuildIndustry(const CommandCost &result, TileIndex tile, uint32 p1, uint32 p2)
00151 {
00152   if (result.Succeeded()) return;
00153 
00154   uint8 indtype = GB(p1, 0, 8);
00155   if (indtype < NUM_INDUSTRYTYPES) {
00156     const IndustrySpec *indsp = GetIndustrySpec(indtype);
00157     if (indsp->enabled) {
00158       SetDParam(0, indsp->name);
00159       ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, result.GetErrorMessage(), WL_INFO, TileX(tile) * TILE_SIZE, TileY(tile) * TILE_SIZE);
00160     }
00161   }
00162 }
00163 
00165 enum DynamicPlaceIndustriesWidgets {
00166   DPIW_MATRIX_WIDGET,
00167   DPIW_SCROLLBAR,
00168   DPIW_INFOPANEL,
00169   DPIW_DISPLAY_WIDGET,
00170   DPIW_FUND_WIDGET,
00171 };
00172 
00173 static const NWidgetPart _nested_build_industry_widgets[] = {
00174   NWidget(NWID_HORIZONTAL),
00175     NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
00176     NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_FUND_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
00177     NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
00178     NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
00179   EndContainer(),
00180   NWidget(NWID_HORIZONTAL),
00181     NWidget(WWT_MATRIX, COLOUR_DARK_GREEN, DPIW_MATRIX_WIDGET), SetDataTip(0x801, STR_FUND_INDUSTRY_SELECTION_TOOLTIP), SetFill(1, 0), SetResize(1, 1), SetScrollbar(DPIW_SCROLLBAR),
00182     NWidget(NWID_VSCROLLBAR, COLOUR_DARK_GREEN, DPIW_SCROLLBAR),
00183   EndContainer(),
00184   NWidget(WWT_PANEL, COLOUR_DARK_GREEN, DPIW_INFOPANEL), SetResize(1, 0),
00185   EndContainer(),
00186   NWidget(NWID_HORIZONTAL),
00187     NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, DPIW_DISPLAY_WIDGET), SetFill(1, 0), SetResize(1, 0),
00188         SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
00189     NWidget(WWT_TEXTBTN, COLOUR_DARK_GREEN, DPIW_FUND_WIDGET), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_JUST_STRING, STR_NULL),
00190     NWidget(WWT_RESIZEBOX, COLOUR_DARK_GREEN),
00191   EndContainer(),
00192 };
00193 
00195 static const WindowDesc _build_industry_desc(
00196   WDP_AUTO, 170, 212,
00197   WC_BUILD_INDUSTRY, WC_NONE,
00198   WDF_CONSTRUCTION,
00199   _nested_build_industry_widgets, lengthof(_nested_build_industry_widgets)
00200 );
00201 
00203 class BuildIndustryWindow : public Window {
00204   int selected_index;                         
00205   IndustryType selected_type;                 
00206   uint16 callback_timer;                      
00207   bool timer_enabled;                         
00208   uint16 count;                               
00209   IndustryType index[NUM_INDUSTRYTYPES + 1];  
00210   bool enabled[NUM_INDUSTRYTYPES + 1];        
00211   Scrollbar *vscroll;
00212 
00214   static const int MATRIX_TEXT_OFFSET = 17;
00215 
00216   void SetupArrays()
00217   {
00218     this->count = 0;
00219 
00220     for (uint i = 0; i < lengthof(this->index); i++) {
00221       this->index[i]   = INVALID_INDUSTRYTYPE;
00222       this->enabled[i] = false;
00223     }
00224 
00225     if (_game_mode == GM_EDITOR) { // give room for the Many Random "button"
00226       this->index[this->count] = INVALID_INDUSTRYTYPE;
00227       this->enabled[this->count] = true;
00228       this->count++;
00229       this->timer_enabled = false;
00230     }
00231     /* Fill the arrays with industries.
00232      * The tests performed after the enabled allow to load the industries
00233      * In the same way they are inserted by grf (if any)
00234      */
00235     for (uint8 i = 0; i < NUM_INDUSTRYTYPES; i++) {
00236       IndustryType ind = _sorted_industry_types[i];
00237       const IndustrySpec *indsp = GetIndustrySpec(ind);
00238       if (indsp->enabled) {
00239         /* Rule is that editor mode loads all industries.
00240          * In game mode, all non raw industries are loaded too
00241          * and raw ones are loaded only when setting allows it */
00242         if (_game_mode != GM_EDITOR && indsp->IsRawIndustry() && _settings_game.construction.raw_industry_construction == 0) {
00243           /* Unselect if the industry is no longer in the list */
00244           if (this->selected_type == ind) this->selected_index = -1;
00245           continue;
00246         }
00247         this->index[this->count] = ind;
00248         this->enabled[this->count] = (_game_mode == GM_EDITOR) || CheckIfCallBackAllowsAvailability(ind, IACT_USERCREATION);
00249         /* Keep the selection to the correct line */
00250         if (this->selected_type == ind) this->selected_index = this->count;
00251         this->count++;
00252       }
00253     }
00254 
00255     /* first indutry type is selected if the current selection is invalid.
00256      * I'll be damned if there are none available ;) */
00257     if (this->selected_index == -1) {
00258       this->selected_index = 0;
00259       this->selected_type = this->index[0];
00260     }
00261 
00262     this->vscroll->SetCount(this->count);
00263   }
00264 
00266   void SetButtons()
00267   {
00268     this->SetWidgetDisabledState(DPIW_FUND_WIDGET, this->selected_type != INVALID_INDUSTRYTYPE && !this->enabled[this->selected_index]);
00269     this->SetWidgetDisabledState(DPIW_DISPLAY_WIDGET, this->selected_type == INVALID_INDUSTRYTYPE && this->enabled[this->selected_index]);
00270   }
00271 
00272 public:
00273   BuildIndustryWindow() : Window()
00274   {
00275     this->timer_enabled = _loaded_newgrf_features.has_newindustries;
00276 
00277     this->selected_index = -1;
00278     this->selected_type = INVALID_INDUSTRYTYPE;
00279 
00280     this->callback_timer = DAY_TICKS;
00281 
00282     this->CreateNestedTree(&_build_industry_desc);
00283     this->vscroll = this->GetScrollbar(DPIW_SCROLLBAR);
00284     this->FinishInitNested(&_build_industry_desc, 0);
00285 
00286     this->SetButtons();
00287   }
00288 
00289   virtual void OnInit()
00290   {
00291     this->SetupArrays();
00292   }
00293 
00294   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00295   {
00296     switch (widget) {
00297       case DPIW_MATRIX_WIDGET: {
00298         Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES);
00299         for (byte i = 0; i < this->count; i++) {
00300           if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
00301           d = maxdim(d, GetStringBoundingBox(GetIndustrySpec(this->index[i])->name));
00302         }
00303         resize->height = FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM;
00304         d.width += MATRIX_TEXT_OFFSET + padding.width;
00305         d.height = 5 * resize->height;
00306         *size = maxdim(*size, d);
00307         break;
00308       }
00309 
00310       case DPIW_INFOPANEL: {
00311         /* Extra line for cost outside of editor + extra lines for 'extra' information for NewGRFs. */
00312         int height = 2 + (_game_mode == GM_EDITOR ? 0 : 1) + (_loaded_newgrf_features.has_newindustries ? 4 : 0);
00313         Dimension d = {0, 0};
00314         for (byte i = 0; i < this->count; i++) {
00315           if (this->index[i] == INVALID_INDUSTRYTYPE) continue;
00316 
00317           const IndustrySpec *indsp = GetIndustrySpec(this->index[i]);
00318 
00319           char cargo_suffix[3][512];
00320           GetAllCargoSuffixes(0, CST_FUND, NULL, this->index[i], indsp, indsp->accepts_cargo, cargo_suffix);
00321           StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00322           byte p = 0;
00323           SetDParam(0, STR_JUST_NOTHING);
00324           SetDParamStr(1, "");
00325           for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
00326             if (indsp->accepts_cargo[j] == CT_INVALID) continue;
00327             if (p > 0) str++;
00328             SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
00329             SetDParamStr(p++, cargo_suffix[j]);
00330           }
00331           d = maxdim(d, GetStringBoundingBox(str));
00332 
00333           /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
00334           GetAllCargoSuffixes(3, CST_FUND, NULL, this->index[i], indsp, indsp->produced_cargo, cargo_suffix);
00335           str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
00336           p = 0;
00337           SetDParam(0, STR_JUST_NOTHING);
00338           SetDParamStr(1, "");
00339           for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
00340             if (indsp->produced_cargo[j] == CT_INVALID) continue;
00341             if (p > 0) str++;
00342             SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
00343             SetDParamStr(p++, cargo_suffix[j]);
00344           }
00345           d = maxdim(d, GetStringBoundingBox(str));
00346         }
00347 
00348         /* Set it to something more sane :) */
00349         size->height = height * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
00350         size->width  = d.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
00351         break;
00352       }
00353 
00354       case DPIW_FUND_WIDGET: {
00355         Dimension d = GetStringBoundingBox(STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
00356         d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY));
00357         d = maxdim(d, GetStringBoundingBox(STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY));
00358         d.width += padding.width;
00359         d.height += padding.height;
00360         *size = maxdim(*size, d);
00361         break;
00362       }
00363     }
00364   }
00365 
00366   virtual void SetStringParameters(int widget) const
00367   {
00368     switch (widget) {
00369       case DPIW_FUND_WIDGET:
00370         /* Raw industries might be prospected. Show this fact by changing the string
00371          * In Editor, you just build, while ingame, or you fund or you prospect */
00372         if (_game_mode == GM_EDITOR) {
00373           /* We've chosen many random industries but no industries have been specified */
00374           SetDParam(0, STR_FUND_INDUSTRY_BUILD_NEW_INDUSTRY);
00375         } else {
00376           const IndustrySpec *indsp = GetIndustrySpec(this->index[this->selected_index]);
00377           SetDParam(0, (_settings_game.construction.raw_industry_construction == 2 && indsp->IsRawIndustry()) ? STR_FUND_INDUSTRY_PROSPECT_NEW_INDUSTRY : STR_FUND_INDUSTRY_FUND_NEW_INDUSTRY);
00378         }
00379         break;
00380     }
00381   }
00382 
00383   virtual void DrawWidget(const Rect &r, int widget) const
00384   {
00385     switch (widget) {
00386       case DPIW_MATRIX_WIDGET:
00387         for (byte i = 0; i < this->vscroll->GetCapacity() && i + this->vscroll->GetPosition() < this->count; i++) {
00388           int x = r.left + WD_MATRIX_LEFT;
00389           int y = r.top + WD_MATRIX_TOP + i * this->resize.step_height;
00390           bool selected = this->selected_index == i + this->vscroll->GetPosition();
00391 
00392           if (this->index[i + this->vscroll->GetPosition()] == INVALID_INDUSTRYTYPE) {
00393             DrawString(x + MATRIX_TEXT_OFFSET, r.right - WD_MATRIX_RIGHT, y, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES, selected ? TC_WHITE : TC_ORANGE);
00394             continue;
00395           }
00396           const IndustrySpec *indsp = GetIndustrySpec(this->index[i + this->vscroll->GetPosition()]);
00397 
00398           /* Draw the name of the industry in white is selected, otherwise, in orange */
00399           DrawString(x + MATRIX_TEXT_OFFSET, r.right - WD_MATRIX_RIGHT, y, indsp->name, selected ? TC_WHITE : TC_ORANGE);
00400           GfxFillRect(x,     y + 1,  x + 10, y + 7, selected ? PC_WHITE : PC_BLACK);
00401           GfxFillRect(x + 1, y + 2,  x +  9, y + 6, indsp->map_colour);
00402         }
00403         break;
00404 
00405       case DPIW_INFOPANEL: {
00406         int y      = r.top    + WD_FRAMERECT_TOP;
00407         int bottom = r.bottom - WD_FRAMERECT_BOTTOM;
00408         int left   = r.left   + WD_FRAMERECT_LEFT;
00409         int right  = r.right  - WD_FRAMERECT_RIGHT;
00410 
00411         if (this->selected_type == INVALID_INDUSTRYTYPE) {
00412           DrawStringMultiLine(left, right, y,  bottom, STR_FUND_INDUSTRY_MANY_RANDOM_INDUSTRIES_TOOLTIP);
00413           break;
00414         }
00415 
00416         const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00417 
00418         if (_game_mode != GM_EDITOR) {
00419           SetDParam(0, indsp->GetConstructionCost());
00420           DrawString(left, right, y, STR_FUND_INDUSTRY_INDUSTRY_BUILD_COST);
00421           y += FONT_HEIGHT_NORMAL;
00422         }
00423 
00424         /* Draw the accepted cargoes, if any. Otherwise, will print "Nothing". */
00425         char cargo_suffix[3][512];
00426         GetAllCargoSuffixes(0, CST_FUND, NULL, this->selected_type, indsp, indsp->accepts_cargo, cargo_suffix);
00427         StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00428         byte p = 0;
00429         SetDParam(0, STR_JUST_NOTHING);
00430         SetDParamStr(1, "");
00431         for (byte j = 0; j < lengthof(indsp->accepts_cargo); j++) {
00432           if (indsp->accepts_cargo[j] == CT_INVALID) continue;
00433           if (p > 0) str++;
00434           SetDParam(p++, CargoSpec::Get(indsp->accepts_cargo[j])->name);
00435           SetDParamStr(p++, cargo_suffix[j]);
00436         }
00437         DrawString(left, right, y, str);
00438         y += FONT_HEIGHT_NORMAL;
00439 
00440         /* Draw the produced cargoes, if any. Otherwise, will print "Nothing". */
00441         GetAllCargoSuffixes(3, CST_FUND, NULL, this->selected_type, indsp, indsp->produced_cargo, cargo_suffix);
00442         str = STR_INDUSTRY_VIEW_PRODUCES_CARGO;
00443         p = 0;
00444         SetDParam(0, STR_JUST_NOTHING);
00445         SetDParamStr(1, "");
00446         for (byte j = 0; j < lengthof(indsp->produced_cargo); j++) {
00447           if (indsp->produced_cargo[j] == CT_INVALID) continue;
00448           if (p > 0) str++;
00449           SetDParam(p++, CargoSpec::Get(indsp->produced_cargo[j])->name);
00450           SetDParamStr(p++, cargo_suffix[j]);
00451         }
00452         DrawString(left, right, y, str);
00453         y += FONT_HEIGHT_NORMAL;
00454 
00455         /* Get the additional purchase info text, if it has not already been queried. */
00456         str = STR_NULL;
00457         if (HasBit(indsp->callback_mask, CBM_IND_FUND_MORE_TEXT)) {
00458           uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_FUND_MORE_TEXT, 0, 0, NULL, this->selected_type, INVALID_TILE);
00459           if (callback_res != CALLBACK_FAILED) {  // Did it fail?
00460             str = GetGRFStringID(indsp->grf_prop.grffile->grfid, 0xD000 + callback_res);  // No. here's the new string
00461             if (str != STR_UNDEFINED) {
00462               PrepareTextRefStackUsage(6);
00463               DrawStringMultiLine(left, right, y, bottom, str);
00464               StopTextRefStackUsage();
00465             }
00466           }
00467         }
00468         break;
00469       }
00470     }
00471   }
00472 
00473   virtual void OnClick(Point pt, int widget, int click_count)
00474   {
00475     switch (widget) {
00476       case DPIW_MATRIX_WIDGET: {
00477         int y = this->vscroll->GetScrolledRowFromWidget(pt.y, this, DPIW_MATRIX_WIDGET);
00478         if (y < this->count) { // Is it within the boundaries of available data?
00479           this->selected_index = y;
00480           this->selected_type = this->index[y];
00481           const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
00482 
00483           this->SetDirty();
00484 
00485           if (_thd.GetCallbackWnd() == this &&
00486               ((_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indsp != NULL && indsp->IsRawIndustry()) ||
00487               this->selected_type == INVALID_INDUSTRYTYPE ||
00488               !this->enabled[this->selected_index])) {
00489             /* Reset the button state if going to prospecting or "build many industries" */
00490             this->RaiseButtons();
00491             ResetObjectToPlace();
00492           }
00493 
00494           this->SetButtons();
00495           if (this->enabled[this->selected_index] && click_count > 1) this->OnClick(pt, DPIW_FUND_WIDGET, 1);
00496         }
00497         break;
00498       }
00499 
00500       case DPIW_DISPLAY_WIDGET:
00501         if (this->selected_type != INVALID_INDUSTRYTYPE) ShowIndustryCargoesWindow(this->selected_type);
00502         break;
00503 
00504       case DPIW_FUND_WIDGET: {
00505         if (this->selected_type == INVALID_INDUSTRYTYPE) {
00506           this->HandleButtonClick(DPIW_FUND_WIDGET);
00507 
00508           if (Town::GetNumItems() == 0) {
00509             ShowErrorMessage(STR_ERROR_CAN_T_GENERATE_INDUSTRIES, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO);
00510           } else {
00511             extern void GenerateIndustries();
00512             _generating_world = true;
00513             GenerateIndustries();
00514             _generating_world = false;
00515           }
00516         } else if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && GetIndustrySpec(this->selected_type)->IsRawIndustry()) {
00517           DoCommandP(0, this->selected_type, InteractiveRandom(), CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
00518           this->HandleButtonClick(DPIW_FUND_WIDGET);
00519         } else {
00520           HandlePlacePushButton(this, DPIW_FUND_WIDGET, SPR_CURSOR_INDUSTRY, HT_RECT);
00521         }
00522         break;
00523       }
00524     }
00525   }
00526 
00527   virtual void OnResize()
00528   {
00529     /* Adjust the number of items in the matrix depending of the resize */
00530     this->vscroll->SetCapacityFromWidget(this, DPIW_MATRIX_WIDGET);
00531     this->GetWidget<NWidgetCore>(DPIW_MATRIX_WIDGET)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
00532   }
00533 
00534   virtual void OnPlaceObject(Point pt, TileIndex tile)
00535   {
00536     bool success = true;
00537     /* We do not need to protect ourselves against "Random Many Industries" in this mode */
00538     const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00539     uint32 seed = InteractiveRandom();
00540 
00541     if (_game_mode == GM_EDITOR) {
00542       /* Show error if no town exists at all */
00543       if (Town::GetNumItems() == 0) {
00544         SetDParam(0, indsp->name);
00545         ShowErrorMessage(STR_ERROR_CAN_T_BUILD_HERE, STR_ERROR_MUST_FOUND_TOWN_FIRST, WL_INFO, pt.x, pt.y);
00546         return;
00547       }
00548 
00549       Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
00550       _generating_world = true;
00551       _ignore_restrictions = true;
00552 
00553       DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed,
00554           CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY), &CcBuildIndustry);
00555 
00556       cur_company.Restore();
00557       _ignore_restrictions = false;
00558       _generating_world = false;
00559     } else {
00560       success = DoCommandP(tile, (InteractiveRandomRange(indsp->num_table) << 8) | this->selected_type, seed, CMD_BUILD_INDUSTRY | CMD_MSG(STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY));
00561     }
00562 
00563     /* If an industry has been built, just reset the cursor and the system */
00564     if (success && !_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
00565   }
00566 
00567   virtual void OnTick()
00568   {
00569     if (_pause_mode != PM_UNPAUSED) return;
00570     if (!this->timer_enabled) return;
00571     if (--this->callback_timer == 0) {
00572       /* We have just passed another day.
00573        * See if we need to update availability of currently selected industry */
00574       this->callback_timer = DAY_TICKS; // restart counter
00575 
00576       const IndustrySpec *indsp = GetIndustrySpec(this->selected_type);
00577 
00578       if (indsp->enabled) {
00579         bool call_back_result = CheckIfCallBackAllowsAvailability(this->selected_type, IACT_USERCREATION);
00580 
00581         /* Only if result does match the previous state would it require a redraw. */
00582         if (call_back_result != this->enabled[this->selected_index]) {
00583           this->enabled[this->selected_index] = call_back_result;
00584           this->SetButtons();
00585           this->SetDirty();
00586         }
00587       }
00588     }
00589   }
00590 
00591   virtual void OnTimeout()
00592   {
00593     this->RaiseButtons();
00594   }
00595 
00596   virtual void OnPlaceObjectAbort()
00597   {
00598     this->RaiseButtons();
00599   }
00600 
00606   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00607   {
00608     if (!gui_scope) return;
00609     this->SetupArrays();
00610 
00611     const IndustrySpec *indsp = (this->selected_type == INVALID_INDUSTRYTYPE) ? NULL : GetIndustrySpec(this->selected_type);
00612     if (indsp == NULL) this->enabled[this->selected_index] = _settings_game.difficulty.industry_density != ID_FUND_ONLY;
00613     this->SetButtons();
00614   }
00615 };
00616 
00617 void ShowBuildIndustryWindow()
00618 {
00619   if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
00620   if (BringWindowToFrontById(WC_BUILD_INDUSTRY, 0)) return;
00621   new BuildIndustryWindow();
00622 }
00623 
00624 static void UpdateIndustryProduction(Industry *i);
00625 
00626 static inline bool IsProductionAlterable(const Industry *i)
00627 {
00628   const IndustrySpec *is = GetIndustrySpec(i->type);
00629   return ((_game_mode == GM_EDITOR || _cheats.setup_prod.value) &&
00630       (is->production_rate[0] != 0 || is->production_rate[1] != 0 || is->IsRawIndustry()));
00631 }
00632 
00634 enum IndustryViewWidgets {
00635   IVW_CAPTION,
00636   IVW_VIEWPORT,
00637   IVW_INFO,
00638   IVW_GOTO,
00639   IVW_DISPLAY,
00640 };
00641 
00642 class IndustryViewWindow : public Window
00643 {
00645   enum Editability {
00646     EA_NONE,              
00647     EA_MULTIPLIER,        
00648     EA_RATE,              
00649   };
00650 
00652   enum InfoLine {
00653     IL_NONE,              
00654     IL_MULTIPLIER,        
00655     IL_RATE1,             
00656     IL_RATE2,             
00657   };
00658 
00659   Editability editable;     
00660   InfoLine editbox_line;    
00661   InfoLine clicked_line;    
00662   byte clicked_button;      
00663   int production_offset_y;  
00664   int info_height;          
00665 
00666   CargoDestinationList dest_list; 
00667   int dest_list_top;        
00668 
00669 public:
00670   IndustryViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(), dest_list(Industry::Get(window_number))
00671   {
00672     this->flags4 |= WF_DISABLE_VP_SCROLL;
00673     this->editbox_line = IL_NONE;
00674     this->clicked_line = IL_NONE;
00675     this->clicked_button = 0;
00676     this->info_height = WD_FRAMERECT_TOP + 2 * FONT_HEIGHT_NORMAL + WD_FRAMERECT_BOTTOM + 1; // Info panel has at least two lines text.
00677 
00678     this->InitNested(desc, window_number);
00679     NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(IVW_VIEWPORT);
00680     nvp->InitializeViewport(this, Industry::Get(window_number)->location.GetCenterTile(), ZOOM_LVL_INDUSTRY);
00681 
00682     this->InvalidateData();
00683   }
00684 
00685   virtual void OnPaint()
00686   {
00687     this->DrawWidgets();
00688 
00689     if (this->IsShaded()) return; // Don't draw anything when the window is shaded.
00690 
00691     NWidgetBase *nwi = this->GetWidget<NWidgetBase>(IVW_INFO);
00692     uint expected = this->DrawInfo(nwi->pos_x, nwi->pos_x + nwi->current_x - 1, nwi->pos_y) - nwi->pos_y;
00693     if (expected > nwi->current_y - 1) {
00694       this->info_height = expected + 1;
00695       this->ReInit();
00696       return;
00697     }
00698   }
00699 
00707   int DrawInfo(uint left, uint right, uint top)
00708   {
00709     Industry *i = Industry::Get(this->window_number);
00710     const IndustrySpec *ind = GetIndustrySpec(i->type);
00711     int y = top + WD_FRAMERECT_TOP;
00712     bool first = true;
00713     bool has_accept = false;
00714     char cargo_suffix[3][512];
00715 
00716     if (HasBit(ind->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(ind->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) {
00717       GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
00718       for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
00719         if (i->accepts_cargo[j] == CT_INVALID) continue;
00720         has_accept = true;
00721         if (first) {
00722           DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_FOR_PROCESSING);
00723           y += FONT_HEIGHT_NORMAL;
00724           first = false;
00725         }
00726         SetDParam(0, i->accepts_cargo[j]);
00727         SetDParam(1, i->incoming_cargo_waiting[j]);
00728         SetDParamStr(2, cargo_suffix[j]);
00729         DrawString(left + WD_FRAMETEXT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_WAITING_STOCKPILE_CARGO);
00730         y += FONT_HEIGHT_NORMAL;
00731       }
00732     } else {
00733       GetAllCargoSuffixes(0, CST_VIEW, i, i->type, ind, i->accepts_cargo, cargo_suffix);
00734       StringID str = STR_INDUSTRY_VIEW_REQUIRES_CARGO;
00735       byte p = 0;
00736       for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
00737         if (i->accepts_cargo[j] == CT_INVALID) continue;
00738         has_accept = true;
00739         if (p > 0) str++;
00740         SetDParam(p++, CargoSpec::Get(i->accepts_cargo[j])->name);
00741         SetDParamStr(p++, cargo_suffix[j]);
00742       }
00743       if (has_accept) {
00744         DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, str);
00745         y += FONT_HEIGHT_NORMAL;
00746       }
00747     }
00748 
00749     GetAllCargoSuffixes(3, CST_VIEW, i, i->type, ind, i->produced_cargo, cargo_suffix);
00750     first = true;
00751     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
00752       if (i->produced_cargo[j] == CT_INVALID) continue;
00753       if (first) {
00754         if (has_accept) y += WD_PAR_VSEP_WIDE;
00755         DrawString(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LAST_MONTH_TITLE);
00756         y += FONT_HEIGHT_NORMAL;
00757         if (this->editable == EA_RATE) this->production_offset_y = y;
00758         first = false;
00759       }
00760 
00761       SetDParam(0, i->produced_cargo[j]);
00762       SetDParam(1, i->last_month_production[j]);
00763       SetDParamStr(2, cargo_suffix[j]);
00764       SetDParam(3, ToPercent8(i->last_month_pct_transported[j]));
00765       uint x = left + WD_FRAMETEXT_LEFT + (this->editable == EA_RATE ? 30 : 0);
00766       DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_TRANSPORTED);
00767       /* Let's put out those buttons.. */
00768       if (this->editable == EA_RATE) {
00769         DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_RATE1 + j) ? this->clicked_button : 0,
00770             i->production_rate[j] > 0, i->production_rate[j] < 255);
00771       }
00772       y += FONT_HEIGHT_NORMAL;
00773     }
00774 
00775     /* Display production multiplier if editable */
00776     if (this->editable == EA_MULTIPLIER) {
00777       y += WD_PAR_VSEP_WIDE;
00778       this->production_offset_y = y;
00779       SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
00780       uint x = left + WD_FRAMETEXT_LEFT + 30;
00781       DrawString(x, right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_VIEW_PRODUCTION_LEVEL);
00782       DrawArrowButtons(left + WD_FRAMETEXT_LEFT, y, COLOUR_YELLOW, (this->clicked_line == IL_MULTIPLIER) ? this->clicked_button : 0,
00783           i->prod_level > PRODLEVEL_MINIMUM, i->prod_level < PRODLEVEL_MAXIMUM);
00784       y += FONT_HEIGHT_NORMAL;
00785     }
00786 
00787     /* Get the extra message for the GUI */
00788     if (HasBit(ind->callback_mask, CBM_IND_WINDOW_MORE_TEXT)) {
00789       uint16 callback_res = GetIndustryCallback(CBID_INDUSTRY_WINDOW_MORE_TEXT, 0, 0, i, i->type, i->location.tile);
00790       if (callback_res != CALLBACK_FAILED) {
00791         StringID message = GetGRFStringID(ind->grf_prop.grffile->grfid, 0xD000 + callback_res);
00792         if (message != STR_NULL && message != STR_UNDEFINED) {
00793           y += WD_PAR_VSEP_WIDE;
00794 
00795           PrepareTextRefStackUsage(6);
00796           /* Use all the available space left from where we stand up to the
00797            * end of the window. We ALSO enlarge the window if needed, so we
00798            * can 'go' wild with the bottom of the window. */
00799           y = DrawStringMultiLine(left + WD_FRAMERECT_LEFT, right - WD_FRAMERECT_RIGHT, y, UINT16_MAX, message);
00800           StopTextRefStackUsage();
00801         }
00802       }
00803     }
00804 
00805     this->dest_list_top = y;
00806     y = this->dest_list.DrawList(left, right, y);
00807 
00808     return y + WD_FRAMERECT_BOTTOM;
00809   }
00810 
00811   virtual void SetStringParameters(int widget) const
00812   {
00813     if (widget == IVW_CAPTION) SetDParam(0, this->window_number);
00814   }
00815 
00816   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
00817   {
00818     if (widget == IVW_INFO) size->height = this->info_height;
00819   }
00820 
00821   virtual void OnClick(Point pt, int widget, int click_count)
00822   {
00823     switch (widget) {
00824       case IVW_INFO: {
00825         Industry *i = Industry::Get(this->window_number);
00826         InfoLine line = IL_NONE;
00827         NWidgetBase *nwi = this->GetWidget<NWidgetBase>(widget);
00828 
00829         /* Test for click on destination list. */
00830         if (pt.y > this->dest_list_top) {
00831           this->dest_list.OnClick(pt.y - this->dest_list_top);
00832           return;
00833         }
00834 
00835         switch (this->editable) {
00836           case EA_NONE: break;
00837 
00838           case EA_MULTIPLIER:
00839             if (IsInsideBS(pt.y, this->production_offset_y, FONT_HEIGHT_NORMAL)) line = IL_MULTIPLIER;
00840             break;
00841 
00842           case EA_RATE:
00843             if (pt.y >= this->production_offset_y) {
00844               int row = (pt.y - this->production_offset_y) / FONT_HEIGHT_NORMAL;
00845               for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
00846                 if (i->produced_cargo[j] == CT_INVALID) continue;
00847                 row--;
00848                 if (row < 0) {
00849                   line = (InfoLine)(IL_RATE1 + j);
00850                   break;
00851                 }
00852               }
00853             }
00854             break;
00855         }
00856         if (line == IL_NONE) return;
00857 
00858         int left = nwi->pos_x + WD_FRAMETEXT_LEFT;
00859         int right = nwi->pos_x + nwi->current_x - 1 - WD_FRAMERECT_RIGHT;
00860         if (IsInsideMM(pt.x, left, left + 20)) {
00861           /* Clicked buttons, decrease or increase production */
00862           byte button = (pt.x < left + 10) ? 1 : 2;
00863           switch (this->editable) {
00864             case EA_MULTIPLIER:
00865               if (button == 1) {
00866                 if (i->prod_level <= PRODLEVEL_MINIMUM) return;
00867                 i->prod_level = max<uint>(i->prod_level / 2, PRODLEVEL_MINIMUM);
00868               } else {
00869                 if (i->prod_level >= PRODLEVEL_MAXIMUM) return;
00870                 i->prod_level = minu(i->prod_level * 2, PRODLEVEL_MAXIMUM);
00871               }
00872               break;
00873 
00874             case EA_RATE:
00875               if (button == 1) {
00876                 if (i->production_rate[line - IL_RATE1] <= 0) return;
00877                 i->production_rate[line - IL_RATE1] = max(i->production_rate[line - IL_RATE1] / 2, 0);
00878               } else {
00879                 if (i->production_rate[line - IL_RATE1] >= 255) return;
00880                 /* a zero production industry is unlikely to give anything but zero, so push it a little bit */
00881                 int new_prod = i->production_rate[line - IL_RATE1] == 0 ? 1 : i->production_rate[line - IL_RATE1] * 2;
00882                 i->production_rate[line - IL_RATE1] = minu(new_prod, 255);
00883               }
00884               break;
00885 
00886             default: NOT_REACHED();
00887           }
00888 
00889           UpdateIndustryProduction(i);
00890           this->SetDirty();
00891           this->flags4 |= WF_TIMEOUT_BEGIN;
00892           this->clicked_line = line;
00893           this->clicked_button = button;
00894         } else if (IsInsideMM(pt.x, left + 30, right)) {
00895           /* clicked the text */
00896           this->editbox_line = line;
00897           switch (this->editable) {
00898             case EA_MULTIPLIER:
00899               SetDParam(0, RoundDivSU(i->prod_level * 100, PRODLEVEL_DEFAULT));
00900               ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION_LEVEL, 10, this, CS_ALPHANUMERAL, QSF_NONE);
00901               break;
00902 
00903             case EA_RATE:
00904               SetDParam(0, i->production_rate[line - IL_RATE1] * 8);
00905               ShowQueryString(STR_JUST_INT, STR_CONFIG_GAME_PRODUCTION, 10, this, CS_ALPHANUMERAL, QSF_NONE);
00906               break;
00907 
00908             default: NOT_REACHED();
00909           }
00910         }
00911         break;
00912       }
00913 
00914       case IVW_GOTO: {
00915         Industry *i = Industry::Get(this->window_number);
00916         if (_ctrl_pressed) {
00917           ShowExtraViewPortWindow(i->location.GetCenterTile());
00918         } else {
00919           ScrollMainWindowToTile(i->location.GetCenterTile());
00920         }
00921         break;
00922       }
00923 
00924       case IVW_DISPLAY: {
00925         Industry *i = Industry::Get(this->window_number);
00926         ShowIndustryCargoesWindow(i->type);
00927         break;
00928       }
00929     }
00930   }
00931 
00932   virtual void OnTimeout()
00933   {
00934     this->clicked_line = IL_NONE;
00935     this->clicked_button = 0;
00936     this->SetDirty();
00937   }
00938 
00939   virtual void OnResize()
00940   {
00941     if (this->viewport != NULL) {
00942       NWidgetViewport *nvp = this->GetWidget<NWidgetViewport>(IVW_VIEWPORT);
00943       nvp->UpdateViewportCoordinates(this);
00944 
00945       ScrollWindowToTile(Industry::Get(this->window_number)->location.GetCenterTile(), this, true); // Re-center viewport.
00946     }
00947   }
00948 
00949   virtual void OnQueryTextFinished(char *str)
00950   {
00951     if (StrEmpty(str)) return;
00952 
00953     Industry *i = Industry::Get(this->window_number);
00954     uint value = atoi(str);
00955     switch (this->editbox_line) {
00956       case IL_NONE: NOT_REACHED();
00957 
00958       case IL_MULTIPLIER:
00959         i->prod_level = ClampU(RoundDivSU(value * PRODLEVEL_DEFAULT, 100), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
00960         break;
00961 
00962       default:
00963         i->production_rate[this->editbox_line - IL_RATE1] = ClampU(RoundDivSU(value, 8), 0, 255);
00964         break;
00965     }
00966     UpdateIndustryProduction(i);
00967     this->SetDirty();
00968   }
00969 
00975   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
00976   {
00977     if (!gui_scope) return;
00978     const Industry *i = Industry::Get(this->window_number);
00979     if (IsProductionAlterable(i)) {
00980       const IndustrySpec *ind = GetIndustrySpec(i->type);
00981       this->editable = ind->UsesSmoothEconomy() ? EA_RATE : EA_MULTIPLIER;
00982     } else {
00983       this->editable = EA_NONE;
00984     }
00985 
00986     /* Rebuild destination list if data is not zero, otherwise just resort. */
00987     if (data != 0) {
00988       this->dest_list.InvalidateData();
00989     } else {
00990       this->dest_list.Resort();
00991     }
00992   }
00993 
00994   virtual bool IsNewGRFInspectable() const
00995   {
00996     return ::IsNewGRFInspectable(GSF_INDUSTRIES, this->window_number);
00997   }
00998 
00999   virtual void ShowNewGRFInspectWindow() const
01000   {
01001 		::ShowNewGRFInspectWindow(GSF_INDUSTRIES, this->window_number);
01002   }
01003 };
01004 
01005 static void UpdateIndustryProduction(Industry *i)
01006 {
01007   const IndustrySpec *indspec = GetIndustrySpec(i->type);
01008   if (!indspec->UsesSmoothEconomy()) i->RecomputeProductionMultipliers();
01009 
01010   for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
01011     if (i->produced_cargo[j] != CT_INVALID) {
01012       i->last_month_production[j] = 8 * i->production_rate[j];
01013     }
01014   }
01015 }
01016 
01018 static const NWidgetPart _nested_industry_view_widgets[] = {
01019   NWidget(NWID_HORIZONTAL),
01020     NWidget(WWT_CLOSEBOX, COLOUR_CREAM),
01021     NWidget(WWT_CAPTION, COLOUR_CREAM, IVW_CAPTION), SetDataTip(STR_INDUSTRY_VIEW_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01022     NWidget(WWT_DEBUGBOX, COLOUR_CREAM),
01023     NWidget(WWT_SHADEBOX, COLOUR_CREAM),
01024     NWidget(WWT_STICKYBOX, COLOUR_CREAM),
01025   EndContainer(),
01026   NWidget(WWT_PANEL, COLOUR_CREAM),
01027     NWidget(WWT_INSET, COLOUR_CREAM), SetPadding(2, 2, 2, 2),
01028       NWidget(NWID_VIEWPORT, INVALID_COLOUR, IVW_VIEWPORT), SetMinimalSize(254, 86), SetFill(1, 0), SetPadding(1, 1, 1, 1), SetResize(1, 1),
01029     EndContainer(),
01030   EndContainer(),
01031   NWidget(WWT_PANEL, COLOUR_CREAM, IVW_INFO), SetMinimalSize(260, 2), SetResize(1, 0),
01032   EndContainer(),
01033   NWidget(NWID_HORIZONTAL),
01034     NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, IVW_GOTO), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_BUTTON_LOCATION, STR_INDUSTRY_VIEW_LOCATION_TOOLTIP),
01035     NWidget(WWT_PUSHTXTBTN, COLOUR_CREAM, IVW_DISPLAY), SetFill(1, 0), SetResize(1, 0), SetDataTip(STR_INDUSTRY_DISPLAY_CHAIN, STR_INDUSTRY_DISPLAY_CHAIN_TOOLTIP),
01036     NWidget(WWT_RESIZEBOX, COLOUR_CREAM),
01037   EndContainer(),
01038 };
01039 
01041 static const WindowDesc _industry_view_desc(
01042   WDP_AUTO, 260, 120,
01043   WC_INDUSTRY_VIEW, WC_NONE,
01044   WDF_UNCLICK_BUTTONS,
01045   _nested_industry_view_widgets, lengthof(_nested_industry_view_widgets)
01046 );
01047 
01048 void ShowIndustryViewWindow(int industry)
01049 {
01050   AllocateWindowDescFront<IndustryViewWindow>(&_industry_view_desc, industry);
01051 }
01052 
01054 enum IndustryDirectoryWidgets {
01055   IDW_DROPDOWN_ORDER,
01056   IDW_DROPDOWN_CRITERIA,
01057   IDW_INDUSTRY_LIST,
01058   IDW_SCROLLBAR,
01059 };
01060 
01062 static const NWidgetPart _nested_industry_directory_widgets[] = {
01063   NWidget(NWID_HORIZONTAL),
01064     NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
01065     NWidget(WWT_CAPTION, COLOUR_BROWN), SetDataTip(STR_INDUSTRY_DIRECTORY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01066     NWidget(WWT_SHADEBOX, COLOUR_BROWN),
01067     NWidget(WWT_STICKYBOX, COLOUR_BROWN),
01068   EndContainer(),
01069   NWidget(NWID_HORIZONTAL),
01070     NWidget(NWID_VERTICAL),
01071       NWidget(NWID_HORIZONTAL),
01072         NWidget(WWT_TEXTBTN, COLOUR_BROWN, IDW_DROPDOWN_ORDER), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER),
01073         NWidget(WWT_DROPDOWN, COLOUR_BROWN, IDW_DROPDOWN_CRITERIA), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
01074         NWidget(WWT_PANEL, COLOUR_BROWN), SetResize(1, 0), EndContainer(),
01075       EndContainer(),
01076       NWidget(WWT_PANEL, COLOUR_BROWN, IDW_INDUSTRY_LIST), SetDataTip(0x0, STR_INDUSTRY_DIRECTORY_LIST_CAPTION), SetResize(1, 1), SetScrollbar(IDW_SCROLLBAR), EndContainer(),
01077     EndContainer(),
01078     NWidget(NWID_VERTICAL),
01079       NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, IDW_SCROLLBAR),
01080       NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
01081     EndContainer(),
01082   EndContainer(),
01083 };
01084 
01085 typedef GUIList<const Industry*> GUIIndustryList;
01086 
01087 
01091 class IndustryDirectoryWindow : public Window {
01092 protected:
01093   /* Runtime saved values */
01094   static Listing last_sorting;
01095   static const Industry *last_industry;
01096 
01097   /* Constants for sorting stations */
01098   static const StringID sorter_names[];
01099   static GUIIndustryList::SortFunction * const sorter_funcs[];
01100 
01101   GUIIndustryList industries;
01102   Scrollbar *vscroll;
01103 
01105   void BuildSortIndustriesList()
01106   {
01107     if (this->industries.NeedRebuild()) {
01108       this->industries.Clear();
01109 
01110       const Industry *i;
01111       FOR_ALL_INDUSTRIES(i) {
01112         *this->industries.Append() = i;
01113       }
01114 
01115       this->industries.Compact();
01116       this->industries.RebuildDone();
01117       this->vscroll->SetCount(this->industries.Length()); // Update scrollbar as well.
01118     }
01119 
01120     if (!this->industries.Sort()) return;
01121     IndustryDirectoryWindow::last_industry = NULL; // Reset name sorter sort cache
01122     this->SetWidgetDirty(IDW_INDUSTRY_LIST); // Set the modified widget dirty
01123   }
01124 
01132   static inline int GetCargoTransportedPercentsIfValid(const Industry *i, uint id)
01133   {
01134     assert(id < lengthof(i->produced_cargo));
01135 
01136     if (i->produced_cargo[id] == CT_INVALID) return 101;
01137     return ToPercent8(i->last_month_pct_transported[id]);
01138   }
01139 
01147   static int GetCargoTransportedSortValue(const Industry *i)
01148   {
01149     int p1 = GetCargoTransportedPercentsIfValid(i, 0);
01150     int p2 = GetCargoTransportedPercentsIfValid(i, 1);
01151 
01152     if (p1 > p2) Swap(p1, p2); // lower value has higher priority
01153 
01154     return (p1 << 8) + p2;
01155   }
01156 
01158   static int CDECL IndustryNameSorter(const Industry * const *a, const Industry * const *b)
01159   {
01160     static char buf_cache[96];
01161     static char buf[96];
01162 
01163     SetDParam(0, (*a)->index);
01164     GetString(buf, STR_INDUSTRY_NAME, lastof(buf));
01165 
01166     if (*b != last_industry) {
01167       last_industry = *b;
01168       SetDParam(0, (*b)->index);
01169       GetString(buf_cache, STR_INDUSTRY_NAME, lastof(buf_cache));
01170     }
01171 
01172     return strnatcmp(buf, buf_cache); // Sort by name (natural sorting).
01173   }
01174 
01176   static int CDECL IndustryTypeSorter(const Industry * const *a, const Industry * const *b)
01177   {
01178     int it_a = 0;
01179     while (it_a != NUM_INDUSTRYTYPES && (*a)->type != _sorted_industry_types[it_a]) it_a++;
01180     int it_b = 0;
01181     while (it_b != NUM_INDUSTRYTYPES && (*b)->type != _sorted_industry_types[it_b]) it_b++;
01182     int r = it_a - it_b;
01183     return (r == 0) ? IndustryNameSorter(a, b) : r;
01184   }
01185 
01187   static int CDECL IndustryProductionSorter(const Industry * const *a, const Industry * const *b)
01188   {
01189     uint prod_a = 0, prod_b = 0;
01190     for (uint i = 0; i < lengthof((*a)->produced_cargo); i++) {
01191       if ((*a)->produced_cargo[i] != CT_INVALID) prod_a += (*a)->last_month_production[i];
01192       if ((*b)->produced_cargo[i] != CT_INVALID) prod_b += (*b)->last_month_production[i];
01193     }
01194     int r = prod_a - prod_b;
01195 
01196     return (r == 0) ? IndustryTypeSorter(a, b) : r;
01197   }
01198 
01200   static int CDECL IndustryTransportedCargoSorter(const Industry * const *a, const Industry * const *b)
01201   {
01202     int r = GetCargoTransportedSortValue(*a) - GetCargoTransportedSortValue(*b);
01203     return (r == 0) ? IndustryNameSorter(a, b) : r;
01204   }
01205 
01211   StringID GetIndustryString(const Industry *i) const
01212   {
01213     const IndustrySpec *indsp = GetIndustrySpec(i->type);
01214     byte p = 0;
01215 
01216     /* Industry name */
01217     SetDParam(p++, i->index);
01218 
01219     static char cargo_suffix[lengthof(i->produced_cargo)][512];
01220     GetAllCargoSuffixes(3, CST_DIR, i, i->type, indsp, i->produced_cargo, cargo_suffix);
01221 
01222     /* Industry productions */
01223     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
01224       if (i->produced_cargo[j] == CT_INVALID) continue;
01225       SetDParam(p++, i->produced_cargo[j]);
01226       SetDParam(p++, i->last_month_production[j]);
01227       SetDParamStr(p++, cargo_suffix[j]);
01228     }
01229 
01230     /* Transported productions */
01231     for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
01232       if (i->produced_cargo[j] == CT_INVALID) continue;
01233       SetDParam(p++, ToPercent8(i->last_month_pct_transported[j]));
01234     }
01235 
01236     /* Drawing the right string */
01237     switch (p) {
01238       case 1:  return STR_INDUSTRY_DIRECTORY_ITEM_NOPROD;
01239       case 5:  return STR_INDUSTRY_DIRECTORY_ITEM;
01240       default: return STR_INDUSTRY_DIRECTORY_ITEM_TWO;
01241     }
01242   }
01243 
01244 public:
01245   IndustryDirectoryWindow(const WindowDesc *desc, WindowNumber number) : Window()
01246   {
01247     this->CreateNestedTree(desc);
01248     this->vscroll = this->GetScrollbar(IDW_SCROLLBAR);
01249 
01250     this->industries.SetListing(this->last_sorting);
01251     this->industries.SetSortFuncs(IndustryDirectoryWindow::sorter_funcs);
01252     this->industries.ForceRebuild();
01253     this->BuildSortIndustriesList();
01254 
01255     this->FinishInitNested(desc, 0);
01256   }
01257 
01258   ~IndustryDirectoryWindow()
01259   {
01260     this->last_sorting = this->industries.GetListing();
01261   }
01262 
01263   virtual void SetStringParameters(int widget) const
01264   {
01265     if (widget == IDW_DROPDOWN_CRITERIA) SetDParam(0, IndustryDirectoryWindow::sorter_names[this->industries.SortType()]);
01266   }
01267 
01268   virtual void DrawWidget(const Rect &r, int widget) const
01269   {
01270     switch (widget) {
01271       case IDW_DROPDOWN_ORDER:
01272         this->DrawSortButtonState(widget, this->industries.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
01273         break;
01274 
01275       case IDW_INDUSTRY_LIST: {
01276         int n = 0;
01277         int y = r.top + WD_FRAMERECT_TOP;
01278         if (this->industries.Length() == 0) {
01279           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, STR_INDUSTRY_DIRECTORY_NONE);
01280           break;
01281         }
01282         for (uint i = this->vscroll->GetPosition(); i < this->industries.Length(); i++) {
01283           DrawString(r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, y, this->GetIndustryString(this->industries[i]));
01284 
01285           y += this->resize.step_height;
01286           if (++n == this->vscroll->GetCapacity()) break; // max number of industries in 1 window
01287         }
01288         break;
01289       }
01290     }
01291   }
01292 
01293   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
01294   {
01295     switch (widget) {
01296       case IDW_DROPDOWN_ORDER: {
01297         Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
01298         d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
01299         d.height += padding.height;
01300         *size = maxdim(*size, d);
01301         break;
01302       }
01303 
01304       case IDW_DROPDOWN_CRITERIA: {
01305         Dimension d = {0, 0};
01306         for (uint i = 0; IndustryDirectoryWindow::sorter_names[i] != INVALID_STRING_ID; i++) {
01307           d = maxdim(d, GetStringBoundingBox(IndustryDirectoryWindow::sorter_names[i]));
01308         }
01309         d.width += padding.width;
01310         d.height += padding.height;
01311         *size = maxdim(*size, d);
01312         break;
01313       }
01314 
01315       case IDW_INDUSTRY_LIST: {
01316         Dimension d = GetStringBoundingBox(STR_INDUSTRY_DIRECTORY_NONE);
01317         for (uint i = 0; i < this->industries.Length(); i++) {
01318           d = maxdim(d, GetStringBoundingBox(this->GetIndustryString(this->industries[i])));
01319         }
01320         resize->height = d.height;
01321         d.height *= 5;
01322         d.width += padding.width + WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT;
01323         d.height += padding.height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
01324         *size = maxdim(*size, d);
01325         break;
01326       }
01327     }
01328   }
01329 
01330 
01331   virtual void OnClick(Point pt, int widget, int click_count)
01332   {
01333     switch (widget) {
01334       case IDW_DROPDOWN_ORDER:
01335         this->industries.ToggleSortOrder();
01336         this->SetDirty();
01337         break;
01338 
01339       case IDW_DROPDOWN_CRITERIA:
01340         ShowDropDownMenu(this, IndustryDirectoryWindow::sorter_names, this->industries.SortType(), IDW_DROPDOWN_CRITERIA, 0, 0);
01341         break;
01342 
01343       case IDW_INDUSTRY_LIST: {
01344         uint p = this->vscroll->GetScrolledRowFromWidget(pt.y, this, IDW_INDUSTRY_LIST, WD_FRAMERECT_TOP);
01345         if (p < this->industries.Length()) {
01346           if (_ctrl_pressed) {
01347             ShowExtraViewPortWindow(this->industries[p]->location.tile);
01348           } else {
01349             ScrollMainWindowToTile(this->industries[p]->location.tile);
01350           }
01351         }
01352         break;
01353       }
01354     }
01355   }
01356 
01357   virtual void OnDropdownSelect(int widget, int index)
01358   {
01359     if (this->industries.SortType() != index) {
01360       this->industries.SetSortType(index);
01361       this->BuildSortIndustriesList();
01362     }
01363   }
01364 
01365   virtual void OnResize()
01366   {
01367     this->vscroll->SetCapacityFromWidget(this, IDW_INDUSTRY_LIST);
01368   }
01369 
01370   virtual void OnPaint()
01371   {
01372     if (this->industries.NeedRebuild()) this->BuildSortIndustriesList();
01373     this->DrawWidgets();
01374   }
01375 
01376   virtual void OnHundredthTick()
01377   {
01378     this->industries.ForceResort();
01379     this->BuildSortIndustriesList();
01380   }
01381 
01387   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
01388   {
01389     if (data == 0) {
01390       /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
01391       this->industries.ForceRebuild();
01392     } else {
01393       this->industries.ForceResort();
01394     }
01395   }
01396 };
01397 
01398 Listing IndustryDirectoryWindow::last_sorting = {false, 0};
01399 const Industry *IndustryDirectoryWindow::last_industry = NULL;
01400 
01401 /* Available station sorting functions. */
01402 GUIIndustryList::SortFunction * const IndustryDirectoryWindow::sorter_funcs[] = {
01403   &IndustryNameSorter,
01404   &IndustryTypeSorter,
01405   &IndustryProductionSorter,
01406   &IndustryTransportedCargoSorter
01407 };
01408 
01409 /* Names of the sorting functions */
01410 const StringID IndustryDirectoryWindow::sorter_names[] = {
01411   STR_SORT_BY_NAME,
01412   STR_SORT_BY_TYPE,
01413   STR_SORT_BY_PRODUCTION,
01414   STR_SORT_BY_TRANSPORTED,
01415   INVALID_STRING_ID
01416 };
01417 
01418 
01420 static const WindowDesc _industry_directory_desc(
01421   WDP_AUTO, 428, 190,
01422   WC_INDUSTRY_DIRECTORY, WC_NONE,
01423   WDF_UNCLICK_BUTTONS,
01424   _nested_industry_directory_widgets, lengthof(_nested_industry_directory_widgets)
01425 );
01426 
01427 void ShowIndustryDirectory()
01428 {
01429   AllocateWindowDescFront<IndustryDirectoryWindow>(&_industry_directory_desc, 0);
01430 }
01431 
01433 enum IndustryCargoesWidgets {
01434   ICW_CAPTION,
01435   ICW_NOTIFY,
01436   ICW_PANEL,
01437   ICW_SCROLLBAR,
01438 };
01439 
01441 static const NWidgetPart _nested_industry_cargoes_widgets[] = {
01442   NWidget(NWID_HORIZONTAL),
01443     NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
01444     NWidget(WWT_CAPTION, COLOUR_BROWN, ICW_CAPTION), SetDataTip(STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
01445     NWidget(WWT_SHADEBOX, COLOUR_BROWN),
01446     NWidget(WWT_STICKYBOX, COLOUR_BROWN),
01447   EndContainer(),
01448   NWidget(NWID_HORIZONTAL),
01449     NWidget(NWID_VERTICAL),
01450       NWidget(WWT_PANEL, COLOUR_BROWN, ICW_PANEL), SetResize(1, 10), SetMinimalSize(200, 90), SetScrollbar(ICW_SCROLLBAR), EndContainer(),
01451       NWidget(NWID_HORIZONTAL),
01452         NWidget(WWT_TEXTBTN, COLOUR_BROWN, ICW_NOTIFY),
01453           SetDataTip(STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP, STR_INDUSTRY_CARGOES_NOTIFY_SMALLMAP_TOOLTIP),
01454         NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 0), SetResize(1, 0), EndContainer(),
01455       EndContainer(),
01456     EndContainer(),
01457     NWidget(NWID_VERTICAL),
01458       NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, ICW_SCROLLBAR),
01459       NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
01460     EndContainer(),
01461   EndContainer(),
01462 };
01463 
01465 static const WindowDesc _industry_cargoes_desc(
01466   WDP_AUTO, 300, 210,
01467   WC_INDUSTRY_CARGOES, WC_NONE,
01468   0,
01469   _nested_industry_cargoes_widgets, lengthof(_nested_industry_cargoes_widgets)
01470 );
01471 
01473 enum CargoesFieldType {
01474   CFT_EMPTY,       
01475   CFT_SMALL_EMPTY, 
01476   CFT_INDUSTRY,    
01477   CFT_CARGO,       
01478   CFT_CARGO_LABEL, 
01479   CFT_HEADER,      
01480 };
01481 
01482 static const uint MAX_CARGOES = 3; 
01483 
01485 struct CargoesField {
01486   static const int VERT_INTER_INDUSTRY_SPACE;
01487   static const int HOR_CARGO_BORDER_SPACE;
01488   static const int CARGO_STUB_WIDTH;
01489   static const int HOR_CARGO_WIDTH, HOR_CARGO_SPACE;
01490   static const int CARGO_FIELD_WIDTH;
01491   static const int VERT_CARGO_SPACE, VERT_CARGO_EDGE;
01492   static const int BLOB_DISTANCE, BLOB_WIDTH, BLOB_HEIGHT;
01493 
01494   static const int INDUSTRY_LINE_COLOUR;
01495   static const int CARGO_LINE_COLOUR;
01496 
01497   static int small_height, normal_height;
01498   static int industry_width;
01499 
01500   CargoesFieldType type; 
01501   union {
01502     struct {
01503       IndustryType ind_type;                 
01504       CargoID other_produced[MAX_CARGOES];   
01505       CargoID other_accepted[MAX_CARGOES];   
01506     } industry; 
01507     struct {
01508       CargoID vertical_cargoes[MAX_CARGOES]; 
01509       byte num_cargoes;                      
01510       CargoID supp_cargoes[MAX_CARGOES];     
01511       byte top_end;                          
01512       CargoID cust_cargoes[MAX_CARGOES];     
01513       byte bottom_end;                       
01514     } cargo; 
01515     struct {
01516       CargoID cargoes[MAX_CARGOES];          
01517       bool left_align;                       
01518     } cargo_label;   
01519     StringID header; 
01520   } u; // Data for each type.
01521 
01526   void MakeEmpty(CargoesFieldType type)
01527   {
01528     this->type = type;
01529   }
01530 
01536   void MakeIndustry(IndustryType ind_type)
01537   {
01538     this->type = CFT_INDUSTRY;
01539     this->u.industry.ind_type = ind_type;
01540     MemSetT(this->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
01541     MemSetT(this->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
01542   }
01543 
01550   int ConnectCargo(CargoID cargo, bool producer)
01551   {
01552     assert(this->type == CFT_CARGO);
01553     if (cargo == INVALID_CARGO) return -1;
01554 
01555     /* Find the vertical cargo column carrying the cargo. */
01556     int column = -1;
01557     for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
01558       if (cargo == this->u.cargo.vertical_cargoes[i]) {
01559         column = i;
01560         break;
01561       }
01562     }
01563     if (column < 0) return -1;
01564 
01565     if (producer) {
01566       assert(this->u.cargo.supp_cargoes[column] == INVALID_CARGO);
01567       this->u.cargo.supp_cargoes[column]  = column;
01568     } else {
01569       assert(this->u.cargo.cust_cargoes[column] == INVALID_CARGO);
01570       this->u.cargo.cust_cargoes[column] = column;
01571     }
01572     return column;
01573   }
01574 
01579   bool HasConnection()
01580   {
01581     assert(this->type == CFT_CARGO);
01582 
01583     for (uint i = 0; i < MAX_CARGOES; i++) {
01584       if (this->u.cargo.supp_cargoes[i] != INVALID_CARGO) return true;
01585       if (this->u.cargo.cust_cargoes[i] != INVALID_CARGO) return true;
01586     }
01587     return false;
01588   }
01589 
01599   void MakeCargo(const CargoID *cargoes, uint length, int count = -1, bool top_end = false, bool bottom_end = false)
01600   {
01601     this->type = CFT_CARGO;
01602     uint i;
01603     uint num = 0;
01604     for (i = 0; i < MAX_CARGOES && i < length; i++) {
01605       if (cargoes[i] != INVALID_CARGO) {
01606         this->u.cargo.vertical_cargoes[num] = cargoes[i];
01607         num++;
01608       }
01609     }
01610     this->u.cargo.num_cargoes = (count < 0) ? num : count;
01611     for (; num < MAX_CARGOES; num++) this->u.cargo.vertical_cargoes[num] = INVALID_CARGO;
01612     this->u.cargo.top_end = top_end;
01613     this->u.cargo.bottom_end = bottom_end;
01614     MemSetT(this->u.cargo.supp_cargoes, INVALID_CARGO, MAX_CARGOES);
01615     MemSetT(this->u.cargo.cust_cargoes, INVALID_CARGO, MAX_CARGOES);
01616   }
01617 
01624   void MakeCargoLabel(const CargoID *cargoes, uint length, bool left_align)
01625   {
01626     this->type = CFT_CARGO_LABEL;
01627     uint i;
01628     for (i = 0; i < MAX_CARGOES && i < length; i++) this->u.cargo_label.cargoes[i] = cargoes[i];
01629     for (; i < MAX_CARGOES; i++) this->u.cargo_label.cargoes[i] = INVALID_CARGO;
01630     this->u.cargo_label.left_align = left_align;
01631   }
01632 
01637   void MakeHeader(StringID textid)
01638   {
01639     this->type = CFT_HEADER;
01640     this->u.header = textid;
01641   }
01642 
01648   int GetCargoBase(int xpos) const
01649   {
01650     assert(this->type == CFT_CARGO);
01651 
01652     switch (this->u.cargo.num_cargoes) {
01653       case 0: return xpos + CARGO_FIELD_WIDTH / 2;
01654       case 1: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH / 2;
01655       case 2: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE / 2;
01656       case 3: return xpos + CARGO_FIELD_WIDTH / 2 - HOR_CARGO_WIDTH - HOR_CARGO_SPACE - HOR_CARGO_WIDTH / 2;
01657       default: NOT_REACHED();
01658     }
01659   }
01660 
01666   void Draw(int xpos, int ypos) const
01667   {
01668     switch (this->type) {
01669       case CFT_EMPTY:
01670       case CFT_SMALL_EMPTY:
01671         break;
01672 
01673       case CFT_HEADER:
01674         ypos += (small_height - FONT_HEIGHT_NORMAL) / 2;
01675         DrawString(xpos, xpos + industry_width, ypos, this->u.header, TC_WHITE, SA_HOR_CENTER);
01676         break;
01677 
01678       case CFT_INDUSTRY: {
01679         int ypos1 = ypos + VERT_INTER_INDUSTRY_SPACE / 2;
01680         int ypos2 = ypos + normal_height - 1 - VERT_INTER_INDUSTRY_SPACE / 2;
01681         int xpos2 = xpos + industry_width - 1;
01682         GfxDrawLine(xpos,  ypos1, xpos2, ypos1, INDUSTRY_LINE_COLOUR);
01683         GfxDrawLine(xpos,  ypos1, xpos,  ypos2, INDUSTRY_LINE_COLOUR);
01684         GfxDrawLine(xpos,  ypos2, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
01685         GfxDrawLine(xpos2, ypos1, xpos2, ypos2, INDUSTRY_LINE_COLOUR);
01686         ypos += (normal_height - FONT_HEIGHT_NORMAL) / 2;
01687         if (this->u.industry.ind_type < NUM_INDUSTRYTYPES) {
01688           const IndustrySpec *indsp = GetIndustrySpec(this->u.industry.ind_type);
01689           SetDParam(0, indsp->name);
01690           DrawString(xpos, xpos2, ypos, STR_JUST_STRING, TC_WHITE, SA_HOR_CENTER);
01691 
01692           /* Draw the industry legend. */
01693           int blob_left, blob_right;
01694           if (_current_text_dir == TD_RTL) {
01695             blob_right = xpos2 - BLOB_DISTANCE;
01696             blob_left  = blob_right - BLOB_WIDTH;
01697           } else {
01698             blob_left  = xpos + BLOB_DISTANCE;
01699             blob_right = blob_left + BLOB_WIDTH;
01700           }
01701           GfxFillRect(blob_left,     ypos2 - BLOB_DISTANCE - BLOB_HEIGHT,     blob_right,     ypos2 - BLOB_DISTANCE,     PC_BLACK); // Border
01702           GfxFillRect(blob_left + 1, ypos2 - BLOB_DISTANCE - BLOB_HEIGHT + 1, blob_right - 1, ypos2 - BLOB_DISTANCE - 1, indsp->map_colour);
01703         } else {
01704           DrawString(xpos, xpos2, ypos, STR_INDUSTRY_CARGOES_HOUSES, TC_FROMSTRING, SA_HOR_CENTER);
01705         }
01706 
01707         /* Draw the other_produced/other_accepted cargoes. */
01708         const CargoID *other_right, *other_left;
01709         if (_current_text_dir == TD_RTL) {
01710           other_right = this->u.industry.other_accepted;
01711           other_left  = this->u.industry.other_produced;
01712         } else {
01713           other_right = this->u.industry.other_produced;
01714           other_left  = this->u.industry.other_accepted;
01715         }
01716         ypos1 += VERT_CARGO_EDGE;
01717         for (uint i = 0; i < MAX_CARGOES; i++) {
01718           if (other_right[i] != INVALID_CARGO) {
01719             const CargoSpec *csp = CargoSpec::Get(other_right[i]);
01720             int xp = xpos + industry_width + CARGO_STUB_WIDTH;
01721             DrawHorConnection(xpos + industry_width, xp - 1, ypos1, csp);
01722             GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
01723           }
01724           if (other_left[i] != INVALID_CARGO) {
01725             const CargoSpec *csp = CargoSpec::Get(other_left[i]);
01726             int xp = xpos - CARGO_STUB_WIDTH;
01727             DrawHorConnection(xp + 1, xpos - 1, ypos1, csp);
01728             GfxDrawLine(xp, ypos1, xp, ypos1 + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
01729           }
01730           ypos1 += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01731         }
01732         break;
01733       }
01734 
01735       case CFT_CARGO: {
01736         int cargo_base = this->GetCargoBase(xpos);
01737         int top = ypos + (this->u.cargo.top_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0);
01738         int bot = ypos - (this->u.cargo.bottom_end ? VERT_INTER_INDUSTRY_SPACE / 2 + 1 : 0) + normal_height - 1;
01739         int colpos = cargo_base;
01740         for (int i = 0; i < this->u.cargo.num_cargoes; i++) {
01741           if (this->u.cargo.top_end) GfxDrawLine(colpos, top - 1, colpos + HOR_CARGO_WIDTH - 1, top - 1, CARGO_LINE_COLOUR);
01742           if (this->u.cargo.bottom_end) GfxDrawLine(colpos, bot + 1, colpos + HOR_CARGO_WIDTH - 1, bot + 1, CARGO_LINE_COLOUR);
01743           GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
01744           colpos++;
01745           const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[i]);
01746           GfxFillRect(colpos, top, colpos + HOR_CARGO_WIDTH - 2, bot, csp->legend_colour, FILLRECT_OPAQUE);
01747           colpos += HOR_CARGO_WIDTH - 2;
01748           GfxDrawLine(colpos, top, colpos, bot, CARGO_LINE_COLOUR);
01749           colpos += 1 + HOR_CARGO_SPACE;
01750         }
01751 
01752         const CargoID *hor_left, *hor_right;
01753         if (_current_text_dir == TD_RTL) {
01754           hor_left  = this->u.cargo.cust_cargoes;
01755           hor_right = this->u.cargo.supp_cargoes;
01756         } else {
01757           hor_left  = this->u.cargo.supp_cargoes;
01758           hor_right = this->u.cargo.cust_cargoes;
01759         }
01760         ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
01761         for (uint i = 0; i < MAX_CARGOES; i++) {
01762           if (hor_left[i] != INVALID_CARGO) {
01763             int col = hor_left[i];
01764             int dx = 0;
01765             const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
01766             for (; col > 0; col--) {
01767               int lf = cargo_base + col * HOR_CARGO_WIDTH + (col - 1) * HOR_CARGO_SPACE;
01768               DrawHorConnection(lf, lf + HOR_CARGO_SPACE - dx, ypos, csp);
01769               dx = 1;
01770             }
01771             DrawHorConnection(xpos, cargo_base - dx, ypos, csp);
01772           }
01773           if (hor_right[i] != INVALID_CARGO) {
01774             int col = hor_right[i];
01775             int dx = 0;
01776             const CargoSpec *csp = CargoSpec::Get(this->u.cargo.vertical_cargoes[col]);
01777             for (; col < this->u.cargo.num_cargoes - 1; col++) {
01778               int lf = cargo_base + (col + 1) * HOR_CARGO_WIDTH + col * HOR_CARGO_SPACE;
01779               DrawHorConnection(lf + dx - 1, lf + HOR_CARGO_SPACE - 1, ypos, csp);
01780               dx = 1;
01781             }
01782             DrawHorConnection(cargo_base + col * HOR_CARGO_SPACE + (col + 1) * HOR_CARGO_WIDTH - 1 + dx, xpos + CARGO_FIELD_WIDTH - 1, ypos, csp);
01783           }
01784           ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01785         }
01786         break;
01787       }
01788 
01789       case CFT_CARGO_LABEL:
01790         ypos += VERT_CARGO_EDGE + VERT_INTER_INDUSTRY_SPACE / 2;
01791         for (uint i = 0; i < MAX_CARGOES; i++) {
01792           if (this->u.cargo_label.cargoes[i] != INVALID_CARGO) {
01793             const CargoSpec *csp = CargoSpec::Get(this->u.cargo_label.cargoes[i]);
01794             DrawString(xpos + WD_FRAMERECT_LEFT, xpos + industry_width - 1 - WD_FRAMERECT_RIGHT, ypos, csp->name, TC_WHITE,
01795                 (this->u.cargo_label.left_align) ? SA_LEFT : SA_RIGHT);
01796           }
01797           ypos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01798         }
01799         break;
01800 
01801       default:
01802         NOT_REACHED();
01803     }
01804   }
01805 
01813   CargoID CargoClickedAt(const CargoesField *left, const CargoesField *right, Point pt) const
01814   {
01815     assert(this->type == CFT_CARGO);
01816 
01817     /* Vertical matching. */
01818     int cpos = this->GetCargoBase(0);
01819     uint col;
01820     for (col = 0; col < this->u.cargo.num_cargoes; col++) {
01821       if (pt.x < cpos) break;
01822       if (pt.x < cpos + CargoesField::HOR_CARGO_WIDTH) return this->u.cargo.vertical_cargoes[col];
01823       cpos += CargoesField::HOR_CARGO_WIDTH + CargoesField::HOR_CARGO_SPACE;
01824     }
01825     /* col = 0 -> left of first col, 1 -> left of 2nd col, ... this->u.cargo.num_cargoes right of last-col. */
01826 
01827     int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
01828     uint row;
01829     for (row = 0; row < MAX_CARGOES; row++) {
01830       if (pt.y < vpos) return INVALID_CARGO;
01831       if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
01832       vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01833     }
01834     if (row == MAX_CARGOES) return INVALID_CARGO;
01835 
01836     /* row = 0 -> at first horizontal row, row = 1 -> second horizontal row, 2 = 3rd horizontal row. */
01837     if (col == 0) {
01838       if (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]];
01839       if (left != NULL) {
01840         if (left->type == CFT_INDUSTRY) return left->u.industry.other_produced[row];
01841         if (left->type == CFT_CARGO_LABEL && !left->u.cargo_label.left_align) return left->u.cargo_label.cargoes[row];
01842       }
01843       return INVALID_CARGO;
01844     }
01845     if (col == this->u.cargo.num_cargoes) {
01846       if (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) return this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]];
01847       if (right != NULL) {
01848         if (right->type == CFT_INDUSTRY) return right->u.industry.other_accepted[row];
01849         if (right->type == CFT_CARGO_LABEL && right->u.cargo_label.left_align) return right->u.cargo_label.cargoes[row];
01850       }
01851       return INVALID_CARGO;
01852     }
01853     if (row >= col) {
01854       /* Clicked somewhere in-between vertical cargo connection.
01855        * Since the horizontal connection is made in the same order as the vertical list, the above condition
01856        * ensures we are left-below the main diagonal, thus at the supplying side.
01857        */
01858       return (this->u.cargo.supp_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.supp_cargoes[row]] : INVALID_CARGO;
01859     } else {
01860       /* Clicked at a customer connection. */
01861       return (this->u.cargo.cust_cargoes[row] != INVALID_CARGO) ? this->u.cargo.vertical_cargoes[this->u.cargo.cust_cargoes[row]] : INVALID_CARGO;
01862     }
01863   }
01864 
01870   CargoID CargoLabelClickedAt(Point pt) const
01871   {
01872     assert(this->type == CFT_CARGO_LABEL);
01873 
01874     int vpos = VERT_INTER_INDUSTRY_SPACE / 2 + VERT_CARGO_EDGE;
01875     uint row;
01876     for (row = 0; row < MAX_CARGOES; row++) {
01877       if (pt.y < vpos) return INVALID_CARGO;
01878       if (pt.y < vpos + FONT_HEIGHT_NORMAL) break;
01879       vpos += FONT_HEIGHT_NORMAL + VERT_CARGO_SPACE;
01880     }
01881     if (row == MAX_CARGOES) return INVALID_CARGO;
01882     return this->u.cargo_label.cargoes[row];
01883   }
01884 
01885 private:
01893   static void DrawHorConnection(int left, int right, int top, const CargoSpec *csp)
01894   {
01895     GfxDrawLine(left, top, right, top, CARGO_LINE_COLOUR);
01896     GfxFillRect(left, top + 1, right, top + FONT_HEIGHT_NORMAL - 2, csp->legend_colour, FILLRECT_OPAQUE);
01897     GfxDrawLine(left, top + FONT_HEIGHT_NORMAL - 1, right, top + FONT_HEIGHT_NORMAL - 1, CARGO_LINE_COLOUR);
01898   }
01899 };
01900 
01901 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, produced_cargo));
01902 assert_compile(MAX_CARGOES >= cpp_lengthof(IndustrySpec, accepts_cargo));
01903 
01904 int CargoesField::small_height;   
01905 int CargoesField::normal_height;  
01906 int CargoesField::industry_width; 
01907 const int CargoesField::VERT_INTER_INDUSTRY_SPACE = 6; 
01908 
01909 const int CargoesField::HOR_CARGO_BORDER_SPACE = 15; 
01910 const int CargoesField::CARGO_STUB_WIDTH       = 10; 
01911 const int CargoesField::HOR_CARGO_WIDTH        = 15; 
01912 const int CargoesField::HOR_CARGO_SPACE        =  5; 
01913 const int CargoesField::VERT_CARGO_EDGE        =  4; 
01914 const int CargoesField::VERT_CARGO_SPACE       =  4; 
01915 
01916 const int CargoesField::BLOB_DISTANCE =  5; 
01917 const int CargoesField::BLOB_WIDTH    = 12; 
01918 const int CargoesField::BLOB_HEIGHT   =  9; 
01919 
01921 const int CargoesField::CARGO_FIELD_WIDTH = HOR_CARGO_BORDER_SPACE * 2 + HOR_CARGO_WIDTH * MAX_CARGOES + HOR_CARGO_SPACE * (MAX_CARGOES - 1);
01922 
01923 const int CargoesField::INDUSTRY_LINE_COLOUR = PC_YELLOW; 
01924 const int CargoesField::CARGO_LINE_COLOUR    = PC_YELLOW; 
01925 
01927 struct CargoesRow {
01928   CargoesField columns[5]; 
01929 
01934   void ConnectIndustryProduced(int column)
01935   {
01936     CargoesField *ind_fld   = this->columns + column;
01937     CargoesField *cargo_fld = this->columns + column + 1;
01938     assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
01939 
01940     MemSetT(ind_fld->u.industry.other_produced, INVALID_CARGO, MAX_CARGOES);
01941 
01942     if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
01943       CargoID others[MAX_CARGOES]; // Produced cargoes not carried in the cargo column.
01944       int other_count = 0;
01945 
01946       const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
01947       for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
01948         int col = cargo_fld->ConnectCargo(indsp->produced_cargo[i], true);
01949         if (col < 0) others[other_count++] = indsp->produced_cargo[i];
01950       }
01951 
01952       /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
01953       for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
01954         if (cargo_fld->u.cargo.supp_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_produced[i] = others[--other_count];
01955       }
01956     } else {
01957       /* Houses only display what is demanded. */
01958       for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
01959         CargoID cid = cargo_fld->u.cargo.vertical_cargoes[i];
01960         if (cid == CT_PASSENGERS || cid == CT_MAIL) cargo_fld->ConnectCargo(cid, true);
01961       }
01962     }
01963   }
01964 
01970   void MakeCargoLabel(int column, bool accepting)
01971   {
01972     CargoID cargoes[MAX_CARGOES];
01973     MemSetT(cargoes, INVALID_CARGO, lengthof(cargoes));
01974 
01975     CargoesField *label_fld = this->columns + column;
01976     CargoesField *cargo_fld = this->columns + (accepting ? column - 1 : column + 1);
01977 
01978     assert(cargo_fld->type == CFT_CARGO && label_fld->type == CFT_EMPTY);
01979     for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
01980       int col = cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], !accepting);
01981       cargoes[col] = cargo_fld->u.cargo.vertical_cargoes[i];
01982     }
01983     label_fld->MakeCargoLabel(cargoes, lengthof(cargoes), accepting);
01984   }
01985 
01986 
01991   void ConnectIndustryAccepted(int column)
01992   {
01993     CargoesField *ind_fld   = this->columns + column;
01994     CargoesField *cargo_fld = this->columns + column - 1;
01995     assert(ind_fld->type == CFT_INDUSTRY && cargo_fld->type == CFT_CARGO);
01996 
01997     MemSetT(ind_fld->u.industry.other_accepted, INVALID_CARGO, MAX_CARGOES);
01998 
01999     if (ind_fld->u.industry.ind_type < NUM_INDUSTRYTYPES) {
02000       CargoID others[MAX_CARGOES]; // Accepted cargoes not carried in the cargo column.
02001       int other_count = 0;
02002 
02003       const IndustrySpec *indsp = GetIndustrySpec(ind_fld->u.industry.ind_type);
02004       for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
02005         int col = cargo_fld->ConnectCargo(indsp->accepts_cargo[i], false);
02006         if (col < 0) others[other_count++] = indsp->accepts_cargo[i];
02007       }
02008 
02009       /* Allocate other cargoes in the empty holes of the horizontal cargo connections. */
02010       for (uint i = 0; i < MAX_CARGOES && other_count > 0; i++) {
02011         if (cargo_fld->u.cargo.cust_cargoes[i] == INVALID_CARGO) ind_fld->u.industry.other_accepted[i] = others[--other_count];
02012       }
02013     } else {
02014       /* Houses only display what is demanded. */
02015       for (uint i = 0; i < cargo_fld->u.cargo.num_cargoes; i++) {
02016         for (uint h = 0; h < HOUSE_MAX; h++) {
02017           HouseSpec *hs = HouseSpec::Get(h);
02018           if (!hs->enabled) continue;
02019 
02020           for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
02021             if (cargo_fld->u.cargo.vertical_cargoes[i] == hs->accepts_cargo[j]) {
02022               cargo_fld->ConnectCargo(cargo_fld->u.cargo.vertical_cargoes[i], false);
02023               goto next_cargo;
02024             }
02025           }
02026         }
02027 next_cargo: ;
02028       }
02029     }
02030   }
02031 };
02032 
02033 
02061 struct IndustryCargoesWindow : public Window {
02062   static const int HOR_TEXT_PADDING, VERT_TEXT_PADDING;
02063 
02064   typedef SmallVector<CargoesRow, 4> Fields;
02065 
02066   Fields fields;  
02067   uint ind_cargo; 
02068 
02069   Scrollbar *vscroll;
02070 
02071   IndustryCargoesWindow(int id) : Window()
02072   {
02073     this->OnInit();
02074     this->CreateNestedTree(&_industry_cargoes_desc);
02075     this->vscroll = this->GetScrollbar(ICW_SCROLLBAR);
02076     this->FinishInitNested(&_industry_cargoes_desc, 0);
02077     this->OnInvalidateData(id);
02078   }
02079 
02080   virtual void OnInit()
02081   {
02082     /* Initialize static CargoesField size variables. */
02083     Dimension d = GetStringBoundingBox(STR_INDUSTRY_CARGOES_PRODUCERS);
02084     d = maxdim(d, GetStringBoundingBox(STR_INDUSTRY_CARGOES_CUSTOMERS));
02085     d.width  += WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT;
02086     d.height += WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM;
02087     CargoesField::small_height = d.height;
02088 
02089     /* Decide about the size of the box holding the text of an industry type. */
02090     d.height = 0;
02091     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02092       const IndustrySpec *indsp = GetIndustrySpec(it);
02093       if (!indsp->enabled) continue;
02094       SetDParam(0, indsp->name);
02095       d = maxdim(d, GetStringBoundingBox(STR_JUST_STRING));
02096     }
02097     /* Box must also be wide enough to hold any cargo label. */
02098     for (uint i = 0; i < NUM_CARGO; i++) {
02099       const CargoSpec *csp = CargoSpec::Get(i);
02100       if (!csp->IsValid()) continue;
02101       d = maxdim(d, GetStringBoundingBox(csp->name));
02102     }
02103     d.width  += 2 * HOR_TEXT_PADDING;
02104     /* Ensure the height is enough for the industry type text, for the horizontal connections, and for the cargo labels. */
02105     uint min_ind_height = CargoesField::VERT_CARGO_EDGE * 2 + MAX_CARGOES * FONT_HEIGHT_NORMAL + (MAX_CARGOES - 1) *  CargoesField::VERT_CARGO_SPACE;
02106     d.height = max(d.height + 2 * VERT_TEXT_PADDING, min_ind_height);
02107 
02108     CargoesField::industry_width = d.width;
02109     CargoesField::normal_height = d.height + CargoesField::VERT_INTER_INDUSTRY_SPACE;
02110   }
02111 
02112   virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
02113   {
02114     if (widget != ICW_PANEL) return;
02115 
02116     size->width = WD_FRAMETEXT_LEFT + CargoesField::industry_width * 3 + CargoesField::CARGO_FIELD_WIDTH * 2 + WD_FRAMETEXT_RIGHT;
02117   }
02118 
02119 
02120   CargoesFieldType type; 
02121   virtual void SetStringParameters  (int widget) const
02122   {
02123     if (widget != ICW_CAPTION) return;
02124 
02125     if (this->ind_cargo < NUM_INDUSTRYTYPES) {
02126       const IndustrySpec *indsp = GetIndustrySpec(this->ind_cargo);
02127       SetDParam(0, indsp->name);
02128     } else {
02129       const CargoSpec *csp = CargoSpec::Get(this->ind_cargo - NUM_INDUSTRYTYPES);
02130       SetDParam(0, csp->name);
02131     }
02132   }
02133 
02142   static bool HasCommonValidCargo(const CargoID *cargoes1, uint length1, const CargoID *cargoes2, uint length2)
02143   {
02144     while (length1 > 0) {
02145       if (*cargoes1 != INVALID_CARGO) {
02146         for (uint i = 0; i < length2; i++) if (*cargoes1 == cargoes2[i]) return true;
02147       }
02148       cargoes1++;
02149       length1--;
02150     }
02151     return false;
02152   }
02153 
02160   static bool HousesCanSupply(const CargoID *cargoes, uint length)
02161   {
02162     for (uint i = 0; i < length; i++) {
02163       if (cargoes[i] == INVALID_CARGO) continue;
02164       if (cargoes[i] == CT_PASSENGERS || cargoes[i] == CT_MAIL) return true;
02165     }
02166     return false;
02167   }
02168 
02175   static bool HousesCanAccept(const CargoID *cargoes, uint length)
02176   {
02177     HouseZones climate_mask;
02178     switch (_settings_game.game_creation.landscape) {
02179       case LT_TEMPERATE: climate_mask = HZ_TEMP; break;
02180       case LT_ARCTIC:    climate_mask = HZ_SUBARTC_ABOVE | HZ_SUBARTC_BELOW; break;
02181       case LT_TROPIC:    climate_mask = HZ_SUBTROPIC; break;
02182       case LT_TOYLAND:   climate_mask = HZ_TOYLND; break;
02183       default: NOT_REACHED();
02184     }
02185     for (uint i = 0; i < length; i++) {
02186       if (cargoes[i] == INVALID_CARGO) continue;
02187 
02188       for (uint h = 0; h < HOUSE_MAX; h++) {
02189         HouseSpec *hs = HouseSpec::Get(h);
02190         if (!hs->enabled || !(hs->building_availability & climate_mask)) continue;
02191 
02192         for (uint j = 0; j < lengthof(hs->accepts_cargo); j++) {
02193           if (cargoes[i] == hs->accepts_cargo[j]) return true;
02194         }
02195       }
02196     }
02197     return false;
02198   }
02199 
02206   static int CountMatchingAcceptingIndustries(const CargoID *cargoes, uint length)
02207   {
02208     int count = 0;
02209     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02210       const IndustrySpec *indsp = GetIndustrySpec(it);
02211       if (!indsp->enabled) continue;
02212 
02213       if (HasCommonValidCargo(cargoes, length, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) count++;
02214     }
02215     return count;
02216   }
02217 
02224   static int CountMatchingProducingIndustries(const CargoID *cargoes, uint length)
02225   {
02226     int count = 0;
02227     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02228       const IndustrySpec *indsp = GetIndustrySpec(it);
02229       if (!indsp->enabled) continue;
02230 
02231       if (HasCommonValidCargo(cargoes, length, indsp->produced_cargo, lengthof(indsp->produced_cargo))) count++;
02232     }
02233     return count;
02234   }
02235 
02242   void ShortenCargoColumn(int column, int top, int bottom)
02243   {
02244     while (top < bottom && !this->fields[top].columns[column].HasConnection()) {
02245       this->fields[top].columns[column].MakeEmpty(CFT_EMPTY);
02246       top++;
02247     }
02248     this->fields[top].columns[column].u.cargo.top_end = true;
02249 
02250     while (bottom > top && !this->fields[bottom].columns[column].HasConnection()) {
02251       this->fields[bottom].columns[column].MakeEmpty(CFT_EMPTY);
02252       bottom--;
02253     }
02254     this->fields[bottom].columns[column].u.cargo.bottom_end = true;
02255   }
02256 
02263   void PlaceIndustry(int row, int col, IndustryType it)
02264   {
02265     assert(this->fields[row].columns[col].type == CFT_EMPTY);
02266     this->fields[row].columns[col].MakeIndustry(it);
02267     if (col == 0) {
02268       this->fields[row].ConnectIndustryProduced(col);
02269     } else {
02270       this->fields[row].ConnectIndustryAccepted(col);
02271     }
02272   }
02273 
02277   void NotifySmallmap()
02278   {
02279     if (!this->IsWidgetLowered(ICW_NOTIFY)) return;
02280 
02281     /* Only notify the smallmap window if it exists. In particular, do not
02282      * bring it to the front to prevent messing up any nice layout of the user. */
02283     InvalidateWindowClassesData(WC_SMALLMAP, 0);
02284   }
02285 
02290   void ComputeIndustryDisplay(IndustryType it)
02291   {
02292     this->GetWidget<NWidgetCore>(ICW_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_INDUSTRY_CAPTION;
02293     this->ind_cargo = it;
02294     _displayed_industries = 1ULL << it;
02295 
02296     this->fields.Clear();
02297     CargoesRow *row = this->fields.Append();
02298     row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
02299     row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
02300     row->columns[2].MakeEmpty(CFT_SMALL_EMPTY);
02301     row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
02302     row->columns[4].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
02303 
02304     const IndustrySpec *central_sp = GetIndustrySpec(it);
02305     bool houses_supply = HousesCanSupply(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
02306     bool houses_accept = HousesCanAccept(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
02307     /* Make a field consisting of two cargo columns. */
02308     int num_supp = CountMatchingProducingIndustries(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo)) + houses_supply;
02309     int num_cust = CountMatchingAcceptingIndustries(central_sp->produced_cargo, lengthof(central_sp->produced_cargo)) + houses_accept;
02310     int num_indrows = max(3, max(num_supp, num_cust)); // One is needed for the 'it' industry, and 2 for the cargo labels.
02311     for (int i = 0; i < num_indrows; i++) {
02312       CargoesRow *row = this->fields.Append();
02313       row->columns[0].MakeEmpty(CFT_EMPTY);
02314       row->columns[1].MakeCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo));
02315       row->columns[2].MakeEmpty(CFT_EMPTY);
02316       row->columns[3].MakeCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo));
02317       row->columns[4].MakeEmpty(CFT_EMPTY);
02318     }
02319     /* Add central industry. */
02320     int central_row = 1 + num_indrows / 2;
02321     this->fields[central_row].columns[2].MakeIndustry(it);
02322     this->fields[central_row].ConnectIndustryProduced(2);
02323     this->fields[central_row].ConnectIndustryAccepted(2);
02324 
02325     /* Add cargo labels. */
02326     this->fields[central_row - 1].MakeCargoLabel(2, true);
02327     this->fields[central_row + 1].MakeCargoLabel(2, false);
02328 
02329     /* Add suppliers and customers of the 'it' industry. */
02330     int supp_count = 0;
02331     int cust_count = 0;
02332     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02333       const IndustrySpec *indsp = GetIndustrySpec(it);
02334       if (!indsp->enabled) continue;
02335 
02336       if (HasCommonValidCargo(central_sp->accepts_cargo, lengthof(central_sp->accepts_cargo), indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
02337         this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
02338         SetBit(_displayed_industries, it);
02339         supp_count++;
02340       }
02341       if (HasCommonValidCargo(central_sp->produced_cargo, lengthof(central_sp->produced_cargo), indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
02342         this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, it);
02343         SetBit(_displayed_industries, it);
02344         cust_count++;
02345       }
02346     }
02347     if (houses_supply) {
02348       this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
02349       supp_count++;
02350     }
02351     if (houses_accept) {
02352       this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 4, NUM_INDUSTRYTYPES);
02353       cust_count++;
02354     }
02355 
02356     this->ShortenCargoColumn(1, 1, num_indrows);
02357     this->ShortenCargoColumn(3, 1, num_indrows);
02358     const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(ICW_PANEL);
02359     this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
02360     this->SetDirty();
02361     this->NotifySmallmap();
02362   }
02363 
02368   void ComputeCargoDisplay(CargoID cid)
02369   {
02370     this->GetWidget<NWidgetCore>(ICW_CAPTION)->widget_data = STR_INDUSTRY_CARGOES_CARGO_CAPTION;
02371     this->ind_cargo = cid + NUM_INDUSTRYTYPES;
02372     _displayed_industries = 0;
02373 
02374     this->fields.Clear();
02375     CargoesRow *row = this->fields.Append();
02376     row->columns[0].MakeHeader(STR_INDUSTRY_CARGOES_PRODUCERS);
02377     row->columns[1].MakeEmpty(CFT_SMALL_EMPTY);
02378     row->columns[2].MakeHeader(STR_INDUSTRY_CARGOES_CUSTOMERS);
02379     row->columns[3].MakeEmpty(CFT_SMALL_EMPTY);
02380     row->columns[4].MakeEmpty(CFT_SMALL_EMPTY);
02381 
02382     bool houses_supply = HousesCanSupply(&cid, 1);
02383     bool houses_accept = HousesCanAccept(&cid, 1);
02384     int num_supp = CountMatchingProducingIndustries(&cid, 1) + houses_supply + 1; // Ensure room for the cargo label.
02385     int num_cust = CountMatchingAcceptingIndustries(&cid, 1) + houses_accept;
02386     int num_indrows = max(num_supp, num_cust);
02387     for (int i = 0; i < num_indrows; i++) {
02388       CargoesRow *row = this->fields.Append();
02389       row->columns[0].MakeEmpty(CFT_EMPTY);
02390       row->columns[1].MakeCargo(&cid, 1);
02391       row->columns[2].MakeEmpty(CFT_EMPTY);
02392       row->columns[3].MakeEmpty(CFT_EMPTY);
02393       row->columns[4].MakeEmpty(CFT_EMPTY);
02394     }
02395 
02396     this->fields[num_indrows].MakeCargoLabel(0, false); // Add cargo labels at the left bottom.
02397 
02398     /* Add suppliers and customers of the cargo. */
02399     int supp_count = 0;
02400     int cust_count = 0;
02401     for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
02402       const IndustrySpec *indsp = GetIndustrySpec(it);
02403       if (!indsp->enabled) continue;
02404 
02405       if (HasCommonValidCargo(&cid, 1, indsp->produced_cargo, lengthof(indsp->produced_cargo))) {
02406         this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, it);
02407         SetBit(_displayed_industries, it);
02408         supp_count++;
02409       }
02410       if (HasCommonValidCargo(&cid, 1, indsp->accepts_cargo, lengthof(indsp->accepts_cargo))) {
02411         this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, it);
02412         SetBit(_displayed_industries, it);
02413         cust_count++;
02414       }
02415     }
02416     if (houses_supply) {
02417       this->PlaceIndustry(1 + supp_count * num_indrows / num_supp, 0, NUM_INDUSTRYTYPES);
02418       supp_count++;
02419     }
02420     if (houses_accept) {
02421       this->PlaceIndustry(1 + cust_count * num_indrows / num_cust, 2, NUM_INDUSTRYTYPES);
02422       cust_count++;
02423     }
02424 
02425     this->ShortenCargoColumn(1, 1, num_indrows);
02426     const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(ICW_PANEL);
02427     this->vscroll->SetCount(CeilDiv(WD_FRAMETEXT_TOP + WD_FRAMETEXT_BOTTOM + CargoesField::small_height + num_indrows * CargoesField::normal_height, nwp->resize_y));
02428     this->SetDirty();
02429     this->NotifySmallmap();
02430   }
02431 
02439   virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
02440   {
02441     if (!gui_scope) return;
02442     if (data == NUM_INDUSTRYTYPES) {
02443       if (this->IsWidgetLowered(ICW_NOTIFY)) {
02444         this->RaiseWidget(ICW_NOTIFY);
02445         this->SetWidgetDirty(ICW_NOTIFY);
02446       }
02447       return;
02448     }
02449 
02450     assert(data >= 0 && data < NUM_INDUSTRYTYPES);
02451     this->ComputeIndustryDisplay(data);
02452   }
02453 
02454   virtual void DrawWidget(const Rect &r, int widget) const
02455   {
02456     if (widget != ICW_PANEL) return;
02457 
02458     DrawPixelInfo tmp_dpi, *old_dpi;
02459     int width = r.right - r.left + 1;
02460     int height = r.bottom - r.top + 1 - WD_FRAMERECT_TOP - WD_FRAMERECT_BOTTOM;
02461     if (!FillDrawPixelInfo(&tmp_dpi, r.left + WD_FRAMERECT_LEFT, r.top + WD_FRAMERECT_TOP, width, height)) return;
02462     old_dpi = _cur_dpi;
02463     _cur_dpi = &tmp_dpi;
02464 
02465     int left_pos = WD_FRAMERECT_LEFT;
02466     if (this->ind_cargo >= NUM_INDUSTRYTYPES) left_pos += (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2;
02467     int last_column = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
02468 
02469     const NWidgetBase *nwp = this->GetWidget<NWidgetBase>(ICW_PANEL);
02470     int vpos = -this->vscroll->GetPosition() * nwp->resize_y;
02471     for (uint i = 0; i < this->fields.Length(); i++) {
02472       int row_height = (i == 0) ? CargoesField::small_height : CargoesField::normal_height;
02473       if (vpos + row_height >= 0) {
02474         int xpos = left_pos;
02475         int col, dir;
02476         if (_current_text_dir == TD_RTL) {
02477           col = last_column;
02478           dir = -1;
02479         } else {
02480           col = 0;
02481           dir = 1;
02482         }
02483         while (col >= 0 && col <= last_column) {
02484           this->fields[i].columns[col].Draw(xpos, vpos);
02485           xpos += (col & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
02486           col += dir;
02487         }
02488       }
02489       vpos += row_height;
02490       if (vpos >= height) break;
02491     }
02492 
02493     _cur_dpi = old_dpi;
02494   }
02495 
02503   bool CalculatePositionInWidget(Point pt, Point *fieldxy, Point *xy)
02504   {
02505     const NWidgetBase *nw = this->GetWidget<NWidgetBase>(ICW_PANEL);
02506     pt.x -= nw->pos_x;
02507     pt.y -= nw->pos_y;
02508 
02509     int vpos = WD_FRAMERECT_TOP + CargoesField::small_height - this->vscroll->GetPosition() * nw->resize_y;
02510     if (pt.y < vpos) return false;
02511 
02512     int row = (pt.y - vpos) / CargoesField::normal_height; // row is relative to row 1.
02513     if (row + 1 >= (int)this->fields.Length()) return false;
02514     vpos = pt.y - vpos - row * CargoesField::normal_height; // Position in the row + 1 field
02515     row++; // rebase row to match index of this->fields.
02516 
02517     int xpos = 2 * WD_FRAMERECT_LEFT + ((this->ind_cargo < NUM_INDUSTRYTYPES) ? 0 :  (CargoesField::industry_width + CargoesField::CARGO_FIELD_WIDTH) / 2);
02518     if (pt.x < xpos) return false;
02519     int column;
02520     for (column = 0; column <= 5; column++) {
02521       int width = (column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width;
02522       if (pt.x < xpos + width) break;
02523       xpos += width;
02524     }
02525     int num_columns = (this->ind_cargo < NUM_INDUSTRYTYPES) ? 4 : 2;
02526     if (column > num_columns) return false;
02527     xpos = pt.x - xpos;
02528 
02529     /* Return both positions, compensating for RTL languages (which works due to the equal symmetry in both displays). */
02530     fieldxy->y = row;
02531     xy->y = vpos;
02532     if (_current_text_dir == TD_RTL) {
02533       fieldxy->x = num_columns - column;
02534       xy->x = ((column & 1) ? CargoesField::CARGO_FIELD_WIDTH : CargoesField::industry_width) - xpos;
02535     } else {
02536       fieldxy->x = column;
02537       xy->x = xpos;
02538     }
02539     return true;
02540   }
02541 
02542   virtual void OnClick(Point pt, int widget, int click_count)
02543   {
02544     switch (widget) {
02545       case ICW_PANEL: {
02546         Point fieldxy, xy;
02547         if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
02548 
02549         const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
02550         switch (fld->type) {
02551           case CFT_INDUSTRY:
02552             if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES) this->ComputeIndustryDisplay(fld->u.industry.ind_type);
02553             break;
02554 
02555           case CFT_CARGO: {
02556             CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
02557             CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
02558             CargoID cid = fld->CargoClickedAt(lft, rgt, xy);
02559             if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
02560             break;
02561           }
02562 
02563           case CFT_CARGO_LABEL: {
02564             CargoID cid = fld->CargoLabelClickedAt(xy);
02565             if (cid != INVALID_CARGO) this->ComputeCargoDisplay(cid);
02566             break;
02567           }
02568 
02569           default:
02570             break;
02571         }
02572         break;
02573       }
02574 
02575       case ICW_NOTIFY:
02576         this->ToggleWidgetLoweredState(ICW_NOTIFY);
02577         this->SetWidgetDirty(ICW_NOTIFY);
02578         SndPlayFx(SND_15_BEEP);
02579 
02580         if (this->IsWidgetLowered(ICW_NOTIFY)) {
02581           if (FindWindowByClass(WC_SMALLMAP) == NULL) ShowSmallMap();
02582           this->NotifySmallmap();
02583         }
02584         break;
02585     }
02586   }
02587 
02588   virtual void OnHover(Point pt, int widget)
02589   {
02590     if (widget != ICW_PANEL) return;
02591 
02592     Point fieldxy, xy;
02593     if (!CalculatePositionInWidget(pt, &fieldxy, &xy)) return;
02594 
02595     const CargoesField *fld = this->fields[fieldxy.y].columns + fieldxy.x;
02596     CargoID cid = INVALID_CARGO;
02597     switch (fld->type) {
02598       case CFT_CARGO: {
02599         CargoesField *lft = (fieldxy.x > 0) ? this->fields[fieldxy.y].columns + fieldxy.x - 1 : NULL;
02600         CargoesField *rgt = (fieldxy.x < 4) ? this->fields[fieldxy.y].columns + fieldxy.x + 1 : NULL;
02601         cid = fld->CargoClickedAt(lft, rgt, xy);
02602         break;
02603       }
02604 
02605       case CFT_CARGO_LABEL: {
02606         cid = fld->CargoLabelClickedAt(xy);
02607         break;
02608       }
02609 
02610       case CFT_INDUSTRY:
02611         if (fld->u.industry.ind_type < NUM_INDUSTRYTYPES && (this->ind_cargo >= NUM_INDUSTRYTYPES || fieldxy.x != 2)) {
02612           GuiShowTooltips(this, STR_INDUSTRY_CARGOES_INDUSTRY_TOOLTIP, 0, NULL, TCC_HOVER);
02613         }
02614         return;
02615 
02616       default:
02617         break;
02618     }
02619     if (cid != INVALID_CARGO && (this->ind_cargo < NUM_INDUSTRYTYPES || cid != this->ind_cargo - NUM_INDUSTRYTYPES)) {
02620       const CargoSpec *csp = CargoSpec::Get(cid);
02621       uint64 params[5];
02622       params[0] = csp->name;
02623       GuiShowTooltips(this, STR_INDUSTRY_CARGOES_CARGO_TOOLTIP, 1, params, TCC_HOVER);
02624     }
02625   }
02626 
02627   virtual void OnResize()
02628   {
02629     this->vscroll->SetCapacityFromWidget(this, ICW_PANEL);
02630   }
02631 };
02632 
02633 const int IndustryCargoesWindow::HOR_TEXT_PADDING  = 5; 
02634 const int IndustryCargoesWindow::VERT_TEXT_PADDING = 5; 
02635 
02640 static void ShowIndustryCargoesWindow(IndustryType id)
02641 {
02642   assert(id < NUM_INDUSTRYTYPES);
02643 
02644   Window *w = BringWindowToFrontById(WC_INDUSTRY_CARGOES, 0);
02645   if (w != NULL) {
02646     w->InvalidateData(id);
02647     return;
02648   }
02649   new IndustryCargoesWindow(id);
02650 }

Generated on Sun May 8 07:30:13 2011 for OpenTTD by  doxygen 1.6.1