"require" issue [Resolved]

Place to get help with not working mods / modding interface.
User avatar
Ranakastrasz
Smart Inserter
Smart Inserter
Posts: 2174
Joined: Thu Jun 12, 2014 3:05 am
Contact:

"require" issue [Resolved]

Post by Ranakastrasz »

I attempted to split a config file off of the main control file. While it now works normally with a new game or one without the mod having ran before, loading it from an existing game causes a gamecrash around 3 seconds after loading. The error message is "Unexpected error"

The old file and the two new ones.

Code: Select all

require "defines"

--[[
    This module handles the gameloop alteration, allowing conduit modules in power armor grid to tranfer energy between your power grid and your armor.

]]--

--[[
Charging Module Icon
Artist: Treetog ArtWork (Available for custom work)
Iconset: Junior Icons (146 icons)
License: Free for personal desktop use only.
Commercial usage: Not allowed
]]--

--[[          Gen , Size, Gen/size
    Conduit :  250kw,  1x1, 150  kw  
    Solar 1 :   75kw,  1x1,  75  kw  *0.7  52.5kw
    Solar 2 : 1000kw,  3x3, 111.1kw *0.7 77.7kw
    Burner  :  500kw,  2x2, 125  kw
    Fusion  : 5000Mw,  4x4, 312.5kw
    
    
           Energy , duration
    Wood  :  4 MJ ,  40
    Coal  :  8 MJ ,  80
    Fuel  : 25 MJ , 250

    Fusion: 112.5 MJ, 120
    
    
]]--
--[[
    Figure out if you can access energy network with the get network command thinggy.
    Alternately, do aura search, steal power from accumulators and roboports.
    
    Add command to disable conduit mechanics.
    -Shield pulse visial
    -Better Energy Distribution
    -Sheld autobalance
    -Boost batteries. Add higher tier,larger battery(s) /Done
    -Finish tech fixing
    -Add GUI display for fuel.
    -Add custom fuel slot.
    -Method to discharge energy into network?
    -Better energy distribution
    -Shield autobalance
]]--
local Debug = false

local surface = game.surfaces['nauvis']

local tickRate = 1
local ticksPerSecond = 60
local secondsPerTick = tickRate/ticksPerSecond -- To avoid division operations in a loop
--local conversionRatio = 1.0                         -- Internal armor has values 1/1000th of the normal power network. As of 0.12, it is now a ratio of 10
--local conversionAntiRatio = 1.0/conversionRatio        -- avoid division
local accumulatorEnergyCap = 5. * 1000 * 1000       -- 100 slots, 20/slot + 80, 2080 transfer rate, 5mil should be sufficient.. This must match accumulator dummy power capacity.

local ArmorTransferRatePerGridSize    = (250.0/25)  * 1000 * secondsPerTick -- with 50/25, 50 At T1, 98 @ T2, 200 @ t3
local ConduitTransferRatePerEquipment = 250. * 1000 * secondsPerTick
--local ShieldDecayPerTick              = (1./100.) * secondsPerTick

--local SteamFuelRatePerEquipment       = 
--local FusionFuelRatePerEquipment      = 

local fuelCoef = 1.0

local fuelValues =
{
    [1] = {
        type = "engine-equipment",
        name = "burner",
        power = 500. * 1000 * secondsPerTick,       -- Production per tick at max rate
        threshhold = 0.9,                      -- Power must be below this value for this type of generator to run
        {[1] = {"solid-fuel", 25.*1000*1000*fuelCoef}}, -- Value of each fuel type.
        {[2] = {"coal"      ,  8.*1000*1000*fuelCoef}}, 
        {[3] = {"raw-wood"  ,  4.*1000*1000*fuelCoef}},
    },
    [2] = {
        type = "fusion-reactor-equipment",
        name = "fusion",
        threshhold = 0.5,
        power = 4500. * 1000 * secondsPerTick, -- actually 5000k, but 500k is always active.
        {[1] = {"alien-fuel", 100.*1000*1000*fuelCoef}},
    }
}

local priorities = 
{
    {
        type = "input",
        {[1] = "primary-input" },
        {[2] = "secondary-input" },
    },
    {
        type = "output",
        {[1] = "primary-output"},
        {[2] = "secondary-output"},
    }
}

--[[remote.addinterface("ModularArmor", {
    reset = function()
		global.ticking = nil
        
        --global.modularArmor = {}
    end
})]]--


function verifySettings()
	if (tickRate < 0) then
		tickRate = 0
		throwError("Tick rate must be >= 0.")
	end
end

function onload()  -- this function 
       -- globalPrint("onLoad")
	if (global.loaded == nil) then
		global.loaded = true
       -- globalPrint("loaded")
        
		verifySettings()
	end
    
    if (not global.modularArmor) then
        global.modularArmor = {}
    end
    if (global.ticking == nil) then
        global.ticking = 0
    end
    game.on_event(defines.events.on_tick, ticker)
end

game.on_init(onload)
game.on_load(onload)


function globalPrint(msg)
  local players = game.players
  if Debug then
      for i=1, #players do
        players[i].print(msg)
      end
  end
end


function tableIsEmpty(t)
	if (t) then
		for k in pairs(t) do
			return false
		end
	end
	return true
end

function ticker() -- run once per tickRate number of gameticks.
	if (global.ticking == 0) then
		global.ticking = tickRate - 1
		tick()
	else
		global.ticking = global.ticking - 1
	end
end

