/
dsh_cop_weather.script
1986 lines (1766 loc) · 77.6 KB
/
dsh_cop_weather.script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- ogse_weather_mgr.script
-- Менеджер динамической погоды
-- OGS Evolution Team 2014
-- version 2.0
--
-- Тут много всего наворочено, посему выделяю суть. Менеджер погоды
-- содержит массив self.forecast, который представляет собой список
-- погодных секций и времён, в которые их надо последовательно включать.
-- Это массив с индексацией от единицы. Первые два элемента - это всегда
-- текущий погодный фрейм.
--
-- При смене фрейма (при переходе через границу текущего) первая точка
-- удаляется, текущим фреймом становятся следующие две точки (бывшая №2
-- становится №1) и т.д. При этом массив прогноза дополняется с конца
-- необходимым количеством точек по алгоритму смены погоды. Если на
-- локации не используется дефолтовая погода, то ротация и обновление
-- массива прогноза также выполняется, но без фактической установки
-- погоды. Это позволяет держать массив прогноза заполненным и также
-- обеспечивает работу выброса
--
-- Выброс управляется отсюда, из погодного менеджера. Фактически, выброс
-- представляет собой цепочку специальных погодных кадров, вставленных в
-- прогноз с начала выброса. Кадры содержат в себе информацию об
-- инфопорциях, которые должны выдаваться при включении этих кадров. Эти
-- инфопорции управляют остальными эффектами выброса, которые включаются
-- уже в менеджере выброса.
-- алгоритм выбора погоды, имитирующий исходный из Atmosfear
--
-- end_w - это максимальное кол-во секций этой погоды, идущих подряд.
-- При достижении этого кол-ва будет выбрана новая погода. А до этого
-- момента, чем дольше длиться эта погода, тем вероятнее, что она
-- смениться на другую. Т.к. одна секция, как правило, длится один
-- час, для простоты можно считать, что это макс. кол-во часов.
--
-- tr_w - таблица со списком возможных циклов (для перехода с данного)
-- и их весов
local wind_velocity_settings = {
foggy = function() return math.random(200) end,
clear = function() return math.random(100, 350) end,
cloudy = function() return math.random(250, 600) end,
rain = function() return math.random(500, 850) end,
rain_thun = function() return math.random(700, 1000) end,
}
local weather_transitions_common = {
----------------------------------------------------
clear = {
wind_velocity = wind_velocity_settings.clear,
end_w = math.random(3, 6),
tr_w = {
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
rain = math.random(40, 75),
rain_thun = math.random(40, 75),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
clear2 = {
wind_velocity = wind_velocity_settings.clear,
end_w = math.random(3, 6),
tr_w = {
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
rain = math.random(40, 75),
rain_thun = math.random(40, 75),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
clear3 = {
wind_velocity = wind_velocity_settings.clear,
end_w = math.random(3, 6),
tr_w = {
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
rain = math.random(40, 75),
rain_thun = math.random(40, 75),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
clear4 = {
wind_velocity = wind_velocity_settings.clear,
end_w = math.random(3, 6),
tr_w = {
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
rain = math.random(40, 75),
rain_thun = math.random(40, 75),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
swtc = {
wind_velocity = wind_velocity_settings.clear,
end_w = math.random(3, 6),
tr_w = {
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
rain = math.random(40, 75),
rain_thun = math.random(40, 75),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
----------------------------------------------------
cloudy = {
wind_velocity = wind_velocity_settings.cloudy,
end_w = math.random(3, 6),
tr_w = {
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(60, 85),
rain_thun = math.random(60, 85),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
cloudy2 = {
wind_velocity = wind_velocity_settings.cloudy,
end_w = math.random(3, 6),
tr_w = {
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(60, 85),
rain_thun = math.random(60, 85),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
cloudy2rm = {
wind_velocity = wind_velocity_settings.cloudy,
end_w = math.random(3, 6),
tr_w = {
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(60, 85),
rain_thun = math.random(60, 85),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
cloudy3 = {
wind_velocity = wind_velocity_settings.cloudy,
end_w = math.random(3, 6),
tr_w = {
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(60, 85),
rain_thun = math.random(60, 85),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
cloudy4 = {
wind_velocity = wind_velocity_settings.cloudy,
end_w = math.random(3, 6),
tr_w = {
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(60, 85),
rain_thun = math.random(60, 85),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
swtc_dark = {
wind_velocity = wind_velocity_settings.cloudy,
end_w = math.random(3, 6),
tr_w = {
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(60, 85),
rain_thun = math.random(60, 85),
foggy = math.random(10, 25),
foggy_ns = math.random(10, 25),
},
},
----------------------------------------------------
rain = {
wind_velocity = wind_velocity_settings.rain,
end_w = math.random(6, 9),
tr_w = {
rain = math.random(60, 85),
rain_thun = math.random(60, 85),
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
clear = math.random(20, 45),
clear2 = math.random(20, 45),
clear3 = math.random(20, 45),
clear4 = math.random(20, 45),
swtc = math.random(20, 45),
foggy = math.random(20, 35),
foggy_ns = math.random(20, 35),
},
},
rain_thun = {
wind_velocity = wind_velocity_settings.rain_thun,
end_w = math.random(6, 9),
tr_w = {
rain = math.random(60, 85),
rain_thun = math.random(60, 85),
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
clear = math.random(20, 45),
clear2 = math.random(20, 45),
clear3 = math.random(20, 45),
clear4 = math.random(20, 45),
swtc = math.random(20, 45),
foggy = math.random(20, 35),
foggy_ns = math.random(20, 35),
},
},
----------------------------------------------------
foggy = {
wind_velocity = wind_velocity_settings.foggy,
end_w = math.random(1, 4),
tr_w = {
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(40, 75),
rain_thun = math.random(40, 75),
},
},
foggy_ns = {
wind_velocity = wind_velocity_settings.foggy,
end_w = math.random(1, 4),
tr_w = {
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(40, 75),
rain_thun = math.random(40, 75),
},
},
veryfoggy = {
wind_velocity = wind_velocity_settings.foggy,
end_w = math.random(1, 4),
tr_w = {
cloudy = math.random(40, 75),
cloudy2 = math.random(40, 75),
cloudy2rm = math.random(40, 75),
cloudy3 = math.random(40, 75),
cloudy4 = math.random(40, 75),
swtc_dark = math.random(40, 75),
clear = math.random(40, 75),
clear2 = math.random(40, 75),
clear3 = math.random(40, 75),
clear4 = math.random(40, 75),
swtc = math.random(40, 75),
rain = math.random(40, 75),
rain_thun = math.random(40, 75),
},
},
----------------------------------------------------
}
local weather_transitions = {
[ "default" ] = weather_transitions_common,
}
function attach( sm ) -- для менеджера сигналов
sm:subscribe({ signal = "on_init", fun = this.on_actor_init })
sm:subscribe({ signal = "on_update", fun = this.on_update })
sm:subscribe({ signal = "on_key_down", fun = this.on_key_down })
sm:subscribe({ signal = "on_first_update", fun = this.on_first_update })
sm:subscribe({ signal = "on_save", fun = this.on_save })
end
local pt, wm
function on_actor_init()
pt = game.CTime( game.get_game_time() )
wm = WeatherManager() -- создание
end
local total_debug = false
local always_reset = false
-- если вторая граница фрейма с выбросом будет ближе пяти минут к
-- моменту выброса, то притянуть её к этому моменту чтобы итоговый
-- фрейм с выбросом был не меньше пяти минут TODO: сделать это время
-- чуть меньше длительности выброса (по-любому эта граница будет
-- удалена при размещении точек выброса)
local point_del_tol = 60 * 5
local forecast_shown = false
local show_next_fc = false
-- установка таймфактора в 0 на время сохранения и потом возвращение его обратно
-- нужно для того, чтобы избежать скачка времени после загрузки
local normal_time_factor = get_float( "alife", "time_factor" )
-- при первом впдейте после загрузки ставим стандартное значение
function on_first_update()
-- level.set_time_factor( normal_time_factor )
if level.get_time_factor() ~= normal_time_factor then
log2(
"[%s]: restore time_factor: %s -> %s",
script_name(), level.get_time_factor(), normal_time_factor
)
level.set_time_factor( normal_time_factor )
end
log2(
"[%s]: time diff on first update is %s",
script_name(), game.get_game_time():diffSec( pt )
)
if get_surge_time() < -1 then
log1( "!!Surge is fucked up, resetting" )
ogse_surge_mgr.surge_final()
end
end
-- на время сохранения ставим в ноль, это и запомнится в сейве
function on_save()
level.set_time_factor( 0 )
pt = game.CTime( game.get_game_time() )
dsh.exec_on_update(
function()
level.set_time_factor( normal_time_factor )
log2(
"[%s]: time diff after save is %s",
script_name(), game.get_game_time():diffSec( pt )
)
end
)
end
function on_update()
local st = get_hud():AddCustomStatic( "ogse_weather", true ):wnd()
st:SetTextX( 200 )
st:SetTextY( 10 )
if forecast_shown then
st:SetTextColor( 255, 255, 0, 0 )
local wm = get_weather_mgr()
st:SetText( table.concat( wm:dump_state2lines( 30 ), "\\n" ) )
else
st:SetText( "" )
end
end
function get_surge_time()
return get_weather_mgr():time_to_next_surge()
end
function on_key_down( key, bind )
if GetShift() and key == DIK_keys.DIK_O and not level.main_input_receiver() then
if not GetLAlt() then
forecast_shown = not forecast_shown
get_weather_mgr():show_active_forecast()
elseif forecast_shown then
get_weather_mgr():show_next_forecast()
end
end
end
function get_weather_mgr()
ASSERT( wm, "" )
return wm
end
-- внутренние параметры менеджера погоды
-- Количество часов, на которое просчитывается погода.
-- Число задаётся таким, чтобы "прогноз" с гарантией был больше
-- времени сна, чтобы погода не менялась случайным образом после того,
-- как ГГ проснулся. С другой стороны, число не должно быть чрезмерно
-- большим, чтобы уменьшить количество вычислений и объём сохраняемой
-- информации. Два дня выглядит разумным компромиссом.
local forecast_time = 20
-- минимальная длительность кадра перехода между циклами в
-- минутах. Точка в цикле, к которому идёт переход, будет искаться на
-- расстоянии не меньше этого. Необходимо для того, чтобы при переходе
-- от одного цикла к другому не получился очень короткий кадр, если в
-- двух циклах временнЫе точки оказались рядом. на переходах между
-- точками в пределах цикла никак не сказывается, т.е. при
-- необходимости в пределах цикла могут быть очень короткие кадры.
local _min_transition_time = 60 -- в минутах
-- как готовый объект game.CTime для экономии вычислений
local min_transition_time = game.CTime()
min_transition_time:setHMS( 0, _min_transition_time, 0 )
-- минимальное приращение для поиска следующей точки в пределах одного цикла
-- TODO: получать следующую точку в том же цикле без поиска
local search_step = game.CTime()
search_step:setHMS( 0, 0, 1 )
local weather_ini_files = {}
function get_weather_ini( weather_name, is_effect )
if not weather_ini_files[ weather_name ] then
local prefix = "environment\\" .. (
is_effect and "weather_effects" or "weathers"
) .. "\\"
local ltx = prefix .. weather_name .. ".ltx"
weather_ini_files[ weather_name ] = ini_file( ltx )
end
return weather_ini_files[ weather_name ]
end
function read_cycle_points( cycle_ltx, points_table, is_effect )
local ini = get_weather_ini( cycle_ltx, is_effect )
ini:iterate_sections(
function( time_str )
local h, m, s = time_str:match( "^(%d%d):(%d%d):(%d%d)$" )
ASSERT( ( h and m and s ), "" )
local t = {}
t.time = h * 3600 + m * 60 + s -- время в секундах
t.time_orig = t.time -- сохраним исходное время на всякий случай
t.section = time_str
table.insert( points_table, t )
end
)
ASSERT(
table.getn( points_table ) > 0,
"[%s]: %s is empty", script_name(), cycle_ltx
)
table.sort( points_table, function( a1, a2 ) return a1.time < a2.time end )
-- прописываем в каждую точку её индекс для облегчения поиска в дальнейшем
-- нужно это делать только после сортировки, т.к. она может изменить порядок
-- и соотв. индексы
for i, t in ipairs( points_table ) do
t.index = i
-- первый фрейм выброса удлиняем на 5 реальных секунд, которые
-- движок прибавляет, для плавного перехода от нормальной погоды
-- к выбросу. Т.е. смещаем на эти 5 секунд время начала всех остальных
-- фреймов.
if i > 1 and is_effect then
t.time = t.time + 5 * level.get_time_factor()
t.time_orig = t.time
end
end
return ini
end
-- вспомогательная функция, которая оформляет структуру данных цикла,
-- включая заключающую точку и заготовку под статистику
function build_cycle_data( weather_name, sect )
local cycle_ltx
if sect then
cycle_ltx = get_string( sect, weather_name )
else
cycle_ltx = weather_name
end
ASSERT(
cycle_ltx,
"[%s]: cannot get weather section for the weather name '%s'",
script_name(), weather_name
)
local cycle_points = {}
local ini = read_cycle_points( cycle_ltx, cycle_points ) -- читаем все секции
-- цикла первая точка ВСЕГДА должна быть в начале суток. движок
-- этого не требует, но с этим дополнительным ограничением всё
-- сильно упрощается
ASSERT(
cycle_points[ 1 ].time == 0,
"[%s] cycle '%s' has first point at not zero time!",
script_name(), cycle_ltx
)
-- добавляем фейковую точку в конце суток для упрощения поиска
local last = table.clone_simple( cycle_points[ 1 ] ) -- копия первой,
last.time = 3600 * 24 -- кроме времени (ровно конец суток в
-- секундах) в последнюю фейковую точку прописываем вместо её
-- собственного индекса индекс первой точки
last.index = 1
table.insert( cycle_points, last ) -- добавляем в конец
return {
ini = ini,
ltx = cycle_ltx,
points = cycle_points,
skipped = 0,
weather_name = weather_name,
}
end
local function update_env_descriptors_params(wname1, wname2, forced)
local env = level.environment()
for idx = forced and 0 or 1, 1 do
local wname = idx == 0 and wname1 or wname2
local wt = weather_transitions_common[wname]
if not wt then goto CONTINUE end
local env_desc = env:getCurrentWeather( idx )
env_desc.wind_velocity = wt.wind_velocity() --Силу ветра берем из таблицы
env_desc.wind_direction = utils.deg2rad(math.random(360)) --Угол ветра будет всегда рандомный
--Силу раскачки деревьев будем считать от силы ветра --Теперь не используется
--local def_min_TAI, def_max_TAI = 0.01, 0.07
--local def_TAI = def_min_TAI + ((env_desc.wind_velocity * 0.001) * (def_max_TAI - def_min_TAI));
--env_desc.m_fTreeAmplitudeIntensity = def_TAI
--if wname:find("^clear") or wname:find("^cloudy") or wname:find("^swtc") or wname:find("^fog") then
--Рандомная интенсивность лучей
env_desc.m_fSunShaftsIntensity = math.random(3000) * 0.0001
--end
log3("--[%s][%s] wind_velocity: [%s], wind_direction: [%s], m_fSunShaftsIntensity: [%s]", script_name(), wname, env_desc.wind_velocity, env_desc.wind_direction, env_desc.m_fSunShaftsIntensity)
::CONTINUE::
end
end
-- базовый класс прогноза погоды
-- архитектурно класс прогноза предназначен для отделения функционала
-- прогнозирования погоды от функционала технических манипуляций с
-- движком. Необходимость в этом возникла по причине того, что
-- прогнозов несколько: один дефолтный с полной динамикой и по одному
-- на каждый уровень со статикой.
-- данный класс предназначен для замены статической погоды на
-- управление под скриптовым менеджером. является основой для
-- следующего класса прогноза с вариативной погодой из нескольких
-- циклов
class "StaticForecast"
function StaticForecast:__init( weather_name )
ogse_surge_mgr.surge_log( "StaticForecast:__init" )
ASSERT( weather_name, "[%s] weather name is a nil reference", script_name() )
self.name = weather_name
-- является ли активной погодой (таким может быть и должен быть
-- только один из всех)
self.active = false
-- таблица с временнЫми точками на ближайшие forecast_time+ часов
self.forecast = {}
self.surge_frame_assigned = false
self.static_weather_name = weather_name
-- данные цикла по ключу-имени: здесь будет всего один цикл
self.cycles = {
[ weather_name ] = build_cycle_data( weather_name ),
}
-- затычка для общего алгоритма
self.idx2cycle = { weather_name }
ogse_surge_mgr.surge_log( "StaticForecast:__init - END" )
end
function StaticForecast:get_p1()
return self.forecast[ 1 ]
end
function StaticForecast:get_p2()
return self.forecast[ 2 ]
end
function StaticForecast:get_p3()
return self.forecast[ 3 ]
end
function StaticForecast:get_first_frame()
return self.forecast[ 1 ], self.forecast[ 2 ]
end
function StaticForecast:get_p_after_surge()
for i, t in ipairs( self.forecast ) do
if not t.surge_frame then
return t
end
end
end
local point_flags = {
surge_begin = 1, -- 001b
surge_frame = 2, -- 010b
processed = 4, -- 100b
}
function StaticForecast:load()
ogse_surge_mgr.surge_log( "StaticForecast:on_load" )
-- читаем данные прогноза
local forecast_data = ogse.load_var_safe(
string.format( "%s.StaticForecast.%s", script_name(), self.name )
)
if not forecast_data then
log2(
"[%s]: StaticForecast: loading of %s skipped: data not found",
script_name(), self.name
)
return
end
ogse_surge_mgr.surge_log( "forecast points" )
self.forecast = {}
for _, t in ipairs( forecast_data ) do
local cycle, flags, point_idx, time = unpack( t )
local p = {}
-- название цикла. Для статики будет избыточность, но не хочется
-- дублировать код
p.cycle = cycle
p.time = time
-- читаем и разбираем флаги точки
local pflags = flags16():assign( flags )
p.surge_start = pflags:test( point_flags.surge_begin )
p.surge_frame = pflags:test( point_flags.surge_frame )
p.processed = pflags:test( point_flags.processed )
-- как только встретим первый true, то так true и останется
self.surge_frame_assigned = self.surge_frame_assigned or p.surge_start
-- в конце ещё проверим на валидность
ASSERT(
point_idx ~= 0,
"[StaticForecast:on_load] cycle '%s' without index", p.cycle
)
-- в зависимости от типа точки обычная/выброс данные о цикле берём
-- либо из общей таблицы погодных циклов, либо из дополнительно
-- подгруженной таблицы для выброса
local cycle_points = {}
if self.cycles[ p.cycle ] then
cycle_points = self.cycles[ p.cycle ].points
elseif p.surge_frame then
local ini = read_cycle_points( p.cycle, cycle_points, true )
self.cycles[ p.cycle ] = {
ini = ini,
ltx = p.cycle,
points = cycle_points,
weather_name = p.cycle,
}
end
ASSERT(
point_idx <= table.getn( cycle_points ),
"[%s]: cycle[%s] point_idx[%s] cycle_points[%s] time[%s]",
script_name(), p.cycle, point_idx, table.getn( cycle_points ),
time2string( p.time )
)
p.data = cycle_points[ point_idx ]
table.insert( self.forecast, p )
ogse_surge_mgr.surge_log(
"cycle '%s', idx = %d/%d, t = %s, %s %s",
p.cycle,
p.data.index, point_idx,
time2string( p.time ),
p.surge_start and "surge_start" or "",
p.surge_frame and "surge_frame" or ""
)
end
log2(
"[%s]: StaticForecast: %s loaded: %s items",
script_name(), self.name, table.getn( self.forecast )
)
ogse_surge_mgr.surge_log( "StaticForecast:on_load - END" )
end
function StaticForecast:clear_saved_data()
local var_name = string.format(
"%s.StaticForecast.%s", script_name(), self.name
)
if ogse.var_exists( var_name ) then
ogse.delete_var( var_name )
end
end
function StaticForecast:save()
ogse_surge_mgr.surge_log( "StaticForecast:on_save" )
-- начинаем записывать свои данные
-- пишем данные текушего прогноза
ogse_surge_mgr.surge_log( "forecast_points:" )
local data = {}
for _, point_data in ipairs( self.forecast ) do -- сами точки
-- записываем минимум информации для восстановления точки в дальнейшем
-- формируем и записываем флаги точки
local pflags = flags16():zero()
pflags:set( point_flags.surge_begin, point_data.surge_start == true )
pflags:set( point_flags.surge_frame, point_data.surge_frame == true )
pflags:set( point_flags.processed, point_data.processed == true )
local t = {
point_data.cycle, -- название цикла
pflags:get(), -- флаги точки
point_data.data.index, -- индекс точки цикла
point_data.time,
}
table.insert( data, t )
ogse_surge_mgr.surge_log(
"cycle '%s', idx = %d, t = %s, %s %s",
point_data.cycle,
point_data.data.index,
time2string( point_data.time ),
point_data.surge_start and "surge_start" or "",
point_data.surge_frame and "surge_frame" or ""
)
end
ogse.save_var(
string.format( "%s.StaticForecast.%s", script_name(), self.name ),
data, "array_template", { "string", "u16", "u8", "time" }
)
log2(
"[%s]: StaticForecast: %s saved: %s items",
script_name(), self.name, table.getn( data )
)
ogse_surge_mgr.surge_log( "StaticForecast:on_save - END" )
end
function StaticForecast:to_strings( max_lines )
if table.getn( self.forecast ) == 0 then return {} end
if not max_lines then max_lines = 10 end
local prev_time = self.forecast[ 1 ].time
local fist_point_time = self.forecast[ 1 ].time
local t = {}
for i, point in ipairs( self.forecast ) do
local dif1 = point.time:diffSec( fist_point_time )
if math.abs( dif1 ) < 1e-6 then dif1 = 0 end
local dif2 = point.time:diffSec( prev_time )
if math.abs(dif2) < 1e-6 then dif2 = 0 end
local s = string.format(
"%02d: [%s] %07d %06.1f|%06.1f, '%s', %s,%s%s%s",
i, --%d
point.time:dateToString( game.CTime.DateToDay )
.. '_' .. point.time:timeToString( game.CTime.TimeToSeconds ), --%s
get_day_time_sec( point.time ),
dif1, dif2,
point.cycle, -- %s
point.data.section, -- %s
point.surge_start and " surge_start" or "",
point.surge_frame and " surge_frame" or "",
point.processed and " processed" or ""
)
prev_time = point.time
table.insert( t, s )
if i == max_lines then break end
end
return t
end
function build_forecast_point( day_start_time, frame_point_data, cycle_name )
-- формируем точку фрейма как время начала суток + время фрейма
local point_time = game.CTime()
point_time:setHMS( 0, 0, frame_point_data.time )
point_time:add( day_start_time )
return {
cycle = cycle_name,
data = table.clone_simple( frame_point_data ),
time = point_time,
}
end
function StaticForecast:insert_forecast_point( day_start_time, frame_point_data, cycle_name, insert_position )
local point = build_forecast_point(
day_start_time, frame_point_data, cycle_name
)
table.insert( self.forecast, insert_position, point )
return point -- пригодится
end
function StaticForecast:append_forecast_point( day_start_time, frame_point_data, cycle_name )
ogse_surge_mgr.surge_log( "StaticForecast:append_forecast_point" )
local point = build_forecast_point(
day_start_time, frame_point_data, cycle_name
)
local y, m, d, h, min, s, ms = point.time:get()
ogse_surge_mgr.surge_log(
"cycle: %s, time (s): %f, time: %04d:%02d:%02d-%02d:%02d:%02d:%d",
point.cycle, point.data.time, y, m, d, h, min, s, ms
)
table.insert( self.forecast, point )
ogse_surge_mgr.surge_log( "StaticForecast:append_forecast_point - END" )
return point -- пригодится
end
-- получить следующую погоду по информации из прогноза и статистики
function StaticForecast:aux_choose_next_weather()
ogse_surge_mgr.surge_log( "StaticForecast:aux_choose_next_weather" )
return self:get_last_point().cycle -- всегда одна и та-же погода
end
function get_frame_by_time( cycle_data, t )
-- секунды, прошедшие с начала суток
local cur_day_seconds = get_day_time_sec( t )
-- ищем фрейм в цикле, включающий текущий момент времени
-- перебираем все промежутки (т.е. идём до предпоследнего индекса)
for i = 1, table.getn( cycle_data ) - 1 do
-- данные о границах промежутка
local fd1_, fd2_ = cycle_data[ i ], cycle_data[ i + 1 ]
if cur_day_seconds >= fd1_.time and cur_day_seconds < fd2_.time then
return fd1_, fd2_
end
end
ASSERT( false, "" ) -- такого быть не должно, если всё сделали верно
end
function process_weather_section_inf( weather_section, ini )
-- если в погодной секции есть параметр give_info, тогда выдать
-- соответствующую инфопорцию
if ini:section_exist( weather_section ) then
local info = get_string( weather_section, "give_info", nil, ini )
if info then
db.actor:give_info_portion( info )
end
end
end
function StaticForecast:process_first_point_info()
ogse_surge_mgr.surge_log( "StaticForecast:process_first_point_info" )
local first_point = self:get_p1()
local script_weather_section = first_point.data.section
ogse_surge_mgr.surge_log(
"before_process_weather_section_inf - set frame: %s", script_weather_section
)
if self.active and not first_point.processed then
-- если флаг не установлен, значит инфопорция из секции не выдавалась
ogse_surge_mgr.surge_log( "Was not processed. Process info (if any)." )
local ini = self.cycles[ first_point.cycle ].ini
process_weather_section_inf( script_weather_section, ini ) -- выдать
end
-- запомнить флаг, чтобы не повторить потом ещё раз
first_point.processed = true
ogse_surge_mgr.surge_log( "StaticForecast:process_first_point_info - END" )
end
function StaticForecast:reset_statistics()
end
-- получить из времени в формате CTime время начала суток для этого
-- момента времени тоже в формате CTime
function get_day_start_time( t )
local y, m, d, h, min, s, ms = t:get()
local day_start_time = game.CTime()
day_start_time:set( y, m, d, 0, 0, 0, 0 )
return day_start_time
end
-- обновить цепочку фреймов на ближайшие forecast_time часов
-- здесь также осуществляется вставка кадров выброса
function StaticForecast:update( next_surge_time )
ogse_surge_mgr.surge_log( "StaticForecast:update" )
local current_time = game.get_game_time() -- текущее время
-- сперва удаляем уже отработавшие точки
while table.getn( self.forecast ) > 0 do -- пока имеется хотя бы одна точка
-- если первая точка вдруг оказалась в будущем, чего быть по идее не может
if not (self.forecast[ 1 ].time <= current_time) then
log3("!![%s] first point of forecast is in the future. Check the logic!", script_name())
end
-- проверяем ситуацию, когда в прогнозе осталась одна точка.
-- такое теоретически может случиться, когда спали дольше, чем
-- имеем прогноз или конец сна попал в последний кадр
-- прогноза. Тогда последняя точка прогноза в процессе удаления
-- останется единственной. Этой ситуации надо избегать и длина
-- прогноза специально выбирается так, чтобы покрывать
-- длительность сна с запасом.
ASSERT(
table.getn( self.forecast ) > 1,
"[%s]: forecast has only one point. Check the logic!",
script_name()
)
self:process_first_point_info()
-- если есть следующая точка и она в будущем, то мы в текущем фрейме
if self.forecast[ 2 ].time > current_time then
break -- переходим к добавлению новых точек
end
-- все остальные варианты включают:
-- 1. за этой точкой есть ещё одна в прошлом
-- 2. эта точка последняя
-- в любом случае удаляем её
-- log1( "remove point" )
-- перед удалением не забыть выдать инфопорции из удаляемых точек
ogse_surge_mgr.surge_log(
"Remove past forecast point: %s, surge_start = %s",
self.forecast[ 1 ].data.section,
tostring( self.forecast[ 1 ].surge_start )
)
if self.forecast[ 1 ].surge_start then
self.surge_frame_assigned = false
end
table.remove( self.forecast, 1 )
end
-- здесь имеем две возможные ситуации:
-- 1. self.forecast пустой, что может получиться если:
-- а) заполняем первый раз
-- б) как-то перескочили за forecast_time часов, что опять же может
-- получиться по-разному:
-- б.1) после совсем уж длинного сна
-- или, что более вероятно,