Debian Codegraph @

CorsixTH/Lua/calls_dispatcher.lua

raw
1 --[[ Copyright (c) 2010 Sam Wong
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 corsixth.require("announcer")
22
23 local AnnouncementPriority = _G["AnnouncementPriority"]
24
25 class "CallsDispatcher"
26
27 ---@type CallsDispatcher
28 local CallsDispatcher = _G["CallsDispatcher"]
29
30 local debug_enabled = false -- Turn on for debug message
31
32 function CallsDispatcher:CallsDispatcher(world)
33 self.world = world
34 self.call_queue = {}
35 self.change_callback = {}
36 self.tick = 0
37 end
38
39 function CallsDispatcher:onTick()
40 self.tick = self.tick + 1
41 end
42
43 function CallsDispatcher:addChangeCallback(callback, self_value)
44 self.change_callback[callback] = self_value
45 end
46
47 function CallsDispatcher:removeChangeCallback(callback)
48 self.change_callback[callback] = nil
49 end
50
51 function CallsDispatcher:onChange()
52 for callback, self_value in pairs(self.change_callback) do
53 callback(self_value)
54 end
55 end
56
57 function CallsDispatcher:callForStaff(room)
58 local missing = room:getMissingStaff(room:getRequiredStaffCriteria())
59 local anyone_missed = false
60 for attribute, count in pairs(missing) do
61 anyone_missed = true
62 for i = 1, count do
63 self:callForStaffEachRoom(room, attribute, attribute .. i)
64 end
65 end
66 local sound = room.room_info.call_sound
67 if anyone_missed and sound and not room.sound_played then
68 room.world.ui:playAnnouncement(sound, AnnouncementPriority.Normal)
69 room.sound_played = true
70 end
71 end
72
73 function CallsDispatcher:callForStaffEachRoom(room, attribute, key)
74 if not key then
75 key = "-"
76 end
77 local new_call = self:enqueue(
78 room,
79 key,
80 _S.calls_dispatcher.staff:format(room.room_info.name, attribute),
81 --[[persistable:call_dispatcher_staff_verification]] function(staff)
82 return CallsDispatcher.verifyStaffForRoom(room, attribute, staff)
83 end,
84 --[[persistable:call_dispatcher_staff_priority]] function(staff)
85 return CallsDispatcher.getPriorityForRoom(room, attribute, staff)
86 end,
87 --[[persistable:call_dispatcher_staff_execute]] function(staff)
88 return CallsDispatcher.sendStaffToRoom(room, staff)
89 end
90 )
91 return new_call
92 end
93
94 -- Call for repair
95 --!param urgent Announcement should be made
96 --!param manual This call should not trigger advisor for "your machine is failing"
97 function CallsDispatcher:callForRepair(object, urgent, manual)
98
99 local call = {
100 verification = --[[persistable:call_dispatcher_repair_verification]] function() return false end,
101 priority = --[[persistable:call_dispatcher_repair_priority]] function() return 1 end,
102 execute = --[[persistable:call_dispatcher_repair_execute]] function(staff) return CallsDispatcher.sendStaffToRepair(object, staff) end,
103 object = object,
104 key = "repair",
105 description = _S.calls_dispatcher.repair:format(object.object_type.name),
106 dispatcher = self,
107 created = self.tick,
108 assigned = nil,
109 dropped = nil
110 }
111
112 if not manual and urgent then
113 object.hospital:giveAdvice({_A.warnings.machines_falling_apart})
114 elseif object.hospital:countStaffOfCategory("Handyman", 1) == 0 then
115 -- Advise about hiring Handyman
116 object.hospital:giveAdvice({_A.warnings.machinery_damaged2})
117 end
118
119 if not self.call_queue[object] then
120 self.call_queue[object] = {}
121 end
122 self.call_queue[object]["repair"] = call
123 return call
124 end
125
126 function CallsDispatcher:callForWatering(plant)
127 local call = {
128 verification = --[[persistable:call_dispatcher_watering_verification]]function()
129 return false end,
130 priority = --[[persistable:call_dispatcher_watering_priority]] function()
131 return 1 end,
132 execute = --[[persistable:call_dispatcher_watering_execute]] function(staff) return CallsDispatcher.sendStaffToWatering(plant, staff) end,
133 object = plant,
134 key = "watering",
135 description = _S.calls_dispatcher.watering:format(plant.tile_x, plant.tile_y),
136 dispatcher = self,
137 created = self.tick,
138 assigned = nil,
139 dropped = nil
140 }
141 if not self.call_queue[plant] then
142 self.call_queue[plant] = {}
143 end
144 self.call_queue[plant]["watering"] = call
145 return call
146 end
147
148 --[[ Queues a call for vaccination of a patient
149 @param patient (Patient) the patient who wishes to be vaccinated
150 @return call (table) the call which was queued ]]
151 function CallsDispatcher:callNurseForVaccination(patient)
152 local call = {
153 object = patient,
154 key = "vaccinate",
155 description = "Vaccinating patient at: " ..
156 tostring(patient.tile_x) .. "," .. tostring(patient.tile_y),
157 verification = --[[persistable:call_dispatcher_vaccinate_verification]] function(staff)
158 return CallsDispatcher.verifyStaffForVaccination(patient, staff)
159 end,
160 priority = --[[persistable:call_dispatcher_vaccinate_priority]] function(staff)
161 return CallsDispatcher.getPriorityForVaccination(patient,staff)
162 end,
163 execute = --[[persistable:call_dispatcher_vaccinate_execute]] function(staff)
164 return CallsDispatcher.sendNurseToVaccinate(patient, staff)
165 end,
166 dispatcher = self,
167 created = self.tick,
168 assigned = nil,
169 dropped = nil
170 }
171 if not self.call_queue[patient] then
172 self.call_queue[patient] = {}
173 end
174 self.call_queue[patient]["vaccinate"] = call
175
176 return call
177 end
178
179 --[[Determines if a member of staff is suitable to vaccinate a patient they
180 must be a nurse and not busy or too far away.
181 @param patient (Patient) the patient calling for vaccination
182 @param staff (Staff) staff member to verify if suitable to vaccinate
183 @return true if suitable for vaccination false otherwise (boolean) ]]
184 function CallsDispatcher.verifyStaffForVaccination(patient, staff)
185 -- If staff is not a nurse, or nurse is busy, or patient is busy, cannot vaccinate.
186 if not class.is(staff, Nurse) or not staff:isIdle() or
187 staff:getRoom() or patient:getRoom() then
188 return false
189 end
190
191 -- Test proximity of staff and patient.
192 local px,py = patient.tile_x, patient.tile_y
193 local nx,ny = staff.tile_x, staff.tile_y
194
195 -- If any of the nurse or the patient tiles are nil
196 if not px or not py or not nx or not ny then return false end
197
198 local x_diff = math.abs(px - nx)
199 local y_diff = math.abs(py - ny)
200 local test_radius = 5
201
202 -- Test if the patient's room is still empty in case they are just entering
203 -- a room when they call for a staff to vaccinate them
204 return x_diff <= test_radius and y_diff <= test_radius
205 end
206
207 --[[ Determine which nurse has the highest priority to vaccinate a patient
208 the patient should be easily reachable from the nurse
209 @param patient (Patient) the patient calling for vaccination
210 @param nurse (Staff, humanoid_class Nurse) the nurse to verify if they
211 have priority to vaccinate
212 @return score (Integer) lowest score has higher priority to vaccinate ]]
213 function CallsDispatcher.getPriorityForVaccination(patient, nurse)
214 assert(class.is(nurse, Nurse))
215 --Lower the priority "score" the more urgent it is
216 --The closest nurse to the patient has the highest priority for vaccination
217 --Any nurse who cannot reach the paitient suffers a priority penalty
218 local score = 0
219 local nil_penalty = 10000
220 local x, y = patient.tile_x, patient.tile_y
221
222 -- Nurses prefer to vaccinate the closest patient
223 local distance =
224 patient.world:getPathDistance(nurse.tile_x, nurse.tile_y, x, y)
225 if distance then
226 score = score + distance
227 else
228 score = score + nil_penalty
229 end
230 return score
231 end
232
233 --[[ Once a nurse has been verified and priority decided do the actions to
234 perform the actually vaccination, delegated to Epidemic class (@see
235 Epidemic:createVaccinationActions) @param patient (Patient) the patient calling
236 for vaccination @param nurse (Staff, humanoid_class Nurse) the nurse to perform
237 the vaccination actions ]]
238 function CallsDispatcher.sendNurseToVaccinate(patient, nurse)
239 assert(class.is(nurse, Nurse))
240
241 local epidemic = nurse.hospital.epidemic
242 if epidemic then
243 epidemic:createVaccinationActions(patient,nurse)
244 else
245 -- The epidemic may have ended before the call can be executed
246 -- so just finish the call immediately
247 CallsDispatcher.queueCallCheckpointAction(nurse)
248 nurse:queueAction(AnswerCallAction())
249 nurse:finishAction()
250 patient.reserved_for = nil
251 end
252 end
253
254
255 -- Enqueue the call
256 -- returns: True if the call is inserted and queued, but not served
257 -- False if the call is served right away, or has been queued and assigned
258 function CallsDispatcher:enqueue(object, key, description, verification, priority, execute)
259 if self.call_queue[object] and self.call_queue[object][key] then
260 -- already queued
261 return self.call_queue[object][key].assigned and true or false
262 elseif not self.call_queue[object] then
263 self.call_queue[object] = {}
264 end
265
266 local call = {
267 verification = verification,
268 priority = priority,
269 execute = execute,
270 object = object,
271 key = key,
272 description = description,
273 dispatcher = self,
274 created = self.tick
275 }
276 self.call_queue[object][key] = call
277
278 return not self:findSuitableStaff(call)
279 end
280
281 -- Find suitable (best) staff for working on a specific call
282 -- True
283 function CallsDispatcher:findSuitableStaff(call)
284 if call.dropped then
285 -- If a call was thought needed to be reinserted, but actually it was dropped...
286 return
287 end
288
289 -- TODO: Preempt staff those even on_call already.
290 -- Say - when an machine broke down, preempt the nearby handyman for repairing
291 -- even if he was going to water a far away plant
292 -- TODO: Doctor could go to other room with real needs, even there are patients queued up
293 -- (think of emergency? or surgeons still in GP office?)
294 local min_score = 2^30
295 local min_staff = nil
296 for _, e in ipairs(self.world.entities) do
297 if class.is(e, Staff) then
298 if not class.is(e, Handyman) then
299 local score = call.verification(e) and call.priority(e) or nil
300 if score ~= nil and score < min_score then
301 min_score = score
302 min_staff = e
303 end
304 end
305 end
306 end
307
308 if min_staff then
309 if debug_enabled then CallsDispatcher.dumpCall(call, 'executed right away') end
310 self:executeCall(call, min_staff)
311 return true
312 else
313 if debug_enabled then CallsDispatcher.dumpCall(call, 'queued') self:dump(self.call_queue) end
314 self:onChange()
315 return false
316 end
317 end
318
319 -- Find the best call for a staff to work on.
320 -- When a staff goes to meandering mode, it should call this function to look for new call
321 -- Return true if a call is answered. False if there is no suitable call waiting and the staff is really free.
322 function CallsDispatcher:answerCall(staff)
323 local min_score = 2^30
324 local min_call = nil
325 assert(not staff.on_call, "Staff member looking for work while already answering a call.")
326 assert(staff.hospital, "Staff should still be a member of the hospital to answer a call.")
327
328 if class.is(staff, Handyman) then
329 staff:searchForHandymanTask()
330 return true
331 end
332 -- Find the call with the highest priority (smaller means more urgency)
333 -- if the staff satisfy the criteria
334 for _, queue in pairs(self.call_queue) do
335 for _, call in pairs(queue) do
336 local score = call.verification(staff) and call.priority(staff) or nil
337 if score ~= nil then
338 if call.assigned then -- already being assigned? Can it be preempted?
339 local another_score = call.priority(call.assigned)
340 if another_score <= score then
341 score = nil
342 end
343 end
344 if score ~= nil and score < min_score then
345 min_score = score
346 min_call = call
347 end
348 end
349 end
350 end
351
352 if min_call then
353 if debug_enabled then self:dump() CallsDispatcher.dumpCall(min_call, 'answered') end
354 if min_call.assigned then
355 CallsDispatcher.unassignCall(min_call, true)
356 end
357 -- Check if the object is still in the world, live and not destroy
358 assert(min_call.object.tile_x or min_call.object.x, "An destroyed object still has requested in the dispatching queue. Please check the Entity:onDestroy function")
359 self:executeCall(min_call, staff)
360 return true
361 end
362 return false
363 end
364
365 -- Dump the current call table for debugging
366 function CallsDispatcher:dump()
367 print("--- Queue ---")
368 for _, queue in pairs(self.call_queue) do
369 for _, call in pairs(queue) do
370 CallsDispatcher.dumpCall(call, (call.assigned and 'assigned' or 'unassigned'))
371 end
372 end
373 print("----")
374 end
375
376 function CallsDispatcher.dumpCall(call, message)
377 if message ~= nil then
378 message = ': ' .. message
379 else
380 message = ''
381 end
382
383 local call_obj = call.object
384
385 local position = 'nowhere'
386 if call_obj.tile_x then
387 position = call_obj.tile_x .. ',' .. call_obj.tile_y
388 end
389 if call_obj.x then
390 position = call_obj.x .. ',' .. call_obj.y
391 end
392 if(class.is(call_obj,Humanoid)) then
393 print(call.key .. '@' .. position .. message)
394 else
395 print((call_obj.room_info and call_obj.room_info.id or call_obj.object_type.id) ..
396 '-' .. call.key .. '@' .. position .. message)
397 end
398 end
399
400 -- Add checkpoint action
401 -- All call execution method should add this action in appropriate place to signify
402 -- the job is finished.
403 -- A interrupt handler could be supplied if special handling is needed.
404 -- If not, the default would be reinsert the call into the queue
405 function CallsDispatcher.queueCallCheckpointAction(humanoid, interrupt_handler)
406 interrupt_handler = interrupt_handler or CallsDispatcher.actionInterruptHandler
407 return humanoid:queueAction(CallCheckPointAction(humanoid.on_call, interrupt_handler))
408 end
409
410 -- Default checkpoint interrupt handler
411 -- Reset the assigned status, and find an replacement staff
412 function CallsDispatcher.actionInterruptHandler(action, humanoid)
413 if action.call.assigned == humanoid then
414 action.call.assigned = nil
415 humanoid.on_call = nil
416 humanoid.world.dispatcher:findSuitableStaff(action.call)
417 end
418 end
419
420 --! Called when a call is completed successfully.
421 function CallsDispatcher.onCheckpointCompleted(call)
422 if not call.dropped and call.assigned then
423 if debug_enabled then CallsDispatcher.dumpCall(call, "completed") end
424 call.assigned.on_call = nil
425 call.assigned = nil
426 call.dispatcher:dropFromQueue(call.object, call.key)
427 end
428 end
429
430 function CallsDispatcher:executeCall(call, staff)
431 assert(not call.assigned, "call to be executed is still assigned")
432 assert(not call.dropped, "call to be executed is dropped")
433 assert(not staff.on_call, "staff was on call and assigned to a new call")
434 call.assigned = staff
435 staff.on_call = call
436 self:onChange()
437 call.execute(staff)
438 end
439
440 -- Drop any call associated with the object (and/or key).
441 --
442 -- Expected to be called when the call is no longer needed
443 -- (like a machine that needed repaired were replaced),
444 -- or when the object is destroyed, etc.
445 function CallsDispatcher:dropFromQueue(object, key)
446 if debug_enabled then self:dump() end
447 if key and self.call_queue[object] then
448 local call = self.call_queue[object][key]
449 if call then
450 call.dropped = true
451 if call.assigned then
452 CallsDispatcher.unassignCall(call, true)
453 end
454 self.call_queue[object][key] = nil
455 end
456 elseif self.call_queue[object] then
457 for _, call in pairs(self.call_queue[object]) do
458 call.dropped = true
459 if call.assigned then
460 CallsDispatcher.unassignCall(call, true)
461 end
462 end
463 self.call_queue[object] = nil
464 end
465 self:onChange()
466 end
467
468 --! Unassign call
469 --!param call call to unassign from assigned humanoid.
470 --!param answer_next_call (bool) should the humanoid assigned to this call then
471 -- answer for another new call
472 function CallsDispatcher.unassignCall(call, answer_next_call)
473 local assigned = call.assigned
474 assert(assigned.on_call == call, "Unassigning call but the staff was not on call or a different call")
475 call.assigned = nil
476 assigned.on_call = nil
477 if answer_next_call then
478 assigned:setNextAction(AnswerCallAction())
479 end
480 end
481
482 function CallsDispatcher.verifyStaffForRoom(room, attribute, staff)
483 if not staff:isIdle() or not staff:fulfillsCriterion(attribute) then
484 return false
485 end
486
487 -- Staff is in another room, not usable.
488 local current_room = staff:getRoom()
489 if not staff.hospital.policies["staff_allowed_to_move"] and
490 current_room and current_room ~= room then
491 return false
492 end
493
494 return true
495 end
496
497 function CallsDispatcher.getPriorityForRoom(room, attribute, staff)
498 local score = 0
499 local x, y = room:getEntranceXY()
500
501 -- Doctor prefer serving nearby rooms
502 local distance = room.world:getPathDistance(staff.tile_x, staff.tile_y, x, y)
503 if distance then
504 score = score + distance
505 end
506
507 -- More people on the queue has to be served earlier
508 if room.door.queue then
509 score = score - room.door.queue:reportedSize() * 5 -- 5 is just a weighting scale
510 if room.door.queue:hasEmergencyPatient() then
511 score = score - 200000 -- Emergency on queue trumps
512 end
513 end
514
515 -- Prefer the tirer staff (such that less chance to have "resting synchronization issue")
516 score = score - staff:getAttribute("fatigue") * 40 -- 40 is just a weighting scale
517
518 -- Prefer a wandering staff member over a staff member in a room
519 if not staff:getRoom() then
520 score = score - 50
521 end
522
523 -- TODO: Assign doctor with higher ability
524
525 -- Room requires specilitist trumps over normal rooms
526 if attribute == "Researcher" or attribute == "Psychiatrist" or attribute == "Surgeon" then
527 score = score - 100000
528 end
529
530 return score
531 end
532
533 function CallsDispatcher.sendStaffToRoom(room, staff)
534 if staff:getRoom() == room then
535 room:onHumanoidLeave(staff)
536 CallsDispatcher.queueCallCheckpointAction(staff, CallsDispatcher.staffActionInterruptHandler)
537 room:onHumanoidEnter(staff)
538 else
539 staff:setNextAction(room:createEnterAction(staff))
540 CallsDispatcher.queueCallCheckpointAction(staff, CallsDispatcher.staffActionInterruptHandler)
541 end
542 staff:setDynamicInfoText(_S.dynamic_info.staff.actions.heading_for:format(room.room_info.name))
543 end
544
545 function CallsDispatcher.staffActionInterruptHandler(action, humanoid)
546 if action.call.assigned == humanoid then
547 action.call.assigned = nil
548 humanoid.on_call = nil
549 if not action.call.dropped then
550 humanoid.world.dispatcher:callForStaff(action.call.object)
551 end
552 end
553 end
554
555 --! 'execute' callback for repairing an object (eg a machine).
556 --!param object Object to repair.
557 --!param handyman Staff to use.
558 function CallsDispatcher.sendStaffToRepair(object, handyman)
559 object:createHandymanActions(handyman)
560 end
561
562 --! 'execute' callback for watering a plant.
563 --!param plant Plant to give water.
564 --!param handyman Staff to use.
565 function CallsDispatcher.sendStaffToWatering(plant, handyman)
566 plant:createHandymanActions(handyman)
567 end