function tickDummies(id,positionz)

    if not id.units then
        id.units = {}
    else
        -- Already exists.
    end
    if not id.units.accumulator then
        id.units.accumulator = surface.create_entity{name = "laser-turret-dummy", position = positionz, force=game.forces.player}
        id.units.accumulator.energy = accumulatorEnergyCap -- initialize energy levels
        id.previousEnergy = accumulatorEnergyCap -- and previous energy level from last tick
        id.units.accumulator.destructible = false -- Make dummy invulnerable.
    else
        id.units.accumulator.teleport(positionz) -- Ensure that the power drain dummy is always at the player's position.
    end
    
    if not id.units.pole then
        id.units.pole = surface.create_entity{name = "electric-pole-dummy", position = positionz, force=game.forces.player}
        id.units.pole.destructible = false
    else
        id.units.pole.teleport(positionz)
    end
    
    if not id.units.solar then
        id.units.solar = surface.create_entity{name = "solar-panel-dummy", position = positionz, force=game.forces.player}
        id.units.solar.destructible = false
    else
        id.units.solar.teleport(positionz)
    end
end
function killDummies(id)
    if id.units then
        if id.units.accumulator then
            id.units.accumulator.destroy()
            id.units.accumulator = nil
        else
            -- Already gone
        end
        if id.units.pole then
            id.units.pole.destroy()
            id.units.pole = nil
        else
            -- Already gone
        end
        if id.units.solar then
            id.units.solar.destroy()
            id.units.solar = nil
        else
          -- Already gone
        end
    else
        -- Already deleted.
    end
