Compare commits

...

18 Commits

Author SHA1 Message Date
e98a23778b вынес из внешнего редактирования ссылки 2025-05-30 04:42:57 +07:00
3e15603f17 отрисовка префаба в левом списке теперь происходит корректно
(высота списка теперь корректно обновляется при изменении количества ошибок)
2025-05-28 00:57:42 +07:00
adbf4faed0 теперь поведение кнопки с отображением описания
не протекает в другие приборы
2025-05-27 22:10:21 +07:00
1851b2d959 синхронизовал состояние кнопки с отображением
дополнительного описания
2025-05-27 13:58:07 +07:00
895287b145 не протекает состояние кнопки с анимацией
при переключение режимов и датчиков
2025-05-26 20:35:34 +07:00
4104adf0f7 исправил проблему с мерцанием списка характеристик
и аварий перейдя на механизм виртуализации и
использовав механизм отложенной загрузки
2025-05-26 18:13:56 +07:00
da9f2bfbf8 забыл добавить состояние сцены 2025-05-24 04:26:21 +07:00
1d81901b6a избавил от подгрузки по чанкам и перешел на
отрисовку из пула, теперь поведение элементов
 с подсказкой уже лучше, осталось ввести по элементный
 пул .
2025-05-24 04:22:26 +07:00
6a5ba19e3d избавился от инверсии при скролле, добавил скролл
на правый список
2025-05-19 14:53:13 +07:00
6ee71adb4c изменил хралище ошибок на обычный TS синглтон
и адаптировал менеджер аварий под его использование
2025-05-11 23:04:51 +07:00
ba8a5f95a9 забыл добавить состояние сцены 2025-05-11 13:39:58 +07:00
98e9d62db7 везде где только мог сделал с безопасной подпиской/отпиской через optional chaining
— так компоненты не упадут, даже если кнопка или её node к моменту onDestroy уже не существует
сделал ноды менеджеров списка оборудовани, деталей,
и аварий Persistent Node, чтобы при смене сцены не сбрасывалось
их состояние.
2025-05-11 13:33:08 +07:00
c3a9b4f4b4 добавил возможность вернуться на предыдущую сцену 2025-05-08 02:38:55 +07:00
78546e6a7d исправил баг при котором происходила отписка
обновления списка от которого уже отписались
и не происходил переход на новую сцену
2025-05-08 02:01:21 +07:00
d7c00a42f2 добавил скрол по touchEvent по скролл бару 2025-05-06 15:53:10 +07:00
6eb39e0791 добавил в компонент описания дополнительную логику
сокрытия кнопки с вопросом если нет
описания .
2025-04-23 15:41:34 +07:00
2e0f682a8e изменил внешний вид кнопки с вопросом ,
добавил анимацию отображения доп информации.
2025-04-23 13:29:31 +07:00
91ed3138e9 добавлены ассеты кнопки доп информации ,
сделан класс для смены внешнего вида кнопки
при нажатии
2025-04-22 17:41:06 +07:00
37 changed files with 3850 additions and 999 deletions

View File

@ -0,0 +1,9 @@
{
"ver": "1.2.0",
"importer": "directory",
"imported": true,
"uuid": "d4d56f7c-d44b-41dc-aea7-0db93e48b08b",
"files": [],
"subMetas": {},
"userData": {}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 471 B

View File

@ -0,0 +1,134 @@
{
"ver": "1.0.27",
"importer": "image",
"imported": true,
"uuid": "1788b2a1-dfef-4811-983e-c90103a790e4",
"files": [
".json",
".png"
],
"subMetas": {
"6c48a": {
"importer": "texture",
"uuid": "1788b2a1-dfef-4811-983e-c90103a790e4@6c48a",
"displayName": "morph1",
"id": "6c48a",
"name": "texture",
"userData": {
"wrapModeS": "clamp-to-edge",
"wrapModeT": "clamp-to-edge",
"minfilter": "linear",
"magfilter": "linear",
"mipfilter": "none",
"anisotropy": 0,
"isUuid": true,
"imageUuidOrDatabaseUri": "1788b2a1-dfef-4811-983e-c90103a790e4",
"visible": false
},
"ver": "1.0.22",
"imported": true,
"files": [
".json"
],
"subMetas": {}
},
"f9941": {
"importer": "sprite-frame",
"uuid": "1788b2a1-dfef-4811-983e-c90103a790e4@f9941",
"displayName": "morph1",
"id": "f9941",
"name": "spriteFrame",
"userData": {
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0.5,
"trimX": 7,
"trimY": 5,
"width": 18,
"height": 21,
"rawWidth": 32,
"rawHeight": 32,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"packable": true,
"pixelsToUnit": 100,
"pivotX": 0.5,
"pivotY": 0.5,
"meshType": 0,
"vertices": {
"rawPosition": [
-9,
-10.5,
0,
9,
-10.5,
0,
-9,
10.5,
0,
9,
10.5,
0
],
"indexes": [
0,
1,
2,
2,
1,
3
],
"uv": [
7,
27,
25,
27,
7,
6,
25,
6
],
"nuv": [
0.21875,
0.1875,
0.78125,
0.1875,
0.21875,
0.84375,
0.78125,
0.84375
],
"minPos": [
-9,
-10.5,
0
],
"maxPos": [
9,
10.5,
0
]
},
"isUuid": true,
"imageUuidOrDatabaseUri": "1788b2a1-dfef-4811-983e-c90103a790e4@6c48a",
"atlasUuid": ""
},
"ver": "1.0.12",
"imported": true,
"files": [
".json"
],
"subMetas": {}
}
},
"userData": {
"hasAlpha": true,
"type": "sprite-frame",
"fixAlphaTransparencyArtifacts": false,
"redirect": "1788b2a1-dfef-4811-983e-c90103a790e4@6c48a"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 413 B

View File

@ -0,0 +1,134 @@
{
"ver": "1.0.27",
"importer": "image",
"imported": true,
"uuid": "5aaba3c0-d9f0-40c6-a2e3-9a10e2969775",
"files": [
".json",
".png"
],
"subMetas": {
"6c48a": {
"importer": "texture",
"uuid": "5aaba3c0-d9f0-40c6-a2e3-9a10e2969775@6c48a",
"displayName": "qex",
"id": "6c48a",
"name": "texture",
"userData": {
"wrapModeS": "clamp-to-edge",
"wrapModeT": "clamp-to-edge",
"minfilter": "linear",
"magfilter": "linear",
"mipfilter": "none",
"anisotropy": 0,
"isUuid": true,
"imageUuidOrDatabaseUri": "5aaba3c0-d9f0-40c6-a2e3-9a10e2969775",
"visible": false
},
"ver": "1.0.22",
"imported": true,
"files": [
".json"
],
"subMetas": {}
},
"f9941": {
"importer": "sprite-frame",
"uuid": "5aaba3c0-d9f0-40c6-a2e3-9a10e2969775@f9941",
"displayName": "qex",
"id": "f9941",
"name": "spriteFrame",
"userData": {
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 0,
"trimY": 0,
"width": 13,
"height": 21,
"rawWidth": 13,
"rawHeight": 21,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"packable": true,
"pixelsToUnit": 100,
"pivotX": 0.5,
"pivotY": 0.5,
"meshType": 0,
"vertices": {
"rawPosition": [
-6.5,
-10.5,
0,
6.5,
-10.5,
0,
-6.5,
10.5,
0,
6.5,
10.5,
0
],
"indexes": [
0,
1,
2,
2,
1,
3
],
"uv": [
0,
21,
13,
21,
0,
0,
13,
0
],
"nuv": [
0,
0,
1,
0,
0,
1,
1,
1
],
"minPos": [
-6.5,
-10.5,
0
],
"maxPos": [
6.5,
10.5,
0
]
},
"isUuid": true,
"imageUuidOrDatabaseUri": "5aaba3c0-d9f0-40c6-a2e3-9a10e2969775@6c48a",
"atlasUuid": ""
},
"ver": "1.0.12",
"imported": true,
"files": [
".json"
],
"subMetas": {}
}
},
"userData": {
"hasAlpha": true,
"type": "sprite-frame",
"fixAlphaTransparencyArtifacts": false,
"redirect": "5aaba3c0-d9f0-40c6-a2e3-9a10e2969775@6c48a"
}
}

BIN
assets/Icons/morphQex/x.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 B

View File

@ -0,0 +1,134 @@
{
"ver": "1.0.27",
"importer": "image",
"imported": true,
"uuid": "a614fdf0-1d85-4032-8b5c-7265394beb85",
"files": [
".json",
".png"
],
"subMetas": {
"6c48a": {
"importer": "texture",
"uuid": "a614fdf0-1d85-4032-8b5c-7265394beb85@6c48a",
"displayName": "x",
"id": "6c48a",
"name": "texture",
"userData": {
"wrapModeS": "clamp-to-edge",
"wrapModeT": "clamp-to-edge",
"minfilter": "linear",
"magfilter": "linear",
"mipfilter": "none",
"anisotropy": 0,
"isUuid": true,
"imageUuidOrDatabaseUri": "a614fdf0-1d85-4032-8b5c-7265394beb85",
"visible": false
},
"ver": "1.0.22",
"imported": true,
"files": [
".json"
],
"subMetas": {}
},
"f9941": {
"importer": "sprite-frame",
"uuid": "a614fdf0-1d85-4032-8b5c-7265394beb85@f9941",
"displayName": "x",
"id": "f9941",
"name": "spriteFrame",
"userData": {
"trimType": "auto",
"trimThreshold": 1,
"rotated": false,
"offsetX": 0,
"offsetY": 0,
"trimX": 0,
"trimY": 0,
"width": 17,
"height": 17,
"rawWidth": 17,
"rawHeight": 17,
"borderTop": 0,
"borderBottom": 0,
"borderLeft": 0,
"borderRight": 0,
"packable": true,
"pixelsToUnit": 100,
"pivotX": 0.5,
"pivotY": 0.5,
"meshType": 0,
"vertices": {
"rawPosition": [
-8.5,
-8.5,
0,
8.5,
-8.5,
0,
-8.5,
8.5,
0,
8.5,
8.5,
0
],
"indexes": [
0,
1,
2,
2,
1,
3
],
"uv": [
0,
17,
17,
17,
0,
0,
17,
0
],
"nuv": [
0,
0,
1,
0,
0,
1,
1,
1
],
"minPos": [
-8.5,
-8.5,
0
],
"maxPos": [
8.5,
8.5,
0
]
},
"isUuid": true,
"imageUuidOrDatabaseUri": "a614fdf0-1d85-4032-8b5c-7265394beb85@6c48a",
"atlasUuid": ""
},
"ver": "1.0.12",
"imported": true,
"files": [
".json"
],
"subMetas": {}
}
},
"userData": {
"hasAlpha": true,
"type": "sprite-frame",
"fixAlphaTransparencyArtifacts": false,
"redirect": "a614fdf0-1d85-4032-8b5c-7265394beb85@6c48a"
}
}

View File

@ -1032,6 +1032,7 @@
"__id__": 0
},
"fileId": "4aBpvR+bhJdI7i8LzRRtvb",
"instance": null
"instance": null,
"targetOverrides": null
}
]

File diff suppressed because it is too large Load Diff

View File

