Ticket #3707: t3707_repair_cost2.diff

File t3707_repair_cost2.diff, 2.5 KB (added by bb, 8 years ago)
  • binaries/data/mods/public/simulation/components/Repairable.js

     
    11function Repairable() {}
    22
     3var g_CostMultiplier = 0.5
     4
    35Repairable.prototype.Schema =
    46    "<a:help>Deals with repairable structures and units.</a:help>" +
    57    "<a:example>" +
     
    1315{
    1416    this.builders = []; // builder entities
    1517    this.buildMultiplier = 1; // Multiplier for the amount of work builders do.
     18    this.costsToPay = { "food": 0, "wood": 0, "metal": 0, "stone": 0 };
    1619    this.repairTimeRatio = +this.template.RepairTimeRatio;
    1720};
    1821
     
    5053        this.buildMultiplier = Math.pow(numBuilders, 0.7) / numBuilders;
    5154};
    5255
    53 // TODO: should we have resource costs?
    5456Repairable.prototype.Repair = function(builderEnt, rate)
    5557{
    5658    let cmpHealth = Engine.QueryInterface(this.entity, IID_Health);
    5759    let cmpCost = Engine.QueryInterface(this.entity, IID_Cost);
    58     if (!cmpHealth || !cmpCost)
     60    let cmpPlayer = QueryOwnerInterface(this.entity);
     61    if (!cmpHealth || !cmpCost || !cmpPlayer)
    5962        return;
    6063    let damage = cmpHealth.GetMaxHitpoints() - cmpHealth.GetHitpoints();
    6164    if (damage <= 0)
     
    6467    // Calculate the amount of hitpoints that will be added (using diminishing rate when several builders)
    6568    let work = rate * this.buildMultiplier * this.GetRepairRate();
    6669    let amount = Math.min(damage, work);
    67     cmpHealth.Increase(amount);
    6870
    69     // If we repaired all the damage, send a message to entities to stop repairing this building
    70     if (amount >= damage)
     71    // Calculate resource costs for the added hitpoints
     72    let newPrice = cmpCost.GetResourceCosts();
     73    let resourcesToSubtract = {};
     74    for (let type in newPrice)
     75    {
     76        this.costsToPay[type] += g_CostMultiplier * newPrice[type] * amount / cmpHealth.GetMaxHitpoints();
     77        resourcesToSubtract[type] = Math.floor(this.costsToPay[type]);
     78        this.costsToPay[type] -= resourcesToSubtract[type];
     79    }
     80
     81    // TrySubtractResources should report error to player (if they ran out of resources)
     82    let affordable = cmpPlayer.TrySubtractResources(resourcesToSubtract)
     83    if (affordable)
     84        cmpHealth.Increase(amount);
     85
     86    // If we repaired all the damage or ran out of resource, send a message to entities to stop repairing this building
     87    if (amount >= damage || !affordable)
    7188        Engine.PostMessage(this.entity, MT_ConstructionFinished, { "entity": this.entity, "newentity": this.entity });
    7289};
    7390