end
function tick()
	local shouldKeepTicking
    local thisPlayer = nil
    local players = game.players
        --globalPrint("tick")
    shouldKeepTicking = true -- Due to lack of any alternate method of detecting player's armor state, we have to always tick.

    for i=1, #players do
        thisPlayer = players[i]
        if (thisPlayer.character) then
            --game.getplayer(1).print(i..' '..player)
            
            --if not global.modularArmor[i] then
            --    global.modularArmor[i] = {}
            --end
            local modularArmor = global.modularArmor[i]
            
            if (not modularArmor) then
                
                modularArmor = {} -- ensure player has data attached
                --modularArmor.storedFuel = {["steam"] = 0, ["fusion"] = 0}
                global.modularArmor[i] = modularArmor
                
                if (Debug == true) then
            
                    game.always_day=true -- test mode stuff
                    thisPlayer.insert{name="basic-grenade",count=50}
                    thisPlayer.insert{name="energy-shield-basic-equipment",count=20}
                    thisPlayer.insert{name="energy-shield-equipment",count=20}
                    thisPlayer.insert{name="energy-shield-mk2-equipment",count=10}
                    --thisPlayer.insert{name="energy-shield-module-equipment",count=10}
                    --thisPlayer.insert{name="energy-shield-core-equipment",count=5}
                    
                    thisPlayer.insert{name="power-conduit-equipment",count=40}
                    thisPlayer.insert{name="engine-equipment",count=10}
                    thisPlayer.insert{name="fusion-reactor-equipment",count=10}
                    --thisPlayer.insert{name="power-conduit-core-equipment",count=5}
                    
                    thisPlayer.insert{name="coal",count=50}
                    thisPlayer.insert{name="solid-fuel",count=50}
                    thisPlayer.insert{name="alien-fuel",count=50}

                    --thisPlayer.insert{name="solar-panel-equipment-node",count=20}
                    thisPlayer.insert{name="solar-panel-equipment",count=20}
                    thisPlayer.insert{name="solar-panel-equipment-mk2",count=10}
                    thisPlayer.insert{name="basic-actuator-equipment",count=20}
                    thisPlayer.insert{name="basic-exoskeleton-equipment",count=20}

                    thisPlayer.insert{name="battery-equipment",count=5}
                    thisPlayer.insert{name="battery-mk2-equipment",count=5}
                    thisPlayer.insert{name="battery-mk3-equipment",count=5}
                    thisPlayer.insert{name="battery-mk4-equipment",count=5}
                    thisPlayer.insert{name="power-armor-mk2",count=1}
                    thisPlayer.insert{name="power-armor",count=1}
                    thisPlayer.insert{name="basic-modular-armor",count=1}
                    
                    
                    thisPlayer.insert{name="basic-laser-defense-equipment",count=5}
                    thisPlayer.insert{name="basic-electric-discharge-defense-equipment",count=5}
                    thisPlayer.insert{name="basic-electric-discharge-defense-remote",count=1}
                    
                    
                    thisPlayer.insert{name="small-electric-pole",count=50}
                    thisPlayer.insert{name="solar-panel",count=50}
                    thisPlayer.insert{name="basic-accumulator",count=50}
                    thisPlayer.insert{name="basic-mining-drill",count=50}
                end
                
            end
            if (not modularArmor.storedFuel) then
                modularArmor.storedFuel = {}
                for i,fuelVal in ipairs(fuelValues) do
                    modularArmor.storedFuel[i] = 1
                end
            end
            
            -- Removed till I can figure out how to fix the entity.
            --[[if modularArmor.units and modularArmor.units.name == "modular-accumulator-dummy" then
                modularArmor.units.destroy()
            end
            if modularArmor.units == nil then
                modularArmor.units = {}
            end]]--
            -- Ensure dummies exist.
            --[[]]--
            
            local armor = thisPlayer.get_inventory(defines.inventory.player_armor)[1] -- Check for armour presence.
            
            if (armor.valid_for_read) then
                
                if (armor.has_grid) then -- Check for grid existence.
                    local grid = armor.grid
                    
                    tickDummies(modularArmor,thisPlayer.character.position)-- validate, create, and move dummy units.
                    
                    
                    
                    local transferRate = 0 -- Rate of transfer from external network to armor.
                
                    transferRate = transferRate + ArmorTransferRatePerGridSize*grid.width*grid.height
                    
                    local fuelRate = {}
                
                    local energy = 0 -- Total energy and energy capacity
                    local energyCap = 0 -- need smallest fraction count as well. Essentially, if any of them have less than 50% or 90%, activate fusion and steam respectively.
                    local hasBattery = false -- Due to lack of a good energy distrubution system, I only limit production so long as you have a battery. Otherwise, things near the end of the list don't get any energy.
                    local shieldHealth = 0 -- Total shield and shield capacity for auto-balancing.
                    local shieldCap = 0
                    for i,equipment in ipairs(grid.equipment) do -- Loop through all equipment.
                        if (equipment.max_energy ~= 0) then
                            energy = energy + equipment.energy -- If it has energy, add values to total value.
                            energyCap = energyCap + equipment.max_energy
                            if equipment.type == "battery-equipment" then
                                hasBattery = true
                            else
                            
                            end
                        else
                        
                        end
                        
                        if equipment.max_shield ~= 0 then
                            shieldHealth = shieldHealth + equipment.shield -- Same with shield.
                            shieldCap = shieldCap + equipment.max_shield
                        else
                        end
                        
                        for i,fuelVal in ipairs(fuelValues) do
                            if (equipment.name == fuelVal.type) then
                            --globalPrint(equipment.name.." ? "..fuelType)
                                if not fuelRate[i] then
                                    fuelRate[i] = fuelVal.power
                                else
                                    fuelRate[i] = fuelRate[i] + fuelVal.power
                                end
                            else
                                
                            end
                        end
                        
                            
                        if (equipment.name == "power-conduit-equipment") then -- Also count each conduit module.
                            transferRate = transferRate + ConduitTransferRatePerEquipment
                        end
                    end
                    
                    local shieldFraction = shieldHealth/shieldCap
                    
                    local energyWanted = energyCap-energy
                    local transferRate = math.min(transferRate,energyWanted) -- We cant transfer energy without space to put it into
                    
                    --local accumulatorEnergy = 0*conversionAntiRatio -- Temporarily removed.
                    local accumulatorEnergy = (modularArmor.units.accumulator.energy - modularArmor.previousEnergy)--*conversionAntiRatio -- How much energy was accumulated since last tick
                    --globalPrint("Accumulator "..accumulatorEnergy)
                    local energyToAdd = math.min(transferRate,accumulatorEnergy) -- Accumulated energy, or transfer wanted, whichever is lower.
                    local newEnergy = energy+energyToAdd
                    local storageRatio = newEnergy/energyCap
                    
                    accumulatorEnergy = accumulatorEnergy - energyToAdd -- Remove 
                    --globalPrint("Accumulator -- "..accumulatorEnergy)

                    for i,fuelVal in ipairs(fuelValues) do -- Currently, Fusion power is being used when steam is supposed to be.
                       --globalPrint("detected Generator "..(fuelRate.fuelType)..(fuelType))
                        if fuelRate[i] and fuelRate[i] > 0.0 then
                            --globalPrint("detected Generator "..fuelRate.fuelType..fuelType)
                            -- This type exists
                            local threshhold = energyCap -- How much power this generator is allowed to bring you up to.
                            if hasBattery then
                                threshhold = threshhold * fuelVal.threshhold -- Without a battery, you cannot regulate energy production.
                            else
                                
                            end
                            local energyWanted = threshhold - newEnergy -- How much power we want to generate
                            energyWanted = math.max(energyWanted,0) -- Can't request negative power
                            energyWanted = math.min(energyWanted,fuelRate[i]) -- Can't make more power than the engines can support
                            local energyToGenerate = 0
                            
                            --globalPrint("Stored "..modularArmor.storedFuel[i]..fuelType)
                            --globalPrint("Wanted "..energyWanted)
                            if (modularArmor.storedFuel[i] < energyWanted) then
                                -- Check for fuel. If available, consume. If not, spend what you have
                                local mainInventory = thisPlayer.get_inventory(defines.inventory.player_main)
                                local validFuel = nil
                                for i,fuel in ipairs(fuelVal) do
                                    if (mainInventory.get_item_count(fuel[i][1]) > 0) then
                                        -- Got some
                                        validFuel = fuel[i]
                                        break
                                    else
                                        -- No luck, skip it
                                    end
                                    --globalPrint(fuel[i][1].." "..mainInventory.get_item_count(fuel[i][1]))
                                end
                                if (validFuel) then
                                    mainInventory.remove{name = validFuel[1], count = 1}
                                    modularArmor.storedFuel[i] = modularArmor.storedFuel[i] + validFuel[2]
                                    --surface.create_entity{name="flying-text", position=thisPlayer.character.position, text=("-1 "..validFuel[1]), color={r=1,g=1,b=1}}
                                    --globalPrint(validFuel[1].." "..modularArmor.storedFuel[i])
                                else
                                    --if (game.tick%ticksPerSecond == 0) then
                                        --surface.create_entity{name="flying-text", position=thisPlayer.character.position, text=("No fuel"), color={r=1,g=0.25,b=0.25}}

                                    --else
                                        
                                    --end

                                    -- Out of fuel
                                    --globalPrint("No fuel")
                                end
                                
                                
                            else
                                -- Have enough fuel already.
                            end
                            energyToGenerate = math.min(modularArmor.storedFuel[i],energyWanted)
                            modularArmor.storedFuel[i] = modularArmor.storedFuel[i] - energyToGenerate
                            
                                
                            energyToAdd = energyToAdd + energyToGenerate
                            
                            
                          
                                
                            --end
                        else
                            -- No such generator.
                        end
                    end
                    
                    -- I have energy to add, Energy Cap, and current energy.
                    -- I want to give amount proportional to amount missing to each elements. Ones with less get a higher fraction.
                    -- The amount I have available needs to be split into fractions of amount missing overall.
                    -- For each point missing from an element, add energyFraction to it.
                    -- Calc extra as well, and if it is greater than like 10%, feed into accumulator for next tick.
                    
                    
                    --globalPrint("energyFraction"..energyFraction)
                    --globalPrint("energyToAdd"..energyToAdd)
                    
                    --globalPrint("energySpent"..energySpent)
                    for i,equipment in ipairs(grid.equipment) do -- Basic Setup. Distribute as much to first in line, remainder to next, and next, till you run out.
                        if (equipment.max_energy ~= 0 and energyToAdd > 0) then          -- Poor Distribution method.
                            local difference = equipment.max_energy - equipment.energy
                            if (energyToAdd > difference) then
                                energyToAdd = energyToAdd - difference
                                equipment.energy = equipment.max_energy
                            else
                                equipment.energy = equipment.energy + energyToAdd
                                energyToAdd = 0
                                --break -- Removed since it interferes with shield.
                            end
                            
                        elseif (equipment.max_shield ~= 0) then
                            equipment.shield = equipment.max_shield * shieldFraction -- This part is a quick autobalance. All shields get equal power.
                            --equipment.shield = equipment.shield - (equipment.max_shield*ShieldDecayPerTick)
                        else -- Ideally, I want to send power from high efficiency ones to lower efficiency ones. That minimizes power consumption.
                            
                        end
                    end
                    
                    
                           
                    --globalPrint("accumulatorEnergy "..accumulatorEnergy)
                    --globalPrint("transferRate "..transferRate)
                    --globalPrint("accumulatorEnergyCap "..accumulatorEnergyCap)
                    
                    modularArmor.units.accumulator.energy = accumulatorEnergyCap - transferRate--*conversionRatio
                    modularArmor.previousEnergy = modularArmor.units.accumulator.energy --*conversionRatio -- The additional accumulated energy over
                    
                    
                    
                else
                    killDummies(modularArmor)
                end
            else
                killDummies(modularArmor)
            end
        else
            -- No player
            -- killDummies(modularArmor)
        end
    end
    
	if (not shouldKeepTicking) then
		global.ticking = nil
		game.onevent(defines.events.ontick, nil)
	end