@ -6161,7 +6161,7 @@
"_priority": 1073741824,
"_fov": 45,
"_fovAxis": 0,
"_orthoHeight": 381.2971342383107,
"_orthoHeight": 364.88687782805425,
"_near": 1,
"_far": 2000,
"_color": {
@ -7155,6 +7155,7 @@
},
"_enabled": true,
"__prefab": null,
"toggleButton": null,
"equipmentList": {
"__id__": 185
},
@ -12560,6 +12561,7 @@
"header": {
"__id__": 335
},
"visibleItemCount": 15,
"_id": "21wy+/2mRJFqMMSBRnfwOL"
},
{
@ -12709,7 +12711,7 @@
"errorListNode": {
"__id__": 293
},
"soundEnabled": true,
"audioSource": null,
"_id": "04STMQ5PlDB5K9Q+T+Nc5I"
},
{
@ -12792,6 +12794,7 @@
},
"_enabled": true,
"__prefab": null,
"toggleButton": null,
"equipmentList": {
"__id__": 185
},
@ -13916,6 +13919,7 @@
"__id__": 34
},
"spacing": 10,
"visibleItemCount": 15,
"_id": "02Z+hMjflI57Ua6GmQMDOg"
},
{

View File

@ -24,6 +24,9 @@
},
{
"__id__": 7
},
{
"__id__": 10
}
],
"_active": true,
@ -58,7 +61,7 @@
},
"autoReleaseAssets": false,
"_globals": {
"__id__": 10
"__id__": 26
},
"_id": "658bce01-ef82-4cee-8fd2-af66cebdba02"
},
@ -350,30 +353,628 @@
"_bakeToReflectionProbe": true
},
{
"__type__": "cc.SceneGlobals",
"ambient": {
"__type__": "cc.Node",
"_name": "Canvas",
"_objFlags": 0,
"__editorExtras__": {},
"_parent": {
"__id__": 1
},
"_children": [
{
"__id__": 11
},
{
"__id__": 13
}
],
"_active": true,
"_components": [
{
"__id__": 23
},
{
"__id__": 24
},
{
"__id__": 25
}
],
"_prefab": null,
"_lpos": {
"__type__": "cc.Vec3",
"x": 640,
"y": 360,
"z": 0
},
"_lrot": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_lscale": {
"__type__": "cc.Vec3",
"x": 1,
"y": 1,
"z": 1
},
"_mobility": 0,
"_layer": 33554432,
"_euler": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_id": "e3ju1q0VlDeZ8iHIwAKyQZ"
},
{
"__type__": "cc.Node",
"_name": "Camera",
"_objFlags": 0,
"__editorExtras__": {},
"_parent": {
"__id__": 10
},
"_children": [],
"_active": true,
"_components": [
{
"__id__": 12
}
],
"_prefab": null,
"_lpos": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 1000
},
"_lrot": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_lscale": {
"__type__": "cc.Vec3",
"x": 1,
"y": 1,
"z": 1
},
"_mobility": 0,
"_layer": 1073741824,
"_euler": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_id": "65rHvUwytC4ajYZFIVkhl8"
},
{
"__type__": "cc.Camera",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 11
},
"shadows": {
"__id__": 12
"_enabled": true,
"__prefab": null,
"_projection": 0,
"_priority": 1073741824,
"_fov": 45,
"_fovAxis": 0,
"_orthoHeight": 360,
"_near": 1,
"_far": 2000,
"_color": {
"__type__": "cc.Color",
"r": 0,
"g": 0,
"b": 0,
"a": 255
},
"_skybox": {
"_depth": 1,
"_stencil": 0,
"_clearFlags": 6,
"_rect": {
"__type__": "cc.Rect",
"x": 0,
"y": 0,
"width": 1,
"height": 1
},
"_aperture": 19,
"_shutter": 7,
"_iso": 0,
"_screenScale": 1,
"_visibility": 41943040,
"_targetTexture": null,
"_postProcess": null,
"_usePostProcess": false,
"_cameraType": -1,
"_trackingType": 0,
"_id": "81LKHmU+ZIA6YN2LFfugXi"
},
{
"__type__": "cc.Node",
"_name": "BackButton",
"_objFlags": 0,
"__editorExtras__": {},
"_parent": {
"__id__": 10
},
"_children": [
{
"__id__": 14
}
],
"_active": true,
"_components": [
{
"__id__": 17
},
{
"__id__": 18
},
{
"__id__": 19
},
{
"__id__": 21
},
{
"__id__": 22
}
],
"_prefab": null,
"_lpos": {
"__type__": "cc.Vec3",
"x": -585,
"y": 335,
"z": 0
},
"_lrot": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_lscale": {
"__type__": "cc.Vec3",
"x": 1,
"y": 1,
"z": 1
},
"_mobility": 0,
"_layer": 33554432,
"_euler": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_id": "e037NNW2RG3LhGiVWi6QW5"
},
{
"__type__": "cc.Node",
"_name": "Label",
"_objFlags": 512,
"__editorExtras__": {},
"_parent": {
"__id__": 13
},
"fog": {
"_children": [],
"_active": true,
"_components": [
{
"__id__": 15
},
{
"__id__": 16
}
],
"_prefab": null,
"_lpos": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_lrot": {
"__type__": "cc.Quat",
"x": 0,
"y": 0,
"z": 0,
"w": 1
},
"_lscale": {
"__type__": "cc.Vec3",
"x": 1,
"y": 1,
"z": 1
},
"_mobility": 0,
"_layer": 33554432,
"_euler": {
"__type__": "cc.Vec3",
"x": 0,
"y": 0,
"z": 0
},
"_id": "8eSSv/RGRLXpSjHxNrb2iD"
},
{
"__type__": "cc.UITransform",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 14
},
"_enabled": true,
"__prefab": null,
"_contentSize": {
"__type__": "cc.Size",
"width": 100,
"height": 40
},
"_anchorPoint": {
"__type__": "cc.Vec2",
"x": 0.5,
"y": 0.5
},
"_id": "bdxkDQRzlHyqRhniZTc5/d"
},
{
"__type__": "cc.Label",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 14
},
"_enabled": true,
"__prefab": null,
"_customMaterial": null,
"_srcBlendFactor": 2,
"_dstBlendFactor": 4,
"_color": {
"__type__": "cc.Color",
"r": 0,
"g": 0,
"b": 0,
"a": 255
},
"_string": "НАЗАД",
"_horizontalAlign": 1,
"_verticalAlign": 1,
"_actualFontSize": 26.166666666666668,
"_fontSize": 20,
"_fontFamily": "Arial",
"_lineHeight": 40,
"_overflow": 1,
"_enableWrapText": false,
"_font": null,
"_isSystemFontUsed": true,
"_spacingX": 0,
"_isItalic": false,
"_isBold": false,
"_isUnderline": false,
"_underlineHeight": 2,
"_cacheMode": 0,
"_enableOutline": false,
"_outlineColor": {
"__type__": "cc.Color",
"r": 0,
"g": 0,
"b": 0,
"a": 255
},
"_outlineWidth": 2,
"_enableShadow": false,
"_shadowColor": {
"__type__": "cc.Color",
"r": 0,
"g": 0,
"b": 0,
"a": 255
},
"_shadowOffset": {
"__type__": "cc.Vec2",
"x": 2,
"y": 2
},
"_shadowBlur": 2,
"_id": "ef1dxe0tZMj7iqcQYaDLZ9"
},
{
"__type__": "cc.UITransform",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 13
},
"_enabled": true,
"__prefab": null,
"_contentSize": {
"__type__": "cc.Size",
"width": 100,
"height": 40
},
"_anchorPoint": {
"__type__": "cc.Vec2",
"x": 0.5,
"y": 0.5
},
"_id": "af4elT6LhNmpENKNQVkz4l"
},
{
"__type__": "cc.Sprite",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 13
},
"_enabled": true,
"__prefab": null,
"_customMaterial": null,
"_srcBlendFactor": 2,
"_dstBlendFactor": 4,
"_color": {
"__type__": "cc.Color",
"r": 214,
"g": 214,
"b": 214,
"a": 255
},
"_spriteFrame": {
"__uuid__": "20835ba4-6145-4fbc-a58a-051ce700aa3e@f9941",
"__expectedType__": "cc.SpriteFrame"
},
"_type": 1,
"_fillType": 0,
"_sizeMode": 0,
"_fillCenter": {
"__type__": "cc.Vec2",
"x": 0,
"y": 0
},
"_fillStart": 0,
"_fillRange": 0,
"_isTrimmedMode": true,
"_useGrayscale": false,
"_atlas": null,
"_id": "5aaLNCablJv70zWqg6R6au"
},
{
"__type__": "cc.Button",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 13
},
"_enabled": true,
"__prefab": null,
"clickEvents": [
{
"__id__": 20
}
],
"_interactable": true,
"_transition": 1,
"_normalColor": {
"__type__": "cc.Color",
"r": 214,
"g": 214,
"b": 214,
"a": 255
},
"_hoverColor": {
"__type__": "cc.Color",
"r": 211,
"g": 211,
"b": 211,
"a": 255
},
"_pressedColor": {
"__type__": "cc.Color",
"r": 255,
"g": 255,
"b": 255,
"a": 255
},
"_disabledColor": {
"__type__": "cc.Color",
"r": 124,
"g": 124,
"b": 124,
"a": 255
},
"_normalSprite": {
"__uuid__": "20835ba4-6145-4fbc-a58a-051ce700aa3e@f9941",
"__expectedType__": "cc.SpriteFrame"
},
"_hoverSprite": {
"__uuid__": "20835ba4-6145-4fbc-a58a-051ce700aa3e@f9941",
"__expectedType__": "cc.SpriteFrame"
},
"_pressedSprite": {
"__uuid__": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8@f9941",
"__expectedType__": "cc.SpriteFrame"
},
"_disabledSprite": {
"__uuid__": "951249e0-9f16-456d-8b85-a6ca954da16b@f9941",
"__expectedType__": "cc.SpriteFrame"
},
"_duration": 0.1,
"_zoomScale": 1.2,
"_target": {
"__id__": 13
},
"_id": "21VtWEzAVIvJaMTjGE0rLq"
},
{
"__type__": "cc.ClickEvent",
"target": {
"__id__": 13
},
"component": "",
"_componentId": "78f7278cNtNboFFr8iKBJ46",
"handler": "onBackClick",
"customEventData": ""
},
{
"__type__": "cc.Widget",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 13
},
"_enabled": true,
"__prefab": null,
"_alignFlags": 9,
"_target": null,
"_left": 5,
"_right": 0,
"_top": 5,
"_bottom": 0,
"_horizontalCenter": 0,
"_verticalCenter": 0,
"_isAbsLeft": true,
"_isAbsRight": true,
"_isAbsTop": true,
"_isAbsBottom": true,
"_isAbsHorizontalCenter": true,
"_isAbsVerticalCenter": true,
"_originalWidth": 0,
"_originalHeight": 0,
"_alignMode": 2,
"_lockFlags": 9,
"_id": "485GyxVfVObbEv0Lu+fgWz"
},
{
"__type__": "78f7278cNtNboFFr8iKBJ46",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 13
},
"_enabled": true,
"__prefab": null,
"targetScene": {
"__uuid__": "955c22b7-7b7e-4af8-ad45-8415a0c23e60",
"__expectedType__": "cc.SceneAsset"
},
"button": {
"__id__": 19
},
"_id": "b1rhKm2LNE35aZjPg01Jy0"
},
{
"__type__": "cc.UITransform",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 10
},
"_enabled": true,
"__prefab": null,
"_contentSize": {
"__type__": "cc.Size",
"width": 1280,
"height": 720
},
"_anchorPoint": {
"__type__": "cc.Vec2",
"x": 0.5,
"y": 0.5
},
"_id": "4f1tpBW+ZJjoChRkZRRMqh"
},
{
"__type__": "cc.Canvas",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 10
},
"_enabled": true,
"__prefab": null,
"_cameraComponent": {
"__id__": 12
},
"_alignCanvasWithScreen": true,
"_id": "05CFc1aXFGz7ouIAsjtOa2"
},
{
"__type__": "cc.Widget",
"_name": "",
"_objFlags": 0,
"__editorExtras__": {},
"node": {
"__id__": 10
},
"_enabled": true,
"__prefab": null,
"_alignFlags": 45,
"_target": null,
"_left": 0,
"_right": 0,
"_top": 0,
"_bottom": 0,
"_horizontalCenter": 0,
"_verticalCenter": 0,
"_isAbsLeft": true,
"_isAbsRight": true,
"_isAbsTop": true,
"_isAbsBottom": true,
"_isAbsHorizontalCenter": true,
"_isAbsVerticalCenter": true,
"_originalWidth": 0,
"_originalHeight": 0,
"_alignMode": 2,
"_lockFlags": 0,
"_id": "bckGXntVhOEKTI5/U+lyHG"
},
{
"__type__": "cc.SceneGlobals",
"ambient": {
"__id__": 27
},
"shadows": {
"__id__": 28
},
"_skybox": {
"__id__": 29
},
"fog": {
"__id__": 30
},
"octree": {
"__id__": 15
"__id__": 31
},
"skin": {
"__id__": 16
"__id__": 32
},
"lightProbeInfo": {
"__id__": 17
"__id__": 33
},
"postSettings": {
"__id__": 18
"__id__": 34
},
"bakedWithStationaryMainLight": false,
"bakedWithHighpLightmap": false

View File

@ -18,16 +18,10 @@ export class FirstPersonController extends Component {
@property
public maxSpeed: number = 20;
// Вектор направления движения
// Movement and rotation state
private _moveDirection: Vec3 = new Vec3();
// Храним текущие углы поворота (в градусах)
private _eulerAngles: Vec3 = new Vec3();
// Флаг нажатия левой кнопки мыши
private _isLeftMousePressed: boolean = false;
// Для эмитации события движения – запоминаем последнее положение
private _lastEmittedPosition: Vec3 = new Vec3();
onLoad() {
@ -38,58 +32,41 @@ export class FirstPersonController extends Component {
input.on(Input.EventType.MOUSE_MOVE, this._onMouseMove, this);
input.on(Input.EventType.MOUSE_WHEEL, this._onMouseWheel, this);
// Инициализируем углы текущей ориентацией ноды player
// Initialize rotation angles
this._eulerAngles = this.node.eulerAngles.clone();
// Сохраняем начальное положение для эмитации события "moved"
// Save start position for "moved" event
this._lastEmittedPosition = this.node.getPosition().clone();
}
onDestroy() {
input.off(Input.EventType.KEY_DOWN, this._onKeyDown, this);
input.off(Input.EventType.KEY_UP, this._onKeyUp, this);
input.off(Input.EventType.MOUSE_DOWN, this._onMouseDown, this);
input.off(Input.EventType.MOUSE_UP, this._onMouseUp, this);
input.off(Input.EventType.MOUSE_MOVE, this._onMouseMove, this);
input.off(Input.EventType.MOUSE_WHEEL, this._onMouseWheel, this);
// Safely unsubscribe from input events
input?.off(Input.EventType.KEY_DOWN, this._onKeyDown, this);
input?.off(Input.EventType.KEY_UP, this._onKeyUp, this);
input?.off(Input.EventType.MOUSE_DOWN, this._onMouseDown, this);
input?.off(Input.EventType.MOUSE_UP, this._onMouseUp, this);
input?.off(Input.EventType.MOUSE_MOVE, this._onMouseMove, this);
input?.off(Input.EventType.MOUSE_WHEEL, this._onMouseWheel, this);
}
private _onKeyDown(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_W:
this._moveDirection.z = 1;
break;
case KeyCode.KEY_S:
this._moveDirection.z = -1;
break;
case KeyCode.KEY_A:
this._moveDirection.x = -1;
break;
case KeyCode.KEY_D:
this._moveDirection.x = 1;
break;
case KeyCode.KEY_Q:
this._moveDirection.y = -1;
break;
case KeyCode.KEY_E:
this._moveDirection.y = 1;
break;
case KeyCode.KEY_W: this._moveDirection.z = 1; break;
case KeyCode.KEY_S: this._moveDirection.z = -1; break;
case KeyCode.KEY_A: this._moveDirection.x = -1; break;
case KeyCode.KEY_D: this._moveDirection.x = 1; break;
case KeyCode.KEY_Q: this._moveDirection.y = -1; break;
case KeyCode.KEY_E: this._moveDirection.y = 1; break;
}
}
private _onKeyUp(event: EventKeyboard) {
switch (event.keyCode) {
case KeyCode.KEY_W:
case KeyCode.KEY_S:
this._moveDirection.z = 0;
break;
case KeyCode.KEY_S: this._moveDirection.z = 0; break;
case KeyCode.KEY_A:
case KeyCode.KEY_D:
this._moveDirection.x = 0;
break;
case KeyCode.KEY_D: this._moveDirection.x = 0; break;
case KeyCode.KEY_Q:
case KeyCode.KEY_E:
this._moveDirection.y = 0;
break;
case KeyCode.KEY_E: this._moveDirection.y = 0; break;
}
}
@ -106,23 +83,17 @@ export class FirstPersonController extends Component {
}
private _onMouseMove(event: EventMouse) {
if (this._isLeftMousePressed) {
// Обновляем углы поворота: горизонтальный (yaw) и вертикальный (pitch)
this._eulerAngles.y -= event.movementX * this.lookSpeed;
this._eulerAngles.x -= event.movementY * this.lookSpeed;
// Ограничиваем pitch, чтобы не перевернуться
this._eulerAngles.x = Math.max(-89, Math.min(89, this._eulerAngles.x));
if (!this._isLeftMousePressed) return;
// Update yaw and pitch
this._eulerAngles.y -= event.movementX * this.lookSpeed;
this._eulerAngles.x -= event.movementY * this.lookSpeed;
this._eulerAngles.x = Math.max(-89, Math.min(89, this._eulerAngles.x));
// Применяем поворот к ноде player
const newQuat = new Quat();
Quat.fromEuler(newQuat, this._eulerAngles.x, this._eulerAngles.y, 0);
this.node.setRotation(newQuat);
// Если камера дочерняя нода, сбрасываем её локальное вращение
if (this.camera) {
this.camera.setRotation(Quat.IDENTITY);
}
}
// Apply rotation
const newQuat = Quat.fromEuler(new Quat(), this._eulerAngles.x, this._eulerAngles.y, 0);
this.node.setRotation(newQuat);
// Reset camera local rotation if child
this.camera?.setRotation(Quat.IDENTITY);
}
private _onMouseWheel(event: EventMouse) {
@ -135,23 +106,19 @@ export class FirstPersonController extends Component {
}
update(deltaTime: number) {
// Вычисляем направление движения с учётом ориентации игрока
// Movement in world space
const forward = Vec3.transformQuat(new Vec3(), Vec3.FORWARD, this.node.worldRotation);
const right = Vec3.transformQuat(new Vec3(), Vec3.RIGHT, this.node.worldRotation);
const move = new Vec3();
Vec3.scaleAndAdd(move, move, forward, this._moveDirection.z * this.moveSpeed * deltaTime);
Vec3.scaleAndAdd(move, move, right, this._moveDirection.x * this.moveSpeed * deltaTime);
Vec3.scaleAndAdd(move, move, Vec3.UP, this._moveDirection.y * this.moveSpeed * deltaTime);
// Перемещаем игрока в мировом пространстве
this.node.translate(move, NodeSpace.WORLD);
// После перемещения проверяем, изменилась ли позиция существенно, чтобы эмитировать событие "moved"
// Emit "moved" if significant change
const currentPos = this.node.getPosition();
if (Vec3.distance(currentPos, this._lastEmittedPosition) > 0.1) {
this.node.emit('moved');
// Обновляем последнее сохранённое положение
this._lastEmittedPosition = currentPos.clone();
}
}

View File

@ -2,121 +2,89 @@
import { _decorator, Component, MeshRenderer, Material, Color, math } from "cc";
import { apiSensors } from "./stores/apiSensors";
import { EquipmentManager } from "./stores/EquipmentManager";
const { ccclass, property } = _decorator;
@ccclass("PulsatingHighlighter")
export class PulsatingHighlighter extends Component {
@property(Material)
redMaterial: Material = null!;
@property(Material) redMaterial: Material = null!;
@property(Material) greenMaterial: Material = null!;
@property(Material) yellowMaterial: Material = null!;
@property(Material)
greenMaterial: Material = null!;
@property(Material)
yellowMaterial: Material = null!;
// Храним оригинальные материалы для восстановления
private _originalMaterials: Material[] = [];
private _currentAlpha = 0;
private _direction = 1;
private _animationSpeed = 3; // Скорость анимации пульсации
private _animationSpeed = 3;
// Статическая переменная для хранения активного экземпляра
private static _activeInstance: PulsatingHighlighter | null = null;
// Свойство для поиска соответствующего датчика (если используется)
@property
public sensorName: string = "";
// Флаг, определяющий, должна ли происходить авто-подсветка при обновлении данных
@property
public autoHighlight: boolean = false;
@property public sensorName: string = "";
@property public autoHighlight: boolean = false;
onLoad() {
this._storeOriginalMaterials();
// Если авто-подсветка включена, подписываемся на обновления EquipmentManager
if (this.autoHighlight) {
this.waitForEquipmentManager();
}
}
private waitForEquipmentManager() {
if (!EquipmentManager.instance) {
this.scheduleOnce(() => { this.waitForEquipmentManager(); }, 0.1);
this.scheduleOnce(() => this.waitForEquipmentManager(), 0.1);
return;
}
EquipmentManager.instance.node.on('data-updated', this._onDataUpdated, this);
}
private _storeOriginalMaterials() {
const renderer = this.node.getComponent(MeshRenderer);
if (!renderer) return;
this._originalMaterials = renderer.materials
.filter((m): m is Material => !!m)
.map((m) => {
const newMat = new Material();
newMat.copy(m);
return newMat;
.map(m => {
const copy = new Material();
copy.copy(m);
return copy;
});
}
private _onDataUpdated() {
// Если авто-подсветка выключена, не реагируем на обновления данных
if (!this.autoHighlight) return;
const sensors: apiSensors[] = EquipmentManager.instance.dataList;
const sensorData = sensors.find((s) => s.name === this.sensorName);
if (sensorData) {
let color = "";
if (sensorData.value === 2) {
color = "red";
} else if (sensorData.value === 1) {
color = "green";
} else if (sensorData.value === 0) {
color = "yellow";
} else {
console.warn(`Неожиданное значение sensorData.value: ${sensorData.value}`);
return;
}
this.switchToColor(color);
}
const data = EquipmentManager.instance.dataList.find(s => s.name === this.sensorName);
if (!data) return;
const color = data.value === 2 ? 'red'
: data.value === 1 ? 'green'
: data.value === 0 ? 'yellow'
: '';
if (color) this.switchToColor(color);
}
public switchToColor(color: string) {
const renderer = this.node.getComponent(MeshRenderer);
if (!renderer) return;
// Если уже есть активный объект и он не этот, сбрасываем его подсветку
// Если есть другой активный хайлайтер — сбросим его, но только если его node ещё жив
if (PulsatingHighlighter._activeInstance && PulsatingHighlighter._activeInstance !== this) {
PulsatingHighlighter._activeInstance.resetHighlight();
const prev = PulsatingHighlighter._activeInstance;
if (prev.node) {
prev.resetHighlight();
}
}
PulsatingHighlighter._activeInstance = this;
let selectedMaterial: Material | null = null;
if (color === "red" && this.redMaterial) {
selectedMaterial = this.redMaterial;
} else if (color === "green" && this.greenMaterial) {
selectedMaterial = this.greenMaterial;
} else if (color === "yellow" && this.yellowMaterial) {
selectedMaterial = this.yellowMaterial;
} else {
console.warn(`Неизвестный цвет "${color}", используем оригинальный.`);
return;
}
// Выбираем материал
let sel: Material | null = null;
if (color === 'red') sel = this.redMaterial;
else if (color === 'green') sel = this.greenMaterial;
else if (color === 'yellow') sel = this.yellowMaterial;
if (!sel) return;
// Создаем копию выбранного материала для эффекта подсветки
const highlightMat = new Material();
highlightMat.copy(selectedMaterial);
// Применяем и запускаем анимацию
const highlightMat = new Material(); highlightMat.copy(sel);
renderer.materials = renderer.materials.map(() => highlightMat);
// Запускаем анимацию пульсации
this._currentAlpha = 0;
this._direction = 1;
this._currentAlpha = 0; this._direction = 1;
this.schedule(this._updateAlpha, 0.016);
// Через 10 секунд возвращаем объект в исходное состояние, если он активен
// Запланируем сброс через 10 секунд
this.scheduleOnce(() => {
if (PulsatingHighlighter._activeInstance === this) {
this.resetHighlight();
@ -128,22 +96,18 @@ export class PulsatingHighlighter extends Component {
private _updateAlpha() {
this._currentAlpha += this._direction * this._animationSpeed;
this._currentAlpha = math.clamp(this._currentAlpha, 0, 255);
if (this._currentAlpha === 0 || this._currentAlpha === 255) this._direction *= -1;
if (this._currentAlpha === 255 || this._currentAlpha === 0) {
this._direction *= -1;
}
const renderer = this.node.getComponent(MeshRenderer);
const renderer = this.node?.getComponent(MeshRenderer);
if (renderer) {
renderer.materials.forEach((mat) => {
const mainColor = mat?.getProperty("mainColor") as Color;
mainColor.a = this._currentAlpha;
mat?.setProperty("mainColor", mainColor);
renderer.materials.forEach(mat => {
const c = mat?.getProperty('mainColor') as Color;
c.a = this._currentAlpha;
mat?.setProperty('mainColor', c);
});
}
}
// Сброс подсветки: остановка анимации и восстановление оригинальных материалов
public resetHighlight() {
this.unschedule(this._updateAlpha);
this.unscheduleAllCallbacks();
@ -151,20 +115,24 @@ export class PulsatingHighlighter extends Component {
}
private _restoreOriginalMaterials() {
// Guard: node мог быть уничтожен
if (!this.node) return;
const renderer = this.node.getComponent(MeshRenderer);
if (!renderer) return;
renderer.materials = this._originalMaterials.map((m) => {
const mat = new Material();
mat.copy(m);
return mat;
renderer.materials = this._originalMaterials.map(orig => {
const copy = new Material();
copy.copy(orig);
return copy;
});
}
onDestroy() {
// Снимаем подписку и сбрасываем статический инстанс, если он — наш
EquipmentManager.instance?.node?.off('data-updated', this._onDataUpdated, this);
this.unscheduleAllCallbacks();
if (EquipmentManager.instance) {
EquipmentManager.instance.node.off('data-updated', this._onDataUpdated, this);
if (PulsatingHighlighter._activeInstance === this) {
PulsatingHighlighter._activeInstance = null;
}
}
}

View File

@ -1,5 +1,5 @@
/* EquipmentManager.ts simplified without mutex */
import { _decorator, Component } from 'cc';
// EquipmentManager.ts
import { _decorator, Component, director } from 'cc';
import { apiSensors } from './apiSensors';
const { ccclass, property } = _decorator;
@ -7,20 +7,25 @@ const { ccclass, property } = _decorator;
export class EquipmentManager extends Component {
public static instance: EquipmentManager;
@property
public apiUrl: string = 'http://localhost:3030/api/v2/sensors';
private _dataList: apiSensors[] = [];
public totalCount: number = 0;
private _intervalId: number | null = null;
// Используем оператор "!" для отложенной инициализации
public initialDataPromise!: Promise<void>;
onLoad() {
// Сохраняем синглтон
EquipmentManager.instance = this;
// Промис будет разрешён после первой загрузки данных
// Делаем этот узел персистентным — он не будет уничтожаться при loadScene
director.addPersistRootNode(this.node);
// Первичная загрузка и Promise для крайних случаев
this.initialDataPromise = this.loadItems();
// Подписка на периодическое обновление
this._intervalId = window.setInterval(() => {
this.loadItems();
}, 10000);
@ -34,14 +39,13 @@ export class EquipmentManager extends Component {
try {
const response = await fetch(this.apiUrl);
const data = await response.json();
if (data && data.items && Array.isArray(data.items)) {
if (data?.items && Array.isArray(data.items)) {
this._dataList = data.items;
this.totalCount = this._dataList.length;
console.log('Данные оборудования обновлены:', this._dataList);
// Триггерим событие, на которое подписывается LazyLoadList
this.node.emit('data-updated');
} else {
console.error('Некорректный формат данных', data);
}
}
} catch (error) {
console.error('Ошибка при загрузке данных:', error);
}
@ -52,6 +56,9 @@ export class EquipmentManager extends Component {
}
onDestroy() {
// Если по какой-то причине хотите убрать persist:
// director.removePersistRootNode(this.node);
if (this._intervalId !== null) {
window.clearInterval(this._intervalId);
this._intervalId = null;

View File

@ -1,5 +1,5 @@
// ErrorManager.ts
import { _decorator, Component, Node, AudioSource } from 'cc';
// scripts/stores/ErrorManager.ts
import { _decorator, Component, Node, AudioSource, director } from 'cc';
import { EquipmentManager } from './EquipmentManager';
import { apiSensors } from './apiSensors';
import { ErrorsStore, ApiErrorsResponse } from './ErrorsStore';
@ -8,100 +8,126 @@ const { ccclass, property } = _decorator;
@ccclass('ErrorManager')
export class ErrorManager extends Component {
@property(Node)
public errorListNode: Node = null!;
@property(Node)
public errorListNode: Node = null!;
@property(AudioSource)
@property(AudioSource)
public audioSource: AudioSource | null = null;
private soundEnabled = true;
private currentErrors: string[] = [];
private errorItems: apiSensors[] = [];
private disabledAlerts: string[] = [];
// Инициализируем через getInstance()
private errorsStore = ErrorsStore.getInstance();
private soundEnabled: boolean = true;
private currentErrors: string[] = [];
private errorItems: apiSensors[] = [];
private disabledAlerts: string[] = [];
// Используем единый экземпляр ErrorsStore (Singleton)
private errorsStore: ErrorsStore = ErrorsStore.instance;
static instance: ErrorManager;
static instance: ErrorManager;
onLoad() {
ErrorManager.instance = this;
// Делаем узел устойчивым к смене сцен
director.addPersistRootNode(this.node);
this.node.on('touchstart', this.disableSoundAlert, this);
}
onLoad() {
ErrorManager.instance = this;
this.node.on('touchstart', this.disableSoundAlert, this);
start() {
EquipmentManager.instance?.node?.on('data-updated', this.checkErrors, this);
this.schedule(this.checkErrors, 5);
this.schedule(this.fetchApiErrors, 10);
}
onDestroy() {
this.node.off('touchstart', this.disableSoundAlert, this);
EquipmentManager.instance?.node?.off('data-updated', this.checkErrors, this);
this.unscheduleAllCallbacks();
}
/**
* Возвращает список текущих локальных ошибок по оборудованию и ошибки из API.
*/
public getErrorList(): { equipmentErrors: apiSensors[]; apiErrors: ApiErrorsResponse } {
return {
equipmentErrors: this.errorItems,
apiErrors: this.errorsStore.getApiErrors(),
};
}
/**
* Проверка локальных состояний ошибок по EquipmentManager.
* Добавляет новые, убирает снятые, эмитит 'errors-updated'.
*/
checkErrors() {
const dataList = EquipmentManager.instance?.dataList ?? [];
let updated = false;
// Фильтруем снятые ошибки
const prevErrors = [...this.currentErrors];
this.currentErrors = this.currentErrors.filter(tag =>
dataList.some(item => item.tag === tag && item.value === 2)
);
if (prevErrors.length !== this.currentErrors.length) {
this.errorItems = this.errorItems.filter(item =>
dataList.some(it => it.tag === item.tag && it.value === 2)
);
updated = true;
}
start() {
if (EquipmentManager.instance) {
EquipmentManager.instance.node.on('data-updated', this.checkErrors, this);
this.schedule(this.checkErrors, 5);
} else {
// Добавляем новые ошибки
dataList.forEach(item => {
if (item.value === 2 && this.currentErrors.indexOf(item.tag) === -1) {
this.currentErrors.push(item.tag);
this.errorItems.push(item);
this.addErrorToUI(item);
updated = true;
if (this.soundEnabled && this.disabledAlerts.indexOf(item.tag) === -1) {
this.audioSource?.play();
}
this.schedule(() => { this.fetchApiErrors(); }, 10);
}
});
if (updated) {
this.node.emit('errors-updated');
}
// Всегда проверяем API-ошибки после локальных изменений
this.fetchApiErrors();
}
public getErrorList(): { equipmentErrors: apiSensors[], apiErrors: ApiErrorsResponse } {
return { equipmentErrors: this.errorItems, apiErrors: this.errorsStore.getApiErrors() };
/**
* Запрашивает свежие ошибки у API и эмитит 'errors-updated'.
*/
async fetchApiErrors() {
try {
await this.errorsStore.fetchApiErrors();
this.node.emit('errors-updated');
} catch (e) {
console.error('ErrorManager.fetchApiErrors:', e);
}
}
checkErrors() {
const dataList = EquipmentManager.instance.dataList;
let updated = false;
/**
* Добавляет запись об ошибке в UI-список.
* Реализуйте логику вставки нод в this.errorListNode.
*/
addErrorToUI(item: apiSensors) {
// TODO: ваша логика по созданию и добавлению ноды в this.errorListNode
}
const prevErrors = [...this.currentErrors];
this.currentErrors = this.currentErrors.filter(tag =>
dataList.some(item => item.tag === tag && item.value === 2)
);
if (prevErrors.length !== this.currentErrors.length) {
this.errorItems = this.errorItems.filter(item =>
dataList.some(it => it.tag === item.tag && it.value === 2)
);
updated = true;
}
/** Отключает проигрывание звуковых оповещений. */
disableSoundAlert() {
this.soundEnabled = false;
}
dataList.forEach(item => {
if (item.value === 2 && this.currentErrors.indexOf(item.tag) === -1) {
this.currentErrors.push(item.tag);
this.errorItems.push(item);
this.addErrorToUI(item);
updated = true;
if (this.soundEnabled && this.disabledAlerts.indexOf(item.tag) === -1) {
}
}
});
if (updated) {
this.node.emit('errors-updated');
}
this.fetchApiErrors();
/** Помечает ошибку как «заблокированную» — звук для неё больше не будет играться. */
public disableAlertForError(tag: string): void {
if (this.disabledAlerts.indexOf(tag) === -1) {
this.disabledAlerts.push(tag);
}
}
async fetchApiErrors() {
await this.errorsStore.fetchApiErrors();
this.node.emit('errors-updated');
}
addErrorToUI(item: apiSensors) {
// Реализация обновления UI
}
disableSoundAlert() {
this.soundEnabled = false;
}
public disableAlertForError(tag: string): void {
if (this.disabledAlerts.indexOf(tag) === -1) {
this.disabledAlerts.push(tag);
}
}
confirmError(tag: string) {
this.currentErrors = this.currentErrors.filter(e => e !== tag);
this.errorItems = this.errorItems.filter(item => item.tag !== tag);
this.node.emit('errors-updated');
}
/** Подтверждает ошибку — удаляет её из локального списка. */
confirmError(tag: string) {
this.currentErrors = this.currentErrors.filter(e => e !== tag);
this.errorItems = this.errorItems.filter(item => item.tag !== tag);
this.node.emit('errors-updated');
}
}

View File

@ -1,8 +1,3 @@
import { _decorator, } from 'cc';
const { ccclass, property } = _decorator;
export interface ApiError {
alarmCode: number;
description: string;
@ -13,37 +8,50 @@ export interface ApiErrorsResponse {
[sensorName: string]: ApiError[];
}
@ccclass('ErrorsStore')
/**
* ErrorsStore — обычный TypeScript singleton для хранения и загрузки ошибок.
* Независим от Cocos Creator (@ccclass).
*/
export class ErrorsStore {
private static _instance: ErrorsStore;
private static _instance: ErrorsStore | null = null;
private apiErrors: ApiErrorsResponse = {};
/**
* Скрытый конструктор для предотвращения создания дополнительных экземпляров.
*/
private constructor() {}
public static get instance(): ErrorsStore {
/**
* Получить единственный экземпляр ErrorsStore.
*/
public static getInstance(): ErrorsStore {
if (!ErrorsStore._instance) {
ErrorsStore._instance = new ErrorsStore();
}
return ErrorsStore._instance;
}
// Асинхронный запрос ошибок с API
async fetchApiErrors(): Promise<void> {
/**
* Асинхронно загрузить ошибки с API и сохранить в хранилище.
*/
public async fetchApiErrors(): Promise<void> {
try {
const response = await fetch("http://localhost:3030/api/v2/errors");
if (response.ok) {
const errors = await response.json() as ApiErrorsResponse;
this.apiErrors = errors;
} else {
console.error("Ошибка при получении ошибок с API, статус:", response.status);
if (!response.ok) {
console.error("ErrorsStore: ошибка при получении ошибок, статус:", response.status);
return;
}
const errors = (await response.json()) as ApiErrorsResponse;
this.apiErrors = errors;
} catch (error) {
console.error("Ошибка запроса ошибок с API:", error);
console.error("ErrorsStore: ошибка запроса ошибок с API:", error);
}
}
// Получение текущего состояния ошибок с API
getApiErrors(): ApiErrorsResponse {
/**
* Вернуть текущее состояние ошибок.
*/
public getApiErrors(): ApiErrorsResponse {
return this.apiErrors;
}
}
}

View File

@ -1,3 +1,4 @@
// SensorDetailManager.ts
import { _decorator, Component, Node } from 'cc';
import { SensorDetailStore } from './SensorDetailStore';
import { ErrorLazyLoadList } from '../ui/ErrorLazyLoadList';
@ -5,48 +6,50 @@ const { ccclass } = _decorator;
@ccclass('SensorDetailManager')
export class SensorDetailManager extends Component {
private currentSensorName: string = "";
private currentSensorName: string = '';
onLoad() {
const equipmentManagerNode = this.node.scene.getChildByName('EquipmentManager');
if (equipmentManagerNode) {
equipmentManagerNode.on('showSensorDetails', this.onShowSensorDetails, this);
}
// Подпишемся только если менеджер существует в сцене
const equipmentManagerNode = this.node.scene?.getChildByName('EquipmentManager');
equipmentManagerNode?.on('showSensorDetails', this.onShowSensorDetails, this);
}
onDestroy() {
// Отпишемся и уберём все расписанные коллбэки
const equipmentManagerNode = this.node.scene?.getChildByName('EquipmentManager');
equipmentManagerNode?.off('showSensorDetails', this.onShowSensorDetails, this);
this.unscheduleAllCallbacks();
}
/**
* Обработчик события показа деталей датчика.
* Получает имя датчика, запрашивает данные и передаёт их компоненту, который отрисовывает список.
* @param sensorName Имя выбранного датчика/оборудования.
*/
public onShowSensorDetails(sensorName: string) {
// Если уже показываем детали того же датчика — ничего не делаем
if (this.currentSensorName === sensorName && ErrorLazyLoadList.instance?.mode === 'details') {
// Если датчик не изменился и уже отображаем details, то ничего не делаем
return;
}
this.currentSensorName = sensorName;
// Сбрасываем предыдущий интервал обновлений
this.unschedule(this.updateSensorDetails);
// Запросим и отобразим детали
SensorDetailStore.getInstance().fetchSensorDetails(sensorName)
.then(data => {
if (data && ErrorLazyLoadList.instance) {
ErrorLazyLoadList.instance.showSensorDetails(data);
}
});
})
.catch(console.error);
// Запланируем периодические обновления, если компонент активен
if (this.node.active) {
this.schedule(this.updateSensorDetails, 5);
}
this.node.active = true;
}
onEnable() {
// При включении заново запускаем обновления, если есть текущий датчик
if (this.currentSensorName) {
// Убедимся, что обновление не запускается дважды
this.unschedule(this.updateSensorDetails);
this.schedule(this.updateSensorDetails, 5);
}
@ -56,24 +59,16 @@ export class SensorDetailManager extends Component {
this.unschedule(this.updateSensorDetails);
}
/**
* Периодическое обновление данных датчика (если активно).
* Получает обновлённые данные и передаёт их в ErrorLazyLoadList для перерисовки.
*/
private updateSensorDetails() {
if (!this.currentSensorName) return;
SensorDetailStore.getInstance()
.fetchSensorDetails(this.currentSensorName)
.then(data => {
if (data && ErrorLazyLoadList.instance) {
// Проверяем текущий режим перед обновлением
if (ErrorLazyLoadList.instance.mode === "details") {
ErrorLazyLoadList.instance.showSensorDetails(data);
}
if (data && ErrorLazyLoadList.instance?.mode === 'details') {
// Используем updateSensorDetails для обновления без сброса UI
ErrorLazyLoadList.instance.updateSensorDetails(data);
}
});
})
.catch(console.error);
}
}
}

View File

@ -0,0 +1,29 @@
// scripts/ui/BackButton.ts
import { _decorator, Component, Button, director, SceneAsset } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('BackButton')
export class BackButton extends Component {
@property({ type: SceneAsset, tooltip: 'Сцена для возврата' })
public targetScene: SceneAsset | null = null;
@property(Button)
public button: Button | null = null;
onLoad() {
this.button?.node?.on('click', this.onBackClick, this);
}
onDestroy() {
// защищённо отписываемся только если node ещё жив
this.button?.node?.off('click', this.onBackClick, this);
}
public onBackClick() {
if (this.targetScene) {
director.loadScene(this.targetScene.name);
} else {
console.warn('BackButton: не задан targetScene');
}
}
}

View File

@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "78f72efc-70db-4d6e-8145-afc88a049e3a",
"files": [],
"subMetas": {},
"userData": {}
}

View File

@ -1,229 +1,779 @@
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, Label } from 'cc';
import { ErrorItemData } from '../stores/ErrorItemData';
import { ErrorManager } from '../stores/ErrorManager';
import { ErrorItemButton } from '../ux/ErrorItemButton';
import { ErrorItemNamedButton } from '../ux/ErrorItemNamedButton';
import { SensorDescription } from '../stores/SensorDescriptionField';
import { SensorFieldItem } from './SensorFieldItem';
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, Label, NodePool, Vec3 } from 'cc';
import { ErrorItemData } from '../stores/ErrorItemData';
import { ErrorManager } from '../stores/ErrorManager';
import { ErrorItemButton } from '../ux/ErrorItemButton';
import { ErrorItemNamedButton } from '../ux/ErrorItemNamedButton';
import { SensorDescription } from '../stores/SensorDescriptionField';
import { SensorFieldItem } from './SensorFieldItem';
import { MorphButtonWithButton } from '../ux/MorphButtonWithButton';
const { ccclass, property } = _decorator;
const { ccclass, property } = _decorator;
@ccclass("ErrorLazyLoadList")
export class ErrorLazyLoadList extends Component {
public static instance: ErrorLazyLoadList | null = null;
@ccclass("ErrorLazyLoadList")
export class ErrorLazyLoadList extends Component {
public static instance: ErrorLazyLoadList | null = null;
// Статические поля для сохранения состояния между сценами
private static _savedMode: "errors" | "details" = "errors";
private static _savedSensorDescription: SensorDescription | null = null;
private static _savedFilteredData: ErrorItemData[] | null = null;
@property(Prefab)
public errorItemPrefab: Prefab = null!;
@property(Prefab)
public errorItemPrefab: Prefab = null!;
@property(Prefab)
public sensorFieldItemPrefab: Prefab = null!;
@property(Prefab)
public sensorFieldItemPrefab: Prefab = null!;
@property(Prefab)
public errorItemNamedPrefab: Prefab = null!;
@property(Prefab)
public errorItemNamedPrefab: Prefab = null!;
@property(ScrollView)
public scrollView: ScrollView = null!;
@property(ScrollView)
public scrollView: ScrollView = null!;
@property
public spacing: number = 10;
@property
public spacing: number = 10;
@property(Label)
public header: Label = null!;
@property(Label)
public header: Label = null!;
private _data: ErrorItemData[] = [];
private _filteredData: ErrorItemData[] | null = null;
private _mode: "errors" | "details" = "errors";
private _sensorDescription: SensorDescription = null!;
private _totalCount: number = 0;
private _loadedCount: number = 0;
private _itemHeight: number = 0;
private _content: Node = null!;
private _contentUI: UITransform = null!;
@property
public visibleItemCount: number = 15; // Visible items buffer size
public get mode(): "errors" | "details" {
return this._mode;
private _data: ErrorItemData[] = [];
private _filteredData: ErrorItemData[] | null = null;
private _mode: "errors" | "details" = "errors";
private _sensorDescription: SensorDescription = null!;
private _totalCount: number = 0;
private _itemHeight: number = 0; // Including spacing
private _content: Node = null!;
private _contentUI: UITransform = null!;
// Lazy-created NodePools
private _errorItemPool: NodePool | null = null;
private _namedErrorItemPool: NodePool | null = null;
private _sensorFieldItemPools: Map<string, NodePool> = new Map(); // Пул для каждого датчика
private _activeSensorNames: Set<string> = new Set(); // Отслеживаем активные датчики
private _activeSensorFieldItems: Map<string, Set<Node>> = new Map(); // Отслеживаем активные элементы для каждого датчика
// Active items tracking
private _activeItems: Node[] = [];
private _activeItemsData: any[] = []; // Данные для отслеживания изменений
private _firstVisibleIndex: number = 0;
private _lastVisibleIndex: number = 0;
public get mode(): "errors" | "details" {
return this._mode;
}
onLoad() {
ErrorLazyLoadList.instance = this;
if (!this.scrollView.content) {
console.error("ScrollView.content is null!");
return;
}
onLoad() {
ErrorLazyLoadList.instance = this;
this._content = this.scrollView.content;
this._contentUI = this._content.getComponent(UITransform)!;
if (!this.scrollView.content) {
console.error("ScrollView.content is null!");
return;
}
// Calculate item height including spacing
const tempNode: Node = instantiate(this.errorItemPrefab);
const tempUI = tempNode.getComponent(UITransform);
this._itemHeight = tempUI!.height + this.spacing;
tempNode.destroy();
this._content = this.scrollView.content;
this._contentUI = this._content.getComponent(UITransform)!;
const tempNode: Node = instantiate(this.errorItemPrefab);
const tempUI = tempNode.getComponent(UITransform);
this._itemHeight = tempUI!.height;
tempNode.destroy();
this._mode = "errors";
this.waitForErrorManager();
this.scrollView.node.on('scrolling', this.onScrolling, this);
// Восстанавливаем сохраненное состояние
this._mode = ErrorLazyLoadList._savedMode;
if (ErrorLazyLoadList._savedSensorDescription) {
this._sensorDescription = ErrorLazyLoadList._savedSensorDescription;
}
this._filteredData = ErrorLazyLoadList._savedFilteredData;
// Устанавливаем правильный заголовок
if (this._mode === "details" && this._sensorDescription) {
this.header.string = `Детали ${this._sensorDescription.sensorName}`;
} else if (this._filteredData) {
this.header.string = `Аварии на ${this._filteredData[0]?.sensorName || "неизвестно"}`;
} else {
this.header.string = "Список всех аварий";
}
private onScrolling() {
const offsetY = this.scrollView.getScrollOffset().y;
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
const contentHeight = this._contentUI.height;
this.waitForErrorManager();
this.scrollView.node.on('scrolling', this.onScrolling, this);
}
if (offsetY + viewHeight + (this._itemHeight * 2) >= contentHeight) {
this.loadNextBatch(20);
onDestroy() {
// Сохраняем текущее состояние перед уничтожением
ErrorLazyLoadList._savedMode = this._mode;
ErrorLazyLoadList._savedSensorDescription = this._sensorDescription;
ErrorLazyLoadList._savedFilteredData = this._filteredData;
// Clean up event listeners
this.scrollView?.node?.off('scrolling', this.onScrolling, this);
const errorManagerNode = (ErrorManager.instance as any)?.node;
if (errorManagerNode) {
errorManagerNode.off('errors-updated', this.onDataUpdated, this);
}
// Clear pools and active items tracking
this._errorItemPool?.clear();
this._namedErrorItemPool?.clear();
this._sensorFieldItemPools.forEach(pool => pool.clear());
this._sensorFieldItemPools.clear();
this._activeSensorNames.clear();
this._activeSensorFieldItems.clear();
if (ErrorLazyLoadList.instance === this) {
ErrorLazyLoadList.instance = null;
}
}
private getOrCreateErrorItemPool(): NodePool {
if (!this._errorItemPool) {
this._errorItemPool = new NodePool();
for (let i = 0; i < this.visibleItemCount; i++) {
this._errorItemPool.put(instantiate(this.errorItemPrefab));
}
}
return this._errorItemPool;
}
onDestroy() {
if (ErrorLazyLoadList.instance === this) {
ErrorLazyLoadList.instance = null;
private getOrCreateNamedErrorItemPool(): NodePool {
if (!this._namedErrorItemPool) {
this._namedErrorItemPool = new NodePool();
for (let i = 0; i < this.visibleItemCount; i++) {
this._namedErrorItemPool.put(instantiate(this.errorItemNamedPrefab));
}
}
return this._namedErrorItemPool;
}
private getOrCreateSensorFieldItemPool(sensorName: string): NodePool {
// Используем один общий пул для всех датчиков
if (!this._sensorFieldItemPools.has('common')) {
const pool = new NodePool();
// Создаем пул достаточного размера
const poolSize = Math.max(this.visibleItemCount, 20);
for (let i = 0; i < poolSize; i++) {
const item = instantiate(this.sensorFieldItemPrefab);
// Сбрасываем состояние кнопок при создании
this.resetSensorFieldItemState(item);
pool.put(item);
}
this._sensorFieldItemPools.set('common', pool);
}
return this._sensorFieldItemPools.get('common')!;
}
private resetSensorFieldItemState(item: Node) {
// Сбрасываем состояние компонента SensorFieldItem
const sensorFieldItem = item.getComponent(SensorFieldItem);
if (sensorFieldItem) {
sensorFieldItem.resetState();
sensorFieldItem.reinitialize();
}
}
/**
* Полностью очищает все пулы и уничтожает элементы
*/
private clearAllPools() {
console.log('[ErrorLazyLoadList] Clearing all pools');
// Очищаем и уничтожаем элементы в пулах
if (this._errorItemPool) {
this._errorItemPool.clear();
this._errorItemPool = null;
}
if (this._namedErrorItemPool) {
this._namedErrorItemPool.clear();
this._namedErrorItemPool = null;
}
// Очищаем пулы датчиков
this._sensorFieldItemPools.forEach(pool => {
pool.clear();
});
this._sensorFieldItemPools.clear();
this._activeSensorNames.clear();
this._activeSensorFieldItems.clear();
}
private waitForErrorManager() {
if (!ErrorManager.instance) {
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
if (!ErrorManager.instance) {
this.scheduleOnce(() => { this.waitForErrorManager(); }, 0.1);
return;
}
// ErrorManager extends Component, so it has a node property
const errorManagerNode = (ErrorManager.instance as any).node;
if (errorManagerNode && typeof errorManagerNode.on === 'function') {
errorManagerNode.on('errors-updated', this.onDataUpdated, this);
} else {
console.warn("Could not subscribe to ErrorManager events - node not found");
}
// Обновляем отображение в зависимости от режима
if (this._mode === "errors") {
this.onDataUpdated();
} else if (this._mode === "details") {
// Для режима details обновляем размеры и элементы
this.updateVisibleItems(true); // Принудительно обновляем (включая высоту)
}
}
private onDataUpdated() {
if (this._mode !== "errors") return;
const apiErrors = ErrorManager.instance.getErrorList().apiErrors;
const flattened: ErrorItemData[] = [];
for (const sensorName in apiErrors) {
for (const err of apiErrors[sensorName]) {
flattened.push({ sensorName, alarmCode: err.alarmCode, description: err.description, timestamp: err.timestamp });
}
}
const oldDataLength = this._data.length;
this._data = flattened;
// Update both filtered and unfiltered views
if (this._filteredData) {
// If we have a filter, reapply it to the new data
const currentFilter = this._filteredData.length > 0 ? this._filteredData[0].sensorName : '';
if (currentFilter) {
const oldFilteredLength = this._filteredData.length;
this._filteredData = this._data.filter(item => item.sensorName === currentFilter);
this._totalCount = this._filteredData.length;
// Принудительно обновляем высоту если изменилось количество отфильтрованных элементов
if (oldFilteredLength !== this._filteredData.length) {
this.updateVisibleItems(true);
return;
}
}
} else {
this._totalCount = this._data.length;
// Принудительно обновляем высоту если изменилось общее количество элементов
if (oldDataLength !== this._data.length) {
this.updateVisibleItems(true);
return;
}
ErrorManager.instance.node.on('errors-updated', this.onDataUpdated, this);
this.onDataUpdated();
}
private onDataUpdated() {
if (this._mode !== "errors") return;
const apiErrors = ErrorManager.instance.getErrorList().apiErrors;
const flattened: ErrorItemData[] = [];
for (const sensorName in apiErrors) {
for (const err of apiErrors[sensorName]) {
flattened.push({ sensorName, alarmCode: err.alarmCode, description: err.description, timestamp: err.timestamp });
}
}
this._data = flattened;
if (!this._filteredData) {
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
}
private loadNextBatch(batchSize: number) {
let currentData: any[] = [];
if (this._mode === "errors") {
currentData = this._filteredData || this._data;
} else if (this._mode === "details") {
currentData = this._sensorDescription?.fields || [];
}
if (this._loadedCount >= currentData.length) return;
const endIndex = Math.min(this._loadedCount + batchSize, currentData.length);
for (let i = this._loadedCount; i < endIndex; i++) {
let item: Node;
switch (this._mode) {
case "errors":
item = instantiate(this._filteredData ? this.errorItemNamedPrefab : this.errorItemPrefab);
const componentName = this._filteredData ? "ErrorItemNamedButton" : "ErrorItemButton";
const errorItem = item.getComponent(componentName) as unknown as ErrorItemNamedButton | ErrorItemButton;
errorItem?.initialize(currentData[i]);
break;
case "details":
item = instantiate(this.sensorFieldItemPrefab);
const sensorFieldItem = item.getComponent(SensorFieldItem);
sensorFieldItem?.setData(currentData[i]);
break;
default:
continue;
}
item.setPosition(0, -(this._loadedCount * (this._itemHeight + this.spacing) + this._itemHeight / 2), 0);
this._content.addChild(item);
this._loadedCount++;
}
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing);
}
// Просто обновляем видимые элементы без уничтожения
this.updateVisibleItems();
}
private onScrolling() {
this.updateVisibleItems();
}
private updateVisibleItems(forceUpdate: boolean = false) {
const totalItems = this.getTotalItems();
private repositionChildren() {
let cumulativeHeight = 0;
// Проходим по всем дочерним элементам контейнера
for (let i = 0; i < this._content.children.length; i++) {
const child = this._content.children[i];
// Получаем актуальную высоту через UITransform
const childHeight = child.getComponent(UITransform)?.height || 0;
// Вычисляем позицию для этого элемента так, чтобы его центр был ниже предыдущего элемента
child.setPosition(0, - (cumulativeHeight + childHeight / 2), 0);
// Добавляем к накопленной высоте высоту элемента плюс spacing
cumulativeHeight += childHeight + this.spacing;
}
// Обновляем высоту контейнера, чтобы ScrollView корректно показывал содержимое
this._contentUI.height = cumulativeHeight;
// При принудительном обновлении всегда обновляем высоту контента
// Также обновляем высоту если изменилось общее количество элементов
if (forceUpdate || this._totalCount !== totalItems) {
this._totalCount = totalItems;
this.updateContentHeight();
}
const scrollY = this.scrollView.getScrollOffset().y;
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
// Calculate the first visible item index based on scroll position
const newFirstVisible = Math.floor(Math.max(0, scrollY) / this._itemHeight);
// Handle the case when there are no items
if (totalItems <= 0) {
this.hideAllItems();
return;
}
const newLastVisible = Math.min(
newFirstVisible + Math.ceil(viewHeight / this._itemHeight) + 2,
totalItems - 1
);
// Always update if visible range changed OR if forced
const needsUpdate = forceUpdate ||
newFirstVisible !== this._firstVisibleIndex ||
newLastVisible !== this._lastVisibleIndex;
if (!needsUpdate) {
return;
}
this._firstVisibleIndex = Math.max(0, newFirstVisible);
this._lastVisibleIndex = Math.max(0, newLastVisible);
/**
* В
/**
* Фильтрует список ошибок по имени оборудования.
* @param sensorName имя оборудования, по которому необходимо отфильтровать список
*/
public filterBySensor(sensorName: string) {
this.updatePoolItems();
}
private hideAllItems() {
// Return all active items to their pools
// Создаем копию массива, так как returnItemToPool может изменять _activeItems
const itemsToReturn = [...this._activeItems];
for (const item of itemsToReturn) {
this.returnItemToPool(item);
}
this._activeItems = [];
this._activeItemsData = []; // Очищаем данные отслеживания
}
private returnItemToPool(item: Node) {
if (!item || !item.isValid) return;
item.active = false;
item.removeFromParent();
// Determine which pool this item belongs to and return it
if (item.getComponent(ErrorItemButton)) {
this.getOrCreateErrorItemPool().put(item);
} else if (item.getComponent(ErrorItemNamedButton)) {
this.getOrCreateNamedErrorItemPool().put(item);
} else if (item.getComponent(SensorFieldItem)) {
// Для датчиков НЕ возвращаем в пул, а уничтожаем для гарантии чистого состояния
console.log(`[ErrorLazyLoadList] Destroying SensorFieldItem instead of pooling`);
// Удаляем из активных элементов
const sensorFieldItem = item.getComponent(SensorFieldItem);
if (sensorFieldItem && sensorFieldItem.sensorName) {
const activeItems = this._activeSensorFieldItems.get(sensorFieldItem.sensorName);
if (activeItems) {
activeItems.delete(item);
console.log(`[ErrorLazyLoadList] Removed item from active items for ${sensorFieldItem.sensorName}, remaining: ${activeItems.size}`);
}
}
if (sensorFieldItem) {
sensorFieldItem.resetState(); // Сбрасываем состояние перед уничтожением
}
item.destroy(); // Полностью уничтожаем элемент
}
}
private updatePoolItems() {
const currentData = this.getCurrentData();
const itemsToShow = Math.min(
this._lastVisibleIndex - this._firstVisibleIndex + 1,
currentData.length - this._firstVisibleIndex
);
// Определяем нужный пул для текущего режима
let currentPool: NodePool;
let expectedComponentType: string;
if (this._mode === "errors") {
if (this._filteredData) {
currentPool = this.getOrCreateNamedErrorItemPool();
expectedComponentType = "ErrorItemNamedButton";
} else {
currentPool = this.getOrCreateErrorItemPool();
expectedComponentType = "ErrorItemButton";
}
} else if (this._mode === "details") {
const sensorName = this._sensorDescription.sensorName;
currentPool = this.getOrCreateSensorFieldItemPool(sensorName);
expectedComponentType = "SensorFieldItem";
this._activeSensorNames.add(sensorName);
// Инициализируем Set для активных элементов этого датчика, если его нет
if (!this._activeSensorFieldItems.has(sensorName)) {
this._activeSensorFieldItems.set(sensorName, new Set());
}
} else {
return;
}
// Проверяем совместимость существующих элементов с текущим режимом
const incompatibleItems: Node[] = [];
for (const item of this._activeItems) {
const hasCorrectComponent = item.getComponent(expectedComponentType);
if (!hasCorrectComponent) {
incompatibleItems.push(item);
}
}
// Убираем несовместимые элементы
for (const item of incompatibleItems) {
const index = this._activeItems.indexOf(item);
if (index !== -1) {
this._activeItems.splice(index, 1);
this._activeItemsData.splice(index, 1);
this.returnItemToPool(item);
}
}
// Переиспользуем существующие элементы или создаем недостающие
const targetActiveCount = Math.max(0, itemsToShow);
// Если элементов больше чем нужно - скрываем лишние
while (this._activeItems.length > targetActiveCount) {
const item = this._activeItems.pop()!;
this._activeItemsData.pop();
this.returnItemToPool(item);
}
// Если элементов меньше чем нужно - добавляем новые
while (this._activeItems.length < targetActiveCount) {
let item: Node | null = null;
if (this._mode === "details") {
// Для датчиков всегда создаем новые элементы
item = this.createItemForCurrentMode();
} else {
// Для ошибок используем пул
item = currentPool.get() || this.createItemForCurrentMode();
}
if (!item) break;
this._content.addChild(item);
item.active = true;
this._activeItems.push(item);
this._activeItemsData.push(null); // Placeholder для новых элементов
// Если это элемент датчика, добавляем его в активные элементы
if (this._mode === "details") {
const sensorName = this._sensorDescription.sensorName;
let activeItems = this._activeSensorFieldItems.get(sensorName);
if (!activeItems) {
activeItems = new Set();
this._activeSensorFieldItems.set(sensorName, activeItems);
}
activeItems.add(item);
console.log(`[ErrorLazyLoadList] Added SensorFieldItem to active items for ${sensorName}, total: ${activeItems.size}`);
}
}
// Обновляем данные в существующих элементах ТОЛЬКО если данные изменились
for (let i = 0; i < this._activeItems.length; i++) {
const dataIndex = this._firstVisibleIndex + i;
const item = this._activeItems[i];
if (dataIndex >= 0 && dataIndex < currentData.length) {
const newData = currentData[dataIndex];
const oldData = this._activeItemsData[i];
// Для новых элементов датчиков всегда обновляем данные
// Для остальных - сравниваем данные и обновляем только если изменились
const isNewSensorItem = this._mode === "details" && !oldData;
// Для датчиков проверяем изменения в значениях полей более детально
let dataChanged = false;
if (this._mode === "details" && oldData && newData) {
dataChanged = oldData.name !== newData.name ||
oldData.value !== newData.value ||
oldData.unit !== newData.unit ||
oldData.description !== newData.description;
}
const needsUpdate = isNewSensorItem || !oldData ||
dataChanged ||
JSON.stringify(oldData) !== JSON.stringify(newData) ||
dataIndex !== this._activeItemsData[i]?.lastDataIndex;
if (needsUpdate) {
// Обновляем данные компонента
const component = this.getComponentForCurrentMode(item);
try {
switch (this._mode) {
case "errors":
if (component && 'initialize' in component && typeof component.initialize === 'function') {
(component as ErrorItemButton | ErrorItemNamedButton).initialize(newData);
}
break;
case "details":
if (component && 'setData' in component && typeof component.setData === 'function') {
console.log(`[ErrorLazyLoadList] Updating SensorFieldItem data: ${newData.name}`);
// Для новых элементов используем setData (полная инициализация)
// Для существующих элементов используем updateData (сохранение состояния UI)
if (isNewSensorItem) {
(component as SensorFieldItem).setData(newData);
} else {
(component as SensorFieldItem).updateData(newData);
}
}
break;
}
// Сохраняем новые данные для будущих сравнений
this._activeItemsData[i] = { ...newData, lastDataIndex: dataIndex };
} catch (e) {
console.warn("Error updating item component:", e);
}
}
// Позиционируем элемент (это нужно делать всегда для виртуализации)
item.setPosition(0, -(dataIndex * this._itemHeight + this._itemHeight / 2 - this.spacing / 2), 0);
// Показываем элемент только если он еще не виден
if (!item.active) {
item.active = true;
}
} else {
// Скрываем элементы вне диапазона
if (item.active) {
item.active = false;
}
this._activeItemsData[i] = null;
}
}
}
private createItemForCurrentMode(): Node | null {
if (this._mode === "errors") {
if (this._filteredData) {
return instantiate(this.errorItemNamedPrefab);
} else {
return instantiate(this.errorItemPrefab);
}
} else if (this._mode === "details") {
// Для датчиков всегда создаем новые элементы для гарантии чистого состояния
if (this._sensorDescription && this._sensorDescription.sensorName) {
console.log(`[ErrorLazyLoadList] Creating fresh SensorFieldItem for ${this._sensorDescription.sensorName}`);
const item = instantiate(this.sensorFieldItemPrefab);
// Сбрасываем состояние нового элемента
this.resetSensorFieldItemState(item);
return item;
}
return null;
}
return null;
}
private getComponentForCurrentMode(item: Node): Component | null {
if (this._mode === "errors") {
if (this._filteredData) {
return item.getComponent(ErrorItemNamedButton);
} else {
return item.getComponent(ErrorItemButton);
}
} else if (this._mode === "details") {
return item.getComponent(SensorFieldItem);
}
return null;
}
private getCurrentData(): any[] {
if (this._mode === "errors") {
return this._filteredData || this._data;
} else if (this._mode === "details") {
return this._sensorDescription?.fields || [];
}
return [];
}
private getTotalItems(): number {
return this.getCurrentData().length;
}
private updateContentHeight() {
const totalItems = this.getTotalItems();
const newHeight = totalItems * this._itemHeight;
const oldHeight = this._contentUI.height;
if (oldHeight !== newHeight) {
console.log(`[ErrorLazyLoadList] Updating content height: ${oldHeight} -> ${newHeight} (items: ${totalItems})`);
this._contentUI.height = newHeight;
}
}
private preserveScrollPosition(callback: () => void) {
const oldOffset = this.scrollView.getScrollOffset();
callback();
this.scheduleOnce(() => {
this.scrollView.scrollToOffset(oldOffset, 0.1);
}, 0);
}
/**
* Фильтрует список ошибок по имени оборудования.
* @param sensorName имя оборудования, по которому необходимо отфильтровать список
*/
public filterBySensor(sensorName: string) {
// Проверяем, действительно ли меняется фильтр
const isNewFilter = !this._filteredData ||
this._filteredData.length === 0 ||
this._filteredData[0].sensorName !== sensorName;
this.preserveScrollPosition(() => {
// Уничтожаем элементы и очищаем пулы если меняется фильтр
if (isNewFilter) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем пулы
}
this._mode = "errors";
this.header.string = `Аварии на ${sensorName}`;
this._filteredData = this._data.filter(item => item.sensorName === sensorName);
this._totalCount = this._filteredData.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
// Принудительно обновляем данные
this.updateVisibleItems(true);
});
}
/**
* Сбрасывает фильтр и возвращает отображение полного списка ошибок.
*/
public resetFilter() {
this.header.string = "Список всех аварий";
/**
* Сбрасывает фильтр и возвращает отображение полного списка ошибок.
*/
public resetFilter() {
// Проверяем, действительно ли есть активный фильтр
const hasActiveFilter = this._filteredData !== null;
this.preserveScrollPosition(() => {
// Уничтожаем элементы и очищаем пулы если был активный фильтр
if (hasActiveFilter) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем пулы
}
this.header.string = "Список всех аварий";
this._mode = "errors";
this._filteredData = null;
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
// Принудительно обновляем данные
this.updateVisibleItems(true);
});
}
/**
* Принимает данные описания оборудования и переключает режим отображения в "details".
* @param data Объект с деталями датчика.
*/
public showSensorDetails(data: { sensorName: string, fields: any[] }) {
/**
* Принимает данные описания оборудования и переключает режим отображения в "details".
* @param data Объект с деталями датчика.
*/
public showSensorDetails(data: { sensorName: string, fields: any[] }) {
// Проверяем, действительно ли меняется датчик или режим
const isNewSensor = !this._sensorDescription || this._sensorDescription.sensorName !== data.sensorName;
const isModeChange = this._mode !== "details";
this.preserveScrollPosition(() => {
// Уничтожаем элементы и очищаем пулы если меняется датчик или режим
if (isNewSensor || isModeChange) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем все пулы
}
this._mode = "details";
this.header.string = `Детали ${data.sensorName}`;
this._sensorDescription = {
sensorName: data.sensorName,
fields: data.fields
fields: data.fields || []
};
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
}
// Принудительно обновляем данные
this.updateVisibleItems(true);
});
}
/**
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
*/
public showErrors() {
/**
* Обновляет данные датчика без сброса UI состояния (для периодических обновлений).
* @param data Объект с деталями датчика.
*/
public updateSensorDetails(data: { sensorName: string, fields: any[] }) {
// Обновляем только если мы в режиме details и это тот же датчик
if (this._mode !== "details" || !this._sensorDescription ||
this._sensorDescription.sensorName !== data.sensorName) {
return;
}
console.log(`[ErrorLazyLoadList] updateSensorDetails: ${data.sensorName}, fields count: ${data.fields?.length || 0}`);
// Сохраняем старое количество полей для сравнения
const oldFieldsCount = this._sensorDescription.fields?.length || 0;
const newFieldsCount = data.fields?.length || 0;
// Обновляем данные
this._sensorDescription = {
sensorName: data.sensorName,
fields: data.fields || []
};
// Принудительно сбрасываем данные отслеживания для принудительного обновления
this._activeItemsData = this._activeItemsData.map(() => null);
// Принудительно обновляем все активные элементы датчика
this.forceUpdateActiveSensorItems(data.sensorName, data.fields);
// Если изменилось количество полей, принудительно обновляем высоту контента
if (oldFieldsCount !== newFieldsCount) {
this.updateVisibleItems(true);
} else {
// Обновляем видимые элементы без принудительного обновления высоты
this.updateVisibleItems(false);
}
}
/**
* Принудительно обновляет все активные элементы конкретного датчика
*/
private forceUpdateActiveSensorItems(sensorName: string, fields: any[]) {
const activeItems = this._activeSensorFieldItems.get(sensorName);
if (!activeItems || activeItems.size === 0) {
console.log(`[ErrorLazyLoadList] No active items found for sensor ${sensorName}`);
return;
}
console.log(`[ErrorLazyLoadList] Force updating ${activeItems.size} active items for sensor ${sensorName}`);
// Обновляем каждый активный элемент
let itemIndex = 0;
for (const item of activeItems) {
if (!item.isValid || !item.active) {
continue;
}
const component = item.getComponent(SensorFieldItem);
if (component && itemIndex < fields.length) {
const fieldData = fields[itemIndex];
console.log(`[ErrorLazyLoadList] Force updating item ${itemIndex}: ${fieldData.name} = ${fieldData.value}`);
// Используем updateData() вместо setData() для сохранения состояния UI
component.updateData(fieldData);
itemIndex++;
}
}
}
/**
* Возвращает в режим отображения ошибок (например, при переключении вкладок).
*/
public showErrors() {
// Проверяем, действительно ли меняется режим
const isModeChange = this._mode !== "errors";
this.preserveScrollPosition(() => {
// Уничтожаем элементы и очищаем пулы если меняется режим
if (isModeChange) {
this.hideAllItems();
this.clearAllPools(); // Полностью очищаем все пулы
}
this._mode = "errors";
this.header.string = "Список всех аварий";
this._filteredData = null;
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
// Принудительно обновляем данные
this.updateVisibleItems(true);
});
}
private updateSensorFieldItem(item: Node, data: any, dataIndex: number) {
const component = item.getComponent(SensorFieldItem);
if (component) {
component.setData(data);
}
}
private cleanupUnusedSensorPools() {
// Теперь у нас один общий пул, поэтому просто очищаем неиспользуемые ссылки
this._activeSensorNames.clear();
this._activeSensorFieldItems.clear();
}
}

View File

@ -1,5 +1,6 @@
import { _decorator, Component, Label, Color } from 'cc';
import { _decorator, Component, Label, Node } from 'cc'; // <-- добавили Node
import { SensorDescriptionField } from '../stores/SensorDescriptionField';
import { MorphButtonWithButton } from '../ux/MorphButtonWithButton';
const { ccclass, property } = _decorator;
@ccclass('SensorFieldItem')
@ -15,28 +16,226 @@ export class SensorFieldItem extends Component {
@property(Label)
public descriptionLabel: Label | null = null;
/** Нода-контейнер для анимации (спрайт + Label) */
@property({ type: Node })
public descriptionContainer: Node | null = null;
/** Нода Morph, которую нужно скрывать при наличии описания */
@property({ type: Node })
public Morph: Node | null = null;
/** Имя датчика для корректной работы с пулами */
public sensorName: string = "";
private morphButton: MorphButtonWithButton | null = null;
private buttonId: string = "";
private hasDescription: boolean = false;
protected onLoad(): void {
console.log(`[SensorFieldItem] onLoad: ${this.node.name} (${this.node.uuid})`);
// Сразу прячем контейнер, теперь active доступен
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
// Находим кнопку Morph
if (this.Morph) {
this.morphButton = this.Morph.getComponent(MorphButtonWithButton);
if (this.morphButton) {
this.buttonId = this.morphButton.getButtonId();
console.log(`[SensorFieldItem] Found MorphButton: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
// Подписываемся на изменение состояния кнопки
const button = this.Morph.getComponent('cc.Button') as any;
if (button) {
button.node.on('click', this.onMorphButtonClick, this);
}
}
}
}
protected onDestroy(): void {
// Отписываемся от событий при уничтожении
if (this.Morph && this.Morph.isValid) {
try {
const button = this.Morph.getComponent('cc.Button') as any;
if (button && button.node && button.node.isValid) {
button.node.off('click', this.onMorphButtonClick, this);
}
} catch (e) {
// Игнорируем ошибки при уничтожении
console.warn('[SensorFieldItem] Error in onDestroy:', e);
}
}
}
private onMorphButtonClick(): void {
if (!this.hasDescription || !this.morphButton) return;
// Ждем завершения анимации кнопки (2 кадра по 0.055 = 0.11 + небольшой запас)
this.scheduleOnce(() => {
this.syncDescriptionWithButton();
}, 0.15);
}
/**
* Синхронизирует видимость описания с состоянием кнопки
*/
private syncDescriptionWithButton(): void {
if (!this.morphButton || !this.hasDescription) return;
const isShowingDescription = !this.morphButton.getIsQuestion();
console.log(`[SensorFieldItem] syncDescriptionWithButton: button state = ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}, showing description = ${isShowingDescription}`);
if (this.descriptionContainer) {
this.descriptionContainer.active = isShowingDescription;
}
}
/**
* Установить данные для отображения поля датчика.
* @param field Объект поля датчика (name, value, unit, description)
*/
public setData(field: SensorDescriptionField): void {
if (this.nameLabel) this.nameLabel.string = field.name;
if (this.valueLabel) this.valueLabel.string = String(field.value);
if (this.unitLabel) {this.unitLabel.string = field.unit? field.unit: "????"}
// Отображение описания (мелким серым текстом, если есть)
if (this.descriptionLabel) {
if (field.description && field.description.trim() !== "") {
this.descriptionLabel.string = field.description;
// Применяем стили: серый цвет, мелкий шрифт
this.descriptionLabel.node.active = true;
} else {
// Если описания нет, скрываем или очищаем поле описания
this.setDataInternal(field, true); // Полная инициализация с сбросом состояния
}
/**
* Обновить только данные без сброса состояния UI (для обновлений в реальном времени).
* @param field Объект поля датчика (name, value, unit, description)
*/
public updateData(field: SensorDescriptionField): void {
this.setDataInternal(field, false); // Обновление без сброса состояния
}
/**
* Внутренний метод для установки данных с возможностью сохранения состояния UI
* @param field Объект поля датчика
* @param resetUIState Нужно ли сбрасывать состояние UI (кнопки и описания)
*/
private setDataInternal(field: SensorDescriptionField, resetUIState: boolean): void {
console.log(`[SensorFieldItem] ${resetUIState ? 'setData' : 'updateData'}: ${this.node.name} (${this.node.uuid}), field: ${field.name}, buttonId: ${this.buttonId}`);
this.descriptionLabel.node.active = false;
// Обновляем основные данные (это всегда нужно делать)
if (this.nameLabel) this.nameLabel.string = field.name;
if (this.valueLabel) this.valueLabel.string = String(field.value);
if (this.unitLabel) this.unitLabel.string = field.unit ?? "????";
this.hasDescription = !!field.description?.trim();
console.log(`[SensorFieldItem] Has description: ${this.hasDescription}, resetUIState: ${resetUIState}, buttonId: ${this.buttonId}`);
// Работаем с описанием
if (this.descriptionLabel) {
this.descriptionLabel.string = this.hasDescription ? field.description! : "";
}
if (resetUIState) {
// Полная инициализация - сбрасываем состояние UI
// Всегда начинаем с скрытого описания (кнопка в состоянии question)
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
// Morph: показываем кнопку только при наличии описания
if (this.Morph) {
this.Morph.active = this.hasDescription;
// Убеждаемся, что кнопка в состоянии question при первом показе
if (this.morphButton && this.morphButton.getIsQuestion() === false) {
console.log(`[SensorFieldItem] Fully reinitializing button to question state for: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId(); // Обновляем buttonId после полной переинициализации
}
// Принудительно синхронизируем состояние после небольшой задержки
this.scheduleOnce(() => {
this.syncDescriptionWithButton();
}, 0.05);
}
} else {
// Обновление данных - сохраняем текущее состояние UI
if (this.Morph) {
// Показываем/скрываем кнопку в зависимости от наличия описания
this.Morph.active = this.hasDescription;
// НЕ сбрасываем состояние кнопки, сохраняем текущее
// Только синхронизируем видимость описания с текущим состоянием кнопки
if (this.hasDescription) {
this.scheduleOnce(() => {
this.syncDescriptionWithButton();
}, 0.05);
} else {
// Если описания нет, скрываем контейнер
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
}
}
}
}
/**
* Сбросить состояние компонента к начальному
*/
public resetState(): void {
console.log(`[SensorFieldItem] resetState: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}`);
// Сбрасываем все данные
this.hasDescription = false;
this.sensorName = "";
// Сбрасываем текст в лейблах
if (this.nameLabel) this.nameLabel.string = "";
if (this.valueLabel) this.valueLabel.string = "";
if (this.unitLabel) this.unitLabel.string = "";
if (this.descriptionLabel) this.descriptionLabel.string = "";
// Скрываем контейнер описания
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
// Скрываем кнопку и сбрасываем её состояние
if (this.Morph) {
this.Morph.active = false;
if (this.morphButton) {
console.log(`[SensorFieldItem] Fully reinitializing MorphButton state in resetState: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId(); // Обновляем buttonId после полной переинициализации
}
}
}
/**
* Переинициализация компонента после получения из пула
*/
public reinitialize(): void {
console.log(`[SensorFieldItem] reinitialize start: ${this.node.name}`);
// Переинициализируем ссылку на кнопку, так как она могла измениться
if (this.Morph) {
// Сначала очищаем старую ссылку
this.morphButton = null;
// Получаем компонент заново
this.morphButton = this.Morph.getComponent(MorphButtonWithButton);
if (this.morphButton) {
console.log(`[SensorFieldItem] Before fullReinitialize - button state: ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}`);
// Используем полную переинициализацию вместо простого resetState
this.morphButton.fullReinitialize();
this.buttonId = this.morphButton.getButtonId();
console.log(`[SensorFieldItem] After fullReinitialize - button state: ${this.morphButton.getIsQuestion() ? 'question' : 'cross'}`);
console.log(`[SensorFieldItem] Fully reinitialized MorphButton: ${this.Morph.name} (${this.Morph.uuid}), buttonId: ${this.buttonId}`);
} else {
console.warn(`[SensorFieldItem] MorphButton component not found on ${this.Morph.name}`);
}
}
// Гарантируем, что описание скрыто
if (this.descriptionContainer) {
this.descriptionContainer.active = false;
}
}
}

View File

@ -1,4 +1,4 @@
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, MeshRenderer } from 'cc';
import { _decorator, Component, Prefab, ScrollView, instantiate, UITransform, Node, MeshRenderer, NodePool } from 'cc';
import { ItemButton } from '../ux/ItemButton';
import { apiSensors } from '../stores/apiSensors';
import { EquipmentManager } from '../stores/EquipmentManager';
@ -19,12 +19,23 @@ export class LazyLoadList extends Component {
@property
public spacing: number = 10;
@property
public visibleItemCount: number = 15; // Visible items buffer size
private _data: apiSensors[] = [];
private _totalCount: number = 0;
private _loadedCount: number = 0;
private _itemHeight: number = 0;
private _itemHeight: number = 0; // Including spacing
private _content: Node = null!;
private _contentUI: UITransform = null!;
// Pool for item reuse
private _itemPool: NodePool | null = null;
// Active items tracking
private _activeItems: Node[] = [];
private _activeItemsData: any[] = []; // Данные для отслеживания изменений
private _firstVisibleIndex: number = 0;
private _lastVisibleIndex: number = 0;
onLoad() {
if (!this.scrollView.content) {
@ -34,6 +45,7 @@ export class LazyLoadList extends Component {
this._content = this.scrollView.content;
this._contentUI = this._content.getComponent(UITransform)!;
// Calculate item height including spacing
const tempNode: Node = instantiate(this.itemPrefab);
const tempUI = tempNode.getComponent(UITransform);
if (!tempUI) {
@ -41,23 +53,27 @@ export class LazyLoadList extends Component {
tempNode.destroy();
return;
}
this._itemHeight = tempUI.height;
this._itemHeight = tempUI.height + this.spacing;
tempNode.destroy();
this.waitForEquipmentManager();
// Добавляем обработчик прокрутки по аналогии с рабочим компонентом
// Добавляем обработчик прокрутки для виртуализации
this.scrollView.node.on('scrolling', this.onScrolling, this);
}
private onScrolling() {
const offsetY = this.scrollView.getScrollOffset().y;
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
const contentHeight = this._contentUI.height;
if (offsetY + viewHeight + (this._itemHeight * 2) >= contentHeight) {
this.loadNextBatch(20);
private getOrCreateItemPool(): NodePool {
if (!this._itemPool) {
this._itemPool = new NodePool();
for (let i = 0; i < this.visibleItemCount; i++) {
this._itemPool.put(instantiate(this.itemPrefab));
}
}
return this._itemPool;
}
private onScrolling() {
this.updateVisibleItems();
}
private waitForEquipmentManager() {
@ -91,41 +107,163 @@ export class LazyLoadList extends Component {
this._data = allData.filter(item => validNames.indexOf(item.name) !== -1);
this._totalCount = this._data.length;
this._loadedCount = 0;
this._content.removeAllChildren();
this.loadNextBatch(20);
// Очищаем активные элементы
this.hideAllItems();
// Обновляем видимые элементы
this.updateVisibleItems(true);
}
loadNextBatch(batchSize: number) {
if (this._loadedCount >= this._totalCount) return;
const endIndex = Math.min(this._loadedCount + batchSize, this._totalCount);
private updateVisibleItems(forceUpdate: boolean = false) {
// При принудительном обновлении всегда обновляем высоту контента
if (forceUpdate) {
this.updateContentHeight();
}
for (let i = this._loadedCount; i < endIndex; i++) {
const item: Node = instantiate(this.itemPrefab);
const scrollY = this.scrollView.getScrollOffset().y;
const viewHeight = this.scrollView.node.getComponent(UITransform)!.height;
const posY = -(this._loadedCount * (this._itemHeight + this.spacing) + this._itemHeight / 2);
item.setPosition(0, posY, 0);
this._content.addChild(item);
// Calculate the first visible item index based on scroll position
const newFirstVisible = Math.floor(Math.max(0, scrollY) / this._itemHeight);
const totalItems = this._totalCount;
// Handle the case when there are no items
if (totalItems <= 0) {
this.hideAllItems();
return;
}
const newLastVisible = Math.min(
newFirstVisible + Math.ceil(viewHeight / this._itemHeight) + 2,
totalItems - 1
);
const itemButton = item.getComponent(ItemButton);
if (itemButton) {
itemButton.initialize(this._data[i]);
itemButton.itemIndex = i;
} else {
console.error("Компонент ItemButton не найден на ноде", item);
}
// Always update if visible range changed OR if forced
const needsUpdate = forceUpdate ||
newFirstVisible !== this._firstVisibleIndex ||
newLastVisible !== this._lastVisibleIndex;
this._loadedCount++;
if (!needsUpdate) {
return;
}
this._contentUI.height = this._loadedCount * (this._itemHeight + this.spacing);
this._firstVisibleIndex = Math.max(0, newFirstVisible);
this._lastVisibleIndex = Math.max(0, newLastVisible);
this.updatePoolItems();
}
private hideAllItems() {
// Return all active items to pool
const itemsToReturn = [...this._activeItems];
for (const item of itemsToReturn) {
this.returnItemToPool(item);
}
this._activeItems = [];
this._activeItemsData = [];
}
private returnItemToPool(item: Node) {
if (!item || !item.isValid) return;
item.active = false;
item.removeFromParent();
this.getOrCreateItemPool().put(item);
}
private updatePoolItems() {
const currentData = this._data;
const itemsToShow = Math.min(
this._lastVisibleIndex - this._firstVisibleIndex + 1,
currentData.length - this._firstVisibleIndex
);
const currentPool = this.getOrCreateItemPool();
const targetActiveCount = Math.max(0, itemsToShow);
// Если элементов больше чем нужно - скрываем лишние
while (this._activeItems.length > targetActiveCount) {
const item = this._activeItems.pop()!;
this._activeItemsData.pop();
this.returnItemToPool(item);
}
// Если элементов меньше чем нужно - добавляем новые
while (this._activeItems.length < targetActiveCount) {
const item = currentPool.get() || instantiate(this.itemPrefab);
if (!item) break;
this._content.addChild(item);
item.active = true;
this._activeItems.push(item);
this._activeItemsData.push(null); // Placeholder для новых элементов
}
// Обновляем данные в существующих элементах ТОЛЬКО если данные изменились
for (let i = 0; i < this._activeItems.length; i++) {
const dataIndex = this._firstVisibleIndex + i;
const item = this._activeItems[i];
if (dataIndex >= 0 && dataIndex < currentData.length) {
const newData = currentData[dataIndex];
const oldData = this._activeItemsData[i];
// Для новых элементов всегда обновляем данные
// Для остальных - сравниваем данные и обновляем только если изменились
const isNewItem = !oldData;
const needsUpdate = isNewItem ||
JSON.stringify(oldData) !== JSON.stringify(newData) ||
dataIndex !== this._activeItemsData[i]?.lastDataIndex;
if (needsUpdate) {
// Обновляем данные компонента
const component = item.getComponent(ItemButton);
if (component) {
if (isNewItem) {
// Для новых элементов используем полную инициализацию
component.initialize(newData);
} else {
// Для существующих элементов используем обновление данных
component.updateData(newData);
}
component.itemIndex = dataIndex;
}
// Сохраняем новые данные для будущих сравнений
this._activeItemsData[i] = { ...newData, lastDataIndex: dataIndex };
}
// Позиционируем элемент (это нужно делать всегда для виртуализации)
item.setPosition(0, -(dataIndex * this._itemHeight + this._itemHeight / 2 - this.spacing / 2), 0);
// Показываем элемент только если он еще не виден
if (!item.active) {
item.active = true;
}
} else {
// Скрываем элементы вне диапазона
if (item.active) {
item.active = false;
}
this._activeItemsData[i] = null;
}
}
}
private updateContentHeight() {
this._contentUI.height = this._totalCount * this._itemHeight;
}
onDestroy() {
if (EquipmentManager.instance) {
EquipmentManager.instance.node.off('data-updated', this.onDataUpdated, this);
}
this.scrollView.node.off('scrolling', this.onScrolling, this);
// Безопасно отписываемся от обновлений данных
EquipmentManager.instance?.node?.off('data-updated', this.onDataUpdated, this);
// Отписываемся от скроллинга, только если scrollView и его node ещё существуют
this.scrollView?.node?.off('scrolling', this.onScrolling, this);
// Очищаем пул и активные элементы
this._itemPool?.clear();
this._activeItems = [];
this._activeItemsData = [];
}
}

View File

@ -0,0 +1,9 @@
{
"ver": "1.2.0",
"importer": "directory",
"imported": true,
"uuid": "3d1e8b44-c4cc-4df7-85d8-5b53068e3077",
"files": [],
"subMetas": {},
"userData": {}
}

View File

@ -0,0 +1,57 @@
import { _decorator, Component, Node, UITransform, tween, easing, Vec3 } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('CornerToggle')
export class CornerToggle extends Component {
@property({ type: Node, tooltip: "Сюда перетащить ноду с Sprite и Label" })
public targetNode: Node | null = null;
private _origScale = new Vec3(1, 1, 1);
protected start(): void {
if (!this.targetNode) return;
// 1) Ставим pivot в верхний левый угол
const ui = this.targetNode.getComponent(UITransform);
if (ui) {
ui.anchorX = 0;
ui.anchorY = 1;
}
// 2) Запоминаем исходный scale
this._origScale = this.targetNode.scale.clone();
// 3) Приводим масштаб в соответствие текущему active
// (родитель уже мог задать .active = false в своём onLoad)
this.targetNode.scale = this.targetNode.active
? this._origScale.clone()
: new Vec3(0, 0, 0);
}
/** Вызывать из кнопки */
public toggle(): void {
if (!this.targetNode) return;
const node = this.targetNode;
const isVisible = node.active;
// откуда и куда анимируем
const from = isVisible ? this._origScale.clone() : new Vec3(0, 0, 0);
const to = isVisible ? new Vec3(0, 0, 0) : this._origScale.clone();
// если будем показывать — включаем до анимации
if (!isVisible) node.active = true;
node.scale = from;
tween(node)
.to(0.35, { scale: to }, { easing: easing.quadOut })
.call(() => {
// если скрываем — выключаем после
if (isVisible) {
node.active = false;
}
})
.start();
}
}

View File

@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "29a84805-4e9f-4bd5-be09-95f75abf2b99",
"files": [],
"subMetas": {},
"userData": {}
}

View File

@ -1,82 +1,91 @@
import { _decorator, Component, Node, tween, Vec3 } from 'cc';
// scripts/ui/equipmentListSwitch.ts
import { _decorator, Component, Node, tween, Vec3, Button } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('equipmentListSwitch')
export class equipmentListSwitch extends Component {
// Узел со списком оборудования
@property(Node)
public equipmentList: Node = null!;
/** Кнопка, которая переключает список */
@property(Button)
public toggleButton: Button | null = null;
// Смещение по оси X для закрытого состояния списка
@property
public offsetX: number = 250;
/** Узел со списком оборудования */
@property(Node)
public equipmentList: Node = null!;
// Длительность анимации
@property
public animationDuration: number = 0.3;
// Узел стрелки, который будет поворачиваться
@property({ type: Node })
public arrow: Node | null = null;
/** Смещение по X для закрытого состояния */
@property
public offsetX = 250;
// Позиции для анимации списка
private openPos: Vec3 = new Vec3();
private closedPos: Vec3 = new Vec3();
/** Длительность анимации */
@property
public animationDuration = 0.3;
// Флаг, показывающий текущее состояние списка
private isOnToggle: boolean = false;
start() {
// Сохраняем позицию списка как открытое положение
this.openPos = this.equipmentList.getPosition().clone();
// Вычисляем закрытое положение (смещение по оси X)
this.closedPos = new Vec3(this.openPos.x - this.offsetX, this.openPos.y, this.openPos.z);
// Изначально скрываем список, устанавливая его в закрытое положение
this.equipmentList.setPosition(this.closedPos);
// Изначально устанавливаем стрелке угол 0
if (this.arrow) {
this.arrow.angle = 0;
}
/** Узел стрелки, который будет поворачиваться */
@property(Node)
public arrow: Node | null = null;
private openPos = new Vec3();
private closedPos = new Vec3();
private isOnToggle = false;
onLoad() {
// Подписываем кнопку на метод переключения
this.toggleButton?.node?.on('click', this.equipmentSwitch, this);
}
start() {
// Сохраняем открытое и закрытое положения
this.openPos = this.equipmentList.getPosition().clone();
this.closedPos = new Vec3(
this.openPos.x - this.offsetX,
this.openPos.y,
this.openPos.z
);
// Изначально скрываем список (перемещаем в closedPos)
this.equipmentList.setPosition(this.closedPos);
// Изначально стрелка в 0°
if (this.arrow) this.arrow.angle = 0;
}
private stopTween() {
tween(this.equipmentList).stop();
if (this.arrow) tween(this.arrow).stop();
}
/** Вызывается по нажатию toggleButton */
public equipmentSwitch() {
this.stopTween();
if (this.isOnToggle) {
// закрываем
this.isOnToggle = false;
tween(this.equipmentList)
.to(this.animationDuration, { position: this.closedPos })
.start();
if (this.arrow) {
tween(this.arrow)
.to(this.animationDuration, { angle: 0 })
.start();
}
} else {
// открываем
this.isOnToggle = true;
tween(this.equipmentList)
.to(this.animationDuration, { position: this.openPos })
.start();
if (this.arrow) {
tween(this.arrow)
.to(this.animationDuration, { angle: 180 })
.start();
}
}
}
// Метод для остановки всех текущих анимаций
private stopTween() {
tween(this.equipmentList).stop();
if (this.arrow) {
tween(this.arrow).stop();
}
}
// Метод переключения состояния списка и одновременной анимации стрелки
public equipmentSwitch() {
// Останавливаем текущие анимации, чтобы избежать их наложения
this.stopTween();
if (this.isOnToggle) {
// Если список открыт — закрываем его и поворачиваем стрелку обратно в 0°
this.isOnToggle = false;
tween(this.equipmentList)
.to(this.animationDuration, { position: this.closedPos })
.start();
if (this.arrow) {
tween(this.arrow)
.to(this.animationDuration, { angle: 0 })
.start();
}
} else {
// Если список закрыт — открываем его и поворачиваем стрелку на 180°
this.isOnToggle = true;
tween(this.equipmentList)
.to(this.animationDuration, { position: this.openPos })
.start();
if (this.arrow) {
tween(this.arrow)
.to(this.animationDuration, { angle: 180 })
.start();
}
}
}
onDestroy() {
// Корректно отписываемся от клика
this.toggleButton?.node?.off('click', this.equipmentSwitch, this);
// Останавливаем любые выполняющиеся твины
this.stopTween();
}
}

View File

@ -0,0 +1,9 @@
{
"ver": "1.2.0",
"importer": "directory",
"imported": true,
"uuid": "2b40a2c5-8f10-47e1-a279-4e3bca4ec221",
"files": [],
"subMetas": {},
"userData": {}
}

View File

@ -0,0 +1,6 @@
// scripts/utils/SceneHistory.ts
export class SceneHistory {
/** Имя последней загруженной сцены */
public static lastScene: string = '';
}

View File

@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "97252a72-96d8-473b-aa0b-c68fdf00b10b",
"files": [],
"subMetas": {},
"userData": {}
}

View File

@ -13,8 +13,6 @@ export class ErrorItemButton extends Component {
@property(Label)
public timeLabel: Label | null = null;
@property(Button)
public actionButton: Button | null = null; // Первая кнопка – выбирает оборудование
@ -23,117 +21,68 @@ export class ErrorItemButton extends Component {
private itemData: ErrorItemData | null = null;
// Инициализация данных для элемента ошибки
public initialize(data: ErrorItemData) {
this.itemData = data;
if (this.nameLabel) {
this.nameLabel.string = data.sensorName;
}
if (this.timeLabel) {
this.timeLabel.string = data.description;
}
this.nameLabel && (this.nameLabel.string = data.sensorName);
this.timeLabel && (this.timeLabel.string = data.description);
}
onLoad() {
if (this.actionButton) {
this.actionButton.node.on('click', this.onActionClick, this);
}
if (this.disableAlertButton) {
this.disableAlertButton.node.on('click', this.onDisableAlertClick, this);
}
// Подписываемся только если кнопки и их node существуют
this.actionButton?.node?.on('click', this.onActionClick, this);
this.disableAlertButton?.node?.on('click', this.onDisableAlertClick, this);
}
onDestroy() {
if (this.actionButton) {
this.actionButton.node.off('click', this.onActionClick, this);
}
if (this.disableAlertButton) {
this.disableAlertButton.node.off('click', this.onDisableAlertClick, this);
}
// Безопасно отписываемся
this.actionButton?.node?.off('click', this.onActionClick, this);
this.disableAlertButton?.node?.off('click', this.onDisableAlertClick, this);
}
// Обработка клика по кнопке стандартного действия (без изменений)
onActionClick(event?: Event) {
if (!this.itemData) return;
const sensors = EquipmentManager.instance.dataList;
const sensorData = sensors.find(s => s.name === this.itemData!.sensorName);
if (!sensorData) {
console.warn(`Sensor ${this.itemData.sensorName} not found!`);
return;
}
if (!sensorData) return;
let color = "";
if (sensorData.value === 2) {
color = "red";
} else if (sensorData.value === 1) {
color = "green";
} else if (sensorData.value === 0) {
color = "yellow";
} else {
return;
let color = '';
switch (sensorData.value) {
case 2: color = 'red'; break;
case 1: color = 'green'; break;
case 0: color = 'yellow'; break;
default: return;
}
const scene = this.node.scene;
if (!scene) {
return;
}
if (!scene) return;
// Рекурсивно ищем узел с именем, соответствующим sensorName
const targetNode = this.findNodeByName(scene, this.itemData.sensorName);
if (!targetNode) {
return;
}
const highlighter = targetNode.getComponent(PulsatingHighlighter);
if (highlighter) {
highlighter.switchToColor(color);
} else {
}
const cameraMover = scene.getComponentInChildren(CameraMover);
if (cameraMover) {
cameraMover.moveToTarget(targetNode);
} else {
if (targetNode) {
targetNode.getComponent(PulsatingHighlighter)?.switchToColor(color);
scene.getComponentInChildren(CameraMover)?.moveToTarget(targetNode);
}
}
// Обработка клика по кнопке отключения оповещения (отправляет запрос на API)
async onDisableAlertClick(event?: Event) {
if (!this.itemData) return;
try {
const response = await fetch("http://localhost:3030/api/v2/errors/resolve", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
sensorName: this.itemData.sensorName
// Если требуется, можно передать alarmCode: this.itemData.alarmCode
})
const response = await fetch('http://localhost:3030/api/v2/errors/resolve', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sensorName: this.itemData.sensorName })
});
const result = await response.json();
console.log("Error resolved:", result);
// При необходимости можно вызвать обновление состояния ErrorManager
console.log('Error resolved:', await response.json());
} catch (error) {
console.error("Error resolving error via API:", error);
console.error('Error resolving via API:', error);
}
}
// Рекурсивный поиск узла по имени
private findNodeByName(root: Node, name: string): Node | null {
if (root.name === name) return root;
for (let i = 0; i < root.children.length; i++) {
const found = this.findNodeByName(root.children[i], name);
for (const child of root.children) {
const found = this.findNodeByName(child, name);
if (found) return found;
}
return null;

View File

@ -1,5 +1,3 @@
import { _decorator, Component, Label, Button, Node, Event } from 'cc';
import { EquipmentManager } from '../stores/EquipmentManager';
import { PulsatingHighlighter } from '../PulsatingHighlighter';
@ -15,16 +13,11 @@ export class ErrorItemNamedButton extends Component {
@property(Label)
public timeLabel: Label | null = null;
@property(Button)
public actionButton: Button | null = null; // Первая кнопка – выбирает оборудование
private itemData: ErrorItemData | null = null;
// Инициализация данных для элемента ошибки
public initialize(data: ErrorItemData) {
this.itemData = data;
if (this.nameLabel) {
@ -33,27 +26,17 @@ export class ErrorItemNamedButton extends Component {
if (this.timeLabel) {
this.timeLabel.string = data.timestamp;
}
console.log('Initialized ErrorItemButton with data:', data);
}
onLoad() {
if (this.actionButton) {
this.actionButton.node.on('click', this.onActionClick, this);
} else {
console.warn('Action button not assigned.');
}
this.actionButton?.node?.on('click', this.onActionClick, this);
}
onDestroy() {
if (this.actionButton) {
this.actionButton.node.off('click', this.onActionClick, this);
}
this.actionButton?.node?.off('click', this.onActionClick, this);
}
// Обработка клика по кнопке стандартного действия (без изменений)
onActionClick(event?: Event) {
console.log('Action clicked for error:', this.itemData);
if (!this.itemData) return;
@ -83,7 +66,6 @@ export class ErrorItemNamedButton extends Component {
return;
}
// Рекурсивно ищем узел с именем, соответствующим sensorName
const targetNode = this.findNodeByName(scene, this.itemData.sensorName);
if (!targetNode) {
console.warn(`Node with name ${this.itemData.sensorName} not found!`);
@ -105,14 +87,10 @@ export class ErrorItemNamedButton extends Component {
}
}
// Обработка клика по кнопке отключения оповещения (отправляет запрос на API)
// Рекурсивный поиск узла по имени
private findNodeByName(root: Node, name: string): Node | null {
if (root.name === name) return root;
for (let i = 0; i < root.children.length; i++) {
const found = this.findNodeByName(root.children[i], name);
for (const child of root.children) {
const found = this.findNodeByName(child, name);
if (found) return found;
}
return null;

View File

@ -45,10 +45,28 @@ export class ItemButton extends Component {
this.itemData = data;
if (this.nameLabel) {
this.nameLabel.string = data.name;
// Изначально скрываем кнопку ошибок
this.ErrorButton.node.active = false;
}
// Дополнительная логика, если требуется
// Обновляем состояние ошибок без мерцания
this.updateErrorStatus();
}
/**
* Обновляет только данные элемента без полной переинициализации
*/
public updateData(data: apiSensors) {
// Проверяем, действительно ли данные изменились
if (this.itemData && this.itemData.name === data.name && this.itemData.value === data.value) {
return; // Данные не изменились, не обновляем
}
this.itemData = data;
if (this.nameLabel && this.nameLabel.string !== data.name) {
this.nameLabel.string = data.name;
}
// Обновляем состояние ошибок только если данные действительно изменились
this.updateErrorStatus();
}
onLoad() {
@ -70,16 +88,10 @@ export class ItemButton extends Component {
}
onDestroy() {
if (this.button) {
this.button.node.off("click", this.onClick, this);
}
if (this.ErrorButton) {
this.ErrorButton.node.off("click", this.onErrorClick, this);
}
if (ErrorManager.instance) {
ErrorManager.instance.node.off('errors-updated', this.updateErrorStatus, this);
}
}
this.button?.node?.off("click", this.onClick, this);
this.ErrorButton?.node?.off("click", this.onErrorClick, this);
ErrorManager.instance?.node?.off("errors-updated", this.updateErrorStatus, this);
}
/**
* Рекурсивный поиск узла по имени.
@ -215,16 +227,20 @@ export class ItemButton extends Component {
* Обновление состояния ошибки на кнопке в зависимости от данных оборудования.
*/
private updateErrorStatus() {
if (!this.itemData || !EquipmentManager.instance || !ErrorManager.instance) {
return;
}
const sensors = EquipmentManager.instance.dataList;
const sensorData = sensors.find((s) => s.name === this.itemData.name);
if (!sensorData) {
this.ErrorButton.node.active = false;
this.setErrorButtonState(false, "0");
return;
}
// Если датчик активен – скрываем кнопку ошибок
if (sensorData.value === SensorStatus.Active) {
this.ErrorButton.node.active = false;
this.setErrorButtonState(false, "0");
return;
}
@ -238,10 +254,26 @@ export class ItemButton extends Component {
// Если есть хотя бы одна ошибка, отображаем кнопку с количеством ошибок
if (errorCount > 0) {
this.ErrorButton.node.active = true;
this.ErrorNumber.string = errorCount.toString();
this.setErrorButtonState(true, errorCount.toString());
} else {
this.ErrorButton.node.active = false;
this.setErrorButtonState(false, "0");
}
}
/**
* Устанавливает состояние кнопки ошибок только если оно изменилось
*/
private setErrorButtonState(isVisible: boolean, errorText: string) {
if (!this.ErrorButton || !this.ErrorNumber) return;
// Обновляем видимость только если она изменилась
if (this.ErrorButton.node.active !== isVisible) {
this.ErrorButton.node.active = isVisible;
}
// Обновляем текст только если он изменился
if (this.ErrorNumber.string !== errorText) {
this.ErrorNumber.string = errorText;
}
}
}

View File

@ -0,0 +1,146 @@
import { _decorator, Component, Sprite, SpriteFrame, tween, Button, Tween, Node, Color } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('MorphButtonWithButton')
export class MorphButtonWithButton extends Component {
@property(SpriteFrame) questionFrame!: SpriteFrame;
@property(SpriteFrame) noiseFrame!: SpriteFrame;
@property(SpriteFrame) crossFrame!: SpriteFrame;
@property(Sprite) targetSprite!: Sprite;
private isQuestion = true;
private buttonId: string = '';
private currentTween: Tween<Node> | null = null;
onLoad() {
// Генерируем уникальный ID для кнопки
this.buttonId = `${this.node.name}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
console.log(`[MorphButton] onLoad: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}`);
this.initializeSprite();
}
private initializeSprite() {
if (this.targetSprite && this.questionFrame) {
this.targetSprite.spriteFrame = this.questionFrame;
this.isQuestion = true;
}
}
public fullReinitialize() {
console.log(`[MorphButton] fullReinitialize START: ${this.node.name} (${this.node.uuid}), current state: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем все анимации
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
Tween.stopAllByTarget(this.targetSprite?.node);
// Полностью переинициализируем состояние
this.isQuestion = true;
this.currentTween = null;
// Переинициализируем спрайт
this.initializeSprite();
// Генерируем новый ID для отладки
this.buttonId = `${this.node.name}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
console.log(`[MorphButton] fullReinitialize COMPLETE: ${this.node.name}, new state: ${this.isQuestion ? 'question' : 'cross'}, buttonId: ${this.buttonId}`);
}
onDestroy() {
// Останавливаем все анимации при уничтожении
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
Tween.stopAllByTarget(this.targetSprite?.node);
}
public onClick() {
console.log(`[MorphButton] onClick: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}, current state: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем предыдущую анимацию, если она есть
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
const frames = this.isQuestion
? [this.noiseFrame, this.crossFrame]
: [this.noiseFrame, this.questionFrame];
const dt = 0.055;
// Передаём цель – targetSprite.node, чтобы Tween точно запустился
let tw = tween(this.targetSprite.node);
for (const frame of frames) {
tw = tw
.delay(dt)
.call(() => {
this.targetSprite.spriteFrame = frame;
});
}
// Меняем состояние только после завершения анимации
tw = tw.call(() => {
this.isQuestion = !this.isQuestion;
console.log(`[MorphButton] Animation complete, new state: ${this.isQuestion ? 'question' : 'cross'}`);
});
// Сохраняем ссылку на текущий tween
this.currentTween = tw;
tw.start();
}
public resetState() {
console.log(`[MorphButton] resetState: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}, was: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем любые активные анимации
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
// Останавливаем все tween на спрайте
Tween.stopAllByTarget(this.targetSprite.node);
// Сбрасываем состояние
this.isQuestion = true;
// Принудительно сбрасываем спрайт
this.forceResetSprite();
}
private forceResetSprite() {
if (!this.targetSprite || !this.questionFrame) {
console.warn('[MorphButton] Cannot reset sprite - missing targetSprite or questionFrame');
return;
}
// Метод 1: Прямая установка
this.targetSprite.spriteFrame = this.questionFrame;
// Метод 2: Очистка и повторная установка
this.targetSprite.spriteFrame = null;
this.scheduleOnce(() => {
if (this.targetSprite && this.questionFrame) {
this.targetSprite.spriteFrame = this.questionFrame;
console.log(`[MorphButton] Sprite reset complete`);
}
}, 0);
// Метод 3: Принудительное обновление через изменение других свойств
const originalColor = this.targetSprite.color.clone();
this.targetSprite.color = new Color(255, 255, 255, 254);
this.targetSprite.color = originalColor;
}
public getButtonId(): string {
return this.buttonId;
}
public getIsQuestion(): boolean {
return this.isQuestion;
}
}

View File

@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "4d4ae451-9c31-45f6-82d9-79ae9893eefa",
"files": [],
"subMetas": {},
"userData": {}
}

View File

@ -1,4 +1,6 @@
import { _decorator, Component, director, SceneAsset, input, Input, EventMouse, CameraComponent, geometry, PhysicsSystem } from 'cc';
// scripts/SceneLoaderOnDoubleClick3D.ts
import { _decorator, Component, director, SceneAsset, input, Input, EventMouse, geometry, PhysicsSystem, Camera } from 'cc';
import { SceneHistory } from '../utils/SceneHistory';
const { ccclass, property } = _decorator;
@ccclass('SceneLoaderOnDoubleClick3D')
@ -6,54 +8,57 @@ export class SceneLoaderOnDoubleClick3D extends Component {
@property({ type: SceneAsset, tooltip: 'Сцена для загрузки при двойном клике' })
public targetScene: SceneAsset | null = null;
@property({ type: CameraComponent, tooltip: 'Основная камера' })
public camera: CameraComponent | null = null;
@property({ type: Camera, tooltip: 'Основная камера' })
public camera: Camera | null = null;
// Интервал для определения двойного клика (в мс)
private _doubleClickThreshold: number = 300;
private _lastClickTime: number = 0;
private _doubleClickThreshold = 300;
private _lastClickTime = 0;
onLoad() {
// Подписываемся на глобальное событие
input.on(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
}
onDestroy() {
input.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
input?.off(Input.EventType.MOUSE_DOWN, this.onMouseDown, this);
}
onMouseDown(event: EventMouse) {
private onMouseDown(event: EventMouse) {
if (event.getButton() !== EventMouse.BUTTON_LEFT) return;
const now = performance.now();
if (now - this._lastClickTime < this._doubleClickThreshold) {
this.handleDoubleClick(event);
this._lastClickTime = 0;
} else {
this._lastClickTime = now;
}
}
const currentTime = Date.now();
if (currentTime - this._lastClickTime < this._doubleClickThreshold) {
// Если камера не назначена, выводим ошибку
if (!this.camera) {
console.error('Основная камера не назначена!');
return;
}
// Выполняем преобразование экрана в луч
const clickPos = event.getLocation(); // координаты клика
let ray = new geometry.Ray();
this.camera.screenPointToRay(clickPos.x, clickPos.y, ray);
private handleDoubleClick(event: EventMouse) {
if (!this.camera) {
console.error('Камера не назначена!');
return;
}
// Выполняем Raycast
if (PhysicsSystem.instance.raycast(ray)) {
const results = PhysicsSystem.instance.raycastResults;
// Проверяем, что среди результатов есть наш объект
let hit = results.find(result => result.collider.node === this.node);
if (hit) {
console.log(`Двойной клик по ${this.node.name}`);
if (this.targetScene) {
console.log(`Загрузка сцены: ${this.targetScene.name}`);
director.loadScene(this.targetScene.name);
const x = event.getLocationX();
const y = event.getLocationY();
const ray = new geometry.Ray();
this.camera.screenPointToRay(x, y, ray);
if (PhysicsSystem.instance.raycastClosest(ray)) {
const res = PhysicsSystem.instance.raycastClosestResult;
if (res.collider?.node === this.node) {
if (this.targetScene) {
// вариант с проверкой
const cur = director.getScene();
if (cur) {
SceneHistory.lastScene = cur.name;
} else {
console.error('Сцена не указана!');
console.warn('Не удалось получить текущую сцену');
}
director.loadScene(this.targetScene.name);
}
}
}
this._lastClickTime = currentTime;
}
}

View File

@ -0,0 +1,42 @@
// scripts/ui/ScrollHandler.ts
import { _decorator, Component, ScrollView, ScrollBar, UITransform, EventTouch, Vec3, clamp } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('ScrollHandler')
export class ScrollHandler extends Component {
@property(ScrollView) scrollView: ScrollView = null!;
@property(ScrollBar) scrollBar: ScrollBar = null!;
onLoad() {
// Подпишемся, только если есть handle-спрайт
const handleSprite = this.scrollBar.handle;
if (!handleSprite) {
console.error('ScrollHandler: у ScrollBar нет handle–спрайта!');
return;
}
handleSprite.node.on('touch-move', this.onDrag, this);
}
onDestroy() {
// Безопасно отписываемся от события touch-move
this.scrollBar.handle?.node?.off('touch-move', this.onDrag, this);
}
private onDrag(evt: EventTouch) {
const handleSprite = this.scrollBar.handle;
if (!handleSprite) return;
const barNode = this.scrollBar.node;
const ui = barNode.getComponent(UITransform)!;
const worldPos = evt.getLocation();
const local = ui.convertToNodeSpaceAR(new Vec3(worldPos.x, worldPos.y, 0));
const H = ui.height;
const handleH = handleSprite.node.getComponent(UITransform)!.height;
let pct = (local.y + H/2 - handleH/2) / (H - handleH);
pct = clamp(pct, 0, 1);
// ПРОПУСКАЕМ инверсию — передаём pct напрямую
this.scrollView.scrollToPercentVertical(pct, 0);
}
}

View File

@ -0,0 +1,9 @@
{
"ver": "4.0.24",
"importer": "typescript",
"imported": true,
"uuid": "3a213e52-0450-4f60-bdb7-30ab6bd6a528",
"files": [],
"subMetas": {},
"userData": {}
}