end

function activateTicker()
	if (not global.ticking) then
		global.ticking = tickRate
		game.onevent(defines.events.ontick, ticker)
	end
end
New Ones

Code: Select all

if not config then
    config = {}
end
config.Debug = true
config.tickRate = 1
config.ticksPerSecond = 60
config.secondsPerTick = config.tickRate/config.ticksPerSecond -- To avoid division operations in a loop


config.accumulatorEnergyCap = 5. * 1000 * 1000      -- Replace with a lookup.
config.ConduitTransferRatePerEquipment = 500. * 1000 * config.secondsPerTick
--local ShieldDecayPerTick              = (1./100.) * secondsPerTick


config.fuelCoef = 1.0
config.powerCoef = 50.0

config.fuelValues =
{
    [1] = {
        type = "engine-equipment",
        name = "burner",
        power = 500. * 1000 * config.secondsPerTick,       -- Production per tick at max rate
        threshhold = 0.99,                      -- Power must be below this value for this type of generator to run
        {[1] = {"solid-fuel", 25.*1000*1000*config.fuelCoef}}, -- Value of each fuel type.
        {[2] = {"coal"      ,  8.*1000*1000*config.fuelCoef}}, 
        {[3] = {"raw-wood"  ,  4.*1000*1000*config.fuelCoef}},
    },
    [2] = {
        type = "fusion-reactor-equipment",
        name = "fusion",
        threshhold = 0.98,
        power = 5000. * 1000 * config.secondsPerTick,
        {[1] = {"alien-fuel", 100.*1000*1000*config.fuelCoef}},
    }
}

Code: Select all

require "defines"
require "config"

--[[
    This module handles the gameloop alteration, allowing conduit modules in power armor grid to tranfer energy between your power grid and your armor.

]]--

--[[
Charging Module Icon
Artist: Treetog ArtWork (Available for custom work)
Iconset: Junior Icons (146 icons)
License: Free for personal desktop use only.
Commercial usage: Not allowed
]]--

--[[          Gen , Size, Gen/size
    Conduit :  250kw,  1x1, 150  kw  
    Solar 1 :   75kw,  1x1,  75  kw  *0.7  52.5kw
    Solar 2 : 1000kw,  3x3, 111.1kw *0.7 77.7kw
    Burner  :  500kw,  2x2, 125  kw
    Fusion  : 5000Mw,  4x4, 312.5kw
    
    
           Energy , duration
    Wood  :  4 MJ ,  40
    Coal  :  8 MJ ,  80
    Fuel  : 25 MJ , 250

    Fusion: 112.5 MJ, 120
    
    
]]--
--[[
    Figure out if you can access energy network with the get network command thinggy.
    Alternately, do aura search, steal power from accumulators and roboports.
    
    Add command to disable conduit mechanics.
    -Shield pulse visial
    -Better Energy Distribution
    -Sheld autobalance
    -Boost batteries. Add higher tier,larger battery(s) /Done
    -Finish tech fixing
    -Add GUI display for fuel.
    -Add custom fuel slot.
    -Method to discharge energy into network?
    -Better energy distribution
    -Shield autobalance
]]--

global.surface = game.surfaces['nauvis']


--[[priorities = 
{
    {
        type = "input",
        {[1] = "primary-input" },
        {[2] = "secondary-input" },
    },
    {
        type = "output",
        {[1] = "primary-output"},
        {[2] = "secondary-output"},
    }
}]]--

--[[remote.addinterface("ModularArmor", {
    reset = function()
		global.ticking = nil
        
        --global.modularArmor = {}
    end
})]]--


function verifySettings()
	if (config.tickRate < 0) then
		config.tickRate = 0
		throwError("Tick rate must be >= 0.")
	end
end

function onload()  -- this function 
       -- globalPrint("onLoad")
	if (global.loaded == nil) then
		global.loaded = true
       -- globalPrint("loaded")
        
		verifySettings()
	end
    
    if (not global.modularArmor) then
        global.modularArmor = {}
    end
    if (global.ticking == nil) then
        global.ticking = 0
    end
    game.on_event(defines.events.on_tick, ticker)
end

game.on_init(onload)
game.on_load(onload)


function globalPrint(msg)
  local players = game.players
  if config.Debug then
      for i=1, #players do
        players[i].print(msg)
      end
  end
end


function tableIsEmpty(t)
	if (t) then
		for k in pairs(t) do
			return false
		end
	end
	return true
end

function ticker() -- run once per tickRate number of gameticks.
	if (global.ticking == 0) then
		global.ticking = config.tickRate - 1
		tick()
	else
		global.ticking = global.ticking - 1
	end
end

function tickDummies(id,positionz)

    if not id.units then
        id.units = {}
    else
        -- Already exists.
    end
    if not id.units.accumulator then
        id.units.accumulator = global.surface.create_entity{name = "laser-turret-dummy", position = positionz, force=game.forces.player}
        id.units.accumulator.energy = config.accumulatorEnergyCap -- initialize energy levels
        id.previousEnergy = id.units.accumulator.energy -- and previous energy level from last tick
        id.units.accumulator.destructible = false -- Make dummy invulnerable.
    else
        id.units.accumulator.teleport(positionz) -- Ensure that the power drain dummy is always at the player's position.
    end
    
    if not id.units.pole then
        id.units.pole = global.surface.create_entity{name = "electric-pole-dummy", position = positionz, force=game.forces.player}
        id.units.pole.destructible = false
    else
        id.units.pole.teleport(positionz)
    end
    
    if not id.units.solar then
        id.units.solar = global.surface.create_entity{name = "solar-panel-dummy", position = positionz, force=game.forces.player}
        id.units.solar.destructible = false
    else
        id.units.solar.teleport(positionz)
    end
end
function killDummies(id)
    if id.units then
        if id.units.accumulator then
            id.units.accumulator.destroy()
            id.units.accumulator = nil
        else
            -- Already gone
        end
        if id.units.pole then
            id.units.pole.destroy()
            id.units.pole = nil
        else
            -- Already gone
        end
        if id.units.solar then
            id.units.solar.destroy()
            id.units.solar = nil
        else
          -- Already gone
        end
    else
        -- Already deleted.
    end
end
function tick()
	local shouldKeepTicking
    local thisPlayer = nil
    local players = game.players
        --globalPrint("tick")
    shouldKeepTicking = true -- Due to lack of any alternate method of detecting player's armor state, we have to always tick.

    for i=1, #players do
        thisPlayer = players[i]
        if (thisPlayer.character) then
            --game.getplayer(1).print(i..' '..player)
            
            --if not global.modularArmor[i] then
            --    global.modularArmor[i] = {}
            --end
            local modularArmor = global.modularArmor[i]
            
            if (not modularArmor) then
                
                modularArmor = {} -- ensure player has data attached
                --modularArmor.storedFuel = {["steam"] = 0, ["fusion"] = 0}
                global.modularArmor[i] = modularArmor
                
                if (config.Debug == true) then
            
                    game.always_day=true -- test mode stuff
                    thisPlayer.insert{name="basic-grenade",count=50}
                    thisPlayer.insert{name="energy-shield-basic-equipment",count=20}
                    thisPlayer.insert{name="energy-shield-equipment",count=20}
                    thisPlayer.insert{name="energy-shield-mk2-equipment",count=10}
                    --thisPlayer.insert{name="energy-shield-module-equipment",count=10}
                    --thisPlayer.insert{name="energy-shield-core-equipment",count=5}
                    
                    thisPlayer.insert{name="power-conduit-equipment",count=40}
                    thisPlayer.insert{name="engine-equipment",count=10}
                    thisPlayer.insert{name="fusion-reactor-equipment",count=10}
                    --thisPlayer.insert{name="power-conduit-core-equipment",count=5}
                    
                    thisPlayer.insert{name="coal",count=50}
                    thisPlayer.insert{name="solid-fuel",count=50}
                    thisPlayer.insert{name="alien-fuel",count=50}

                    --thisPlayer.insert{name="solar-panel-equipment-node",count=20}
                    thisPlayer.insert{name="solar-panel-equipment",count=20}
                    thisPlayer.insert{name="solar-panel-equipment-mk2",count=10}
                    thisPlayer.insert{name="basic-actuator-equipment",count=20}
                    thisPlayer.insert{name="basic-exoskeleton-equipment",count=20}

                    thisPlayer.insert{name="battery-equipment",count=5}
                    thisPlayer.insert{name="battery-mk2-equipment",count=5}
                    thisPlayer.insert{name="battery-mk3-equipment",count=5}
                    thisPlayer.insert{name="battery-mk4-equipment",count=5}
                    thisPlayer.insert{name="power-armor-mk2",count=1}
                    thisPlayer.insert{name="power-armor",count=1}
                    thisPlayer.insert{name="basic-modular-armor",count=1}
                    
                    
                    thisPlayer.insert{name="basic-laser-defense-equipment",count=5}
                    thisPlayer.insert{name="basic-electric-discharge-defense-equipment",count=5}
                    thisPlayer.insert{name="basic-electric-discharge-defense-remote",count=1}
                    
                    
                    thisPlayer.insert{name="small-electric-pole",count=50}
                    thisPlayer.insert{name="solar-panel",count=50}
                    thisPlayer.insert{name="basic-accumulator",count=50}
                    thisPlayer.insert{name="basic-mining-drill",count=50}
                end
                
            end
            if (not modularArmor.storedFuel) then
                modularArmor.storedFuel = {}
                for i,fuelVal in ipairs(config.fuelValues) do
                    modularArmor.storedFuel[i] = 1
                end
            end
            
            -- Removed till I can figure out how to fix the entity.
            --[[if modularArmor.units and modularArmor.units.name == "modular-accumulator-dummy" then
                modularArmor.units.destroy()
            end
            if modularArmor.units == nil then
                modularArmor.units = {}
            end]]--
            -- Ensure dummies exist.
            --[[]]--
            
            local armor = thisPlayer.get_inventory(defines.inventory.player_armor)[1] -- Check for armour presence.
            
            if (armor.valid_for_read) then
                
                if (armor.has_grid) then -- Check for grid existence.
                    local grid = armor.grid
                    
                    tickDummies(modularArmor,thisPlayer.character.position)-- validate, create, and move dummy units.
                    
                    
                    
                    local transferRate = 0 -- Rate of transfer from external network to armor.
                
                    --transferRate = transferRate + ArmorTransferRatePerGridSize*grid.width*grid.height
                    
                    local fuelRate = {}
                
                    local energy = 0 -- Total energy and energy capacity
                    local energyCap = 0 -- need smallest fraction count as well. Essentially, if any of them have less than 50% or 90%, activate fusion and steam respectively.
                    --local hasBattery = false -- Due to lack of a good energy distrubution system, I only limit production so long as you have a battery. Otherwise, things near the end of the list don't get any energy.
                    -- Disabled, since power distribution percentages of 98 and 99% don't really have problems anymore. You would need 50 mini-shields, which wont happen
                    local shieldHealth = 0 -- Total shield and shield capacity for auto-balancing.
                    local shieldCap = 0
                    for i,equipment in ipairs(grid.equipment) do -- Loop through all equipment.
                        if (equipment.max_energy ~= 0) then
                            energy = energy + equipment.energy -- If it has energy, add values to total value.
                            energyCap = energyCap + equipment.max_energy
                            --if equipment.type == "battery-equipment" then
                            --    hasBattery = true
                            --else
                            
                            --end
                        else
                        
                        end
                        
                        if equipment.max_shield ~= 0 then
                            shieldHealth = shieldHealth + equipment.shield -- Same with shield.
                            shieldCap = shieldCap + equipment.max_shield
                        else
                        end
                        
                        for i,fuelVal in ipairs(config.fuelValues) do
                            if (equipment.name == fuelVal.type) then
                            --globalPrint(equipment.name.." ? "..fuelType)
                                if not fuelRate[i] then
                                    fuelRate[i] = fuelVal.power
                                else
                                    fuelRate[i] = fuelRate[i] + fuelVal.power
                                end
                            else
                                
                            end
                        end
                        
                            
                        if (equipment.name == "power-conduit-equipment") then -- Also count each conduit module.
                            transferRate = transferRate + config.ConduitTransferRatePerEquipment
                        end
                    end
                    
                    local shieldFraction = shieldHealth/shieldCap
                    
                    local energyWanted = energyCap-energy
                    local transferRate = math.min(transferRate,energyWanted) -- We cant transfer energy without space to put it into
                    
                    --local accumulatorEnergy = 0*conversionAntiRatio -- Temporarily removed.
                    local accumulatorEnergy = (modularArmor.units.accumulator.energy - modularArmor.previousEnergy)--*conversionAntiRatio -- How much energy was accumulated since last tick
                    --globalPrint("Accumulator "..accumulatorEnergy)
                    local energyToAdd = math.min(transferRate,accumulatorEnergy) -- Accumulated energy, or transfer wanted, whichever is lower.
                    local newEnergy = energy+energyToAdd
                    local storageRatio = newEnergy/energyCap
                    
                    accumulatorEnergy = accumulatorEnergy - energyToAdd -- Remove 
                    --globalPrint("Accumulator -- "..accumulatorEnergy)

                    for i,fuelVal in ipairs(config.fuelValues) do -- Currently, Fusion power is being used when steam is supposed to be.
                       --globalPrint("detected Generator "..(fuelRate.fuelType)..(fuelType))
                        if fuelRate[i] and fuelRate[i] > 0.0 then
                            --globalPrint("detected Generator "..fuelRate.fuelType..fuelType)
                            -- This type exists
                            local threshhold = energyCap -- How much power this generator is allowed to bring you up to.
                            --if hasBattery then
                                threshhold = threshhold * fuelVal.threshhold -- Without a battery, you cannot regulate energy production.
                            --else
                                
                            --end
                            local energyWanted = threshhold - newEnergy -- How much power we want to generate
                            energyWanted = math.max(energyWanted,0) -- Can't request negative power
                            energyWanted = math.min(energyWanted,fuelRate[i]) -- Can't make more power than the engines can support
                            local energyToGenerate = 0
                            
                            --globalPrint("Stored "..modularArmor.storedFuel[i]..fuelType)
                            --globalPrint("Wanted "..energyWanted)
                            if (modularArmor.storedFuel[i] < energyWanted) then
                                -- Check for fuel. If available, consume. If not, spend what you have
                                local mainInventory = thisPlayer.get_inventory(defines.inventory.player_main)
                                local validFuel = nil
                                for i,fuel in ipairs(fuelVal) do
                                    if (mainInventory.get_item_count(fuel[i][1]) > 0) then
                                        -- Got some
                                        validFuel = fuel[i]
                                        break
                                    else
                                        -- No luck, skip it
                                    end
                                    --globalPrint(fuel[i][1].." "..mainInventory.get_item_count(fuel[i][1]))
                                end
                                if (validFuel) then
                                    mainInventory.remove{name = validFuel[1], count = 1}
                                    modularArmor.storedFuel[i] = modularArmor.storedFuel[i] + validFuel[2]
                                    --surface.create_entity{name="flying-text", position=thisPlayer.character.position, text=("-1 "..validFuel[1]), color={r=1,g=1,b=1}}
                                    --globalPrint(validFuel[1].." "..modularArmor.storedFuel[i])
                                else
                                    if (game.tick%config.ticksPerSecond == 0) then
                                        global.surface.create_entity{name="flying-text", position=thisPlayer.character.position, text=("No "..(fuelVal.name).." fuel"), color={r=1,g=0.25,b=0.25}}

                                    else
                                      
                                    end

                                    -- Out of fuel
                                    --globalPrint("No fuel")
                                end
                                
                                
                            else
                                -- Have enough fuel already.
                            end
                            energyToGenerate = math.min(modularArmor.storedFuel[i],energyWanted)
                            modularArmor.storedFuel[i] = modularArmor.storedFuel[i] - energyToGenerate
                            
                                
                            energyToAdd = energyToAdd + energyToGenerate
                            
                            
                          
                                
                            --end
                        else
                            -- No such generator.
                        end
                    end
                    
                    -- I have energy to add, Energy Cap, and current energy.
                    -- I want to give amount proportional to amount missing to each elements. Ones with less get a higher fraction.
                    -- The amount I have available needs to be split into fractions of amount missing overall.
                    -- For each point missing from an element, add energyFraction to it.
                    -- Calc extra as well, and if it is greater than like 10%, feed into accumulator for next tick.
                    
                    
                    --globalPrint("energyFraction"..energyFraction)
                    --globalPrint("energyToAdd"..energyToAdd)
                    
                    --globalPrint("energySpent"..energySpent)
                    for i,equipment in ipairs(grid.equipment) do -- Basic Setup. Distribute as much to first in line, remainder to next, and next, till you run out.
                        if (equipment.max_energy ~= 0 and energyToAdd > 0) then          -- Poor Distribution method.
                            local difference = equipment.max_energy - equipment.energy
                            if (energyToAdd > difference) then
                                energyToAdd = energyToAdd - difference
                                equipment.energy = equipment.max_energy
                            else
                                equipment.energy = equipment.energy + energyToAdd
                                energyToAdd = 0
                                --break -- Removed since it interferes with shield.
                            end
                            
                        --elseif (equipment.max_shield ~= 0) then
                            --equipment.shield = equipment.max_shield * shieldFraction -- This part is a quick autobalance. All shields get equal power.
                            --equipment.shield = equipment.shield - (equipment.max_shield*ShieldDecayPerTick)
                        --else -- Ideally, I want to send power from high efficiency ones to lower efficiency ones. That minimizes power consumption.
                            
                        end
                    end
                    
                    
                           
                    --globalPrint("accumulatorEnergy "..accumulatorEnergy)
                    --globalPrint("transferRate "..transferRate)
                    --globalPrint("accumulatorEnergyCap "..accumulatorEnergyCap)
                    
                    modularArmor.units.accumulator.energy = config.accumulatorEnergyCap - transferRate--*conversionRatio
                    modularArmor.previousEnergy = modularArmor.units.accumulator.energy --*conversionRatio -- The additional accumulated energy over
                    
                    
                    
                else
                    killDummies(modularArmor)
                end
            else
                killDummies(modularArmor)
            end
        else
            -- No player
            -- killDummies(modularArmor)
        end
    end
    
	if (not shouldKeepTicking) then
		global.ticking = nil
		game.onevent(defines.events.ontick, nil)
	end
end

function activateTicker()
	if (not global.ticking) then
		global.ticking = config.tickRate
		game.onevent(defines.events.ontick, ticker)
	end
end
Last edited by Ranakastrasz on Sat Sep 05, 2015 9:56 pm, edited 2 times in total.
My Mods:
Modular Armor Revamp - V16
Large Chests - V16
Agent Orange - V16
Flare - V16
Easy Refineries - V16
orzelek
Smart Inserter
Smart Inserter
Posts: 3924
Joined: Fri Apr 03, 2015 10:20 am
Contact:

Re: "require" issue

Post by orzelek »

Quick look - you are using Debug without config prefix in second case. Might be more of those :D
User avatar
Ranakastrasz
Smart Inserter
Smart Inserter
Posts: 2174
Joined: Thu Jun 12, 2014 3:05 am
Contact:

Re: "require" issue

Post by Ranakastrasz »

Yep. Missed that one. Got a few others, but even after doing a search for each one, the crash still occurs.
My Mods:
Modular Armor Revamp - V16
Large Chests - V16
Agent Orange - V16
Flare - V16
Easy Refineries - V16
Rseding91
Factorio Staff
Factorio Staff
Posts: 14943
Joined: Wed Jun 11, 2014 5:23 am
Contact:

Re: "require" issue

Post by Rseding91 »

Can you post the crash log?
If you want to get ahold of me I'm almost always on Discord.
User avatar
Ranakastrasz
Smart Inserter
Smart Inserter
Posts: 2174
Joined: Thu Jun 12, 2014 3:05 am
Contact:

Re: "require" issue

Post by Ranakastrasz »

Code: Select all

   0.002 2015-09-01 12:35:08; Factorio 0.12.4 (Build 16397, win64)
   0.002 Operating system: Windows 7 Service Pack 1
   0.002 Program arguments: "C:\Users\Ranakastrasz\Desktop\Factorio_0.12.0 - Modding\bin\x64\Factorio.exe" 
   0.002 Read data path: C:/Users/Ranakastrasz/Desktop/Factorio_0.12.0 - Modding/data
   0.002 Write data path: C:/Users/Ranakastrasz/Desktop/Factorio_0.12.0 - Modding
   0.002 Binaries path: C:/Users/Ranakastrasz/Desktop/Factorio_0.12.0 - Modding/bin
   0.062 Initialised Direct3D: Intel(R) HD Graphics 4000; driver: igdumd64.dll 9.17.10.3062
   0.110 Desktop composition is active.
   0.111 Graphics options: [FullScreen: false] [VSync: true] [UIScale: 90%] [MultiSampling: OFF] [Graphics quality: normal] [Video memory usage: all]
   0.231 Loading mod core 0.0.0 (data.lua)
   0.238 Loading mod base 0.12.4 (data.lua)
   0.346 Loading mod Chests 0.0.4 (data.lua)
   0.422 Loading mod Modular Armor 0.0.10 (data.lua)
   0.493 Loading mod Modular Armor 0.0.10 (data-final-fixes.lua)
   1.401 Initial atlas bitmap size is 8192
   1.418 Created atlas bitmap 8192x8184
   1.420 Created atlas bitmap 8192x6984
  15.352 Info Updater.cpp:720: Downloading https://www.factorio.com/updater/get-available-versions?username=ranakastrasz&token=<private>&apiVersion=2
  15.564 0 packages available to download (experimental updates disabled).
  15.632 Factorio initialised
  20.326 Loading map C:/Users\Ranakastrasz\Desktop\Factorio_0.12.0 - Modding\saves\Coop3.zip
  20.406 Info Scenario.cpp:160: Map version 0.12.4-3
Factorio crashed. Generating symbolized stacktrace, please wait ...
c:\temp\factorio-061386bd\libraries\stackwalker\stackwalker.cpp (923): StackWalker::ShowCallstack
c:\temp\factorio-061386bd\src\util\logger.cpp (283): Logger::writeStacktrace
c:\temp\factorio-061386bd\src\util\logger.cpp (337): Logger::logStacktrace
c:\temp\factorio-061386bd\src\util\crashhandler.cpp (79): CrashHandler::writeStackTrace
c:\temp\factorio-061386bd\src\util\crashhandler.cpp (88): CrashHandler::SehHandler
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 00000000770BB990)
00000000770BB990 (kernel32): (filename not available): UnhandledExceptionFilter
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 00000000771CA0B8)
00000000771CA0B8 (ntdll): (filename not available): EtwEventSetInformation
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 0000000077158008)
0000000077158008 (ntdll): (filename not available): _C_specific_handler
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 000000007716905D)
000000007716905D (ntdll): (filename not available): RtlDecodePointer
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 0000000077158C0F)
0000000077158C0F (ntdll): (filename not available): RtlUnwindEx
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 000000007718D948)
000000007718D948 (ntdll): (filename not available): KiUserExceptionDispatcher
c:\temp\factorio-061386bd\src\entity\assemblingmachine.cpp (349): AssemblingMachine::getStackLimit
c:\temp\factorio-061386bd\src\entity\assemblingmachine.cpp (198): AssemblingMachine::canInsert
c:\temp\factorio-061386bd\src\entity\inserter.cpp (500): Inserter::getPickupTarget
c:\temp\factorio-061386bd\src\entity\inserter.cpp (696): Inserter::update
c:\temp\factorio-061386bd\src\surface\chunk.cpp (448): Chunk::update
c:\temp\factorio-061386bd\src\surface\surface.cpp (811): Surface::update
c:\temp\factorio-061386bd\src\map\map.cpp (907): Map::update
c:\temp\factorio-061386bd\src\game.cpp (142): Game::update
c:\temp\factorio-061386bd\src\scenario\scenario.cpp (735): Scenario::update
c:\temp\factorio-061386bd\src\mainloop.cpp (251): MainLoop::gameUpdateStep
c:\temp\factorio-061386bd\src\mainloop.cpp (353): MainLoop::updateLoop
c:\boost_1_58_0\boost\function\function_template.hpp (160): boost::detail::function::void_function_obj_invoker0<boost::_bi::bind_t<void,void (__cdecl*)(ThreadBarrier * __ptr64,boost::chrono::time_point<boost::chrono::steady_clock,boost::chrono::duration<__int64,boost::ratio<1,1000000000> > > * __ptr64,boost::chrono::time_point<boost::chrono::steady_clock,boost::chrono::duration<__int64,boost::ratio<1,1000000000> > > * __ptr64,bool * __ptr64,bool),boost::_bi::list5<boost::_bi::value<ThreadBarrier * __ptr64>,boost::_bi::value<boost::chrono::time_point<boost::chrono::steady_clock,boost::chrono::duration<__int64,boost::ratio<1,1000000000> > > * __ptr64>,boost::_bi::value<boost::chrono::time_point<boost::chrono::steady_clock,boost::chrono::duration<__int64,boost::ratio<1,1000000000> > > * __ptr64>,boost::_bi::value<bool * __ptr64>,boost::_bi::value<bool> > >,void>::invoke
c:\temp\factorio-061386bd\src\util\thread.cpp (34): Thread::loop
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 000000014001EB53)
000000014001EB53 (Factorio): (filename not available): boost::`anonymous namespace'::thread_start_function
f:\dd\vctools\crt\crtw32\startup\threadex.c (376): _callthreadstartex
f:\dd\vctools\crt\crtw32\startup\threadex.c (354): _threadstartex
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 0000000077035A4D)
0000000077035A4D (kernel32): (filename not available): BaseThreadInitThunk
ERROR: SymGetLineFromAddr64, GetLastError: 487 (Address: 000000007716B831)
000000007716B831 (ntdll): (filename not available): RtlUserThreadStart
  25.776 Error Util.cpp:46: Unexpected error occurred. You can help us to solve the problem by posting the contents of the log file on the Factorio forums.
My Mods:
Modular Armor Revamp - V16
Large Chests - V16
Agent Orange - V16
Flare - V16
Easy Refineries - V16
Rseding91
Factorio Staff
Factorio Staff
Posts: 14943
Joined: Wed Jun 11, 2014 5:23 am
Contact:

Re: "require" issue

Post by Rseding91 »

Update to 0.12.6 - does it still crash there?
If you want to get ahold of me I'm almost always on Discord.
User avatar
Ranakastrasz
Smart Inserter
Smart Inserter
Posts: 2174
Joined: Thu Jun 12, 2014 3:05 am
Contact:

Re: "require" issue

Post by Ranakastrasz »

Nope.
My Mods:
Modular Armor Revamp - V16
Large Chests - V16
Agent Orange - V16
Flare - V16
Easy Refineries - V16
Post Reply

Return to “Modding help”