diff --git a/package-lock.json b/package-lock.json index a899339..a6c8aad 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,10 +25,13 @@ "@mui/styles": "^6.1.6", "@mui/x-date-pickers": "^7.26.0", "@react-pdf/renderer": "^4.3.0", + "@react-three/drei": "^9.105.6", + "@react-three/fiber": "^8.18.0", "@sentry/react": "^8.38.0", "@turf/area": "^7.2.0", "@turf/turf": "^7.2.0", "@types/classnames": "^2.3.0", + "@types/three": "^0.183.1", "axios": "^1.7.7", "crisp-sdk-web": "^1.0.26", "dayjs": "^1.11.13", @@ -61,6 +64,7 @@ "react-virtualized-auto-sizer": "^1.0.25", "recharts": "^2.15.1", "semver": "^7.7.1", + "three": "^0.152.2", "victory": "^37.3.6", "weather-icons-react": "^1.2.0" }, @@ -1775,6 +1779,12 @@ } } }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "license": "Apache-2.0" + }, "node_modules/@emotion/babel-plugin": { "version": "11.13.5", "resolved": "https://registry.npmjs.org/@emotion/babel-plugin/-/babel-plugin-11.13.5.tgz", @@ -2470,6 +2480,12 @@ "gl-style-validate": "dist/gl-style-validate.mjs" } }, + "node_modules/@mediapipe/tasks-vision": { + "version": "0.10.8", + "resolved": "https://registry.npmjs.org/@mediapipe/tasks-vision/-/tasks-vision-0.10.8.tgz", + "integrity": "sha512-Rp7ll8BHrKB3wXaRFKhrltwZl1CiXGdibPxuWXvqGnKTnv8fqa/nvftYNuSbf+pbJWKYCXdBtYTITdAUTGGh0Q==", + "license": "Apache-2.0" + }, "node_modules/@mui/core-downloads-tracker": { "version": "6.5.0", "resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-6.5.0.tgz", @@ -3222,6 +3238,192 @@ "@react-pdf/stylesheet": "^6.1.2" } }, + "node_modules/@react-spring/animated": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@react-spring/animated/-/animated-9.6.1.tgz", + "integrity": "sha512-ls/rJBrAqiAYozjLo5EPPLLOb1LM0lNVQcXODTC1SMtS6DbuBCPaKco5svFUQFMP2dso3O+qcC4k9FsKc0KxMQ==", + "license": "MIT", + "dependencies": { + "@react-spring/shared": "~9.6.1", + "@react-spring/types": "~9.6.1" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/@react-spring/core": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@react-spring/core/-/core-9.6.1.tgz", + "integrity": "sha512-3HAAinAyCPessyQNNXe5W0OHzRfa8Yo5P748paPcmMowZ/4sMfaZ2ZB6e5x5khQI8NusOHj8nquoutd6FRY5WQ==", + "license": "MIT", + "dependencies": { + "@react-spring/animated": "~9.6.1", + "@react-spring/rafz": "~9.6.1", + "@react-spring/shared": "~9.6.1", + "@react-spring/types": "~9.6.1" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/react-spring/donate" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/@react-spring/rafz": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@react-spring/rafz/-/rafz-9.6.1.tgz", + "integrity": "sha512-v6qbgNRpztJFFfSE3e2W1Uz+g8KnIBs6SmzCzcVVF61GdGfGOuBrbjIcp+nUz301awVmREKi4eMQb2Ab2gGgyQ==", + "license": "MIT" + }, + "node_modules/@react-spring/shared": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@react-spring/shared/-/shared-9.6.1.tgz", + "integrity": "sha512-PBFBXabxFEuF8enNLkVqMC9h5uLRBo6GQhRMQT/nRTnemVENimgRd+0ZT4yFnAQ0AxWNiJfX3qux+bW2LbG6Bw==", + "license": "MIT", + "dependencies": { + "@react-spring/rafz": "~9.6.1", + "@react-spring/types": "~9.6.1" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0" + } + }, + "node_modules/@react-spring/three": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@react-spring/three/-/three-9.6.1.tgz", + "integrity": "sha512-Tyw2YhZPKJAX3t2FcqvpLRb71CyTe1GvT3V+i+xJzfALgpk10uPGdGaQQ5Xrzmok1340DAeg2pR/MCfaW7b8AA==", + "license": "MIT", + "dependencies": { + "@react-spring/animated": "~9.6.1", + "@react-spring/core": "~9.6.1", + "@react-spring/shared": "~9.6.1", + "@react-spring/types": "~9.6.1" + }, + "peerDependencies": { + "@react-three/fiber": ">=6.0", + "react": "^16.8.0 || ^17.0.0 || ^18.0.0", + "three": ">=0.126" + } + }, + "node_modules/@react-spring/types": { + "version": "9.6.1", + "resolved": "https://registry.npmjs.org/@react-spring/types/-/types-9.6.1.tgz", + "integrity": "sha512-POu8Mk0hIU3lRXB3bGIGe4VHIwwDsQyoD1F394OK7STTiX9w4dG3cTLljjYswkQN+hDSHRrj4O36kuVa7KPU8Q==", + "license": "MIT" + }, + "node_modules/@react-three/drei": { + "version": "9.105.6", + "resolved": "https://registry.npmjs.org/@react-three/drei/-/drei-9.105.6.tgz", + "integrity": "sha512-JBgYeV36N9N9f1c3o1ZfLYW4rXZA7UQTq32Y8s3DEF6lwj1/y+RP/yq2VG5I8OzUPl7gsmWdy8fpWZgrlAqUpQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.11.2", + "@mediapipe/tasks-vision": "0.10.8", + "@monogrid/gainmap-js": "^3.0.5", + "@react-spring/three": "~9.6.1", + "@use-gesture/react": "^10.2.24", + "camera-controls": "^2.4.2", + "cross-env": "^7.0.3", + "detect-gpu": "^5.0.28", + "glsl-noise": "^0.0.0", + "hls.js": "1.3.5", + "maath": "^0.10.7", + "meshline": "^3.1.6", + "react-composer": "^5.0.3", + "stats-gl": "^2.0.0", + "stats.js": "^0.17.0", + "suspend-react": "^0.1.3", + "three-mesh-bvh": "^0.7.0", + "three-stdlib": "^2.29.9", + "troika-three-text": "^0.49.0", + "tunnel-rat": "^0.1.2", + "utility-types": "^3.10.0", + "uuid": "^9.0.1", + "zustand": "^3.7.1" + }, + "peerDependencies": { + "@react-three/fiber": ">=8.0", + "react": ">=18.0", + "react-dom": ">=18.0", + "three": ">=0.137" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/@react-three/drei/node_modules/@monogrid/gainmap-js": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@monogrid/gainmap-js/-/gainmap-js-3.4.0.tgz", + "integrity": "sha512-2Z0FATFHaoYJ8b+Y4y4Hgfn3FRFwuU5zRrk+9dFWp4uGAdHGqVEdP7HP+gLA3X469KXHmfupJaUbKo1b/aDKIg==", + "license": "MIT", + "dependencies": { + "promise-worker-transferable": "^1.0.4" + }, + "peerDependencies": { + "three": ">= 0.159.0" + } + }, + "node_modules/@react-three/fiber": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.18.0.tgz", + "integrity": "sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.17.8", + "@types/react-reconciler": "^0.26.7", + "@types/webxr": "*", + "base64-js": "^1.5.1", + "buffer": "^6.0.3", + "its-fine": "^1.0.6", + "react-reconciler": "^0.27.0", + "react-use-measure": "^2.1.7", + "scheduler": "^0.21.0", + "suspend-react": "^0.1.3", + "zustand": "^3.7.1" + }, + "peerDependencies": { + "expo": ">=43.0", + "expo-asset": ">=8.4", + "expo-file-system": ">=11.0", + "expo-gl": ">=11.0", + "react": ">=18 <19", + "react-dom": ">=18 <19", + "react-native": ">=0.64", + "three": ">=0.133" + }, + "peerDependenciesMeta": { + "expo": { + "optional": true + }, + "expo-asset": { + "optional": true + }, + "expo-file-system": { + "optional": true + }, + "expo-gl": { + "optional": true + }, + "react-dom": { + "optional": true + }, + "react-native": { + "optional": true + } + } + }, + "node_modules/@react-three/fiber/node_modules/scheduler": { + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.21.0.tgz", + "integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, "node_modules/@remix-run/router": { "version": "1.23.3", "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz", @@ -5575,6 +5777,12 @@ "url": "https://opencollective.com/turf" } }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "license": "MIT" + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -5728,6 +5936,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/draco3d": { + "version": "1.4.10", + "resolved": "https://registry.npmjs.org/@types/draco3d/-/draco3d-1.4.10.tgz", + "integrity": "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw==", + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", @@ -5887,6 +6101,12 @@ "integrity": "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==", "license": "MIT" }, + "node_modules/@types/offscreencanvas": { + "version": "2019.7.3", + "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.3.tgz", + "integrity": "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A==", + "license": "MIT" + }, "node_modules/@types/parse-json": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz", @@ -5971,6 +6191,15 @@ "@types/viewport-mercator-project": "*" } }, + "node_modules/@types/react-reconciler": { + "version": "0.26.7", + "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.26.7.tgz", + "integrity": "sha512-mBDYl8x+oyPX/VBb3E638N0B7xG+SPk/EAMcVPeexqus/5aTpTphQi0curhhshOqRrc9t6OPoJfEUkbymse/lQ==", + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, "node_modules/@types/react-redux": { "version": "7.1.34", "resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.34.tgz", @@ -6025,6 +6254,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "license": "MIT" + }, "node_modules/@types/supercluster": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/@types/supercluster/-/supercluster-7.1.3.tgz", @@ -6034,6 +6269,21 @@ "@types/geojson": "*" } }, + "node_modules/@types/three": { + "version": "0.183.1", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.183.1.tgz", + "integrity": "sha512-f2Pu5Hrepfgavttdye3PsH5RWyY/AvdZQwIVhrc4uNtvF7nOWJacQKcoVJn0S4f0yYbmAE6AR+ve7xDcuYtMGw==", + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": ">=0.5.17", + "@webgpu/types": "*", + "fflate": "~0.8.2", + "meshoptimizer": "~1.0.1" + } + }, "node_modules/@types/trusted-types": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", @@ -6051,6 +6301,12 @@ "gl-matrix": "^3.2.0" } }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.56.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.56.0.tgz", @@ -6320,6 +6576,24 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@use-gesture/core": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/@use-gesture/core/-/core-10.3.1.tgz", + "integrity": "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw==", + "license": "MIT" + }, + "node_modules/@use-gesture/react": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/@use-gesture/react/-/react-10.3.1.tgz", + "integrity": "sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g==", + "license": "MIT", + "dependencies": { + "@use-gesture/core": "10.3.1" + }, + "peerDependencies": { + "react": ">= 16.8.0" + } + }, "node_modules/@vis.gl/react-mapbox": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/@vis.gl/react-mapbox/-/react-mapbox-8.1.0.tgz", @@ -6491,6 +6765,12 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@webgpu/types": { + "version": "0.1.69", + "resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.69.tgz", + "integrity": "sha512-RPmm6kgRbI8e98zSD3RVACvnuktIja5+yLgDAkTmxLr90BEwdTXRQWNLF3ETTTyH/8mKhznZuN5AveXYFEsMGQ==", + "license": "BSD-3-Clause" + }, "node_modules/abs-svg-path": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/abs-svg-path/-/abs-svg-path-0.1.1.tgz", @@ -6936,6 +7216,30 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/buffer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", + "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.2.1" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -7092,6 +7396,15 @@ "node": ">=8" } }, + "node_modules/camera-controls": { + "version": "2.10.1", + "resolved": "https://registry.npmjs.org/camera-controls/-/camera-controls-2.10.1.tgz", + "integrity": "sha512-KnaKdcvkBJ1Irbrzl8XD6WtZltkRjp869Jx8c0ujs9K+9WD+1D7ryBsCiVqJYUqt6i/HR5FxT7RLASieUD+Q5w==", + "license": "MIT", + "peerDependencies": { + "three": ">=0.126.1" + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001770", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001770.tgz", @@ -7332,11 +7645,28 @@ "integrity": "sha512-aNWR3te65YiaVFu/iwdqOo3cyUBZHUheE4d6EtgQu/T18jh/9SpoYXjXF/OzUD3Cqy0pGryoqtuy5gxD8tqX9Q==", "license": "MIT" }, + "node_modules/cross-env": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz", + "integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==", + "license": "MIT", + "dependencies": { + "cross-spawn": "^7.0.1" + }, + "bin": { + "cross-env": "src/bin/cross-env.js", + "cross-env-shell": "src/bin/cross-env-shell.js" + }, + "engines": { + "node": ">=10.14", + "npm": ">=6", + "yarn": ">=1" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -7836,6 +8166,15 @@ "node": ">=0.4.0" } }, + "node_modules/detect-gpu": { + "version": "5.0.70", + "resolved": "https://registry.npmjs.org/detect-gpu/-/detect-gpu-5.0.70.tgz", + "integrity": "sha512-bqerEP1Ese6nt3rFkwPnGbsUF9a4q+gMmpTVVOEzoCyeCc+y7/RvJnQZJx1JwhgQI5Ntg0Kgat8Uu7XpBqnz1w==", + "license": "MIT", + "dependencies": { + "webgl-constants": "^1.1.1" + } + }, "node_modules/dfa": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/dfa/-/dfa-1.2.0.tgz", @@ -7870,6 +8209,12 @@ "url": "https://github.com/sponsors/panva" } }, + "node_modules/draco3d": { + "version": "1.5.7", + "resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.7.tgz", + "integrity": "sha512-m6WCKt/erDXcw+70IJXnG7M3awwQPAsZvJGX5zY7beBqpELw6RDGkYVU0W43AFxye4pDZ5i2Lbyc/NNGqwjUVQ==", + "license": "Apache-2.0" + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -8453,6 +8798,12 @@ } } }, + "node_modules/fflate": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.2.tgz", + "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -9030,6 +9381,12 @@ "dev": true, "license": "MIT" }, + "node_modules/glsl-noise": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/glsl-noise/-/glsl-noise-0.0.0.tgz", + "integrity": "sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w==", + "license": "MIT" + }, "node_modules/goober": { "version": "2.1.18", "resolved": "https://registry.npmjs.org/goober/-/goober-2.1.18.tgz", @@ -9189,6 +9546,12 @@ "node": ">= 0.4" } }, + "node_modules/hls.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.3.5.tgz", + "integrity": "sha512-uybAvKS6uDe0MnWNEPnO0krWVr+8m2R0hJ/viql8H3MVK+itq8gGQuIYoFHL3rECkIpNH98Lw8YuuWMKZxp3Ew==", + "license": "Apache-2.0" + }, "node_modules/hoist-non-react-statics": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz", @@ -9300,6 +9663,26 @@ "dev": true, "license": "ISC" }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", @@ -9310,6 +9693,12 @@ "node": ">= 4" } }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "license": "MIT" + }, "node_modules/import-fresh": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", @@ -9685,6 +10074,12 @@ "node": ">=0.10.0" } }, + "node_modules/is-promise": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-2.2.2.tgz", + "integrity": "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ==", + "license": "MIT" + }, "node_modules/is-regex": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", @@ -9870,7 +10265,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, "license": "ISC" }, "node_modules/isobject": { @@ -9882,6 +10276,27 @@ "node": ">=0.10.0" } }, + "node_modules/its-fine": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/its-fine/-/its-fine-1.2.5.tgz", + "integrity": "sha512-fXtDA0X0t0eBYAGLVM5YsgJGsJ5jEmqZEPrGbzdf5awjv0xE7nqv3TVnvtUF060Tkes15DbDAKW/I48vsb6SyA==", + "license": "MIT", + "dependencies": { + "@types/react-reconciler": "^0.28.0" + }, + "peerDependencies": { + "react": ">=18.0" + } + }, + "node_modules/its-fine/node_modules/@types/react-reconciler": { + "version": "0.28.9", + "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.28.9.tgz", + "integrity": "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg==", + "license": "MIT", + "peerDependencies": { + "@types/react": "*" + } + }, "node_modules/jackspeak": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz", @@ -10212,6 +10627,15 @@ "integrity": "sha512-rDU6bkpuMs8YRt/UpkuYEAsYSoNuDEbrE41I3KNvmXREGH6DGBJ8Wbak4by29wNOQ27zk4g4HL82zf0OGhwRuw==", "license": "MIT" }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, "node_modules/linebreak": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/linebreak/-/linebreak-1.1.0.tgz", @@ -10359,6 +10783,16 @@ "yallist": "^3.0.2" } }, + "node_modules/maath": { + "version": "0.10.8", + "resolved": "https://registry.npmjs.org/maath/-/maath-0.10.8.tgz", + "integrity": "sha512-tRvbDF0Pgqz+9XUa4jjfgAQ8/aPKmQdWXilFu2tMy4GWj4NOsx99HlULO4IeREfbO3a0sA145DZYyvXPkybm0g==", + "license": "MIT", + "peerDependencies": { + "@types/three": ">=0.134.0", + "three": ">=0.134.0" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -10503,6 +10937,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/meshline": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/meshline/-/meshline-3.3.1.tgz", + "integrity": "sha512-/TQj+JdZkeSUOl5Mk2J7eLcYTLiQm2IDzmlSvYm7ov15anEcDJ92GHqqazxTSreeNgfnYu24kiEvvv0WlbCdFQ==", + "license": "MIT", + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/meshoptimizer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.0.1.tgz", + "integrity": "sha512-Vix+QlA1YYT3FwmBBZ+49cE5y/b+pRrcXKqGpS5ouh33d3lSp2PoTpCw19E0cKDFWalembrHnIaZetf27a+W2g==", + "license": "MIT" + }, "node_modules/mime-db": { "version": "1.52.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", @@ -11034,7 +11483,6 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -11275,6 +11723,16 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/promise-worker-transferable": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/promise-worker-transferable/-/promise-worker-transferable-1.0.4.tgz", + "integrity": "sha512-bN+0ehEnrXfxV2ZQvU2PetO0n4gqBD4ulq3MI1WOPLgr7/Mg9yRQkX5+0v1vagr74ZTsl7XtzlaYDo2EuCeYJw==", + "license": "Apache-2.0", + "dependencies": { + "is-promise": "^2.1.0", + "lie": "^3.0.2" + } + }, "node_modules/prop-types": { "version": "15.8.1", "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", @@ -11294,7 +11752,7 @@ }, "node_modules/protobuf-ts": { "version": "1.0.0", - "resolved": "git+https://gitlab+deploy-token-50627:hv8mB4WkyvtjBpJKU1rN@gitlab.com/brandx/protobuf-ts.git#8c5091affb9c1ef4e80c675072435b745b07e612", + "resolved": "git+https://gitlab+deploy-token-50627:hv8mB4WkyvtjBpJKU1rN@gitlab.com/brandx/protobuf-ts.git#9c0f668d4a56b8216dd71a44c3110a818aaf3541", "dependencies": { "protobufjs": "^6.8.8" } @@ -11475,6 +11933,18 @@ "react": "*" } }, + "node_modules/react-composer": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/react-composer/-/react-composer-5.0.3.tgz", + "integrity": "sha512-1uWd07EME6XZvMfapwZmc7NgCZqDemcvicRi3wMJzXsQLvZ3L7fTHVyPy1bZdnWXM4iPjYuNE+uJ41MLKeTtnA==", + "license": "MIT", + "dependencies": { + "prop-types": "^15.6.0" + }, + "peerDependencies": { + "react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0" + } + }, "node_modules/react-day-picker": { "version": "9.13.2", "resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-9.13.2.tgz", @@ -11730,6 +12200,31 @@ "react-dom": "^16.12.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^20.0.0 || ^21.0.0" } }, + "node_modules/react-reconciler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.27.0.tgz", + "integrity": "sha512-HmMDKciQjYmBRGuuhIaKA1ba/7a+UsM5FzOZsMO2JYHt9Jh8reCb7j1eDC95NOyUlKM9KRyvdx0flBuDvYSBoA==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.21.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^18.0.0" + } + }, + "node_modules/react-reconciler/node_modules/scheduler": { + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.21.0.tgz", + "integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, "node_modules/react-redux": { "version": "7.2.9", "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.2.9.tgz", @@ -11834,6 +12329,21 @@ "react-dom": ">=16.6.0" } }, + "node_modules/react-use-measure": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.7.tgz", + "integrity": "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==", + "license": "MIT", + "peerDependencies": { + "react": ">=16.13", + "react-dom": ">=16.13" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, "node_modules/react-virtualized-auto-sizer": { "version": "1.0.26", "resolved": "https://registry.npmjs.org/react-virtualized-auto-sizer/-/react-virtualized-auto-sizer-1.0.26.tgz", @@ -12470,7 +12980,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -12483,7 +12992,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -12800,6 +13308,32 @@ "dev": true, "license": "MIT" }, + "node_modules/stats-gl": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/stats-gl/-/stats-gl-2.4.2.tgz", + "integrity": "sha512-g5O9B0hm9CvnM36+v7SFl39T7hmAlv541tU81ME8YeSb3i1CIP5/QdDeSB3A0la0bKNHpxpwxOVRo2wFTYEosQ==", + "license": "MIT", + "dependencies": { + "@types/three": "*", + "three": "^0.170.0" + }, + "peerDependencies": { + "@types/three": "*", + "three": "*" + } + }, + "node_modules/stats-gl/node_modules/three": { + "version": "0.170.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.170.0.tgz", + "integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ==", + "license": "MIT" + }, + "node_modules/stats.js": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/stats.js/-/stats.js-0.17.0.tgz", + "integrity": "sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw==", + "license": "MIT" + }, "node_modules/std-env": { "version": "3.10.0", "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", @@ -13055,6 +13589,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/suspend-react": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/suspend-react/-/suspend-react-0.1.3.tgz", + "integrity": "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==", + "license": "MIT", + "peerDependencies": { + "react": ">=17.0" + } + }, "node_modules/svg-arc-to-cubic-bezier": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/svg-arc-to-cubic-bezier/-/svg-arc-to-cubic-bezier-3.2.0.tgz", @@ -13131,6 +13674,50 @@ "node": ">=10" } }, + "node_modules/three": { + "version": "0.152.2", + "resolved": "https://registry.npmjs.org/three/-/three-0.152.2.tgz", + "integrity": "sha512-Ff9zIpSfkkqcBcpdiFo2f35vA9ZucO+N8TNacJOqaEE6DrB0eufItVMib8bK8Pcju/ZNT6a7blE1GhTpkdsILw==", + "license": "MIT" + }, + "node_modules/three-mesh-bvh": { + "version": "0.7.6", + "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.7.6.tgz", + "integrity": "sha512-rCjsnxEqR9r1/C/lCqzGLS67NDty/S/eT6rAJfDvsanrIctTWdNoR4ZOGWewCB13h1QkVo2BpmC0wakj1+0m8A==", + "license": "MIT", + "peerDependencies": { + "three": ">= 0.151.0" + } + }, + "node_modules/three-stdlib": { + "version": "2.36.1", + "resolved": "https://registry.npmjs.org/three-stdlib/-/three-stdlib-2.36.1.tgz", + "integrity": "sha512-XyGQrFmNQ5O/IoKm556ftwKsBg11TIb301MB5dWNicziQBEs2g3gtOYIf7pFiLa0zI2gUwhtCjv9fmjnxKZ1Cg==", + "license": "MIT", + "dependencies": { + "@types/draco3d": "^1.4.0", + "@types/offscreencanvas": "^2019.6.4", + "@types/webxr": "^0.5.2", + "draco3d": "^1.4.1", + "fflate": "^0.6.9", + "potpack": "^1.0.1" + }, + "peerDependencies": { + "three": ">=0.128.0" + } + }, + "node_modules/three-stdlib/node_modules/fflate": { + "version": "0.6.10", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.6.10.tgz", + "integrity": "sha512-IQrh3lEPM93wVCEczc9SaAOvkmcoQn/G8Bo1e8ZPlY3X3bnAxWaBdvTdvM1hP62iZp0BXWDy4vTAy4fF0+Dlpg==", + "license": "MIT" + }, + "node_modules/three-stdlib/node_modules/potpack": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/potpack/-/potpack-1.0.2.tgz", + "integrity": "sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ==", + "license": "ISC" + }, "node_modules/tiny-inflate": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", @@ -13273,6 +13860,36 @@ "node": ">=8" } }, + "node_modules/troika-three-text": { + "version": "0.49.1", + "resolved": "https://registry.npmjs.org/troika-three-text/-/troika-three-text-0.49.1.tgz", + "integrity": "sha512-lXGWxgjJP9kw4i4Wh+0k0Q/7cRfS6iOME4knKht/KozPu9GcFA9NnNpRvehIhrUawq9B0ZRw+0oiFHgRO+4Wig==", + "license": "MIT", + "dependencies": { + "bidi-js": "^1.0.2", + "troika-three-utils": "^0.49.0", + "troika-worker-utils": "^0.49.0", + "webgl-sdf-generator": "1.1.1" + }, + "peerDependencies": { + "three": ">=0.125.0" + } + }, + "node_modules/troika-three-utils": { + "version": "0.49.0", + "resolved": "https://registry.npmjs.org/troika-three-utils/-/troika-three-utils-0.49.0.tgz", + "integrity": "sha512-umitFL4cT+Fm/uONmaQEq4oZlyRHWwVClaS6ZrdcueRvwc2w+cpNQ47LlJKJswpqtMFWbEhOLy0TekmcPZOdYA==", + "license": "MIT", + "peerDependencies": { + "three": ">=0.125.0" + } + }, + "node_modules/troika-worker-utils": { + "version": "0.49.0", + "resolved": "https://registry.npmjs.org/troika-worker-utils/-/troika-worker-utils-0.49.0.tgz", + "integrity": "sha512-1xZHoJrG0HFfCvT/iyN41DvI/nRykiBtHqFkGaGgJwq5iXfIZFBiPPEHFpPpgyKM3Oo5ITHXP5wM2TNQszYdVg==", + "license": "MIT" + }, "node_modules/ts-api-utils": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz", @@ -13313,6 +13930,43 @@ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "license": "0BSD" }, + "node_modules/tunnel-rat": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/tunnel-rat/-/tunnel-rat-0.1.2.tgz", + "integrity": "sha512-lR5VHmkPhzdhrM092lI2nACsLO4QubF0/yoOhzX7c+wIpbN1GjHNzCc91QlpxBi+cnx8vVJ+Ur6vL5cEoQPFpQ==", + "license": "MIT", + "dependencies": { + "zustand": "^4.3.2" + } + }, + "node_modules/tunnel-rat/node_modules/zustand": { + "version": "4.5.7", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz", + "integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==", + "license": "MIT", + "dependencies": { + "use-sync-external-store": "^1.2.2" + }, + "engines": { + "node": ">=12.7.0" + }, + "peerDependencies": { + "@types/react": ">=16.8", + "immer": ">=9.0.6", + "react": ">=16.8" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + } + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -13663,12 +14317,43 @@ "react": "^16.8.0 || ^17.0.0 || ^18.0.0" } }, + "node_modules/use-sync-external-store": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", + "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", + "license": "MIT", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, + "node_modules/utility-types": { + "version": "3.11.0", + "resolved": "https://registry.npmjs.org/utility-types/-/utility-types-3.11.0.tgz", + "integrity": "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/uuid": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", + "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", @@ -14703,6 +15388,17 @@ "integrity": "sha512-VlLyZb9rb0Ir/NvC6T3YOcnftzUMg8hDYMb9xf1pzzM5z5wKogL6q1wZeqE5e+oHSw0CVcTFtYCbSa1ZEwnDZQ==", "license": "MIT" }, + "node_modules/webgl-constants": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/webgl-constants/-/webgl-constants-1.1.1.tgz", + "integrity": "sha512-LkBXKjU5r9vAW7Gcu3T5u+5cvSvh5WwINdr0C+9jpzVB41cjQAP5ePArDtk/WHYdVj0GefCgM73BA7FlIiNtdg==" + }, + "node_modules/webgl-sdf-generator": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/webgl-sdf-generator/-/webgl-sdf-generator-1.1.1.tgz", + "integrity": "sha512-9Z0JcMTFxeE+b2x1LJTdnaT8rT8aEp7MVxkNwoycNmJWwPdzoXzMh0BjJSh/AEFP+KPYZUli814h8bJZFIZ2jA==", + "license": "MIT" + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", @@ -14729,7 +15425,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -15229,6 +15924,23 @@ "resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz", "integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==", "license": "MIT" + }, + "node_modules/zustand": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-3.7.2.tgz", + "integrity": "sha512-PIJDIZKtokhof+9+60cpockVOq05sJzHCriyvaLBmEJixseQ1a5Kdov6fWZfWOu5SK9c+FhH1jU0tntLxRJYMA==", + "license": "MIT", + "engines": { + "node": ">=12.7.0" + }, + "peerDependencies": { + "react": ">=16.8" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + } + } } } } diff --git a/package.json b/package.json index 95526be..1fb2505 100644 --- a/package.json +++ b/package.json @@ -38,10 +38,13 @@ "@mui/styles": "^6.1.6", "@mui/x-date-pickers": "^7.26.0", "@react-pdf/renderer": "^4.3.0", + "@react-three/drei": "^9.105.6", + "@react-three/fiber": "^8.18.0", "@sentry/react": "^8.38.0", "@turf/area": "^7.2.0", "@turf/turf": "^7.2.0", "@types/classnames": "^2.3.0", + "@types/three": "^0.183.1", "axios": "^1.7.7", "crisp-sdk-web": "^1.0.26", "dayjs": "^1.11.13", @@ -74,6 +77,7 @@ "react-virtualized-auto-sizer": "^1.0.25", "recharts": "^2.15.1", "semver": "^7.7.1", + "three": "^0.152.2", "victory": "^37.3.6", "weather-icons-react": "^1.2.0" }, diff --git a/src/3dModels/CameraControls/CameraOverlay.tsx b/src/3dModels/CameraControls/CameraOverlay.tsx new file mode 100644 index 0000000..080aab9 --- /dev/null +++ b/src/3dModels/CameraControls/CameraOverlay.tsx @@ -0,0 +1,90 @@ +import { useThree } from "@react-three/fiber"; +import { useEffect, useRef, useState } from "react"; +import ReactDOM from "react-dom"; + +interface Props { + showResetButton?: boolean; + onReset?: () => void; +} + +/** + * Renders camera control UI buttons as a DOM overlay on top of the R3F canvas. + * Must be placed inside a so it has access to useThree(). + * + * Uses a portal into a div that is absolutely positioned over the canvas element, + * so the buttons sit in 2D screen space rather than 3D world space. + */ +export default function CameraOverlay({ showResetButton, onReset }: Props) { + const { gl } = useThree(); + const [container, setContainer] = useState(null); + + useEffect(() => { + const canvas = gl.domElement; + const parent = canvas.parentElement; + if (!parent) return; + + // Ensure the parent is positioned so absolute children are relative to it + const parentPosition = getComputedStyle(parent).position; + if (parentPosition === "static") { + parent.style.position = "relative"; + } + + const div = document.createElement("div"); + div.style.cssText = ` + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + pointer-events: none; + z-index: 10; + `; + parent.appendChild(div); + setContainer(div); + + return () => { + parent.removeChild(div); + }; + }, [gl]); + + if (!container) return null; + + return ReactDOM.createPortal( +
+ {showResetButton && ( + + )} +
, + container + ); +} \ No newline at end of file diff --git a/src/3dModels/CameraControls/OrbitCameraControls.tsx b/src/3dModels/CameraControls/OrbitCameraControls.tsx new file mode 100644 index 0000000..7e098d6 --- /dev/null +++ b/src/3dModels/CameraControls/OrbitCameraControls.tsx @@ -0,0 +1,329 @@ +import React from "react"; +import { useThree } from "@react-three/fiber"; +import { useEffect, useRef } from "react"; +import { Vector2, Vector3 } from "three"; + +interface CameraTarget { + x: number; + y: number; + z: number; +} + +interface Props { + target?: CameraTarget; + clampVerticalRotation?: boolean; + /** + * The minimum vertical rotation in radians + * @default 0.01 + */ + minPhi?: number; + /** + * The maximum vertical rotation in radians + * @default Math.PI - 0.01 + */ + maxPhi?: number; + /** + * Starting camera distance from the target. + * Pass a value computed from the bin dimensions so the whole bin + * fits in frame on first render. If omitted defaults to 10. + */ + initialRadius?: number; + /** + * Maximum zoom-out distance. Defaults to 30 but should be set + * larger when initialRadius is large. + */ + maxRadius?: number; + /** + * used to control the offset of the target from the center that the camera rotates around + */ + offset?: { x: number; y: number; z: number }; + viewOffset?: number; + /** + * Called when the camera is reset to its initial position. + * OrbitCameraControls manages the reset internally — use this to + * trigger it from outside (e.g. from CameraOverlay's reset button). + * Wire it by passing a ref setter: onReset={fn => resetFn.current = fn} + */ + onReset?: (resetFn: () => void) => void; +} + +export default function OrbitCameraControls(props: Props) { + const { + target, + clampVerticalRotation, + minPhi = 0.01, + maxPhi = Math.PI - 0.01, + offset, + viewOffset, + initialRadius, + maxRadius, + onReset, + } = props; + + const { camera, gl } = useThree(); + + const mouse = useRef(new Vector2()); + const targetRef = useRef({ + x: (target?.x ?? 0) + (offset?.x ?? 0), + y: (target?.y ?? 0) + (offset?.y ?? 0), + z: (target?.z ?? 0) + (offset?.z ?? 0), + }); + + const isDragging = useRef(false); + const isPanning = useRef(false); + const lastPos = useRef({ x: 0, y: 0 }); + const panCameraPosition = useRef(new Vector3()); + const lastPinchDist = useRef(0); + + // Spherical coords + const spherical = useRef({ + radius: initialRadius ?? 10, + theta: 0, // horizontal angle + phi: Math.PI / 2, // vertical angle + }); + + useEffect(() => { + // Sync radius whenever initialRadius prop changes (e.g. after bin data loads) + spherical.current.radius = initialRadius ?? 10; + + const canvas = gl.domElement; + canvas.addEventListener("contextmenu", e => e.preventDefault()); + + const updateCamera = () => { + const { radius, theta, phi } = spherical.current; + + const x = radius * Math.sin(phi) * Math.sin(theta); + const y = radius * Math.cos(phi); + const z = radius * Math.sin(phi) * Math.cos(theta); + + camera.position.set( + targetRef.current.x + x, + targetRef.current.y + y, + targetRef.current.z + z + ); + camera.lookAt( + targetRef.current.x, + targetRef.current.y, + targetRef.current.z + ); + + // Shift the projected image without affecting orbit + const { width, height } = gl.domElement.getBoundingClientRect(); + (camera as any).setViewOffset(width, height, viewOffset ?? 0, 0, width, height); + }; + + // Hand the reset function to the caller so they can trigger it + // (e.g. from a button in CameraOverlay) without needing an external ref. + if (onReset) { + onReset(() => { + spherical.current.radius = initialRadius ?? 10; + spherical.current.theta = 0; + spherical.current.phi = Math.PI / 2; + targetRef.current = { + x: (target?.x ?? 0) + (offset?.x ?? 0), + y: (target?.y ?? 0) + (offset?.y ?? 0), + z: (target?.z ?? 0) + (offset?.z ?? 0), + }; + updateCamera(); + }); + } + + updateCamera(); + + const handleMouseDown = (e: MouseEvent) => { + if (e.target !== canvas) return; + + lastPos.current = { x: e.clientX, y: e.clientY }; + panCameraPosition.current.copy(camera.position); + + if (e.button === 0) { + isDragging.current = true; + isPanning.current = false; + } + + if (e.button === 2) { + isPanning.current = true; + isDragging.current = false; + } + }; + + const handleMouseMove = (e: MouseEvent) => { + const deltaX = e.clientX - lastPos.current.x; + const deltaY = e.clientY - lastPos.current.y; + + // ROTATE — left drag + if (isDragging.current) { + spherical.current.theta -= deltaX * 0.005; + spherical.current.phi -= deltaY * 0.005; + + if (clampVerticalRotation) { + spherical.current.phi = Math.max( + minPhi, + Math.min(maxPhi, spherical.current.phi) + ); + } + } + + // PAN — right drag + // Uses screen-space axes derived from the camera so panning is + // correct at any angle including top-down. + if (isPanning.current) { + const distance = spherical.current.radius; + const panSpeed = 0.002 * distance; + + const forward = new Vector3(); + camera.getWorldDirection(forward); + + // Right vector — perpendicular to forward in the horizontal plane + const right = new Vector3(); + right.crossVectors(forward, new Vector3(0, 1, 0)).normalize(); + + // Degenerate guard: when camera is nearly straight up or down, + // fall back to camera.up + if (right.lengthSq() < 0.001) { + right.crossVectors(forward, camera.up).normalize(); + } + + // screenUp — perpendicular to both forward and right. + // This is the actual "up" direction on screen regardless of + // camera tilt, avoiding the zoom-while-panning bug. + const screenUp = new Vector3(); + screenUp.crossVectors(right, forward).normalize(); + + right.multiplyScalar(-deltaX * panSpeed); + screenUp.multiplyScalar(deltaY * panSpeed); + + const pan = new Vector3().addVectors(right, screenUp); + + targetRef.current.x += pan.x; + targetRef.current.y += pan.y; + targetRef.current.z += pan.z; + } + + lastPos.current = { x: e.clientX, y: e.clientY }; + updateCamera(); + }; + + const handleMouseUp = () => { + isDragging.current = false; + isPanning.current = false; + }; + + const handleWheel = (e: WheelEvent) => { + if (e.target !== canvas) return; + + e.preventDefault(); + + spherical.current.radius += e.deltaY * 0.01; + spherical.current.radius = Math.max( + 3, + Math.min(maxRadius ?? 30, spherical.current.radius) + ); + + updateCamera(); + }; + + const handleTouchStart = (e: TouchEvent) => { + if (e.target !== canvas) return; + e.preventDefault(); + + if (e.touches.length === 1) { + isDragging.current = true; + isPanning.current = false; + lastPos.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }; + } else if (e.touches.length === 2) { + isDragging.current = false; + isPanning.current = true; + lastPos.current = { + x: (e.touches[0].clientX + e.touches[1].clientX) / 2, + y: (e.touches[0].clientY + e.touches[1].clientY) / 2, + }; + // Store initial pinch distance for zoom + const dx = e.touches[0].clientX - e.touches[1].clientX; + const dy = e.touches[0].clientY - e.touches[1].clientY; + lastPinchDist.current = Math.sqrt(dx * dx + dy * dy); + } + }; + + const handleTouchMove = (e: TouchEvent) => { + e.preventDefault(); + + if (e.touches.length === 1 && isDragging.current) { + const deltaX = e.touches[0].clientX - lastPos.current.x; + const deltaY = e.touches[0].clientY - lastPos.current.y; + spherical.current.theta -= deltaX * 0.005; + spherical.current.phi -= deltaY * 0.005; + if (clampVerticalRotation) { + spherical.current.phi = Math.max(minPhi, Math.min(maxPhi, spherical.current.phi)); + } + lastPos.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }; + updateCamera(); + + } else if (e.touches.length === 2) { + // Pinch zoom + const dx = e.touches[0].clientX - e.touches[1].clientX; + const dy = e.touches[0].clientY - e.touches[1].clientY; + const dist = Math.sqrt(dx * dx + dy * dy); + const pinchDelta = lastPinchDist.current - dist; + spherical.current.radius += pinchDelta * 0.05; + spherical.current.radius = Math.max(3, Math.min(maxRadius ?? 30, spherical.current.radius)); + lastPinchDist.current = dist; + + // Two-finger pan + const midX = (e.touches[0].clientX + e.touches[1].clientX) / 2; + const midY = (e.touches[0].clientY + e.touches[1].clientY) / 2; + const panDeltaX = midX - lastPos.current.x; + const panDeltaY = midY - lastPos.current.y; + + const distance = spherical.current.radius; + const panSpeed = 0.002 * distance; + const forward = new Vector3(); + camera.getWorldDirection(forward); + const right = new Vector3().crossVectors(forward, new Vector3(0, 1, 0)).normalize(); + if (right.lengthSq() < 0.001) right.crossVectors(forward, camera.up).normalize(); + const screenUp = new Vector3().crossVectors(right, forward).normalize(); + right.multiplyScalar(-panDeltaX * panSpeed); + screenUp.multiplyScalar(panDeltaY * panSpeed); + const pan = new Vector3().addVectors(right, screenUp); + targetRef.current.x += pan.x; + targetRef.current.y += pan.y; + targetRef.current.z += pan.z; + + lastPos.current = { x: midX, y: midY }; + updateCamera(); + } + }; + + const handleTouchEnd = (e: TouchEvent) => { + if (e.touches.length === 0) { + isDragging.current = false; + isPanning.current = false; + } else if (e.touches.length === 1) { + // Transitioned from pinch back to single finger + isDragging.current = true; + isPanning.current = false; + lastPos.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }; + } + }; + + window.addEventListener("mousedown", handleMouseDown); + window.addEventListener("mousemove", handleMouseMove); + window.addEventListener("mouseup", handleMouseUp); + canvas.addEventListener("wheel", handleWheel, { passive: false }); + canvas.addEventListener("touchstart", handleTouchStart, { passive: false }); + canvas.addEventListener("touchmove", handleTouchMove, { passive: false }); + canvas.addEventListener("touchend", handleTouchEnd); + + return () => { + window.removeEventListener("mousedown", handleMouseDown); + window.removeEventListener("mousemove", handleMouseMove); + window.removeEventListener("mouseup", handleMouseUp); + canvas.removeEventListener("wheel", handleWheel); + canvas.removeEventListener("touchstart", handleTouchStart); + canvas.removeEventListener("touchmove", handleTouchMove); + canvas.removeEventListener("touchend", handleTouchEnd); + }; + }, [camera, gl, target, clampVerticalRotation, minPhi, maxPhi, initialRadius, maxRadius]); + + return null; +} \ No newline at end of file diff --git a/src/3dModels/Shapes/3D/Circle.tsx b/src/3dModels/Shapes/3D/Circle.tsx new file mode 100644 index 0000000..8204a29 --- /dev/null +++ b/src/3dModels/Shapes/3D/Circle.tsx @@ -0,0 +1,34 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import BaseMesh, { BaseMeshProps } from "../BaseMesh"; + +export interface CircleGeometry{ + radius: number + radialSegments?: number + thetaStart?: number + thetaLength?: number +} + +interface Props extends Omit { + geometry: CircleGeometry; +} + +export default function Circle(props: Props) { + const { geometry } = props; + + const geo = useMemo(() => { + return new THREE.CircleGeometry( + geometry.radius, + geometry.radialSegments ?? 24, + geometry.thetaStart ?? 0, + geometry.thetaLength ?? Math.PI * 2 + ); + }, [ + geometry.radius, + geometry.radialSegments, + geometry.thetaStart, + geometry.thetaLength + ]); + + return ; +} \ No newline at end of file diff --git a/src/3dModels/Shapes/3D/Cone.tsx b/src/3dModels/Shapes/3D/Cone.tsx new file mode 100644 index 0000000..90d3e81 --- /dev/null +++ b/src/3dModels/Shapes/3D/Cone.tsx @@ -0,0 +1,43 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import BaseMesh, { BaseMeshProps } from "../BaseMesh"; + +export interface ConeGeometry { + radius: number; + height: number; + radialSegments?: number; + heightSegments?: number; + openEnded?: boolean; + thetaStart?: number; + thetaLength?: number; +} + +interface Props extends Omit { + geometry: ConeGeometry; +} + +export default function Cone(props: Props) { + const { geometry } = props; + + const geo = useMemo(() => { + return new THREE.ConeGeometry( + geometry.radius, + geometry.height, + geometry.radialSegments ?? 24, + geometry.heightSegments ?? 1, + geometry.openEnded ?? false, + geometry.thetaStart ?? 0, + geometry.thetaLength ?? Math.PI * 2 + ); + }, [ + geometry.radius, + geometry.height, + geometry.radialSegments, + geometry.heightSegments, + geometry.openEnded, + geometry.thetaStart, + geometry.thetaLength + ]); + + return ; +} \ No newline at end of file diff --git a/src/3dModels/Shapes/3D/Cube.tsx b/src/3dModels/Shapes/3D/Cube.tsx new file mode 100644 index 0000000..94ae03b --- /dev/null +++ b/src/3dModels/Shapes/3D/Cube.tsx @@ -0,0 +1,40 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import BaseMesh, { BaseMeshProps } from "../BaseMesh"; + +export interface CubeGeometry { + height: number; + width: number; + depth: number; + widthSegments?: number; + heightSegments?: number; + depthSegments?: number; +} + +interface Props extends Omit { + geometry: CubeGeometry; +} + +export default function Cube(props: Props) { + const { geometry } = props; + + const geo = useMemo(() => { + return new THREE.BoxGeometry( + geometry.height, + geometry.width, + geometry.depth, + geometry.widthSegments ?? 2, + geometry.heightSegments ?? 2, + geometry.depthSegments ?? 2 + ); + }, [ + geometry.height, + geometry.width, + geometry.depth, + geometry.widthSegments, + geometry.heightSegments, + geometry.depthSegments + ]); + + return ; +} \ No newline at end of file diff --git a/src/3dModels/Shapes/3D/Cylinder.tsx b/src/3dModels/Shapes/3D/Cylinder.tsx new file mode 100644 index 0000000..ee074df --- /dev/null +++ b/src/3dModels/Shapes/3D/Cylinder.tsx @@ -0,0 +1,46 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import BaseMesh, { BaseMeshProps } from "../BaseMesh"; + +export interface CylinderGeometry { + radiusTop: number; + radiusBottom: number; + height: number; + radialSegments?: number; + heightSegments?: number; + openEnded?: boolean; + thetaStart?: number; + thetaLength?: number; +} + +interface Props extends Omit { + geometry: CylinderGeometry; +} + +export default function Cylinder(props: Props) { + const { geometry } = props; + + const geo = useMemo(() => { + return new THREE.CylinderGeometry( + geometry.radiusTop, + geometry.radiusBottom, + geometry.height, + geometry.radialSegments ?? 24, + geometry.heightSegments ?? 1, + geometry.openEnded ?? false, + geometry.thetaStart ?? 0, + geometry.thetaLength ?? Math.PI * 2 + ); + }, [ + geometry.radiusTop, + geometry.radiusBottom, + geometry.height, + geometry.radialSegments, + geometry.heightSegments, + geometry.openEnded, + geometry.thetaStart, + geometry.thetaLength + ]); + + return ; +} \ No newline at end of file diff --git a/src/3dModels/Shapes/3D/Ring.tsx b/src/3dModels/Shapes/3D/Ring.tsx new file mode 100644 index 0000000..1a79d40 --- /dev/null +++ b/src/3dModels/Shapes/3D/Ring.tsx @@ -0,0 +1,40 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import BaseMesh, { BaseMeshProps } from "../BaseMesh"; + +export interface RingGeometry{ + // the radius of the ring from the center to the ouside edge, must be larger than thickness + radius: number + // the thickness of the tube, must be smaller than radius + thickness: number + radialSegments?: number + tubularSegments?: number + // central angle in radians + arc?: number +} + +interface Props extends Omit { + geometry: RingGeometry; +} + +export default function Ring(props: Props) { + const { geometry } = props; + + const geo = useMemo(() => { + return new THREE.TorusGeometry( + geometry.radius, + geometry.thickness, + geometry.radialSegments ?? 12, + geometry.tubularSegments ?? 48, + geometry.arc ?? Math.PI * 2 + ); + }, [ + geometry.radius, + geometry.thickness, + geometry.radialSegments, + geometry.tubularSegments, + geometry.arc + ]); + + return ; +} \ No newline at end of file diff --git a/src/3dModels/Shapes/3D/Sphere.tsx b/src/3dModels/Shapes/3D/Sphere.tsx new file mode 100644 index 0000000..6104369 --- /dev/null +++ b/src/3dModels/Shapes/3D/Sphere.tsx @@ -0,0 +1,43 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import BaseMesh, { BaseMeshProps } from "../BaseMesh"; + +export interface SphereGeometry { + radius: number + widthSegments?: number + heightSegments?: number + phiStart?: number + phiLength?: number + thetaStart?: number + thetaLength?: number +} + +interface Props extends Omit { + geometry: SphereGeometry; +} + +export default function Sphere(props: Props){ + const { geometry } = props; + + const geo = useMemo(() => { + return new THREE.SphereGeometry( + geometry.radius, + geometry.widthSegments, + geometry.heightSegments, + geometry.phiStart, + geometry.phiLength, + geometry.thetaStart, + geometry.thetaLength + ); + }, [ + geometry.radius, + geometry.widthSegments, + geometry.heightSegments, + geometry.phiStart, + geometry.phiLength, + geometry.thetaStart, + geometry.thetaLength + ]); + + return ; +} \ No newline at end of file diff --git a/src/3dModels/Shapes/BaseMesh.tsx b/src/3dModels/Shapes/BaseMesh.tsx new file mode 100644 index 0000000..e468c0c --- /dev/null +++ b/src/3dModels/Shapes/BaseMesh.tsx @@ -0,0 +1,99 @@ +import { Euler, Vector3, BufferGeometry, MaterialParameters, Side } from "three"; +import { ThreeEvent } from "@react-three/fiber"; + +export interface BaseMeshProps { + geometry: BufferGeometry; + position?: Vector3; + rotation?: Euler; + colour?: string; + opacity?: number; + metalness?: number; + roughness?: number; + wireframe?: boolean; + frameColour?: string; + materialType?: "standard" | "basic"; + materialProps?: Partial; + materialOverride?: React.ReactNode; + side?: Side; + depthWrite?: boolean; + depthTest?: boolean; + renderOrder?: number; + onClick?: (event: ThreeEvent) => void; +} + +export default function BaseMesh(props: BaseMeshProps) { + const { + geometry, + position, + rotation, + colour = "#fff", + opacity = 1, + metalness = 0, + roughness = 1, + wireframe = false, + frameColour = "black", + materialType, + materialProps, + materialOverride, + side, + depthWrite = true, + depthTest = true, + renderOrder = 0, + onClick, + } = props; + + const isTransparent = opacity < 1; + + const buildMaterial = () => { + if (materialOverride) return materialOverride; + switch (materialType) { + case "basic": + return ( + + ); + + case "standard": + default: + return ( + + ); + } + }; + + return ( + + {/* Main surface */} + + {buildMaterial()} + + + {/* Optional wireframe overlay */} + {wireframe && ( + + + + )} + + ); +} \ No newline at end of file diff --git a/src/bin/3dView/BinParts/BinShell.tsx b/src/bin/3dView/BinParts/BinShell.tsx new file mode 100644 index 0000000..f4c0c4e --- /dev/null +++ b/src/bin/3dView/BinParts/BinShell.tsx @@ -0,0 +1,140 @@ +import Circle, { CircleGeometry } from "3dModels/Shapes/3D/Circle" +import Cone, { ConeGeometry } from "3dModels/Shapes/3D/Cone" +import Cylinder, { CylinderGeometry } from "3dModels/Shapes/3D/Cylinder" +import React from "react" +import { Euler, Vector3 } from "three" + +interface Props { + radialSegments: number + binBodyColour: string + binMetalness: number + binRoughness: number + binOpacity: number + diameter: number + sidewallHeight: number + roofHeight: number + hopperHeight?: number + wireframe?: boolean + renderOrder?: number +} + +export default function BinShell(props: Props) { + const { radialSegments, binBodyColour, binMetalness, binRoughness, binOpacity, diameter, sidewallHeight, roofHeight, hopperHeight, wireframe, renderOrder } = props + const cylinderGeometry = React.useMemo(() => ({ + radiusTop: diameter / 2, + radiusBottom: diameter / 2, + height: sidewallHeight, + radialSegments, + heightSegments: 2, + openEnded: true, + } as CylinderGeometry), [diameter, sidewallHeight, radialSegments]); + + const roofGeometry = React.useMemo(() => ({ + height: roofHeight, + radius: diameter /2, + radialSegments: radialSegments, + openEnded: true + } as ConeGeometry), [diameter, roofHeight, radialSegments]) + + const hopperGeometry = React.useMemo(() => ({ + height: hopperHeight, + radius: diameter /2, + radialSegments: radialSegments, + openEnded: true + } as ConeGeometry),[hopperHeight, diameter, radialSegments]) + + const flatBottomGeometry = React.useMemo(() => ({ + radius: diameter/2, + radialSegments: radialSegments + } as CircleGeometry),[diameter, radialSegments]) + + const roofPosition = React.useMemo( + () => new Vector3(0, sidewallHeight/2 + roofHeight/2, 0), + [sidewallHeight, roofHeight] + ); + + const bottomPosition = React.useMemo( + () => { + if(hopperHeight !== undefined && hopperHeight > 0){ + //this returns the position for the center of the cone for the hopper + return new Vector3(0, (sidewallHeight/2 + hopperHeight/2)*-1, 0) + } else { + //this returns the position for the circle for the flat bottom + return new Vector3(0, -sidewallHeight/2, 0) + } + }, + [sidewallHeight, hopperHeight] + ) + + const hopperRotation = React.useMemo( + () => new Euler(Math.PI, 0, 0), + [] + ); + + const flatBottomRotation = React.useMemo( + () => new Euler(-Math.PI / 2, 0, 0), + [] + ); + + return ( + + {/* bin roof - cone */} + + {/* bin sidewall - cylinder (open ended for the roof and bottom)*/} + + {/* bin bottom - cone -OR- circle depending on the bins shape*/} + {hopperHeight !== undefined && hopperHeight > 0 ? + + : + + } + + ) + +} \ No newline at end of file diff --git a/src/bin/3dView/Data/BuildCableData.ts b/src/bin/3dView/Data/BuildCableData.ts new file mode 100644 index 0000000..4b34fb9 --- /dev/null +++ b/src/bin/3dView/Data/BuildCableData.ts @@ -0,0 +1,212 @@ +import { RadiansToDegrees } from "common/TrigFunctions"; +import { Bin } from "models"; +import { GrainCable } from "models/GrainCable"; +import { pond } from "protobuf-ts/pond"; +import { Vector3 } from "three"; +import { avg } from "utils"; + +export interface CableData { + cableIndex: number + radius: number + topPosition: Vector3 + bottomPosition: Vector3 + grainCable: pond.GrainCable + radialSegments?: number + heightSegments?: number +} + +export interface CableOrbit { + orbit: number; + radius: number; // in cm + expectedCount: number; + assignedCount?: number; +} + +/** + * Effective bin dimensions used for cable placement. + * Passed in from Bin3dView so that default fallback values are applied + * consistently — cables will always match the rendered shell even when + * the bin has no advanced dimensions configured. + */ +export interface BinDims { + diameter: number + sidewallHeight: number + roofHeight: number + hopperHeight: number +} + + +function getLayoutFromDiameter(diameterCm: number): CableOrbit[] { + const diameterFt = diameterCm / 30.48; + + let summaries: { Orbit: number; DistanceFromCenter: number; NumberOfCables: number }[] = []; + + if (diameterFt < 24) { + summaries.push({ Orbit: 0, DistanceFromCenter: 2, NumberOfCables: 1 }); + } else if (diameterFt < 36) { + summaries.push({ Orbit: 1, DistanceFromCenter: 7, NumberOfCables: 3 }); + } else if (diameterFt < 42) { + summaries.push({ Orbit: 0, DistanceFromCenter: 2, NumberOfCables: 1 }); + summaries.push({ Orbit: 1, DistanceFromCenter: 9, NumberOfCables: 3 }); + } else if (diameterFt < 48) { + summaries.push({ Orbit: 0, DistanceFromCenter: 2, NumberOfCables: 1 }); + summaries.push({ Orbit: 1, DistanceFromCenter: 14, NumberOfCables: 4 }); + } else if (diameterFt < 54) { + summaries.push({ Orbit: 0, DistanceFromCenter: 2, NumberOfCables: 1 }); + summaries.push({ Orbit: 1, DistanceFromCenter: 16, NumberOfCables: 5 }); + } else if (diameterFt < 60) { + summaries.push({ Orbit: 0, DistanceFromCenter: 2, NumberOfCables: 1 }); + summaries.push({ Orbit: 1, DistanceFromCenter: 18, NumberOfCables: 6 }); + } else if (diameterFt < 72) { + summaries.push({ Orbit: 0, DistanceFromCenter: 2, NumberOfCables: 1 }); + summaries.push({ Orbit: 1, DistanceFromCenter: 20, NumberOfCables: 7 }); + } else if (diameterFt < 78) { + summaries.push({ Orbit: 1, DistanceFromCenter: 10, NumberOfCables: 4 }); + summaries.push({ Orbit: 2, DistanceFromCenter: 27, NumberOfCables: 9 }); + } else if (diameterFt < 90) { + summaries.push({ Orbit: 1, DistanceFromCenter: 10, NumberOfCables: 4 }); + summaries.push({ Orbit: 2, DistanceFromCenter: 29, NumberOfCables: 10 }); + } else if (diameterFt < 105) { + summaries.push({ Orbit: 0, DistanceFromCenter: 2, NumberOfCables: 1 }); + summaries.push({ Orbit: 1, DistanceFromCenter: 18, NumberOfCables: 6 }); + summaries.push({ Orbit: 2, DistanceFromCenter: 36, NumberOfCables: 12 }); + } else { + summaries.push({ Orbit: 1, DistanceFromCenter: 9, NumberOfCables: 3 }); + summaries.push({ Orbit: 2, DistanceFromCenter: 26.5, NumberOfCables: 9 }); + summaries.push({ Orbit: 3, DistanceFromCenter: 44, NumberOfCables: 14 }); + } + + return summaries.map(s => ({ + orbit: s.Orbit, + radius: s.DistanceFromCenter * 30.48, // ft → cm + expectedCount: s.NumberOfCables + })); +}; + +function distributeCables(cableCount: number, layout: CableOrbit[]) { + const totalExpected = layout.reduce((sum, o) => sum + o.expectedCount, 0); + + let assigned = layout.map(o => ({ + ...o, + assignedCount: Math.round((o.expectedCount / totalExpected) * cableCount) + })); + + // normalize rounding + let currentTotal = assigned.reduce((sum, o) => sum + (o.assignedCount ?? 0), 0); + + while (currentTotal < cableCount) { + assigned[assigned.length - 1].assignedCount!++; + currentTotal++; + } + + while (currentTotal > cableCount) { + assigned[assigned.length - 1].assignedCount!--; + currentTotal--; + } + + return assigned; +}; + +function getTopY(radiusFromCenter: number, dims: BinDims) { + const binRadius = dims.diameter / 2; + + const distanceFromEdge = binRadius - radiusFromCenter; + + // Use the real roof angle when available; when dimensions aren't configured + // the angle will be 0 which gives a flat cable top — correct for a default shape. + const angleRad = Math.atan((dims.roofHeight) / (binRadius)); + + const roofRise = Math.tan(angleRad) * distanceFromEdge; + + return dims.sidewallHeight / 2 + roofRise; +}; + +function getBottomY(radiusFromCenter: number, dims: BinDims) { + const binRadius = dims.diameter / 2; + + const distanceFromCenter = binRadius - radiusFromCenter; + + const angleRad = Math.atan((dims.hopperHeight) / (binRadius)) + + const hopperDrop = Math.tan(angleRad) * distanceFromCenter; + + const clearance = 60; // cm + + return -dims.sidewallHeight / 2 - hopperDrop + clearance; +}; + + +export function BuildCableData(bin: Bin, dims: BinDims): CableData[] { + const cables = [...(bin.status.grainCables ?? [])]; + + if (cables.length === 0) return []; + + // optional: sort cables (better visual consistency later) + //cables.sort((a, b) => b.celcius.length - a.celcius.length); + cables.sort((a, b) => { + //if the cables have the same number of nodes + if (b.celcius.length === a.celcius.length) { + //sort by temp only last and any type that has humidity first + if ((avg(a.relativeHumidity) === 0) && (avg(b.relativeHumidity) !== 0)) { + return 1; + } else if ((avg(b.relativeHumidity) === 0) && (avg(a.relativeHumidity) !== 0)) { + return -1; + } + else { + return a.key > b.key ? 1 : -1; + } + } + //otherwise sort by the longest cable first + return b.celcius.length - a.celcius.length; + }); + + const layout = getLayoutFromDiameter(dims.diameter); + const distributed = distributeCables(cables.length, layout); + + const cableRadius = 3; + + const result: CableData[] = []; + + let cableIndex = 0; + + distributed.forEach(orbit => { + const count = orbit.assignedCount ?? 0; + + const topY = getTopY(orbit.radius, dims); //this is if we want the cables to start at the roof + //const topY = dims.sidewallHeight/2 //this will start the cables at the top of the sidewall + + const bottomY = getBottomY(orbit.radius, dims); + + if (orbit.orbit === 0 && count > 0) { + const cable = cables[cableIndex]; + if (!cable) return; + result.push({ + cableIndex: cableIndex, + radius: cableRadius, + topPosition: new Vector3(0, topY, 0), + bottomPosition: new Vector3(0, bottomY, 0), + grainCable: cable + }); + cableIndex++; + return; + } + + for (let i = 0; i < count; i++) { + const angle = (i / count) * Math.PI * 2; + const x = Math.cos(angle) * orbit.radius; + const z = Math.sin(angle) * orbit.radius; + const cable = cables[cableIndex]; + + result.push({ + cableIndex: cableIndex, + radius: cableRadius, + topPosition: new Vector3(x, topY, z), + bottomPosition: new Vector3(x, bottomY, z), + grainCable: cable + }); + cableIndex++; + } + }); + + return result; +}; \ No newline at end of file diff --git a/src/bin/3dView/Data/BuildNodeData.ts b/src/bin/3dView/Data/BuildNodeData.ts new file mode 100644 index 0000000..c1d88a8 --- /dev/null +++ b/src/bin/3dView/Data/BuildNodeData.ts @@ -0,0 +1,72 @@ +import { Vector3 } from "three" +import { CableData } from "./BuildCableData" + +export interface NodeData { + cableIndex: number + nodeIndex: number + radius: number + position: Vector3 + celcius: number + humidity?: number + moisture?: number + topNode?: boolean + excluded?: boolean + inGrain?: boolean + /** + * The vertical spacing between nodes on this cable (cm). + * Used by GrainCableFill to offset the grain surface half a spacing above the top node, + * matching the 2D bin view behaviour. + */ + nodeSpacing: number +} + +export function BuildNodeData(cables: CableData[]): NodeData[] { + const nodeRadius = 10 + let nodeData: NodeData[] = [] + + cables.forEach((cable, cableIndex) => { + const grainCable = cable.grainCable + + const nodeCount = grainCable.celcius.length; + + if (nodeCount === 0) return; + + const bottomY = cable.bottomPosition.y; + const topY = cable.topPosition.y; + const height = topY - bottomY; + + const spacing = height / nodeCount; + + grainCable.celcius.forEach((celcius, i) => { + + const nodeY = bottomY + (i * spacing); + + const humidity = grainCable.relativeHumidity[i] || undefined; + const moisture = grainCable.moisture[i] || undefined; + let t = celcius + // for testing + // if(i===0){ + // t = 40 + // } + // if (i===5){ + // t = 0 + // } + + nodeData.push({ + cableIndex: cableIndex, + nodeIndex: i, + radius: nodeRadius, + position: new Vector3(cable.bottomPosition.x, nodeY, cable.bottomPosition.z), + celcius: t, + humidity: humidity, + moisture: moisture, + topNode: grainCable.topNode === i + 1, + excluded: grainCable.excludedNodes?.includes(i) ?? false, + inGrain: i + 1 <= grainCable.topNode || !grainCable.topNode, + nodeSpacing: spacing, + }) + }) + }) + + return nodeData +} \ No newline at end of file diff --git a/src/bin/3dView/Scene/Bin3dView.tsx b/src/bin/3dView/Scene/Bin3dView.tsx new file mode 100644 index 0000000..d14297d --- /dev/null +++ b/src/bin/3dView/Scene/Bin3dView.tsx @@ -0,0 +1,208 @@ +import React from "react"; +import OrbitCameraControls from "3dModels/CameraControls/OrbitCameraControls"; +import CameraOverlay from "3dModels/CameraControls/CameraOverlay"; +import { Canvas } from "@react-three/fiber"; +import { Bin } from "models"; +import BinShell from "../BinParts/BinShell"; +import GrainFillFlat from "../Systems/Inventory/GrainFillFlat"; +import BinCables from "../Systems/Cables/BinCables"; +import { Vector3 } from "three"; +import { useMemo } from "react"; +import { BuildCableData, CableData } from "../Data/BuildCableData"; +import { BuildNodeData, NodeData } from "../Data/BuildNodeData"; +import { pond } from "protobuf-ts/pond"; +import GrainCableFill from "../Systems/Inventory/GrainCableFill"; +import TempHeatMap from "../Systems/Heatmap/TempHeatMap"; +import NodePointCloud from "../Systems/Heatmap/NodePointCloud"; +import { Box } from "@mui/material"; +import MoistureHeatMap from "../Systems/Heatmap/MoistureHeatmap"; +import { grainYBoundsFromFillPercent } from "../utils/grainFillBounds"; +import { RadiansToDegrees } from "common/TrigFunctions"; +// import { GrainCable } from "models/GrainCable" + +// Fallback dimensions used when a bin has no advanced dimensions configured. +// Chosen to resemble a typical mid-size grain bin. +const DEFAULT_ROOF_HEIGHT_CM = 200; // 2 m +const DEFAULT_FLAT_HEIGHT_CM = 0; // flat bottom +const DEFAULT_HOPPER_HEIGHT_CM = 280; // hopper bottom + +interface Props { + bin: Bin + scale: number + /** + * cables can come from the bins status when not passed in, however data may be out of synce from when the cables read to when the bins status updates + * they may need to be passed in but for the moment we wont worry about it due to the last active on the bin page can be used to explain being out of sync + * if it becomes an issue I can make the changes necessary to pass the cable components in + */ + // cables?: GrainCable[] + /** + * the percentage of the bin to be filled, expects a number between 0 and 1 + */ + fillPercent?: number + nodeClick?: (node: NodeData, cable: CableData) => void + showGrain?: boolean + showTempHeatmap?: boolean + showMoistureHeatmap?: boolean + showHotspots?: boolean + /** + * When true renders a reset camera button overlaid on the 3D view. + */ + showResetButton?: boolean + showTemp?: boolean + showMoisture?: boolean + xOffset?: number + width?: number + height?: number +} + +export default function Bin3dView(props: Props) { + const { bin, scale = 100, fillPercent, nodeClick, showTempHeatmap, showGrain, showHotspots, showResetButton, showMoistureHeatmap, showTemp, showMoisture, xOffset, width = 1, height = 1 } = props + + // Resolve effective dimensions, falling back to defaults when advanced + // dimensions have not been configured (bin methods return 0 in that case). + const dims = useMemo(() => ({ + diameter: bin.diameter(), + sidewallHeight: bin.sidewallHeight() || bin.diameter() + 50, //calculated using the diameter so 'default' bins always have the same shape + roofHeight: bin.roofHeight() || DEFAULT_ROOF_HEIGHT_CM, + hopperHeight: bin.hopperHeight() || (bin.binShape() === pond.BinShape.BIN_SHAPE_HOPPER_BOTTOM ? DEFAULT_HOPPER_HEIGHT_CM : DEFAULT_FLAT_HEIGHT_CM), + }), [bin]); + + // Compute the initial camera radius so the full bin fits in frame. + // Uses the perspective camera FOV (default 75°) with a padding factor. + // Both the diameter and total height are considered so neither is clipped. + const initialCameraRadius = useMemo(() => { + const totalHeight = (dims.sidewallHeight + dims.roofHeight + dims.hopperHeight) / scale; + const diameter = dims.diameter / scale; + const largestDim = Math.max(totalHeight, diameter); + const fovRad = (75 * Math.PI) / 180; + const aspect = width/height + const aspectPadding = aspect < 1 ? 1.4 : 1.0 // extra room on mobile + // const padding = 1.3; // 30% breathing room + const padding = (1.1 + (largestDim/100) * 4.5) * aspectPadding + return (largestDim / (2 * Math.tan(fovRad / 2))) * padding; + }, [dims, scale]); + + const cableData = useMemo(() => BuildCableData(bin, dims), [bin, dims]); + const nodeData = useMemo(() => BuildNodeData(cableData), [cableData]); + + const isCableInventory = + bin.inventoryControl() === pond.BinInventoryControl.BIN_INVENTORY_CONTROL_AUTOMATIC || + bin.inventoryControl() === pond.BinInventoryControl.BIN_INVENTORY_CONTROL_HYBRID_CABLE; + + // For cable inventory, TempHeatMap derives the wavy surface directly from + // the top nodes in nodeData — no scalar needed. + // + // Flat fill: Y bounds from the same volume math as GrainFillFlat. + const flatGrainBounds = useMemo(() => { + if (isCableInventory || fillPercent === undefined) return undefined; + return grainYBoundsFromFillPercent( + dims.diameter, + dims.sidewallHeight, + dims.hopperHeight, + dims.roofHeight, + fillPercent + ); + }, [isCableInventory, fillPercent, dims]); + + // Internal ref — wired to OrbitCameraControls and called by CameraOverlay + const resetCameraFn = React.useRef<(() => void) | null>(null); + + const grainInventory = () => { + if (isCableInventory) { + return ( + + ) + } else if (fillPercent) { + return ( + + ) + } + } + + return ( + + { resetCameraFn.current = fn; }} + viewOffset={xOffset} + /> + + + + {showGrain && grainInventory()} + + { + if (nodeClick) nodeClick(node, cable) + }} + renderOrder={5} + /> + + {showHotspots && } + + {/* note that the heatmaps internally use render order 1,2, and 3 for the three separate coloured meshes */} + {showTempHeatmap && ( + + )} + {showMoistureHeatmap && ( + + )} + + + + + + + + + + {/* Overlay — must be inside so it shares the same stacking context */} + {showResetButton && ( + resetCameraFn.current?.()} /> + )} + + ) +} diff --git a/src/bin/3dView/Systems/Cables/BinCables.tsx b/src/bin/3dView/Systems/Cables/BinCables.tsx new file mode 100644 index 0000000..1901178 --- /dev/null +++ b/src/bin/3dView/Systems/Cables/BinCables.tsx @@ -0,0 +1,44 @@ +import GrainCable from "./GrainCable"; +import { Bin } from "models"; +import React from "react"; +import { CableData } from "../../Data/BuildCableData"; +import { NodeData } from "../../Data/BuildNodeData"; + +interface Props { + cableData: CableData[], + nodeData: NodeData[], + bin: Bin, + renderOrder?: number, + displayTemp?: boolean, + displayMoisture?: boolean, + onNodeClick?: (node: NodeData, cable: CableData) => void +} + +export default function BinCables(props: Props){ + const {bin, cableData, nodeData, onNodeClick, renderOrder, displayTemp, displayMoisture} = props + return ( + + {cableData.map((cable, i) => { + const cableNodes = nodeData.filter(n => n.cableIndex === cable.cableIndex); + + return ( + { + if(onNodeClick){ + onNodeClick(node, cable) + } + }} + renderOrder={renderOrder} + /> + )} + )} + + + ) +} \ No newline at end of file diff --git a/src/bin/3dView/Systems/Cables/CableNode.tsx b/src/bin/3dView/Systems/Cables/CableNode.tsx new file mode 100644 index 0000000..faca893 --- /dev/null +++ b/src/bin/3dView/Systems/Cables/CableNode.tsx @@ -0,0 +1,187 @@ +import Sphere, { SphereGeometry } from "3dModels/Shapes/3D/Sphere" +import { useFrame, useThree } from "@react-three/fiber" +import { Text } from "@react-three/drei" +import React, { useMemo } from "react" +import { Euler, Group, Vector3 } from "three" +import { green, grey, orange, red } from "@mui/material/colors"; +import { useGlobalState } from "providers" +import { pond } from "protobuf-ts/pond" +import Ring, { RingGeometry } from "3dModels/Shapes/3D/Ring" +import { NodeData } from "../../Data/BuildNodeData" + +interface Props { + node: NodeData + upperThreshold: number, + targetMoisture: number, + renderOrder?: number, + displayTemp?: boolean, + displayMoisture?: boolean, + onNodeClick?: (node: NodeData) => void +} + +export default function CableNode(props: Props) { + const { node, upperThreshold, targetMoisture, onNodeClick, renderOrder, displayTemp, displayMoisture } = props + const { camera } = useThree(); + const [{ user }] = useGlobalState(); + // const [showLabel, setShowLabel] = useState(false); + const ROW_HEIGHT = 35; + const PADDING = 5; + const LABEL_WIDTH = 200; + const FONT_SIZE = 25; + const flagRef = React.useRef(null); + + useFrame(() => { + if (!flagRef.current || !showLabel) return; + + // Get camera's right direction in world space + const cameraRight = new Vector3(); + camera.getWorldDirection(cameraRight); // forward + const up = new Vector3(0, 1, 0); + cameraRight.crossVectors(cameraRight, up).normalize(); // right = forward × up + + const pos = node.position.clone(); + pos.addScaledVector(cameraRight, LABEL_WIDTH / 2); // offset right in screen space + pos.addScaledVector(camera.position.clone().sub(node.position).normalize(), 1); // nudge toward camera + + flagRef.current.position.copy(pos); + flagRef.current.quaternion.copy(camera.quaternion); + }); + + const tempDisplay = useMemo(() => { + if (user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT) { + return ((node.celcius * 9 / 5) + 32).toFixed(2) + "°F" + } + return node.celcius.toFixed(2) + "°C" + }, [node.celcius, user]); + + const rows = useMemo(() => { + const anyToggleOn = displayTemp || displayMoisture; + + if (node.excluded) { + if (!anyToggleOn) return []; + return [{ text: "Excluded", color: grey[700] }]; + } + + const r: { text: string; color: string }[] = []; + + // TEMP + if (displayTemp && node.celcius !== 0) { + r.push({ + text: tempDisplay, + // color: describeMeasurement(quack.MeasurementType.MEASUREMENT_TYPE_TEMPERATURE).colour() + //will be green when below threshold, orange when it goeas above but by less than 5 degrees, and red if more than 5 over + color: node.celcius > upperThreshold ? node.celcius > upperThreshold + 5 ? red[700] : orange[800]: green[800] + }); + } + + // MOISTURE + if (displayMoisture) { + if (node.moisture && node.moisture > 0) { + r.push({ + text: `${node.moisture.toFixed(2)}% EMC`, + // color: describeMeasurement(quack.MeasurementType.MEASUREMENT_TYPE_GRAIN_EMC).colour() + color: node.moisture > targetMoisture ? node.moisture > targetMoisture + 0.5 ? red[700] : orange[800]: green[800] + }); + } + //apparently we dont want to display humidity at all + // else if (node.humidity && node.humidity > 0) { + // r.push({ + // text: `${node.humidity.toFixed(2)}%`, + // // color: describeMeasurement(quack.MeasurementType.MEASUREMENT_TYPE_PERCENT).colour() + // color: "black" + // }); + // } + } + + const hasData = r.length > 0; + + // Only show top node if there's actual data + if (node.topNode && hasData) { + r.unshift({ text: "Top Node", color: grey[700] }); + } + + return r; + }, [node, tempDisplay, displayTemp, displayMoisture]); + + const geometry = React.useMemo(() => ({ + radius: node.radius, + } as SphereGeometry), [node]); + + const topNodeGeo = React.useMemo(() => ({ + radius: node.radius, + thickness: 5, + } as RingGeometry), [node]); + + const topNodePosition = React.useMemo( + () => new Vector3(node.position.x, node.position.y + 25, node.position.z), + [node] + ); + + const topNodeRotation = React.useMemo(() => new Euler(-Math.PI / 2, 0, 0), []); + + const labelHeight = rows.length * ROW_HEIGHT + PADDING; + + const getRowY = (index: number) => { + const totalHeight = rows.length * ROW_HEIGHT; + return totalHeight / 2 - (index * ROW_HEIGHT) - ROW_HEIGHT / 2; + }; + + const nodeColour = () => { + if (node.excluded) return "grey"; + return "white"; + }; + + const handleClick = (e: any) => { + e.stopPropagation(); + onNodeClick?.(node); + }; + + const showLabel = rows.length > 0; + + return ( + + + + {node.topNode && ( + + )} + + {node.inGrain && showLabel && + + + + + + {rows.map((row, i) => ( + + {row.text} + + ))} + +} + + ) +} \ No newline at end of file diff --git a/src/bin/3dView/Systems/Cables/GrainCable.tsx b/src/bin/3dView/Systems/Cables/GrainCable.tsx new file mode 100644 index 0000000..71ba6bd --- /dev/null +++ b/src/bin/3dView/Systems/Cables/GrainCable.tsx @@ -0,0 +1,50 @@ +import Cylinder, { CylinderGeometry } from "3dModels/Shapes/3D/Cylinder" +import React from "react" +import { Vector3 } from "three" +import CableNode from "./CableNode" +import { Bin } from "models" +import { CableData } from "../../Data/BuildCableData" +import { NodeData } from "../../Data/BuildNodeData" + +interface Props { + cable: CableData, + nodes: NodeData[], + bin: Bin, + renderOrder?: number, + displayTemp?: boolean, + displayMoisture?: boolean, + onNodeClick?: (node: NodeData) => void +} +export default function GrainCable(props: Props) { + const {cable, nodes, bin, onNodeClick, renderOrder, displayTemp, displayMoisture} = props + + const calculateHeight = () => { + return cable.topPosition.distanceTo(cable.bottomPosition) + } + + const calculateCenter = () => { + return cable.bottomPosition.clone() + .add( + cable.topPosition.clone() + .sub(cable.bottomPosition) + .multiplyScalar(0.5) + ); + }; + + const geometry = React.useMemo(() => ({ + radiusTop: cable.radius, + radiusBottom: cable.radius, + height: calculateHeight(), + radialSegments: cable.radialSegments ?? 10, + heightSegments: cable.heightSegments ?? 2 + } as CylinderGeometry), [cable]); + + return ( + + + {nodes.map((node, i) => ( + + ))} + + ) +} \ No newline at end of file diff --git a/src/bin/3dView/Systems/Heatmap/MoistureHeatmap.tsx b/src/bin/3dView/Systems/Heatmap/MoistureHeatmap.tsx new file mode 100644 index 0000000..4756c4a --- /dev/null +++ b/src/bin/3dView/Systems/Heatmap/MoistureHeatmap.tsx @@ -0,0 +1,466 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import { Bin } from "models"; +import { NodeData } from "../../Data/BuildNodeData"; +import React from "react"; +import { BinDims } from "bin/3dView/Data/BuildCableData"; + +interface Props { + binDimensions: BinDims + targetMoisture: number + nodes: NodeData[]; + /** + * For flat fill percent inventory — a scalar Y ceiling for the heatmap top. + * Used when there are no cable top nodes to drive a surface. + */ + flatMaxY?: number; + /** For flat fill percent — Y floor of filled grain (hopper tip or cylinder base). */ + flatMinY?: number; +} + +const RADIAL_RINGS = 20; +const THETA_SEGMENTS = 40; +const HEIGHT_STEPS = 28; + +const YELLOW_DELTA = 2; +const RED_DELTA = 4; + +const IDW_POWER = 4; +const RED_OPACITY = 0.3; +const GREEN_OPACITY = 0.3; +const YELLOW_OPACITY = 0.8; + +const ANGLE_JITTER = 0.2; +const RADIAL_JITTER = 0.05; +const LAYER_TWIST = 0.22; + +// IDW power for the horizontal surface interpolation — +// matches GrainCableFill's default of 2 +const SURFACE_IDW_POWER = 2; + +function moistureToHeat(moisture: number, target: number): number { + if (moisture <= target) return 0; + const delta = moisture - target; + if (delta >= RED_DELTA) return 2; + if (delta >= YELLOW_DELTA) return 1 + (delta - YELLOW_DELTA) / (RED_DELTA - YELLOW_DELTA); + return delta / YELLOW_DELTA; +} + +function heatToRGB(heat: number): number[] { + const GREEN = [0, 0.5, 0.02]; + const YELLOW = [0.7, 0.86, 0.0]; + const RED = [0.8, 0.0, 0.01]; + + if (heat <= 0) return GREEN; + + if (heat <= 1) { + const t = Math.pow(heat, 0.75); + return [ + GREEN[0] + (YELLOW[0] - GREEN[0]) * t, + GREEN[1] + (YELLOW[1] - GREEN[1]) * t, + GREEN[2] + (YELLOW[2] - GREEN[2]) * t, + ]; + } + + const t = Math.pow(heat - 1, 0.75); + return [ + YELLOW[0] + (RED[0] - YELLOW[0]) * t, + YELLOW[1] + (RED[1] - YELLOW[1]) * t, + YELLOW[2] + (RED[2] - YELLOW[2]) * t, + ]; +} + +interface MoistureAnchor { + x: number; y: number; z: number; + moisture: number; +} + +interface SurfaceAnchor { + x: number; z: number; y: number; +} + +// 3D IDW for moisture interpolation +function idwMoisture( + px: number, py: number, pz: number, + anchors: MoistureAnchor[], + power: number +): number { + let totalWeight = 0; + let weightedSum = 0; + + for (const a of anchors) { + const dx = px - a.x; + const dy = py - a.y; + const dz = pz - a.z; + const distSq = dx * dx + dy * dy + dz * dz; + if (distSq < 0.001) return a.moisture; + const weight = 1 / Math.pow(distSq, power / 2); + totalWeight += weight; + weightedSum += a.moisture * weight; + } + + return totalWeight === 0 ? 0 : weightedSum / totalWeight; +} + +// 2D IDW for surface height interpolation — matches GrainCableFill exactly +function idwSurfaceY( + x: number, z: number, + anchors: SurfaceAnchor[], + power: number +): number { + let totalWeight = 0; + let weightedY = 0; + + for (const a of anchors) { + const dx = x - a.x; + const dz = z - a.z; + const distSq = dx * dx + dz * dz; + if (distSq < 0.001) return a.y; + const weight = 1 / Math.pow(distSq, power / 2); + totalWeight += weight; + weightedY += a.y * weight; + } + + return totalWeight === 0 ? 0 : weightedY / totalWeight; +} + +function hashNoise(a: number, b: number, c: number) { + const x = Math.sin(a * 127.1 + b * 311.7 + c * 74.7) * 43758.5453; + return (x - Math.floor(x)) * 2 - 1; +} + +export default function MoistureHeatMap({ binDimensions, targetMoisture, nodes, flatMaxY, flatMinY }: Props) { + const binRadius = binDimensions.diameter / 2; + const sidewallHeight = binDimensions.sidewallHeight; + const hopperHeight = binDimensions.hopperHeight ?? 0; + const roofHeight = binDimensions.roofHeight ?? 0; + + const sidewallBaseY = -sidewallHeight / 2; + const sidewallTopY = sidewallHeight / 2; + const hopperTipY = sidewallBaseY - hopperHeight; + const roofTipY = sidewallTopY + roofHeight; + + const maxRadiusAtY = (y: number) => { + if (y > sidewallTopY) { + if (roofHeight <= 0 || y >= roofTipY) return 0; + return binRadius * (1 - (y - sidewallTopY) / roofHeight); + } + if (y >= sidewallBaseY) return binRadius; + if (hopperHeight <= 0 || y <= hopperTipY) return 0; + return binRadius * ((y - hopperTipY) / hopperHeight); + }; + + // Moisture anchors — all in-grain nodes that have a moisture reading + const moistureAnchors = useMemo( + () => + nodes + .filter(n => n.inGrain && !n.excluded && n.moisture !== undefined) + .map(n => ({ + x: n.position.x, + y: n.position.y, + z: n.position.z, + moisture: n.moisture as number, + })), + [nodes] + ); + + // Surface anchors — top nodes only, Y offset by half spacing. + // Only used when flatMaxY is NOT provided (i.e. Automatic / Hybrid_Cable + // inventory control). For any other control type the caller passes flatMaxY + // and we must use a flat surface instead of the wavy cable-driven one. + const surfaceAnchors = useMemo(() => { + if (flatMaxY !== undefined) { + // Non-cable inventory: force flat surface — ignore cable top nodes + return []; + } + return nodes + .filter(n => n.topNode && n.inGrain && !n.excluded) + .map(n => ({ + x: n.position.x, + z: n.position.z, + y: n.position.y + n.nodeSpacing * 0.5, + })); + }, [nodes, flatMaxY]); + + // Wall clamp Y — average of surface anchor heights. + // Prevents the surface from piling up at the bin wall where there are no cables. + // Matches GrainCableFill's wallY computation. + const wallY = useMemo(() => { + if (surfaceAnchors.length === 0) return flatMaxY ?? sidewallBaseY; + return surfaceAnchors.reduce((sum, a) => sum + a.y, 0) / surfaceAnchors.length; + }, [surfaceAnchors, flatMaxY, sidewallBaseY]); + + // Lowest Y the grain surface or heatmap may occupy (hopper tip or cylinder floor). + const grainFloorY = hopperHeight > 0 ? hopperTipY : sidewallBaseY; + + // For each (x, z) position, returns the Y ceiling of the grain surface. + // Uses cable surface IDW when top nodes exist, falls back to flatMaxY. + const getSurfaceY = (x: number, z: number): number => { + if (surfaceAnchors.length > 0) { + const raw = idwSurfaceY(x, z, surfaceAnchors, SURFACE_IDW_POWER); + return Math.max(grainFloorY, Math.min(roofTipY, raw)); + } + return flatMaxY ?? sidewallBaseY; + }; + + // Global max Y — highest point of the surface (used for grid bottom calc) + const maxGrainY = useMemo(() => { + if (surfaceAnchors.length > 0) { + return Math.max(...surfaceAnchors.map(a => a.y), wallY); + } + return flatMaxY ?? sidewallBaseY; + }, [surfaceAnchors, wallY, flatMaxY, sidewallBaseY]); + + // Bottom of filled grain. Flat fill uses volume bounds; cable fill rests on + // the hopper tip (matches GrainCableFill) rather than the lowest cable node. + const minGrainY = useMemo(() => { + if (flatMinY !== undefined) return flatMinY; + return grainFloorY; + }, [flatMinY, grainFloorY]); + + const geometry = useMemo(() => { + if (!moistureAnchors.length) return null; + + const pointsPerLayer = 1 + RADIAL_RINGS * THETA_SEGMENTS; + const totalVerts = HEIGHT_STEPS * pointsPerLayer + 1; + + const positions = new Float32Array(totalVerts * 3); + const colors = new Float32Array(totalVerts * 3); + const heats = new Float32Array(totalVerts); + + const grainBottomY = minGrainY; + const grainHeight = maxGrainY - grainBottomY; + + if (grainHeight <= 0) return null; + + // Pre-compute the (x, z) position for each (ring, seg) slot so we + // can look up the surface Y ceiling per column + const colX: number[] = new Array(RADIAL_RINGS * THETA_SEGMENTS); + const colZ: number[] = new Array(RADIAL_RINGS * THETA_SEGMENTS); + const colSurfaceY: number[] = new Array(RADIAL_RINGS * THETA_SEGMENTS); + + // Use the outermost layer's radius for surface Y lookup (no jitter/twist) + // so the surface shape matches GrainCableFill cleanly + const topLayerAllowedRadius = maxRadiusAtY(maxGrainY) * 0.97; + + for (let ring = 0; ring < RADIAL_RINGS; ring++) { + const u = (ring + 1) / RADIAL_RINGS; + const rFrac = 1 - Math.pow(1 - u, 2.2); + const r = rFrac * topLayerAllowedRadius; + + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const angle = (seg / THETA_SEGMENTS) * Math.PI * 2; + const x = Math.cos(angle) * r; + const z = Math.sin(angle) * r; + const ci = ring * THETA_SEGMENTS + seg; + colX[ci] = x; + colZ[ci] = z; + // Outermost ring uses wallY, inner rings use full IDW surface + colSurfaceY[ci] = ring === RADIAL_RINGS - 1 + ? wallY + : getSurfaceY(x, z); + } + } + // Center column surface Y + const centerSurfaceY = getSurfaceY(0, 0); + + for (let hStep = 0; hStep < HEIGHT_STEPS; hStep++) { + const t = hStep / (HEIGHT_STEPS - 1); + + const layerBase = hStep * pointsPerLayer; + const allowedRadius = maxRadiusAtY(grainBottomY + t * grainHeight) * 0.97; + + // Center vertex — Y is lerped from bottom to its column surface ceiling + const centerY = grainBottomY + t * (centerSurfaceY - grainBottomY); + + const centerMoisture = idwMoisture(0, centerY, 0, moistureAnchors, IDW_POWER); + const centerHeat = moistureToHeat(centerMoisture, targetMoisture); + const [cr, cg, cb] = heatToRGB(centerHeat); + + positions[layerBase * 3] = 0; + positions[layerBase * 3 + 1] = centerY; + positions[layerBase * 3 + 2] = 0; + colors[layerBase * 3] = cr; + colors[layerBase * 3 + 1] = cg; + colors[layerBase * 3 + 2] = cb; + heats[layerBase] = centerHeat; + + for (let ring = 0; ring < RADIAL_RINGS; ring++) { + const u = (ring + 1) / RADIAL_RINGS; + const rFrac = 1 - Math.pow(1 - u, 2.2); + + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const noiseA = hashNoise(hStep, ring, seg); + const noiseR = hashNoise(seg, hStep, ring + 11); + + const baseRadius = rFrac * allowedRadius; + const jitterRadius = baseRadius + noiseR * RADIAL_JITTER * allowedRadius; + const r = Math.max(0, Math.min(jitterRadius, allowedRadius)); + + const layerPhase = t * LAYER_TWIST; + const angle = + (seg / THETA_SEGMENTS) * Math.PI * 2 + + layerPhase + + noiseA * ANGLE_JITTER; + + const x = Math.cos(angle) * r; + const z = Math.sin(angle) * r; + + // Per-column surface Y ceiling — this is what gives the wavy top + const ci = ring * THETA_SEGMENTS + seg; + const surfaceY = colSurfaceY[ci]; + + // Lerp this vertex Y from grainBottomY up to its column surface ceiling + const y = grainBottomY + t * (surfaceY - grainBottomY); + + const moisture = idwMoisture(x, y, z, moistureAnchors, IDW_POWER); + const heat = moistureToHeat(moisture, targetMoisture); + const [vr, vg, vb] = heatToRGB(heat); + + const vi = layerBase + 1 + ring * THETA_SEGMENTS + seg; + + heats[vi] = heat; + positions[vi * 3] = x; + positions[vi * 3 + 1] = y; + positions[vi * 3 + 2] = z; + colors[vi * 3] = vr; + colors[vi * 3 + 1] = vg; + colors[vi * 3 + 2] = vb; + } + } + } + + const idx = (hStep: number, ring: number, seg: number) => { + if (ring < 0) return hStep * pointsPerLayer; + const s = ((seg % THETA_SEGMENTS) + THETA_SEGMENTS) % THETA_SEGMENTS; + return hStep * pointsPerLayer + 1 + ring * THETA_SEGMENTS + s; + }; + + const green: number[] = []; + const yellow: number[] = []; + const red: number[] = []; + + function pushTri(a: number, b: number, c: number) { + const avg = (heats[a] + heats[b] + heats[c]) / 3; + if (avg < 1) green.push(a, b, c); + else if (avg < 2) yellow.push(a, b, c); + else red.push(a, b, c); + } + + for (let h = 0; h < HEIGHT_STEPS - 1; h++) { + for (let ring = 0; ring < RADIAL_RINGS - 1; ring++) { + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const next = (seg + 1) % THETA_SEGMENTS; + const a = idx(h, ring, seg); + const b = idx(h, ring, next); + const e = idx(h + 1, ring, seg); + const f = idx(h + 1, ring, next); + pushTri(a, e, b); + pushTri(e, f, b); + } + } + + // center fill + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const next = (seg + 1) % THETA_SEGMENTS; + const center0 = idx(h, -1, 0); + const center1 = idx(h + 1, -1, 0); + const a = idx(h, 0, seg); + const b = idx(h, 0, next); + const c = idx(h + 1, 0, seg); + const d = idx(h + 1, 0, next); + pushTri(center0, c, a); + pushTri(center0, center1, c); + pushTri(a, c, b); + pushTri(b, c, d); + } + } + + // Close the bottom at the hopper tip only when grain reaches the tip. + const tipVertexIndex = HEIGHT_STEPS * pointsPerLayer; + if (hopperHeight > 0 && grainBottomY <= hopperTipY + 0.01) { + const tipMoisture = idwMoisture(0, hopperTipY, 0, moistureAnchors, IDW_POWER); + const tipHeat = moistureToHeat(tipMoisture, targetMoisture); + const [tr, tg, tb] = heatToRGB(tipHeat); + + positions[tipVertexIndex * 3] = 0; + positions[tipVertexIndex * 3 + 1] = hopperTipY; + positions[tipVertexIndex * 3 + 2] = 0; + colors[tipVertexIndex * 3] = tr; + colors[tipVertexIndex * 3 + 1] = tg; + colors[tipVertexIndex * 3 + 2] = tb; + heats[tipVertexIndex] = tipHeat; + + const outerRing = RADIAL_RINGS - 1; + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const next = (seg + 1) % THETA_SEGMENTS; + pushTri(tipVertexIndex, idx(0, outerRing, next), idx(0, outerRing, seg)); + } + } + + function makeGeo(indices: number[]) { + const g = new THREE.BufferGeometry(); + g.setAttribute("position", new THREE.BufferAttribute(positions, 3)); + g.setAttribute("color", new THREE.BufferAttribute(colors, 3)); + g.setIndex(indices); + return g; + } + + return { + green: makeGeo(green), + yellow: makeGeo(yellow), + red: makeGeo(red), + }; + }, [ + moistureAnchors, + surfaceAnchors, + wallY, + maxGrainY, + minGrainY, + hopperTipY, + sidewallBaseY, + binRadius, + targetMoisture, + hopperHeight, + roofHeight, + roofTipY, + flatMaxY, + flatMinY, + ]); + + if (!geometry) return null; + + return ( + + + + + + + + + + + + + + ); +} \ No newline at end of file diff --git a/src/bin/3dView/Systems/Heatmap/NodePointCloud.tsx b/src/bin/3dView/Systems/Heatmap/NodePointCloud.tsx new file mode 100644 index 0000000..3d096b4 --- /dev/null +++ b/src/bin/3dView/Systems/Heatmap/NodePointCloud.tsx @@ -0,0 +1,254 @@ +import { NodeData } from "bin/3dView/Data/BuildNodeData"; +import { colourFade } from "bin/3dView/utils/tempToColour"; +import { Bin } from "models"; +import { useMemo } from "react"; +import { CanvasTexture, NormalBlending } from "three"; + +interface Props { + bin: Bin; + nodes: NodeData[]; +} + +export default function NodePointCloud(props: Props) { + const { bin, nodes } = props; + // 🎛️ TUNING KNOBS + const BASE_RADIUS_FACTOR = 0.15; + const INTENSITY_DENSITY_MULT = 1.25; + const INTENSITY_DENSITY_BASE = 0.3; + + const RADIAL_BASE = 6; + const THETA_BASE = 10; + const PHI_BASE = 10; + + const MIN_EDGE_INTENSITY = 0.2; + + const BASE_BRIGHTNESS = 0.7; + const INTENSITY_BRIGHTNESS_MULT = 0.7; + + const OPACITY = 0.3; + const POINT_SIZE = 1; + + // IDW power — how sharply nearer nodes dominate the field + const IDW_POWER = 2; + + // Minimum net signed magnitude to emit a point. + // Keeps near-zero cancellation zones empty rather than noisy. + const EMIT_THRESHOLD = 0.05; + + // ----------------------------- + // BIN GEOMETRY + // ----------------------------- + const binRadius = bin.diameter() / 2; + const sidewallHeight = bin.sidewallHeight(); + const hopperHeight = bin.hopperHeight() ?? 0; + const sidewallBaseY = -sidewallHeight / 2; + const hopperTipY = sidewallBaseY - hopperHeight; + + const maxRadiusAtY = (y: number): number => { + if (y >= sidewallBaseY) return binRadius; + if (hopperHeight <= 0 || y <= hopperTipY) return 0; + const t = (y - hopperTipY) / hopperHeight; + return binRadius * t; + }; + + // ----------------------------- + // GRAIN LIMIT + // ----------------------------- + const maxGrainY = useMemo(() => { + let maxY = -Infinity; + nodes.forEach((node) => { + if (!node.inGrain || node.excluded) return; + if (node.position.y > maxY) maxY = node.position.y; + }); + return maxY; + }, [nodes]); + + // ----------------------------- + // PRE-COMPUTE SIGNED NODE CONTRIBUTIONS + // Only nodes outside threshold contribute to the field. + // Hot nodes carry a positive signed intensity, cold nodes negative. + // ----------------------------- + const signedNodes = useMemo(() => { + return nodes + .filter(n => n.inGrain && !n.excluded) + .map(n => { + const lower = bin.lowerTempThreshold(); + const upper = bin.targetTemp(); + + if (n.celcius >= lower && n.celcius <= upper) return null; + + const distance = n.celcius < lower + ? lower - n.celcius + : n.celcius - upper; + + const intensity = Math.min(1, distance / colourFade); + // positive = hot, negative = cold + const signedIntensity = n.celcius > upper ? intensity : -intensity; + + return { + x: n.position.x, + y: n.position.y, + z: n.position.z, + signedIntensity, + cloudRadius: bin.diameter() * BASE_RADIUS_FACTOR * (0.5 + intensity), + densityMultiplier: INTENSITY_DENSITY_BASE + intensity * INTENSITY_DENSITY_MULT, + }; + }) + .filter(Boolean) as { + x: number; y: number; z: number; + signedIntensity: number; + cloudRadius: number; + densityMultiplier: number; + }[]; + }, [nodes, bin]); + + /** + * Evaluates the net signed field at (px, py, pz) by summing + * IDW-weighted signed intensities from all contributing nodes. + * + * Returns a value in [-1, 1]: + * > 0 → net hot + * < 0 → net cold + * ~0 → cancelled out — point will not be emitted + */ + const evaluateField = (px: number, py: number, pz: number): number => { + let totalWeight = 0; + let weightedSum = 0; + + for (const node of signedNodes) { + const dx = px - node.x; + const dy = py - node.y; + const dz = pz - node.z; + const distSq = dx * dx + dy * dy + dz * dz; + + const weight = distSq < 0.001 + ? 1e6 + : 1 / Math.pow(distSq, IDW_POWER / 2); + + totalWeight += weight; + weightedSum += node.signedIntensity * weight; + } + + if (totalWeight === 0) return 0; + return weightedSum / totalWeight; + }; + + // ----------------------------- + // BUILD POINT CLOUD + // ----------------------------- + const { positions, colors } = useMemo(() => { + const positions: number[] = []; + const colors: number[] = []; + + signedNodes.forEach((node) => { + const radialSteps = Math.floor(RADIAL_BASE * node.densityMultiplier); + const thetaSteps = Math.floor(THETA_BASE * node.densityMultiplier); + const phiSteps = Math.floor(PHI_BASE * node.densityMultiplier); + + for (let rStep = 0; rStep < radialSteps; rStep++) { + const r = Math.sqrt(rStep / radialSteps) * node.cloudRadius; + + for (let pStep = 0; pStep < phiSteps; pStep++) { + const phi = ((pStep + 0.5) / phiSteps) * Math.PI; + + for (let tStep = 0; tStep < thetaSteps; tStep++) { + const theta = (tStep / thetaSteps) * Math.PI * 2; + + const x = node.x + r * Math.sin(phi) * Math.cos(theta); + const y = node.y + r * Math.cos(phi); + const z = node.z + r * Math.sin(phi) * Math.sin(theta); + + // Bin boundary checks + if (y < hopperTipY || y > maxGrainY) continue; + const distXZ = Math.sqrt(x * x + z * z); + if (distXZ > maxRadiusAtY(y)) continue; + + // Evaluate the full signed field at this point. + // A point in the overlap of a hot and cold cloud will have + // a net value near zero and will be skipped rather than + // rendered pink. + const netField = evaluateField(x, y, z); + + if (Math.abs(netField) < EMIT_THRESHOLD) continue; + + positions.push(x, y, z); + + // Brightness driven by net magnitude, not per-node intensity + const netMagnitude = Math.abs(netField); + const falloff = 1 - r / node.cloudRadius; + const spatialFalloff = Math.pow(Math.max(0, falloff), 2); + const adjustedFalloff = MIN_EDGE_INTENSITY + (1 - MIN_EDGE_INTENSITY) * spatialFalloff; + const intensityCurve = netMagnitude * netMagnitude; + const brightness = adjustedFalloff * (BASE_BRIGHTNESS + INTENSITY_BRIGHTNESS_MULT * intensityCurve); + + if (netField > 0) { + colors.push(brightness, 0, 0); // hot → red + } else { + colors.push(0, 0, brightness); // cold → blue + } + } + } + } + }); + + return { + positions: new Float32Array(positions), + colors: new Float32Array(colors), + }; + }, [signedNodes, maxGrainY, hopperTipY]); + + const circleTexture = useMemo(() => { + const size = 64; + const canvas = document.createElement("canvas"); + canvas.width = size; + canvas.height = size; + + const ctx = canvas.getContext("2d")!; + const gradient = ctx.createRadialGradient( + size / 2, size / 2, 0, + size / 2, size / 2, size / 2 + ); + + gradient.addColorStop(0, "rgba(255,255,255,1)"); + gradient.addColorStop(1, "rgba(255,255,255,0)"); + + ctx.fillStyle = gradient; + ctx.fillRect(0, 0, size, size); + + const texture = new CanvasTexture(canvas); + texture.needsUpdate = true; + return texture; + }, []); + + // ----------------------------- + // RENDER + // ----------------------------- + return ( + + + + + + + + + ); +} \ No newline at end of file diff --git a/src/bin/3dView/Systems/Heatmap/TempHeatMap.tsx b/src/bin/3dView/Systems/Heatmap/TempHeatMap.tsx new file mode 100644 index 0000000..1b25f0a --- /dev/null +++ b/src/bin/3dView/Systems/Heatmap/TempHeatMap.tsx @@ -0,0 +1,470 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import { Bin } from "models"; +import { NodeData } from "../../Data/BuildNodeData"; +import React from "react"; +import { BinDims } from "bin/3dView/Data/BuildCableData"; + +interface Props { + binDimensions: BinDims + targetTemp: number + nodes: NodeData[]; + /** + * For flat fill percent inventory — a scalar Y ceiling for the heatmap top. + * Used when there are no cable top nodes to drive a surface. + */ + flatMaxY?: number; + /** For flat fill percent — Y floor of filled grain (hopper tip or cylinder base). */ + flatMinY?: number; +} + +const RADIAL_RINGS = 20; +const THETA_SEGMENTS = 40; +const HEIGHT_STEPS = 28; + +const YELLOW_DELTA = 5; +const RED_DELTA = 10; + +const IDW_POWER = 4; +const RED_OPACITY = 0.3; +const GREEN_OPACITY = 0.3; +const YELLOW_OPACITY = 0.8; + +const ANGLE_JITTER = 0.2; +const RADIAL_JITTER = 0.05; +const LAYER_TWIST = 0.22; + +// IDW power for the horizontal surface interpolation — +// matches GrainCableFill's default of 2 +const SURFACE_IDW_POWER = 2; + +function tempToHeat(temp: number, upper: number): number { + if (temp <= upper) return 0; + const delta = temp - upper; + if (delta >= RED_DELTA) return 2; + if (delta >= YELLOW_DELTA) return 1 + (delta - YELLOW_DELTA) / (RED_DELTA - YELLOW_DELTA); + return delta / YELLOW_DELTA; +} + +function heatToRGB(heat: number): number[] { + const GREEN = [0, 0.5, 0.02]; + const YELLOW = [0.7, 0.86, 0.0]; + const RED = [0.8, 0.0, 0.01]; + + if (heat <= 0) return GREEN; + + if (heat <= 1) { + const t = Math.pow(heat, 0.75); + return [ + GREEN[0] + (YELLOW[0] - GREEN[0]) * t, + GREEN[1] + (YELLOW[1] - GREEN[1]) * t, + GREEN[2] + (YELLOW[2] - GREEN[2]) * t, + ]; + } + + const t = Math.pow(heat - 1, 0.75); + return [ + YELLOW[0] + (RED[0] - YELLOW[0]) * t, + YELLOW[1] + (RED[1] - YELLOW[1]) * t, + YELLOW[2] + (RED[2] - YELLOW[2]) * t, + ]; +} + +interface TempAnchor { + x: number; y: number; z: number; + celcius: number; +} + +interface SurfaceAnchor { + x: number; z: number; y: number; +} + +// 3D IDW for temperature interpolation +function idwTemp( + px: number, py: number, pz: number, + anchors: TempAnchor[], + power: number +): number { + let totalWeight = 0; + let weightedSum = 0; + + for (const a of anchors) { + const dx = px - a.x; + const dy = py - a.y; + const dz = pz - a.z; + const distSq = dx * dx + dy * dy + dz * dz; + if (distSq < 0.001) return a.celcius; + const weight = 1 / Math.pow(distSq, power / 2); + totalWeight += weight; + weightedSum += a.celcius * weight; + } + + return totalWeight === 0 ? 0 : weightedSum / totalWeight; +} + +// 2D IDW for surface height interpolation — matches GrainCableFill exactly +function idwSurfaceY( + x: number, z: number, + anchors: SurfaceAnchor[], + power: number +): number { + let totalWeight = 0; + let weightedY = 0; + + for (const a of anchors) { + const dx = x - a.x; + const dz = z - a.z; + const distSq = dx * dx + dz * dz; + if (distSq < 0.001) return a.y; + const weight = 1 / Math.pow(distSq, power / 2); + totalWeight += weight; + weightedY += a.y * weight; + } + + return totalWeight === 0 ? 0 : weightedY / totalWeight; +} + +function hashNoise(a: number, b: number, c: number) { + const x = Math.sin(a * 127.1 + b * 311.7 + c * 74.7) * 43758.5453; + return (x - Math.floor(x)) * 2 - 1; +} + +export default function TempHeatMap({ binDimensions, targetTemp, nodes, flatMaxY, flatMinY }: Props) { + const binRadius = binDimensions.diameter / 2; + const sidewallHeight = binDimensions.sidewallHeight; + const hopperHeight = binDimensions.hopperHeight ?? 0; + const roofHeight = binDimensions.roofHeight ?? 0; + const upperThreshold = targetTemp; + + const sidewallBaseY = -sidewallHeight / 2; + const sidewallTopY = sidewallHeight / 2; + const hopperTipY = sidewallBaseY - hopperHeight; + const roofTipY = sidewallTopY + roofHeight; + + const maxRadiusAtY = (y: number) => { + // Inside the roof cone — tapers from binRadius at sidewallTopY to 0 at roofTipY + if (y > sidewallTopY) { + if (roofHeight <= 0 || y >= roofTipY) return 0; + return binRadius * (1 - (y - sidewallTopY) / roofHeight); + } + // Straight sidewall + if (y >= sidewallBaseY) return binRadius; + // Inside the hopper cone — tapers from binRadius at sidewallBaseY to 0 at hopperTipY + if (hopperHeight <= 0 || y <= hopperTipY) return 0; + return binRadius * ((y - hopperTipY) / hopperHeight); + }; + + // Temperature anchors — all in-grain nodes + const tempAnchors = useMemo( + () => + nodes + .filter(n => n.inGrain && !n.excluded) + .map(n => ({ + x: n.position.x, + y: n.position.y, + z: n.position.z, + celcius: n.celcius, + })), + [nodes] + ); + + // Surface anchors — top nodes only, Y offset by half spacing. + // Only used when flatMaxY is NOT provided (i.e. Automatic / Hybrid_Cable + // inventory control). For any other control type the caller passes flatMaxY + // and we must use a flat surface instead of the wavy cable-driven one. + const surfaceAnchors = useMemo(() => { + if (flatMaxY !== undefined) { + // Non-cable inventory: force flat surface — ignore cable top nodes + return []; + } + return nodes + .filter(n => n.topNode && n.inGrain && !n.excluded) + .map(n => ({ + x: n.position.x, + z: n.position.z, + y: n.position.y + n.nodeSpacing * 0.5, + })); + }, [nodes, flatMaxY]); + + // Wall clamp Y — average of surface anchor heights. + // Prevents the surface from piling up at the bin wall where there are no cables. + // Matches GrainCableFill's wallY computation. + const wallY = useMemo(() => { + if (surfaceAnchors.length === 0) return flatMaxY ?? sidewallBaseY; + return surfaceAnchors.reduce((sum, a) => sum + a.y, 0) / surfaceAnchors.length; + }, [surfaceAnchors, flatMaxY, sidewallBaseY]); + + // Lowest Y the grain surface or heatmap may occupy (hopper tip or cylinder floor). + const grainFloorY = hopperHeight > 0 ? hopperTipY : sidewallBaseY; + + // For each (x, z) position, returns the Y ceiling of the grain surface. + // Uses cable surface IDW when top nodes exist, falls back to flatMaxY. + const getSurfaceY = (x: number, z: number): number => { + if (surfaceAnchors.length > 0) { + const raw = idwSurfaceY(x, z, surfaceAnchors, SURFACE_IDW_POWER); + return Math.max(grainFloorY, Math.min(roofTipY, raw)); + } + return flatMaxY ?? sidewallBaseY; + }; + + // Global max Y — highest point of the surface (used for grid bottom calc) + const maxGrainY = useMemo(() => { + if (surfaceAnchors.length > 0) { + return Math.max(...surfaceAnchors.map(a => a.y), wallY); + } + return flatMaxY ?? sidewallBaseY; + }, [surfaceAnchors, wallY, flatMaxY, sidewallBaseY]); + + // Bottom of filled grain. Flat fill uses volume bounds; cable fill rests on + // the hopper tip (matches GrainCableFill) rather than the lowest cable node. + const minGrainY = useMemo(() => { + if (flatMinY !== undefined) return flatMinY; + return grainFloorY; + }, [flatMinY, grainFloorY]); + + const geometry = useMemo(() => { + if (!tempAnchors.length) return null; + + const pointsPerLayer = 1 + RADIAL_RINGS * THETA_SEGMENTS; + const totalVerts = HEIGHT_STEPS * pointsPerLayer + 1; + + const positions = new Float32Array(totalVerts * 3); + const colors = new Float32Array(totalVerts * 3); + const heats = new Float32Array(totalVerts); + + const grainBottomY = minGrainY; + const grainHeight = maxGrainY - grainBottomY; + + if (grainHeight <= 0) return null; + + // Pre-compute the (x, z) position for each (ring, seg) slot so we + // can look up the surface Y ceiling per column + const colX: number[] = new Array(RADIAL_RINGS * THETA_SEGMENTS); + const colZ: number[] = new Array(RADIAL_RINGS * THETA_SEGMENTS); + const colSurfaceY: number[] = new Array(RADIAL_RINGS * THETA_SEGMENTS); + + // Use the outermost layer's radius for surface Y lookup (no jitter/twist) + // so the surface shape matches GrainCableFill cleanly + const topLayerAllowedRadius = maxRadiusAtY(maxGrainY) * 0.97; + + for (let ring = 0; ring < RADIAL_RINGS; ring++) { + const u = (ring + 1) / RADIAL_RINGS; + const rFrac = 1 - Math.pow(1 - u, 2.2); + const r = rFrac * topLayerAllowedRadius; + + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const angle = (seg / THETA_SEGMENTS) * Math.PI * 2; + const x = Math.cos(angle) * r; + const z = Math.sin(angle) * r; + const ci = ring * THETA_SEGMENTS + seg; + colX[ci] = x; + colZ[ci] = z; + // Outermost ring uses wallY, inner rings use full IDW surface + colSurfaceY[ci] = ring === RADIAL_RINGS - 1 + ? wallY + : getSurfaceY(x, z); + } + } + // Center column surface Y + const centerSurfaceY = getSurfaceY(0, 0); + + for (let hStep = 0; hStep < HEIGHT_STEPS; hStep++) { + const t = hStep / (HEIGHT_STEPS - 1); + + const layerBase = hStep * pointsPerLayer; + const allowedRadius = maxRadiusAtY(grainBottomY + t * grainHeight) * 0.97; + + // Center vertex — Y is lerped from bottom to its column surface ceiling + const centerY = grainBottomY + t * (centerSurfaceY - grainBottomY); + + const centerTemp = idwTemp(0, centerY, 0, tempAnchors, IDW_POWER); + const centerHeat = tempToHeat(centerTemp, upperThreshold); + const [cr, cg, cb] = heatToRGB(centerHeat); + + positions[layerBase * 3] = 0; + positions[layerBase * 3 + 1] = centerY; + positions[layerBase * 3 + 2] = 0; + colors[layerBase * 3] = cr; + colors[layerBase * 3 + 1] = cg; + colors[layerBase * 3 + 2] = cb; + heats[layerBase] = centerHeat; + + for (let ring = 0; ring < RADIAL_RINGS; ring++) { + const u = (ring + 1) / RADIAL_RINGS; + const rFrac = 1 - Math.pow(1 - u, 2.2); + + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const noiseA = hashNoise(hStep, ring, seg); + const noiseR = hashNoise(seg, hStep, ring + 11); + + const baseRadius = rFrac * allowedRadius; + const jitterRadius = baseRadius + noiseR * RADIAL_JITTER * allowedRadius; + const r = Math.max(0, Math.min(jitterRadius, allowedRadius)); + + const layerPhase = t * LAYER_TWIST; + const angle = + (seg / THETA_SEGMENTS) * Math.PI * 2 + + layerPhase + + noiseA * ANGLE_JITTER; + + const x = Math.cos(angle) * r; + const z = Math.sin(angle) * r; + + // Per-column surface Y ceiling — this is what gives the wavy top + const ci = ring * THETA_SEGMENTS + seg; + const surfaceY = colSurfaceY[ci]; + + // Lerp this vertex Y from grainBottomY up to its column surface ceiling + const y = grainBottomY + t * (surfaceY - grainBottomY); + + const temp = idwTemp(x, y, z, tempAnchors, IDW_POWER); + const heat = tempToHeat(temp, upperThreshold); + const [vr, vg, vb] = heatToRGB(heat); + + const vi = layerBase + 1 + ring * THETA_SEGMENTS + seg; + + heats[vi] = heat; + positions[vi * 3] = x; + positions[vi * 3 + 1] = y; + positions[vi * 3 + 2] = z; + colors[vi * 3] = vr; + colors[vi * 3 + 1] = vg; + colors[vi * 3 + 2] = vb; + } + } + } + + const idx = (hStep: number, ring: number, seg: number) => { + if (ring < 0) return hStep * pointsPerLayer; + const s = ((seg % THETA_SEGMENTS) + THETA_SEGMENTS) % THETA_SEGMENTS; + return hStep * pointsPerLayer + 1 + ring * THETA_SEGMENTS + s; + }; + + const green: number[] = []; + const yellow: number[] = []; + const red: number[] = []; + + function pushTri(a: number, b: number, c: number) { + const avg = (heats[a] + heats[b] + heats[c]) / 3; + if (avg < 1) green.push(a, b, c); + else if (avg < 2) yellow.push(a, b, c); + else red.push(a, b, c); + } + + for (let h = 0; h < HEIGHT_STEPS - 1; h++) { + for (let ring = 0; ring < RADIAL_RINGS - 1; ring++) { + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const next = (seg + 1) % THETA_SEGMENTS; + const a = idx(h, ring, seg); + const b = idx(h, ring, next); + const e = idx(h + 1, ring, seg); + const f = idx(h + 1, ring, next); + pushTri(a, e, b); + pushTri(e, f, b); + } + } + + // center fill + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const next = (seg + 1) % THETA_SEGMENTS; + const center0 = idx(h, -1, 0); + const center1 = idx(h + 1, -1, 0); + const a = idx(h, 0, seg); + const b = idx(h, 0, next); + const c = idx(h + 1, 0, seg); + const d = idx(h + 1, 0, next); + pushTri(center0, c, a); + pushTri(center0, center1, c); + pushTri(a, c, b); + pushTri(b, c, d); + } + } + + // Close the bottom at the hopper tip only when grain reaches the tip. + const tipVertexIndex = HEIGHT_STEPS * pointsPerLayer; + if (hopperHeight > 0 && grainBottomY <= hopperTipY + 0.01) { + const tipTemp = idwTemp(0, hopperTipY, 0, tempAnchors, IDW_POWER); + const tipHeat = tempToHeat(tipTemp, upperThreshold); + const [tr, tg, tb] = heatToRGB(tipHeat); + + positions[tipVertexIndex * 3] = 0; + positions[tipVertexIndex * 3 + 1] = hopperTipY; + positions[tipVertexIndex * 3 + 2] = 0; + colors[tipVertexIndex * 3] = tr; + colors[tipVertexIndex * 3 + 1] = tg; + colors[tipVertexIndex * 3 + 2] = tb; + heats[tipVertexIndex] = tipHeat; + + const outerRing = RADIAL_RINGS - 1; + for (let seg = 0; seg < THETA_SEGMENTS; seg++) { + const next = (seg + 1) % THETA_SEGMENTS; + pushTri(tipVertexIndex, idx(0, outerRing, next), idx(0, outerRing, seg)); + } + } + + function makeGeo(indices: number[]) { + const g = new THREE.BufferGeometry(); + g.setAttribute("position", new THREE.BufferAttribute(positions, 3)); + g.setAttribute("color", new THREE.BufferAttribute(colors, 3)); + g.setIndex(indices); + return g; + } + + return { + green: makeGeo(green), + yellow: makeGeo(yellow), + red: makeGeo(red), + }; + }, [ + tempAnchors, + surfaceAnchors, + wallY, + maxGrainY, + minGrainY, + hopperTipY, + sidewallBaseY, + binRadius, + upperThreshold, + hopperHeight, + roofHeight, + roofTipY, + flatMaxY, + flatMinY, + ]); + + if (!geometry) return null; + + return ( + + + + + + + + + + + + + + ); +} \ No newline at end of file diff --git a/src/bin/3dView/Systems/Inventory/GrainCableFill.tsx b/src/bin/3dView/Systems/Inventory/GrainCableFill.tsx new file mode 100644 index 0000000..3cb8cd7 --- /dev/null +++ b/src/bin/3dView/Systems/Inventory/GrainCableFill.tsx @@ -0,0 +1,352 @@ +import { useMemo } from "react"; +import * as THREE from "three"; +import { NodeData } from "../../Data/BuildNodeData"; +import Cone from "3dModels/Shapes/3D/Cone"; +import { Vector3, Euler } from "three"; +import Cylinder from "3dModels/Shapes/3D/Cylinder"; + +interface Props { + diameter: number; + sidewallHeight: number; + hopperHeight?: number; + nodes: NodeData[]; + grainOpacity?: number + /** + * Fallback flat fill percent (0–1) used when no top nodes are available. + * If undefined and no top nodes exist, nothing is rendered. + */ + fallbackFillPercent?: number; +} + +// Tuning knobs +const RADIAL_RINGS = 24; // vertex rings radiating outward from center +const THETA_SEGMENTS = 36; // vertices around each ring + +/** + * Inverse-distance weighted interpolation of Y height at a given (x, z) point. + * Each top node contributes a weighted Y based on its horizontal distance from the point. + * The power parameter controls how sharply nearer nodes dominate (2 = standard IDW). + */ +function idwHeight( + x: number, + z: number, + anchors: { x: number; z: number; y: number }[], + power = 2 +): number { + let totalWeight = 0; + let weightedY = 0; + + for (const anchor of anchors) { + const dx = x - anchor.x; + const dz = z - anchor.z; + const distSq = dx * dx + dz * dz; + + // If we're sitting exactly on an anchor, return its Y immediately + if (distSq < 0.001) return anchor.y; + + const weight = 1 / Math.pow(distSq, power / 2); + totalWeight += weight; + weightedY += anchor.y * weight; + } + + return weightedY / totalWeight; +} + +export default function GrainCableFill(props: Props) { + const { + diameter, + sidewallHeight, + hopperHeight = 0, + nodes, + fallbackFillPercent, + grainOpacity + } = props; + + const binRadius = diameter / 2; + // Slightly inset to avoid z-fighting with the shell + const grainRadius = binRadius * 0.98; + const grainColour = "#fff302"; + + // --- Collect top nodes (non-excluded, inGrain) --- + const topNodes = useMemo(() => + nodes.filter(n => n.topNode && n.inGrain && !n.excluded), + [nodes] + ); + + // --- Build surface anchors: top node Y + half spacing offset --- + // This places the grain line halfway between the top node and the node above it, + // matching the 2D bin view convention. + const anchors = useMemo(() => + topNodes.map(n => ({ + x: n.position.x, + z: n.position.z, + y: n.position.y + n.nodeSpacing * 0.5, + })), + [topNodes] + ); + + // --- Wall clamp: average of all anchor Y values --- + // Prevents grain from piling up at the wall where there are no cables. + const wallY = useMemo(() => { + if (anchors.length === 0) return -sidewallHeight / 2; + return anchors.reduce((sum, a) => sum + a.y, 0) / anchors.length; + }, [anchors, sidewallHeight]); + + // --- Build the polar surface mesh --- + const surfaceGeometry = useMemo(() => { + if (anchors.length === 0) return null; + + // Total vertices: center point + (RADIAL_RINGS * THETA_SEGMENTS) ring vertices + const ringCount = RADIAL_RINGS; + const segCount = THETA_SEGMENTS; + const vertexCount = 1 + ringCount * segCount; + + const positions = new Float32Array(vertexCount * 3); + const normals = new Float32Array(vertexCount * 3); + const uvs = new Float32Array(vertexCount * 2); + + // Center vertex + const centerY = idwHeight(0, 0, anchors); + positions[0] = 0; + positions[1] = centerY; + positions[2] = 0; + normals[0] = 0; normals[1] = 1; normals[2] = 0; + uvs[0] = 0.5; uvs[1] = 0.5; + + // Ring vertices + for (let ring = 0; ring < ringCount; ring++) { + // sqrt distribution for even area density across rings + const t = Math.sqrt((ring + 1) / ringCount); + const r = t * grainRadius; + + for (let seg = 0; seg < segCount; seg++) { + const angle = (seg / segCount) * Math.PI * 2; + const x = Math.cos(angle) * r; + const z = Math.sin(angle) * r; + + // Outermost ring clamps to wall average; inner rings interpolate + //const isOuterRing = ring === ringCount - 1; + // const y = idwHeight(x, z, anchors); + const rawY = idwHeight(x, z, anchors); + + // Blend outer 20% of radius toward wallY + const edgeStart = 0.8; // start taper at 80% radius + const blendT = Math.max(0, (t - edgeStart) / (1 - edgeStart)); + + // smoothstep + const s = blendT * blendT * (3 - 2 * blendT); + + const y = rawY * (1 - s) + wallY * s; + + // Clamp Y to valid range: no higher than roof base, no lower than bin floor + const clampedY = Math.max( + -sidewallHeight / 2, + Math.min(sidewallHeight / 2, y) + ); + + const vi = (1 + ring * segCount + seg) * 3; + positions[vi] = x; + positions[vi + 1] = clampedY; + positions[vi + 2] = z; + + // Approximate normals — pointing up (will look fine for grain) + normals[vi] = 0; normals[vi + 1] = 1; normals[vi + 2] = 0; + + const ui = (1 + ring * segCount + seg) * 2; + uvs[ui] = (x / grainRadius) * 0.5 + 0.5; + uvs[ui + 1] = (z / grainRadius) * 0.5 + 0.5; + } + } + + // --- Build triangle indices --- + // Center fan: triangles from center point to first ring + const indexList: number[] = []; + + for (let seg = 0; seg < segCount; seg++) { + const next = (seg + 1) % segCount; + indexList.push(0, 1 + seg, 1 + next); + } + + // Ring quads: two triangles per quad between adjacent rings + for (let ring = 0; ring < ringCount - 1; ring++) { + for (let seg = 0; seg < segCount; seg++) { + const next = (seg + 1) % segCount; + + const a = 1 + ring * segCount + seg; + const b = 1 + ring * segCount + next; + const c = 1 + (ring + 1) * segCount + seg; + const d = 1 + (ring + 1) * segCount + next; + + indexList.push(a, c, b); + indexList.push(b, c, d); + } + } + + const geo = new THREE.BufferGeometry(); + geo.setAttribute("position", new THREE.BufferAttribute(positions, 3)); + geo.setAttribute("normal", new THREE.BufferAttribute(normals, 3)); + geo.setAttribute("uv", new THREE.BufferAttribute(uvs, 2)); + geo.setIndex(indexList); + geo.computeVertexNormals(); // smooth out the approximated normals + + return geo; + }, [anchors, wallY, grainRadius, sidewallHeight]); + + // --- Hopper fill (reuse existing cone approach) --- + // The surface mesh handles the cylindrical portion. + // The hopper below is always fully filled if the surface is above the bin floor. + const lowestSurfaceY = useMemo(() => { + if (anchors.length === 0) return -sidewallHeight / 2; + return Math.min(...anchors.map(a => a.y), wallY); + }, [anchors, wallY, sidewallHeight]); + + const hopperIsActive = hopperHeight > 0 && lowestSurfaceY > -sidewallHeight / 2; + + const hopperPosition = useMemo( + () => new Vector3(0, -(sidewallHeight / 2 + hopperHeight / 2), 0), + [sidewallHeight, hopperHeight] + ); + + const hopperRotation = useMemo(() => new Euler(Math.PI, 0, 0), []); + + // --- Fallback: flat fill when no top nodes --- + const fallbackGeometry = useMemo(() => { + if (anchors.length > 0 || fallbackFillPercent === undefined) return null; + + const radius = diameter / 2; + const fbRadius = radius * 0.98; + const cylinderVolume = Math.PI * radius * radius * sidewallHeight; + const hopperVolume = hopperHeight > 0 + ? (1 / 3) * Math.PI * radius * radius * hopperHeight + : 0; + const totalVolume = cylinderVolume + hopperVolume; + const filledVolume = totalVolume * fallbackFillPercent; + + let hopperFillHeight = 0; + let cylinderFillHeight = 0; + + if (hopperHeight > 0 && filledVolume <= hopperVolume) { + const ratio = filledVolume / hopperVolume; + hopperFillHeight = hopperHeight * Math.pow(ratio, 1 / 3); + cylinderFillHeight = 0; + } else { + hopperFillHeight = hopperHeight; + const remaining = filledVolume - hopperVolume; + cylinderFillHeight = Math.max(0, remaining / (Math.PI * radius * radius)); + } + + return { fbRadius, hopperFillHeight, cylinderFillHeight }; + }, [anchors.length, fallbackFillPercent, diameter, sidewallHeight, hopperHeight]); + + // --- Render fallback --- + if (anchors.length === 0) { + if (!fallbackGeometry) return null; + + const { fbRadius, hopperFillHeight, cylinderFillHeight } = fallbackGeometry; + + return ( + <> + {hopperHeight > 0 && hopperFillHeight > 0 && ( + + )} + {cylinderFillHeight > 0 && ( + + )} + + ); + } + + // --- Render cable-driven surface --- + return ( + <> + {/* Interpolated grain surface - i have not made a react component for this shape, not exactly a basic shape, so am just using mesh as is */} + {surfaceGeometry && ( + + + + )} + + {/* Cylindrical body of grain below the surface down to the bin floor / hopper top */} + + + {/* Hopper fill — always full when grain surface exists above the floor */} + {hopperIsActive && ( + + )} + + ); +} \ No newline at end of file diff --git a/src/bin/3dView/Systems/Inventory/GrainFillFlat.tsx b/src/bin/3dView/Systems/Inventory/GrainFillFlat.tsx new file mode 100644 index 0000000..e954a1d --- /dev/null +++ b/src/bin/3dView/Systems/Inventory/GrainFillFlat.tsx @@ -0,0 +1,133 @@ +import React, { useMemo } from "react"; +import Cylinder from "3dModels/Shapes/3D/Cylinder"; +import Cone from "3dModels/Shapes/3D/Cone"; +import { Vector3, Euler } from "three"; + +interface Props { + diameter: number; + sidewallHeight: number; + hopperHeight?: number; + fillPercent: number; + grainOpacity?: number; +} + +export default function GrainFillFlat(props: Props) { + const { + diameter, + sidewallHeight, + hopperHeight = 0, + fillPercent, + grainOpacity + } = props; + + const radius = diameter / 2; + + // Slightly smaller to avoid z-fighting with shell + const grainRadius = radius * 0.98; + + // --- volumes --- + const cylinderVolume = Math.PI * radius * radius * sidewallHeight; + const hopperVolume = hopperHeight > 0 + ? (1 / 3) * Math.PI * radius * radius * hopperHeight + : 0; + + const totalVolume = cylinderVolume + hopperVolume; + const filledVolume = totalVolume * fillPercent; + + // --- result values --- + let hopperFillHeight = 0; + let cylinderFillHeight = 0; + + if (hopperHeight > 0 && filledVolume <= hopperVolume) { + // ONLY hopper filling + const ratio = filledVolume / hopperVolume; + + hopperFillHeight = hopperHeight * Math.pow(ratio, 1 / 3); + cylinderFillHeight = 0; + } else { + // hopper full (or no hopper) + hopperFillHeight = hopperHeight; + + const remainingVolume = filledVolume - hopperVolume; + + cylinderFillHeight = Math.max( + 0, + remainingVolume / (Math.PI * radius * radius) + ); + } + + // --- positions --- + + const hopperPosition = useMemo( + () => new Vector3( + 0, + -(sidewallHeight / 2 + hopperHeight) + hopperFillHeight / 2, //adding the hopper height so it starts at the cone and not the flat side + 0 + ), + [sidewallHeight, hopperFillHeight] + ); + + //flip the cone so it matches the hoppers rotation with the cone pointed down + const hopperRotation = useMemo( + () => new Euler(Math.PI, 0, 0), + [] + ); + + const cylinderPosition = useMemo( + () => new Vector3( + 0, + -sidewallHeight / 2 + cylinderFillHeight / 2, + 0 + ), + [sidewallHeight, cylinderFillHeight] + ); + + // --- material --- + const grainColour = "#fff302"; + + return ( + <> + {/* Hopper fill */} + {hopperHeight > 0 && hopperFillHeight > 0 && ( + + )} + + {/* Cylinder fill */} + {cylinderFillHeight > 0 && ( + + )} + + ); +} \ No newline at end of file diff --git a/src/bin/3dView/utils/grainFillBounds.ts b/src/bin/3dView/utils/grainFillBounds.ts new file mode 100644 index 0000000..d1b6fef --- /dev/null +++ b/src/bin/3dView/utils/grainFillBounds.ts @@ -0,0 +1,71 @@ +import { ConeVolume, CylinderVolume } from "common/TrigFunctions"; + +/** + * Y bounds of filled grain volume — matches GrainFillFlat / GrainCableFill fallback volume math. + */ +export interface GrainYBounds { + minY: number; + maxY: number; +} + +// Grain never physically fills all the way to the roof tip — cap roof fill +// at this fraction of roofHeight so there is always visible breathing room. +const MAX_ROOF_FILL_FRACTION = 0.75; + +export function grainYBoundsFromFillPercent( + diameter: number, + sidewallHeight: number, + hopperHeight: number, + roofHeight: number, + fillPercent: number +): GrainYBounds { + const radius = diameter / 2; + const sidewallBaseY = -sidewallHeight / 2; + const hopperTipY = sidewallBaseY - hopperHeight; + const roofBaseY = sidewallHeight / 2; + + if (fillPercent <= 0) { + return { minY: sidewallBaseY, maxY: sidewallBaseY }; + } + + const cylinderVolume = CylinderVolume(radius, sidewallHeight); + const hopperVolume = hopperHeight > 0 ? ConeVolume(radius, hopperHeight) : 0; + const roofVolume = roofHeight > 0 ? ConeVolume(radius, roofHeight) : 0; + + // Volume of the usable roof portion (up to MAX_ROOF_FILL_FRACTION of height). + // A cone fills as h³ so the capped volume fraction = MAX_ROOF_FILL_FRACTION³. + const roofVolumeCapped = roofVolume * Math.pow(MAX_ROOF_FILL_FRACTION, 3); + + const totalVolume = cylinderVolume + hopperVolume + roofVolumeCapped; + const filledVolume = totalVolume * fillPercent; + + // Fill the hopper first + if (hopperHeight > 0 && filledVolume <= hopperVolume) { + const ratio = filledVolume / hopperVolume; + const hopperFillHeight = hopperHeight * Math.pow(ratio, 1 / 3); + return { + minY: hopperTipY, + maxY: hopperTipY + hopperFillHeight, + }; + } + + // Then fill the cylinder + const volumeAfterHopper = filledVolume - hopperVolume; + if (volumeAfterHopper <= cylinderVolume) { + const cylinderFillHeight = volumeAfterHopper / (Math.PI * radius * radius); + return { + minY: hopperHeight > 0 ? hopperTipY : sidewallBaseY, + maxY: sidewallBaseY + cylinderFillHeight, + }; + } + + // Finally fill into the roof cone, capped at MAX_ROOF_FILL_FRACTION + const roofFilledVolume = volumeAfterHopper - cylinderVolume; + const roofRatio = Math.min(1, roofFilledVolume / roofVolumeCapped); + const roofFillHeight = roofHeight * MAX_ROOF_FILL_FRACTION * Math.pow(roofRatio, 1 / 3); + + return { + minY: hopperHeight > 0 ? hopperTipY : sidewallBaseY, + maxY: roofBaseY + roofFillHeight, + }; +} \ No newline at end of file diff --git a/src/bin/3dView/utils/tempToColour.ts b/src/bin/3dView/utils/tempToColour.ts new file mode 100644 index 0000000..b8317df --- /dev/null +++ b/src/bin/3dView/utils/tempToColour.ts @@ -0,0 +1,68 @@ +import { Color } from "three"; +import { NodeData } from "../Data/BuildNodeData"; + +type ColourMode = "node" | "heatmap"; + +const GREEN = new Color("#52c41a"); +const BLUE = new Color("#3399ff"); +const RED = new Color("#ff4d4f"); + +export const colourFade = 20; +const minimumLightness = 0.3; +const lightnessRange = 0.2; +const minimumSaturation = 0.7; +const saturationRange = 0.8; + +const getTemperatureIntensity = (temp: number, lower: number, upper: number) => { + if (temp >= lower && temp <= upper) return 0; + if (temp < lower) return lower - temp; + return temp - upper; +} + +const getVisualIntensity = (distance: number, mode: ColourMode) => { + // 1 = near threshold, 0 = far + const intensity = Math.min(1, distance / colourFade); + switch(mode){ + case "node": + return 1 - intensity + case "heatmap": + return intensity + } +}; + +export function TempToColour( + node: NodeData, + lower: number, + upper: number, + mode: ColourMode +): Color | null { + + if (!node.inGrain || node.excluded) return null; + + const temp = node.celcius; + + // in-threshold behavior + if (temp >= lower && temp <= upper) { + return mode === "heatmap" ? null : GREEN; + } + + const distance = getTemperatureIntensity(temp, lower, upper); + const intensity = getVisualIntensity(distance, mode); + + const color = new Color(); + const hsl = { h: 0, s: 1, l: 1 }; + + if (temp < lower) { + BLUE.getHSL(hsl); + } else { + RED.getHSL(hsl); + } + + color.setHSL( + hsl.h, + (saturationRange * intensity) + minimumSaturation, + (lightnessRange * intensity) + minimumLightness + ); + + return color; +} \ No newline at end of file diff --git a/src/bin/BinPlayer.tsx b/src/bin/BinPlayer.tsx new file mode 100644 index 0000000..88bc45c --- /dev/null +++ b/src/bin/BinPlayer.tsx @@ -0,0 +1,718 @@ +import { DateRange, PlayArrow, Stop } from "@mui/icons-material"; +import { Box, Button, DialogActions, DialogContent, FormControl, IconButton, LinearProgress, MenuItem, Select, TextField, Typography } from "@mui/material"; +import { grey } from "@mui/material/colors"; +import ResponsiveDialog from "common/ResponsiveDialog"; +import { useMobile } from "hooks"; +import { cloneDeep } from "lodash"; +import { Bin } from "models"; +import moment, { Moment } from "moment"; +import { pond } from "protobuf-ts/pond"; +import { quack } from "protobuf-ts/quack"; +import { useComponentAPI } from "providers"; +import React, { useEffect, useRef, useState } from "react"; + +const CHECKPOINT_COUNT = 10; + +interface StatusCheckpoint { + time: Moment; + timeString: string; + cables: pond.GrainCable[]; + fans: pond.BinFan[]; + heaters: pond.BinHeater[]; +} + +interface Props { + bin: Bin; + setBin: React.Dispatch>; + componentDevices: Map; +} + +type ReadingSlot = { + timestamp: string; + values: number[]; +}; + +type CableReadingsAtCheckpoint = { + temperature?: ReadingSlot; + humidity?: ReadingSlot; + moisture?: ReadingSlot; +}; + +/** + * Per-checkpoint bucket for boolean output components (fans, heaters). + * Only the most recent boolean reading in the time slice is kept. + */ +type BooleanStateAtCheckpoint = { + state?: ReadingSlot; // values[0] is the boolean (1 = on, 0 = off) +}; + +/** Per-checkpoint bucket: cable key → latest temp/humidity/moisture readings in that time slice. */ +type CheckpointReadings = Map; + +/** Per-checkpoint bucket: component key → latest boolean state in that time slice. */ +type CheckpointBooleanStates = Map; + +/** + * Returns true when `candidate` should replace `existing` in a bucket. + * Used so multiple samples in the same checkpoint keep only the newest reading per type. + */ +function readingIsNewer(candidate: ReadingSlot, existing?: ReadingSlot): boolean { + if (!existing) { + return true; + } + return moment(candidate.timestamp).valueOf() > moment(existing.timestamp).valueOf(); +} + +/** + * Stores one sampled reading on a cable's in-progress bucket state. + * Routes by measurement type: temperature → celcius nodes, percent RH → humidity nodes, + * grain EMC → moisture nodes. Ignores the update if an equal-or-newer reading is already stored. + */ +function upsertReading( + readings: CableReadingsAtCheckpoint, + type: quack.MeasurementType, + timestamp: string, + values: number[] +): void { + const slot: ReadingSlot = { timestamp, values }; + if (type === quack.MeasurementType.MEASUREMENT_TYPE_TEMPERATURE) { + if (readingIsNewer(slot, readings.temperature)) { + readings.temperature = slot; + } + } else if (type === quack.MeasurementType.MEASUREMENT_TYPE_PERCENT) { + if (readingIsNewer(slot, readings.humidity)) { + readings.humidity = slot; + } + } else if (type === quack.MeasurementType.MEASUREMENT_TYPE_GRAIN_EMC) { + if (readingIsNewer(slot, readings.moisture)) { + readings.moisture = slot; + } + } +} + +/** + * Produces `count` wall-clock times evenly spaced from `start` through `end` (inclusive). + * These are the playback frames — not derived from measurement data. + */ +function buildCheckpointTimes(start: Moment, end: Moment, count: number): Moment[] { + const startMs = start.valueOf(); + const endMs = end.valueOf(); + if (count <= 1 || endMs <= startMs) { + return [moment(startMs)]; + } + const span = endMs - startMs; + return Array.from({ length: count }, (_, i) => + moment(startMs + (span * i) / (count - 1)) + ); +} + +/** + * Maps a measurement timestamp to a checkpoint bucket index in [0, count - 1]. + * The [start, end] range is split into `count` equal-width segments; a reading lands in + * the segment it falls into. Times before start → 0, after end → last bucket. + */ +function checkpointIndexForTimestamp( + timestamp: Moment, + start: Moment, + end: Moment, + count: number +): number { + const startMs = start.valueOf(); + const endMs = end.valueOf(); + if (count <= 1 || endMs <= startMs) { + return 0; + } + const t = timestamp.valueOf(); + if (t <= startMs) { + return 0; + } + if (t >= endMs) { + return count - 1; + } + const fraction = (t - startMs) / (endMs - startMs); + const idx = Math.floor(fraction * count); + return Math.min(idx, count - 1); +} + +/** + * Creates `count` empty buckets, each pre-populated with an empty reading map per cable key. + * Output length matches checkpoint count; index aligns with `buildCheckpointTimes`. + */ +function emptyCheckpointReadings(cableKeys: string[], count: number): CheckpointReadings[] { + return Array.from({ length: count }, () => { + const map: CheckpointReadings = new Map(); + cableKeys.forEach(key => map.set(key, {})); + return map; + }); +} + +/** + * Creates `count` empty boolean state buckets, each pre-populated per component key. + */ +function emptyCheckpointBooleanStates( + componentKeys: string[], + count: number +): CheckpointBooleanStates[] { + return Array.from({ length: count }, () => { + const map: CheckpointBooleanStates = new Map(); + componentKeys.forEach(key => map.set(key, {})); + return map; + }); +} + +/** + * Walks every sampled measurement from each cable response and places it into a time bucket. + * `measurementResponses[i]` corresponds to `cableKeys[i]` (same order as the sample requests). + * Within a bucket, only the newest reading per measurement type is kept per cable. + */ +function assignMeasurementsToCheckpoints( + cableKeys: string[], + measurementResponses: pond.SampleUnitMeasurementsResponse[], + start: Moment, + end: Moment, + count: number +): CheckpointReadings[] { + const buckets = emptyCheckpointReadings(cableKeys, count); + + measurementResponses.forEach((response, cableIndex) => { + const cableKey = cableKeys[cableIndex]; + if (!cableKey) { + return; + } + + response.measurements.forEach(um => { + um.timestamps.forEach((ts, i) => { + const valueArray = um.values[i]; + if (!ts || !valueArray || valueArray.error) { + return; + } + const idx = checkpointIndexForTimestamp(moment(ts), start, end, count); + const readings = buckets[idx].get(cableKey)!; + upsertReading(readings, um.type, ts, valueArray.values); + }); + }); + }); + + return buckets; +} + +/** + * Walks every sampled measurement from each boolean output component (fan/heater) response + * and places the boolean state into a time bucket. Only the newest MEASUREMENT_TYPE_BOOLEAN + * reading per component per bucket is kept. + */ +function assignBooleanStatesToCheckpoints( + componentKeys: string[], + measurementResponses: pond.SampleUnitMeasurementsResponse[], + start: Moment, + end: Moment, + count: number +): CheckpointBooleanStates[] { + const buckets = emptyCheckpointBooleanStates(componentKeys, count); + + measurementResponses.forEach((response, componentIndex) => { + const componentKey = componentKeys[componentIndex]; + if (!componentKey) { + return; + } + + response.measurements.forEach(um => { + if (um.type !== quack.MeasurementType.MEASUREMENT_TYPE_BOOLEAN) { + return; + } + um.timestamps.forEach((ts, i) => { + const valueArray = um.values[i]; + if (!ts || !valueArray || valueArray.error || valueArray.values.length === 0) { + return; + } + const slot: ReadingSlot = { timestamp: ts, values: valueArray.values }; + const idx = checkpointIndexForTimestamp(moment(ts), start, end, count); + const entry = buckets[idx].get(componentKey)!; + if (readingIsNewer(slot, entry.state)) { + entry.state = slot; + } + }); + }); + }); + + return buckets; +} + +/** + * Picks the newest timestamp across temp, humidity, and moisture slots for a cable. + * Used as `lastRead` on the reconstructed `pond.GrainCable`. + */ +function latestTimestamp(readings: CableReadingsAtCheckpoint): string | undefined { + const slots = [readings.temperature, readings.humidity, readings.moisture].filter( + (s): s is ReadingSlot => s !== undefined + ); + if (slots.length === 0) { + return undefined; + } + return slots.reduce( + (latest, slot) => + moment(slot.timestamp).valueOf() > moment(latest).valueOf() ? slot.timestamp : latest, + slots[0].timestamp + ); +} + +/** + * Combines readings carried forward from earlier checkpoints with readings in the current bucket. + * Any type missing in the current bucket keeps the previous checkpoint's value so playback + * does not drop cables back to template defaults between sparse samples. + */ +function mergeCarriedReadings( + carried: CableReadingsAtCheckpoint, + current: CableReadingsAtCheckpoint +): CableReadingsAtCheckpoint { + return { + temperature: current.temperature ?? carried.temperature, + humidity: current.humidity ?? carried.humidity, + moisture: current.moisture ?? carried.moisture + }; +} + +/** + * Combines boolean states carried forward from earlier checkpoints with the current bucket. + * If no reading exists in the current bucket the last known state is preserved, so fans/heaters + * don't flicker back to their template default between sparse samples. + */ +function mergeCarriedBooleanState( + carried: BooleanStateAtCheckpoint, + current: BooleanStateAtCheckpoint +): BooleanStateAtCheckpoint { + return { + state: current.state ?? carried.state + }; +} + +/** + * Clones a live `pond.GrainCable` template (name, key, device, top node, etc.) and overwrites + * node arrays from reconciled readings. `lastRead` is the newest measurement time, or the + * checkpoint time when no readings exist yet for that cable. + */ +function buildGrainCableFromReadings( + template: pond.GrainCable, + readings: CableReadingsAtCheckpoint, + checkpointTime: Moment +): pond.GrainCable { + const cable = pond.GrainCable.fromObject(cloneDeep(template)); + + // Clear template values so empty checkpoints don't inherit live data + cable.celcius = []; + cable.relativeHumidity = []; + cable.moisture = []; + + if (readings.temperature) { + cable.celcius = [...readings.temperature.values]; + } + if (readings.humidity) { + cable.relativeHumidity = [...readings.humidity.values]; + } + if (readings.moisture) { + cable.moisture = [...readings.moisture.values]; + } + + cable.lastRead = latestTimestamp(readings) ?? checkpointTime.toISOString(); + return cable; +} + +/** + * Clones a `pond.BinFan` template and overwrites its `state` from the reconciled boolean + * reading. If no reading has been seen yet the template state is left as-is (carry-forward + * will eventually set it once the first sample arrives). + */ +function buildBinFanFromState( + template: pond.BinFan, + booleanState: BooleanStateAtCheckpoint +): pond.BinFan { + const fan = pond.BinFan.fromObject(cloneDeep(template)); + if (booleanState.state !== undefined) { + fan.state = booleanState.state.values[0] !== 0; + } + return fan; +} + +/** + * Clones a `pond.BinHeater` template and overwrites its `state` from the reconciled boolean + * reading. Same carry-forward semantics as `buildBinFanFromState`. + */ +function buildBinHeaterFromState( + template: pond.BinHeater, + booleanState: BooleanStateAtCheckpoint +): pond.BinHeater { + const heater = pond.BinHeater.fromObject(cloneDeep(template)); + if (booleanState.state !== undefined) { + heater.state = booleanState.state.values[0] !== 0; + } + return heater; +} + +/** + * End-to-end pipeline: evenly spaced times → bucket measurements → carry-forward merge → cables + fans + heaters. + * Returns one `StatusCheckpoint` per frame with `time` (playback moment), `cables` + * (full `grainCables` array), `fans`, and `heaters` as they would have appeared at that moment. + */ +function buildStatusCheckpoints( + cableTemplates: pond.GrainCable[], + fanTemplates: pond.BinFan[], + heaterTemplates: pond.BinHeater[], + cableMeasurementResponses: pond.SampleUnitMeasurementsResponse[], + fanMeasurementResponses: pond.SampleUnitMeasurementsResponse[], + heaterMeasurementResponses: pond.SampleUnitMeasurementsResponse[], + start: Moment, + end: Moment, + count: number = CHECKPOINT_COUNT +): StatusCheckpoint[] { + const times = buildCheckpointTimes(start, end, count); + console.log(times); + + // --- cables --- + const cableKeys = cableTemplates.map(c => c.key); + const cableBuckets = assignMeasurementsToCheckpoints( + cableKeys, + cableMeasurementResponses, + start, + end, + count + ); + + // --- fans --- + const fanKeys = fanTemplates.map(f => f.key); + const fanBuckets = assignBooleanStatesToCheckpoints( + fanKeys, + fanMeasurementResponses, + start, + end, + count + ); + + // --- heaters --- + const heaterKeys = heaterTemplates.map(h => h.key); + const heaterBuckets = assignBooleanStatesToCheckpoints( + heaterKeys, + heaterMeasurementResponses, + start, + end, + count + ); + + // Carry-forward state per component + const carriedByCable = new Map(); + cableKeys.forEach(key => carriedByCable.set(key, {})); + + const carriedByFan = new Map(); + fanKeys.forEach(key => carriedByFan.set(key, {})); + + const carriedByHeater = new Map(); + heaterKeys.forEach(key => carriedByHeater.set(key, {})); + + return cableBuckets.map((cableBucket, i) => { + const time = times[i]; + + // Build cables + const cables = cableTemplates.map(template => { + const key = template.key; + const bucketReadings = cableBucket.get(key) ?? {}; + const merged = mergeCarriedReadings(carriedByCable.get(key)!, bucketReadings); + carriedByCable.set(key, merged); + return buildGrainCableFromReadings(template, merged, time); + }); + + // Build fans + const fans = fanTemplates.map(template => { + const key = template.key; + const bucketState = fanBuckets[i].get(key) ?? {}; + const merged = mergeCarriedBooleanState(carriedByFan.get(key)!, bucketState); + carriedByFan.set(key, merged); + return buildBinFanFromState(template, merged); + }); + + // Build heaters + const heaters = heaterTemplates.map(template => { + const key = template.key; + const bucketState = heaterBuckets[i].get(key) ?? {}; + const merged = mergeCarriedBooleanState(carriedByHeater.get(key)!, bucketState); + carriedByHeater.set(key, merged); + return buildBinHeaterFromState(template, merged); + }); + + return { time, cables, fans, heaters, timeString: time.toISOString() }; + }).filter(checkpoint => + // Keep checkpoints that have at least some cable data + checkpoint.cables.some(cable => + cable.celcius.length > 0 || + cable.relativeHumidity.length > 0 || + cable.moisture.length > 0 + ) + ); +} + +/** + * Calculates the number of checkpoints to create based on the start and end dates. + * Is hard coded to space the checkpoints 6 hours apart. + * @param start - The start date + * @param end - The end date + * @returns The number of checkpoints to create + */ +function checkpointCountFromRange(start: Moment, end: Moment): number { + const hours = end.diff(start, 'hours'); + return Math.max(1, Math.floor(hours / 6) + 1); +} + +/** + * This component is used to reconcile measurements with an array of bin objects in order to see how the bin has progressed over a set period. + * It gets the measurements for connected components, and uses those measurements to create a bin and simulate what its status would have been + * at that time, creates an array of bins doing this and then uses a timer in a loop to change the bin in the status. + * Fans and heaters are included so playback also reflects which equipment was running at each checkpoint. + * @returns a JSX Element + */ +export default function BinPlayer(props: Props) { + const { bin, componentDevices, setBin } = props; + const isMobile = useMobile(); + const componentAPI = useComponentAPI(); + const [dateSelect, setDateSelect] = useState(0); + const [startDate, setStartDate] = useState(moment().subtract(1, 'week')); + const [endDate, setEndDate] = useState(moment); + const [dateRangeDialog, setDateRangeDialog] = useState(false); + const [tempStartDate, setTempStartDate] = useState(moment().subtract(1, 'week')); + const [tempEndDate, setTempEndDate] = useState(moment()); + const [currentCheckpointTime, setCurrentCheckpointTime] = useState(undefined); + const [displayProgress, setDisplayProgress] = useState(0); + const totalCheckpoints = useRef(0); + const checkpointStartTime = useRef(0); + const currentCheckpointIndex = useRef(0); + const isPlaying = useRef(false); + const PLAYBACK_INTERVAL = 1000; + const [isPlayingState, setIsPlayingState] = useState(false); + const stopPlayer = () => { isPlaying.current = false; }; + const originalBin = useRef(null); + + useEffect(() => { + if (!isPlayingState) return; + + const fps = 30; + const interval = 1000 / fps; + const stepDuration = PLAYBACK_INTERVAL; + + const timer = setInterval(() => { + if (!isPlayingState) { + clearInterval(timer); + setDisplayProgress(0); + return; + } + const total = totalCheckpoints.current; + if (total === 0) return; + + const idx = currentCheckpointIndex.current; + const elapsed = Date.now() - checkpointStartTime.current; + const stepProgress = Math.min(elapsed / stepDuration, 1); + const raw = total <= 1 ? 100 : ((idx + stepProgress) / (total - 1)) * 100; + setDisplayProgress(Math.min(raw, 100)); + }, interval); + + return () => clearInterval(timer); + }, [isPlayingState]); + + /** + * Fetches sampled unit measurements for every grain cable, fan, and heater in the current + * bin status, then builds `statusCheckpoints` for playback over [startDate, endDate]. + */ + const startPlayer = async () => { + originalBin.current = cloneDeep(bin); + isPlaying.current = true; + setIsPlayingState(true); + + // Cable requests + const cableSampleRequests = bin.status.grainCables.map(cable => { + const deviceID = componentDevices.get(cable.key) ?? 0; + return componentAPI.sampleUnitMeasurements(deviceID, cable.key, startDate, endDate, 100, undefined, undefined, undefined, undefined, true); + }); + + // Fan requests + const fanSampleRequests = bin.status.fans.map(fan => { + const deviceID = componentDevices.get(fan.key) ?? 0; + return componentAPI.sampleUnitMeasurements(deviceID, fan.key, startDate, endDate, 100, undefined, undefined, undefined, undefined, true); + }); + + // Heater requests + const heaterSampleRequests = bin.status.heaters.map(heater => { + const deviceID = componentDevices.get(heater.key) ?? 0; + return componentAPI.sampleUnitMeasurements(deviceID, heater.key, startDate, endDate, 100, undefined, undefined, undefined, undefined, true); + }); + + const [cableResponses, fanResponses, heaterResponses] = await Promise.all([ + Promise.all(cableSampleRequests), + Promise.all(fanSampleRequests), + Promise.all(heaterSampleRequests), + ]); + + const checkpoints = buildStatusCheckpoints( + bin.status.grainCables, + bin.status.fans, + bin.status.heaters, + cableResponses.map(r => r.data), + fanResponses.map(r => r.data), + heaterResponses.map(r => r.data), + startDate, + endDate, + checkpointCountFromRange(startDate, endDate) + ); + + for (let i = 0; i < checkpoints.length; i++) { + if (!isPlaying.current) { + setBin(originalBin.current!); + setCurrentCheckpointTime(undefined); + setIsPlayingState(false); + return; + } + currentCheckpointIndex.current = i; + totalCheckpoints.current = checkpoints.length; + checkpointStartTime.current = Date.now(); + + const newBin = cloneDeep(originalBin.current!); + newBin.status.grainCables = checkpoints[i].cables; + newBin.status.fans = checkpoints[i].fans; + newBin.status.heaters = checkpoints[i].heaters; + + setBin(newBin); + setCurrentCheckpointTime(checkpoints[i].time); + await new Promise(res => setTimeout(res, PLAYBACK_INTERVAL)); + } + + isPlaying.current = false; + setIsPlayingState(false); + setBin(originalBin.current!); + setCurrentCheckpointTime(undefined); + }; + + const datePickerDialog = () => { + return ( + setDateRangeDialog(false)} + aria-labelledby="date-range-dialog"> + + { + setTempStartDate(moment(e.target.value)); + }} + /> + { + setTempEndDate(moment(e.target.value)); + }} + /> + + + + + + + ); + }; + + const dateSelector = () => { + return ( + + + + + {dateSelect === 3 && ( + + )} + + ); + }; + + return ( + + {datePickerDialog()} + + {/* start/stop button */} + + {isPlayingState ? ( + + ) : ( + + )} + + {/* progress bar and date display */} + + {currentCheckpointTime ? currentCheckpointTime.format("MMM D, YYYY h:mm A") : moment().format("MMM D, YYYY h:mm A")} + + + {startDate.format("MMM D, YYYY")} + {endDate.format("MMM D, YYYY")} + + + {/* date range selector */} + + {dateSelector()} + + + + ); +} diff --git a/src/bin/BinSVGV2.tsx b/src/bin/BinSVGV2.tsx index ecbeb53..0a24d5c 100644 --- a/src/bin/BinSVGV2.tsx +++ b/src/bin/BinSVGV2.tsx @@ -615,7 +615,9 @@ export default function BinSVGV2(props: Props) { //determine how high to draw the node on the cable const nodeY = nodeSpacingY * (index + 1) + minNodeY; - //if we are using the auto top nodes only show the heatmap for nodes at or below the top node and it is not an ecluded node + //if we are using the auto top nodes only show the heatmap for nodes at or below the top node and it is not an excluded node + //NOTE it is nodeNumber - 1 because the excluded node array uses a 0 based count for the node number but the nodeNumber variable uses a 1 based count + //ie. the bottom node of the cable would be nodeNumber of 1 but in the array it would be 0 if (!cable.excludedNodes.includes(nodeNumber - 1)){ if (cable.topNode > 0) { if (nodeNumber <= cable.topNode) { diff --git a/src/bin/BinSensorCard.tsx b/src/bin/BinSensorCard.tsx new file mode 100644 index 0000000..f14d4a9 --- /dev/null +++ b/src/bin/BinSensorCard.tsx @@ -0,0 +1,104 @@ +import { AccessTime, MoreVert } from "@mui/icons-material"; +import { Avatar, Box, Card, IconButton, Table, TableBody, TableCell, TableHead, TableRow, Typography, useTheme } from "@mui/material"; +import moment from "moment"; +import React from "react"; + +interface SensorRow { + label: string; + data: string; +} + +interface CableRow { + label: string; + min: string; + avg: string; + max: string; +} + +interface Props { + name: string; + icon?: string; + tag: string; + lastReading: string; + onMenuClick: (event: React.MouseEvent) => void; + rows?: SensorRow[]; + cableRows?: CableRow[]; + /** + * the time in hours that a reading is considered 'good' + * defaults to 6 + */ + staleLimit?: number; +} + + +export default function BinSensorCard(props: Props) { + const { name, icon, tag, lastReading, onMenuClick, rows, cableRows, staleLimit = 6 } = props + const theme = useTheme() + const isStale = moment().diff(moment(lastReading), "hours") > staleLimit + + return ( + + + + + {icon && + + } + {name} + - {tag} + + + + + + + + {cableRows ? ( + <> + + + + Min + Avg + Max + + + + {cableRows.map((row) => ( + + {row.label} + {row.min} + {row.avg} + {row.max} + + ))} + + + ) : ( + + {rows?.map((row) => ( + + {row.label} + {row.data} + + ))} + + )} +
+ + + + + {moment(lastReading).fromNow()} + + + +
+
+ ) +} \ No newline at end of file diff --git a/src/bin/BinTableExpanded.tsx b/src/bin/BinTableExpanded.tsx new file mode 100644 index 0000000..afc16a8 --- /dev/null +++ b/src/bin/BinTableExpanded.tsx @@ -0,0 +1,194 @@ +import { Box, Table, TableBody, TableCell, TableHead, TableRow, Theme, Typography, useTheme } from "@mui/material"; +import { pond } from "protobuf-ts/pond"; +import { makeStyles } from "@mui/styles"; +import { useEffect, useMemo, useState } from "react"; +import { avg, celsiusToFahrenheit } from "utils"; +import { useGlobalState } from "providers"; +import { darken } from "@mui/material"; +import React from "react"; + +const useStyles = makeStyles((theme: Theme) => ({ + tableStyle: { + borderCollapse: "separate", + borderSpacing: 0, + }, + headerCellStyle: { + fontWeight: 650, + backgroundColor: darken(theme.palette.background.paper, 0.3), + fontSize: 15, + textAlign: "center", + borderBottom: "none", + padding: 10, + }, + defaultCellStyle: { + padding: 2, + fontWeight: 650, + fontSize: 17, + textAlign: "center", + backgroundColor: darken(theme.palette.background.paper, 0.1), + borderTop: "1px solid " + darken(theme.palette.background.paper, 0.4), + borderBottom: "none", + }, + colouredCellStyle: { + padding: 2, + fontWeight: 650, + fontSize: 17, + textAlign: "center", + borderTop: "1px solid " + darken(theme.palette.background.paper, 0.4), + borderBottom: "none", + }, +})); + +// interface Column { +// label: string // e.g. "Cable 1 Temp", "Cable 2 Moisture" +// cableIndex: number +// type: "temp" | "moisture" +// } + +interface Props { + cables: pond.GrainCable[] + targetTemp: number // in Celsius, for colouring + targetMoisture: number // for colouring + inBounds?: string + caution?: string + warning?: string + +} + +export default function BinTableExpanded(props: Props) { + const { cables, targetTemp, targetMoisture, inBounds = "#43a047", caution = "#f9a825", warning = "#c62828" } = props + const classes = useStyles() + const [{ user }] = useGlobalState() + const theme = useTheme() + + const useFahrenheit = user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT + + // Row count driven by the longest cable + const rowCount = useMemo( + () => Math.max(0, ...cables.map(c => c.celcius.length)), + [cables] + ) + + // Render a single cell value + background colour + const renderCell = (cable: pond.GrainCable, nodeIndex: number, type: "temp" | "moisture") => { + if (type === "temp") { + const raw = cable.celcius[nodeIndex] + if (raw === undefined) return { display: "--", color: "" } + + const isExcluded = cable.excludedNodes.includes(nodeIndex) + if (isExcluded) return { display: "--", color: "" } + + let display: string + let color = "" + const inGrain = nodeIndex < cable.topNode + + if (inGrain) { + if (raw > targetTemp + 10) color = warning + else if (raw > targetTemp + 5) color = caution + else color = inBounds + } + + const converted = useFahrenheit ? celsiusToFahrenheit(raw) : raw + display = converted.toFixed(1) + (useFahrenheit ? " °F" : " °C") + return { display, color } + } + + // moisture + const raw = cable.moisture[nodeIndex] + if (raw === undefined || raw === 0) return { display: "--", color: "" } + + const isExcluded = cable.excludedNodes.includes(nodeIndex) + if (isExcluded) return { display: "--", color: "" } + + let color = "" + const inGrain = nodeIndex < cable.topNode + if (inGrain) { + if (raw > targetMoisture + 1.5) color = warning + else if (raw > targetMoisture + 0.5) color = caution + else color = inBounds + } + return { display: raw.toFixed(2) + "%", color } + } + + const cableTable = (cable: pond.GrainCable) => { + return ( + + + + + Level + + + Temperature + + + Moisture + + + + + {Array.from({ length: rowCount }, (_, i) => rowCount - 1 - i).map((nodeIndex, rowI) => { + const isLast = rowI === rowCount - 1 + const tempData = renderCell(cable, nodeIndex, "temp") + const moistureData = renderCell(cable, nodeIndex, "moisture") + return ( + + + {nodeIndex + 1} + + + {tempData.display} + + + {moistureData.display} + + + ) + })} + +
+ ) + } + + return ( + + {/* Table Legend */} + + + + On target + + + + {user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT ? "~10 °F" : "+5 °C"} above + + + + {user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT ? "~20 °F" : "+10 °C"} above + + + + {cables.map((cable, i) => ( + + + {cable.name} + + {cableTable(cable)} + + ))} + + + ) +} \ No newline at end of file diff --git a/src/bin/bin3dVisualizer.tsx b/src/bin/bin3dVisualizer.tsx new file mode 100644 index 0000000..06bc722 --- /dev/null +++ b/src/bin/bin3dVisualizer.tsx @@ -0,0 +1,425 @@ +import { Box, Checkbox, FormControl, MenuItem, List, ListItem, InputLabel, Select, Typography, Stack, FormControlLabel, useTheme } from "@mui/material"; +import Bin3dView from "bin/3dView/Scene/Bin3dView"; +import { Bin, Component, Device } from "models"; +import { Controller } from "models/Controller"; +import { pond, quack } from "protobuf-ts/pond"; +import React, { useEffect } from "react"; +import { useState } from "react"; +import NodeControls from "./binSummary/components/nodeControls"; +import { NodeData } from "bin/3dView/Data/BuildNodeData"; +import { CableData } from "bin/3dView/Data/BuildCableData"; +import ModeChangeDialog from "bin/conditioning/modeChangeDialog"; +import { cloneDeep } from "lodash"; +import { useMobile } from "hooks"; + +interface Props { + bin: Bin + // cables?: GrainCable[] + devices: Device[] + // fans?: Controller[] + // heaters?: Controller[] + permissions: pond.Permission[] + componentDevices: Map + componentMap: Map + binPrefs?: Map + updateBinCallback?: (bin: Bin) => void +} +export default function bin3dVisualizer(props: Props){ + const {bin, permissions, devices, componentDevices, componentMap, binPrefs, updateBinCallback} = props + const theme = useTheme() + const [showHeatmap, setShowHeatmap] = useState(true) + // const [showHotspots, setShowHotspots] = useState(false) + // const [showFill, setShowFill] = useState(false) + const [showTemp, setShowTemp] = useState(true) + const [showMoisture, setShowMoisture] = useState(false) + const [showMoistureHeatmap, setShowMoistureHeatmap] = useState(false) + const [binDisplay, setBinDisplay] = useState("temp") + const [binMode, setBinMode] = useState(pond.BinMode.BIN_MODE_NONE) + const [openModeChange, setOpenModeChange] = useState(false) + const [selectedCable, setSelectedCable] = useState(undefined) + const [selectedNode, setSelectedNode] = useState(undefined) + const [selectedCableDevice, setSelectedCableDevice] = useState(Device.create()) //this is the device that the cable that has the node that was clicked on belongs to + const [filteredComponents, setFilteredComponents] = useState([]) //components that are filtered to only include ones on the same device + const [openNodeControls, setOpenNodeControls] = useState(false) + const [devMap, setDevMap] = useState>(new Map()) + const [modeChangeInProgress, setModeChangeInProgress] = useState(false) + const [showLabels, setShowLabels] = useState(true) + const isMobile = useMobile() + + useEffect(()=>{ + let newMap: Map = new Map() + devices.forEach(d => { + newMap.set(d.id(), d) + }) + setDevMap(newMap) + },[devices]) + + useEffect(()=>{ + setBinMode(bin.settings.mode) + },[bin]) + + const updateBin = () => { + if(updateBinCallback){ + let clone = cloneDeep(bin) + clone.settings.mode = binMode + updateBinCallback(clone) + } + }; + + const binModeControl = () => { + return ( + + {bin.name()} + + + + + ) + } + + const heatmapDisplay = () => { + return ( + + + Heatmap + + + + + {/* Checkbox moved below dropdown — no longer affects top alignment */} + setShowLabels(checked)} + /> + } + label={Show Values} + sx={{ mt: 0.5, ml: '-9px' }} + /> + + ) + } + + // const controllerState = (controller: Controller) => { + // let state = false + // controller.status.lastGoodMeasurement.forEach(um => { + // if(um.type === quack.MeasurementType.MEASUREMENT_TYPE_BOOLEAN){ + // if(um.values.length > 0){ + // let readings = um.values + // if(readings[readings.length-1].values.length > 0){ + // let nodes = readings[readings.length-1].values + // if (nodes[nodes.length -1] === 1){ + // state = true + // } + // } + // } + // } + // }) + // return state + // } + + const controllerDisplay = () => { + if ((bin.status.fans && bin.status.fans.length > 0) || (bin.status.heaters && bin.status.heaters.length > 0)){ + return ( + + + Controllers + + {bin.status.fans && bin.status.fans.map(fan => { + // let isOn = controllerState(fan) + + return ( + + {fan.name} + + + {fan.state ? "ON" : "OFF"} + + + + + )})} + {bin.status.heaters && bin.status.heaters.map(heater => { + // let isOn = controllerState(heater) + return ( + + {heater.name} + + + {heater.state ? "ON" : "OFF"} + + + + + )})} + + // loop through controllers displaying each one + + ) + }else{ + return + } + } + + const desktopHUD = () => { + return ( + + + {binModeControl()} + {heatmapDisplay()} + {controllerDisplay()} + + + ) + } + + const mobileHUD = () => { + return ( + + {/* Top-left: Bin Name / Mode */} + + + {binModeControl()} + + + + {/* Top-right: Heatmap Display */} + + + {heatmapDisplay()} + + + + {/* Bottom-left: Controller Status */} + + + {controllerDisplay()} + + + + ) + } + + return ( + + {(selectedCable && selectedNode) && + { + setOpenNodeControls(false) + }} + /> + } + { + setOpenModeChange(false) + if(refresh) { + updateBin() + }else{ + setBinMode(bin.settings.mode) + }; + }} + defaultTargetMoisture={bin.settings.inventory?.initialMoisture} + // defaultOutdoorTemp={outdoorTemp} + // defaultOutdoorHumidity={outdoorHumidity} + // changeTargetMoisture={newMoisture => { + // setTargetMoisture(newMoisture) + // }} + // changeOutdoorTemp={newTemp => { + // setOutdoorTemp(newTemp) + // }} + // changeOutdoorHumidity={newHumidity => { + // setOutdoorHumidity(newHumidity) + // }} + startChange={() => { + setModeChangeInProgress(true) + }} + changeComplete={() => { + setModeChangeInProgress(false) + }} + + /> + + { + //this will be how to control the dialog to update the top nodes and node exclusion etc (make new component called NodeControls for this) + //use the cable data to get the device it belongs to + let d = devMap.get(cable.grainCable.device) + if(d !== undefined){ + setSelectedNode(node) + setSelectedCable(cable) + setSelectedCableDevice(d) + //filter the controls so that only components on THIS device are options for new interactions, a side note of this using the components that are in the bins status + //is that it will indirectly also filter by bin as well so only components that are both on the bin and the same device as the cable will appear + let filtered: Component[] = [] + if(bin.status.fans){ + bin.status.fans.forEach((f) => { + if(componentDevices.get(f.key) === d.id()){ + let comp = componentMap.get(f.key) + if(comp){ + filtered.push(comp) + } + } + }) + } + if(bin.status.heaters){ + bin.status.heaters.forEach((h) => { + if(componentDevices.get(h.key) === d.id()){ + let comp = componentMap.get(h.key) + if(comp){ + filtered.push(comp) + } + } + }) + } + //also make sure to push the cable into the list of filtered components for the source + let c = componentMap.get(cable.grainCable.key) + if(c !== undefined){ + filtered.push(c) + } + setFilteredComponents(filtered) + setOpenNodeControls(true) + } + }} + scale={100} + showTempHeatmap={showHeatmap} + showMoistureHeatmap={showMoistureHeatmap} + showTemp={showTemp && showLabels} + showMoisture={showMoisture && showLabels} + // showGrain={showFill} + // showHotspots={showHotspots} + xOffset={isMobile ? undefined : -120} + /> + {isMobile ? mobileHUD() : desktopHUD()} + + + ) +} \ No newline at end of file diff --git a/src/bin/binSensorsDisplay.tsx b/src/bin/binSensorsDisplay.tsx new file mode 100644 index 0000000..9785b5e --- /dev/null +++ b/src/bin/binSensorsDisplay.tsx @@ -0,0 +1,1032 @@ +import { AccessTime, MoreVert } from "@mui/icons-material"; +import { Avatar, Box, Button, Card, Checkbox, FormControlLabel, Grid2, IconButton, Menu, MenuItem, Typography, useTheme } from "@mui/material"; +import BinSensorCard from "bin/BinSensorCard"; +import { GetDefaultDateRange } from "common/time/DateRange"; +import { ExtractMoisture } from "grain"; +import { useMobile, useThemeType } from "hooks"; +import { Bin, Component } from "models"; +import { Ambient } from "models/Ambient"; +import { CO2 } from "models/CO2"; +import { Controller } from "models/Controller"; +import { GrainCable } from "models/GrainCable"; +import { Headspace } from "models/Headspace"; +import { Plenum } from "models/Plenum"; +import { Pressure } from "models/Pressure"; +import moment, { Moment } from "moment"; +import { GetComponentIcon } from "pbHelpers/ComponentType"; +import { pond } from "protobuf-ts/pond"; +import { quack } from "protobuf-ts/quack"; +import { useBinAPI, useComponentAPI, useGlobalState, useSnackbar } from "providers"; +import React, { useEffect, useState } from "react"; +import { avg } from "utils"; +import BinSensorGraph from "./graphs/BinSensorGraph"; +import TimeBar from "common/time/TimeBar"; + +interface Props { + bin: Bin + components: Map; + componentDevices: Map; + preferences?: Map; + setPreferences: React.Dispatch< + React.SetStateAction | undefined> + >; + +} + +export default function BinSensorsDisplay(props: Props){ + const {bin, components, componentDevices, preferences, setPreferences} = props + const themeType = useThemeType() + const [{user, as}] = useGlobalState() + const binAPI = useBinAPI() + const componentAPI = useComponentAPI() + const theme = useTheme() + const snackbar = useSnackbar() + const [cables, setCables] = useState([]) + const [plenums, setPlenums] = useState([]) + const [ambient, setAmbient] = useState([]) + const [pressures, setPressures] = useState([]) + const [fans, setFans] = useState([]) + const [heaters, setHeaters] = useState([]) + //the above component preferences all have only components that are one type of sensor, however headspace has components of three different sensors T/H, CO2, and Lidar + const [headspaceTH, setHeadspaceTH] = useState([]) //the components in the headspace that measure temp/humidity + const [headspaceCO2, setHeadspaceCO2] = useState([]) //the CO2 components in the headspace + const [headspaceLidar, setHeadspaceLidar] = useState([]) //the lidar components in the headspace + + const [unassignedComponents, setUnassignedComponents] = useState([]) + + //using counts so i dont have to have to check multiple arrays for sensors and controllers + const [sensorCount, setSensorCount] = useState(0) + const [controllerCount, setControllerCount] = useState(0) + + const [anchorEl, setAnchorEl] = React.useState(null); + //only used to determine what preferences are options for the selected component ie. DHT can be a plenum or a headspace + const [selectedComponentType, setSelectedComponentType] = useState< + quack.ComponentType | undefined + >(undefined); + const [componentUnassigned, setComponentUnnassigned] = useState(false); + const [selectedComponentKey, setSelectedComponentKey] = useState(""); + const [selectedComponentSubtype, setSelectedComponentSubtype] = useState(0); + const [selectedComponentTopNode, setSelectedComponentTopNode] = useState(0); + const [showGraphs, setShowGraphs] = useState(false); + const defaultDateRange = GetDefaultDateRange(); + const [startDate, setStartDate] = useState(defaultDateRange.start); + const [endDate, setEndDate] = useState(defaultDateRange.end); + const [filterNodes, setFilterNodes] = useState(true) + const isMobile = useMobile() + + //organize the components into the correct 'positions' using the bins preferences + useEffect(()=>{ + let unassigned: Component[] = [] + let cables: GrainCable[] = [] + let plenums: Plenum[] = [] + let ambients: Ambient[] = [] + let pressures: Pressure[] = [] + let fans: Controller[] = [] + let heaters: Controller[] = [] + let headspaceTH: Headspace[] = [] + let headspaceCO2: CO2[] = [] + let headspaceLidar: Component[] = [] + let sensorCount = 0 + let controllerCount = 0 + + components.forEach(comp => { + if(preferences){ + let pref = preferences.get(comp.key()) + switch(pref?.type){ + case pond.BinComponent.BIN_COMPONENT_GRAIN_CABLE: + cables.push(GrainCable.create(comp)) + sensorCount++ + break; + case pond.BinComponent.BIN_COMPONENT_PLENUM: + plenums.push(Plenum.create(comp)) + sensorCount++ + break; + case pond.BinComponent.BIN_COMPONENT_AMBIENT: + ambients.push(Ambient.create(comp)) + sensorCount++ + break; + case pond.BinComponent.BIN_COMPONENT_PRESSURE: + pressures.push(Pressure.create(comp)) + sensorCount++ + break; + case pond.BinComponent.BIN_COMPONENT_FAN: + fans.push(Controller.create(comp)) + controllerCount++ + break; + case pond.BinComponent.BIN_COMPONENT_HEATER: + heaters.push(Controller.create(comp)) + controllerCount++ + break; + case pond.BinComponent.BIN_COMPONENT_HEADSPACE: + if (comp.type() === quack.ComponentType.COMPONENT_TYPE_DHT) { + headspaceTH.push(Headspace.create(comp)); + } else if (comp.type() === quack.ComponentType.COMPONENT_TYPE_LIDAR) { + headspaceLidar.push(comp); + } else if (comp.type() === quack.ComponentType.COMPONENT_TYPE_CO2) { + let coComp = CO2.create(comp) + headspaceCO2.push(coComp); + } + sensorCount++ + break; + default: + unassigned.push(comp) + } + }else{ + unassigned.push(comp) + } + }) + // console.log(cables) + // console.log(unassigned) + setSensorCount(sensorCount) + setControllerCount(controllerCount) + setCables(cables) + setPlenums(plenums) + setPressures(pressures) + setAmbient(ambients) + setFans(fans) + setHeaters(heaters) + setHeadspaceTH(headspaceTH) + setHeadspaceCO2(headspaceCO2) + setHeadspaceLidar(headspaceLidar) + setUnassignedComponents(unassigned) + },[components, preferences]) + + const selectType = (component: string, type: pond.BinComponent, topNode?: number) => { + setAnchorEl(null); + if (!preferences) return + let p = preferences.get(component); + if (p) { + p.type = type; + p.node = topNode ?? 0; + binAPI + .updateComponentPreferences(bin.key(), component, p, as) + .then(() => { + snackbar.success("Component preferences updated"); + preferences.set(component, p!); + setPreferences(new Map(preferences)); + }) + .catch(() => { + snackbar.error("Component preference update failed"); + }); + } + }; + + const getOptions = () => { + let options: JSX.Element[] = []; + + if (!componentUnassigned) { + options.push( + { + selectType(selectedComponentKey, pond.BinComponent.BIN_COMPONENT_UNKNOWN); + }}> + Remove + + ); + } + if ( + selectedComponentType === quack.ComponentType.COMPONENT_TYPE_DHT || + selectedComponentType === quack.ComponentType.COMPONENT_TYPE_GRAIN_CABLE + ) { + options.push( + { + selectType(selectedComponentKey, pond.BinComponent.BIN_COMPONENT_AMBIENT); + }}> + Ambient + + ); + options.push( + { + selectType(selectedComponentKey, pond.BinComponent.BIN_COMPONENT_PLENUM); + }}> + Plenum + + ); + } + if ( + selectedComponentType === quack.ComponentType.COMPONENT_TYPE_DHT || + selectedComponentType === quack.ComponentType.COMPONENT_TYPE_LIDAR || + selectedComponentType === quack.ComponentType.COMPONENT_TYPE_CO2 + ) { + options.push( + { + selectType(selectedComponentKey, pond.BinComponent.BIN_COMPONENT_HEADSPACE); + }}> + Headspace + + ); + } + if ( + selectedComponentType === quack.ComponentType.COMPONENT_TYPE_PRESSURE || + selectedComponentType === quack.ComponentType.COMPONENT_TYPE_PRESSURE_CABLE + ) { + options.push( + { + selectType(selectedComponentKey, pond.BinComponent.BIN_COMPONENT_PRESSURE); + }}> + Plenum Pressure + + ); + } + if (selectedComponentType === quack.ComponentType.COMPONENT_TYPE_GRAIN_CABLE) { + options.push( + { + selectType( + selectedComponentKey, + pond.BinComponent.BIN_COMPONENT_GRAIN_CABLE, + selectedComponentTopNode + ); + }}> + Grain Cable + + ); + } + if (selectedComponentType === quack.ComponentType.COMPONENT_TYPE_BOOLEAN_OUTPUT) { + options.push( + { + if ( + selectedComponentSubtype === quack.BooleanOutputSubtype.BOOLEAN_OUTPUT_SUBTYPE_HEATER + ) { + selectType(selectedComponentKey, pond.BinComponent.BIN_COMPONENT_HEATER); + } else if ( + selectedComponentSubtype === + quack.BooleanOutputSubtype.BOOLEAN_OUTPUT_SUBTYPE_AERATION_FAN + ) { + selectType(selectedComponentKey, pond.BinComponent.BIN_COMPONENT_FAN); + } + }}> + Heaters & Fans + + ); + } + + if (options.length === 0) { + return No Available Options; + } else { + return options; + } + }; + + const assignmentMenu = () => { + return ( + setAnchorEl(null)} + keepMounted + disableAutoFocusItem> + {getOptions()} + + ); + }; + + const cableCard = (cable: GrainCable) => { + const component = cable.asComponent() + let icon = GetComponentIcon(component.type(), component.subType(), themeType) + let unit = user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT ? "°F" : "°C" + + const hasHumidity = cable.aveHumidity() !== 0 + const hasMoisture = cable.grainMoistures.length > 0 + + const rows: { label: string; min: string; avg: string; max: string }[] = [ + { + label: `Temp ${unit}`, + min: cable.minTemp(user.tempUnit(), filterNodes).toFixed(2), + avg: cable.aveTemp(user.tempUnit(), filterNodes).toFixed(2), + max: cable.maxTemp(user.tempUnit(), filterNodes).toFixed(2), + }, + ...(hasHumidity ? [{ + label: "RH %", + min: cable.minHumidity(filterNodes).toFixed(2), + avg: cable.aveHumidity(filterNodes).toFixed(2), + max: cable.maxHumidity(filterNodes).toFixed(2), + }] : []), + ...(hasMoisture ? [{ + label: "EMC %", + min: cable.minMoisture(filterNodes).toFixed(2), + avg: cable.aveMoisture(filterNodes).toFixed(2), + max: cable.maxMoisture(filterNodes).toFixed(2), + }] : []), + ] + + return ( + { + setComponentUnnassigned(false); + setSelectedComponentType(cable.type()); + setSelectedComponentKey(cable.key()); + setSelectedComponentTopNode(cable.settings.grainFilledTo); + setAnchorEl(event.currentTarget); + }}/> + ) + } + + const tempHumidCard = (sensor: Plenum | Ambient | Headspace, showEMC?: boolean) => { + let icon = GetComponentIcon(sensor.settings.type, sensor.settings.subtype, themeType) + let prefDisplay = "" + switch (preferences?.get(sensor.key())?.type){ + case pond.BinComponent.BIN_COMPONENT_PLENUM: + prefDisplay = "Plenum" + break; + case pond.BinComponent.BIN_COMPONENT_AMBIENT: + prefDisplay = "Ambient" + break; + case pond.BinComponent.BIN_COMPONENT_HEADSPACE: + prefDisplay = "Headspace" + } + + let rows: {label: string, data: string}[] = [ + // build temperature row data + { + label: "Temp " + (user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT ? "°F" : "°C"), + data: (user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT ? sensor.temperature * (9 / 5) + 32 : sensor.temperature).toFixed(2) + }, + // build humidity row + { + label: "RH %", + data: sensor.humidity.toFixed(2) + } + ] + // build moisture row assuming the bin has a grain type to use to calculatee the moisture + if(showEMC && bin.grain() !== pond.Grain.GRAIN_INVALID && bin.grain() !== pond.Grain.GRAIN_NONE){ + let emc = ExtractMoisture( + bin.grain(), + sensor.temperature, + sensor.humidity, + bin.customGrain() + ) + rows.push( + { + label: "EMC %", + data: emc.toFixed(2) + } + ) + } + + return ( + { + setComponentUnnassigned(false); + setSelectedComponentType(sensor.type()); + setSelectedComponentKey(sensor.key()); + setAnchorEl(event.currentTarget); + }} + /> + ) + } + + const pressureCard = (pressure: Pressure) => { + let icon = GetComponentIcon(pressure.settings.type, pressure.settings.subtype, themeType) + let rows: {label: string, data: string}[] = [ + { + label: "Pressure " + (user.pressureUnit() === pond.PressureUnit.PRESSURE_UNIT_INCHES_OF_WATER ? "iwg" : "kPa"), + data: (user.pressureUnit() === pond.PressureUnit.PRESSURE_UNIT_INCHES_OF_WATER ? pressure.pascals/249 : pressure.pascals/1000).toFixed(2) + } + ] + + if(pressure.airflow){ + rows.push({ + label: "Airflow CFM", + data: pressure.airflow.toFixed(2) + }) + } + + return ( + { + setComponentUnnassigned(false); + setSelectedComponentType(pressure.type()); + setSelectedComponentKey(pressure.key()); + setAnchorEl(event.currentTarget); + }} + /> + ) + } + const co2Card = (sensor: CO2) => { + let icon = GetComponentIcon(sensor.settings.type, sensor.settings.subtype, themeType) + let rows: {label: string, data: string}[] = [ + { + label: "CO2 ppm", + data: sensor.ppm.toFixed(2) + } + ] + + return ( + { + setComponentUnnassigned(false); + setSelectedComponentType(sensor.type()); + setSelectedComponentKey(sensor.key()); + setAnchorEl(event.currentTarget); + }} + /> + ) + } + + const lidarCard = (sensor: Component) => { + let icon = GetComponentIcon(sensor.settings.type, sensor.settings.subtype, themeType) + let rows: {label: string, data: string}[] = [] + let lastReading = moment.now().toString() + sensor.lastMeasurement.forEach(unitMeasurement => { + let label = "" + let value = 0 + if(sensor.type() === quack.ComponentType.COMPONENT_TYPE_LIDAR){ + if(unitMeasurement.type === quack.MeasurementType.MEASUREMENT_TYPE_DISTANCE_CM){ + label = "Lidar " + (user.distanceUnit() === pond.DistanceUnit.DISTANCE_UNIT_FEET ? " ft" : " M") + if(unitMeasurement.timestamps.length > 0){ + lastReading = unitMeasurement.timestamps[0] + } + if (unitMeasurement.values.length > 0){ + //distance is stored in cm so needs to be converted + value = avg(unitMeasurement.values[0].values) + value = user.distanceUnit() === pond.DistanceUnit.DISTANCE_UNIT_FEET ? value/30.48 : value/100 + } + + } + } + rows.push({label: label, data: value.toFixed(2)}) + }) + + return ( + { + setComponentUnnassigned(false); + setSelectedComponentType(sensor.type()); + setSelectedComponentKey(sensor.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + + const controllerCard = (controller: Controller) => { + const component = controller.asComponent() + let icon = GetComponentIcon(component.type(), component.subType(), themeType) + const isStale = moment().diff(moment(controller.lastReading), "hours") > 6 + const isAuto = controller.mode === quack.OutputMode.OUTPUT_MODE_AUTO + const isOn = controller.mode === quack.OutputMode.OUTPUT_MODE_ON + const isOff = controller.mode === quack.OutputMode.OUTPUT_MODE_OFF + + const prefType = preferences?.get(controller.key())?.type + const tag = prefType === pond.BinComponent.BIN_COMPONENT_FAN ? "Fan" : "Heater" + + const segStyle = (active: boolean, activeColor?: string): React.CSSProperties => ({ + flex: 1, + padding: "5px 0", + fontSize: 11, + fontWeight: 500, + textAlign: "center", + cursor: "pointer", + borderRadius: 0, + backgroundColor: active ? (activeColor ?? theme.palette.success.main) : "transparent", + color: active ? "#fff" : theme.palette.text.secondary, + border: "none", + transition: "background-color 0.15s", + }) + + return ( + + + + + + + {controller.name()} + - {tag} + + ) => { + setComponentUnnassigned(false) + setSelectedComponentType(controller.type()) + setSelectedComponentKey(controller.key()) + setAnchorEl(event.currentTarget) + }} + > + + + + + + Current state + + + + {controller.on ? "Running" : isAuto ? "Standby" : "Off"} + + + + + + {[ + { label: "Auto", mode: quack.OutputMode.OUTPUT_MODE_AUTO, active: isAuto }, + { label: "On", mode: quack.OutputMode.OUTPUT_MODE_ON, active: isOn }, + { label: "Off", mode: quack.OutputMode.OUTPUT_MODE_OFF, active: isOff }, + ].map(({ label, mode, active }, i) => ( + { + //this will update the components settings here to change the mode + console.log("changing mode: " + mode) + controller.settings.defaultOutputState = mode + let device = componentDevices.get(controller.key()) + if(device){ + componentAPI.update(device, controller.settings).then(resp => { + controller.mode = mode // ← update the field the UI reads + + if (prefType === pond.BinComponent.BIN_COMPONENT_FAN) { + setFans(prev => prev.map(f => f.key() === controller.key() ? controller : f)) + } else { + setHeaters(prev => prev.map(h => h.key() === controller.key() ? controller : h)) + } + }).catch(err => { + console.log("there was a problem updating the controller") + }) + } + + }} + sx={{ + ...segStyle(active, label === "Off" ? theme.palette.action.selected : undefined), + borderLeft: i > 0 ? `0.5px solid ${theme.palette.divider}` : "none", + }} + > + {label} + + ))} + + + + + + {moment(controller.lastReading).fromNow()} + + + + + + ) + } + + const unassignedComponentCard = (component: Component) => { + let icon = GetComponentIcon(component.type(), component.subType(), themeType) + const lastReading = component.lastMeasurement.length > 0 + ? component.lastMeasurement[0].timestamps[0] ?? "" + : "" + const isStale = moment().diff(moment(lastReading), "hours") > 6 + + return ( + + + + + + {component.name()} + + ) => { + setComponentUnnassigned(true) + setSelectedComponentType(component.type()) + setSelectedComponentKey(component.key()) + setSelectedComponentSubtype(component.subType()) + setSelectedComponentTopNode(0) + setAnchorEl(event.currentTarget) + }} + > + + + + + + + + {lastReading ? moment(lastReading).fromNow() : "No readings yet"} + + + + + + ) + } + const updateDateRange = (newStartDate: any, newEndDate: any) => { + let range = GetDefaultDateRange(); + range.start = newStartDate; + range.end = newEndDate; + setStartDate(newStartDate); + setEndDate(newEndDate); + }; + + const graphControls = () => { + return ( + + + {showGraphs && !isMobile && + + } + {cables.length > 0 && + { + setFilterNodes(!filterNodes) + }} + /> + } + label={Show All Nodes + } + /> + } + + ) + } + + return ( + + {assignmentMenu()} + {sensorCount > 0 && + + + Sensors + {graphControls()} + + {showGraphs && isMobile && + + } + + {plenums.map(plenum => { + let device = componentDevices.get(plenum.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(plenum.type(), plenum.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(plenum.type()); + setSelectedComponentKey(plenum.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return( + + {tempHumidCard(plenum)} + + ) + } + )} + {pressures.map(pressure => { + let device = componentDevices.get(pressure.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(pressure.type(), pressure.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(pressure.type()); + setSelectedComponentKey(pressure.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return( + + {pressureCard(pressure)} + + ) + })} + {ambient.map(ambient => { + let device = componentDevices.get(ambient.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(ambient.type(), ambient.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(ambient.type()); + setSelectedComponentKey(ambient.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return( + + {tempHumidCard(ambient)} + + ) + } + )} + {headspaceTH.map(h => { + let device = componentDevices.get(h.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(h.type(), h.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(h.type()); + setSelectedComponentKey(h.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return( + + {tempHumidCard(h)} + + ) + })} + + {headspaceCO2.map(co2 => { + let device = componentDevices.get(co2.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(co2.type(), co2.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(co2.type()); + setSelectedComponentKey(co2.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return( + + {co2Card(co2)} + + ) + })} + {headspaceLidar.map(lidar => { + let device = componentDevices.get(lidar.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(lidar.type(), lidar.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(lidar.type()); + setSelectedComponentKey(lidar.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return ( + + {lidarCard(lidar)} + + ) + })} + {cables.map(cable => { + let device = componentDevices.get(cable.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(cable.type(), cable.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(cable.type()); + setSelectedComponentKey(cable.key()); + setSelectedComponentTopNode(cable.settings.grainFilledTo); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return( + + {cableCard(cable)} + + ) + })} + + + } + + {controllerCount > 0 && + + Controllers + + {heaters.map(heater => { + let device = componentDevices.get(heater.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(heater.type(), heater.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(heater.type()); + setSelectedComponentKey(heater.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return ( + + {controllerCard(heater)} + + ) + })} + {fans.map(fan => { + let device = componentDevices.get(fan.key()) + if(showGraphs && device){ + let icon = GetComponentIcon(fan.type(), fan.subType(), themeType) + return( + + { + setComponentUnnassigned(false); + setSelectedComponentType(fan.type()); + setSelectedComponentKey(fan.key()); + setAnchorEl(event.currentTarget); + }} + /> + + ) + } + return ( + + {controllerCard(fan)} + + ) + })} + + + } + {unassignedComponents.length > 0 && + + Unassigned Components + + {unassignedComponents.map(comp => ( + + {unassignedComponentCard(comp)} + + ))} + + + } + + ) +} \ No newline at end of file diff --git a/src/bin/binSummary/BinSummary.tsx b/src/bin/binSummary/BinSummary.tsx new file mode 100644 index 0000000..293a720 --- /dev/null +++ b/src/bin/binSummary/BinSummary.tsx @@ -0,0 +1,396 @@ +import { Box, Card, DialogContent, DialogTitle, Grid2, IconButton, LinearProgress, Skeleton, Slider, Switch, Tooltip, Typography } from "@mui/material"; +import { useMobile } from "hooks"; +import { Bin, Component, Device } from "models"; +import Bin3dVisualizer from "../bin3dVisualizer"; +// import GrassIcon from "@mui/icons-material/Grass" +import { grey, orange, red } from "@mui/material/colors"; +import { AccessTime, Spa } from "@mui/icons-material"; +import moment from "moment"; +import { Controller } from "models/Controller"; +import { GrainCable } from "models/GrainCable"; +import { pond } from "protobuf-ts/pond"; +import BinDetails from "./components/binDetails"; +import { Plenum } from "models/Plenum"; +import BinSensorsDisplay from "../binSensorsDisplay"; +import ResponsiveDialog from "common/ResponsiveDialog"; +import { useEffect, useRef, useState } from "react"; +import SearchSelect from "common/SearchSelect"; +import ChangeGrainDialog from "grain/ChangeGrainDialog"; +import { useGlobalState } from "providers"; +import GrainTransaction from "grain/GrainTransaction"; +import { cloneDeep } from "lodash"; +import BinPlayer from "bin/BinPlayer"; + +interface Props { + bin: Bin + loading?: boolean, + devices: Device[] + cables?: GrainCable[] + plenums?: Plenum[] + fans?: Controller[] + heaters?: Controller[] + permissions: pond.Permission[] + componentDevices: Map + componentMap: Map + binPrefs?: Map + setPreferences: React.Dispatch< + React.SetStateAction | undefined> + >; + updateBinCallback?: (bin: Bin) => void + setBin?: React.Dispatch>; + +} +export default function BinSummary(props: Props){ + const {bin, loading, devices, fans, heaters, permissions, componentDevices, componentMap, binPrefs, updateBinCallback, cables = [], plenums = [], setPreferences, setBin} = props + //const [currentDevice, setCurrentDevice] = useState(undefined) + const isMobile = useMobile() + const [openGrainDialog, setOpenGrainDialog] = useState(false) + const [manualFillPercent, setManualFillPercent] = useState(0) + const [manualBushels, setManualBushels] = useState(0) + const [{user}] = useGlobalState() + const fillCapRef = useRef(null); + const [fillCapWidth, setFillCapWidth] = useState(undefined); + const [openNewTransaction, setOpenNewTransaction] = useState(false) + + useEffect(() => { + if (fillCapRef.current) { + // measure the max possible string width once + fillCapRef.current.textContent = `${bin.grainCapacity(user)}/${bin.grainCapacity(user)}`; + setFillCapWidth(fillCapRef.current.offsetWidth); + } + }, [bin, user]); + + useEffect(()=>{ + setManualFillPercent(bin.fillPercent()) + setManualBushels(bin.bushels()) + },[bin]) + + // useEffect(() => { + // if(devices.length > 0){ + // setCurrentDevice(devices[0]) + // } + // },[devices]) + + const activity = (reading: string) => { + //if the device hasnt checked in in 6 hours = missing 12 hours = inactive within 6 hours = live + let status = "Live" + let colour = "#4caf50" + let diff = moment().diff(moment(reading), "hour") + if(diff > 12){ + status = "Inactive" + colour = red[700] + }else if (diff > 6){ + status = "Missing" + colour = orange[300] + } + + return ( + + + + {status} + + + ) + } + + const currentFill = () => { + if(bin.inventoryControl() === pond.BinInventoryControl.BIN_INVENTORY_CONTROL_MANUAL){ + if(user.grainUnit() === pond.GrainUnit.GRAIN_UNIT_TONNE && bin.bushelsPerTonne() > 1){ + return Math.round((manualBushels / bin.bushelsPerTonne())*10)/10 + }else if (user.grainUnit() === pond.GrainUnit.GRAIN_UNIT_TON && bin.bushelsPerTonne() > 1){ + return Math.round((manualBushels / (bin.bushelsPerTonne() * 0.907))*10)/10 + } + return Math.round(manualBushels) + } + return bin.grainInventory(user) + } + + const inventorySummaryMobile = () => ( + + {/* Header row */} + + + setOpenGrainDialog(true)}> + + + + Grain type + {bin.grainName()} + + + + + + Last updated + {moment(bin.status.timestamp).fromNow()} + + + + + {/* Fill row */} + + + Bin fill + + + {bin.inventoryControl() === pond.BinInventoryControl.BIN_INVENTORY_CONTROL_MANUAL + ? manualFillPercent : bin.fillPercent()}% + + + {currentFill().toLocaleString()} / {bin.grainCapacity(user).toLocaleString()} + + + + {bin.inventoryControl() === pond.BinInventoryControl.BIN_INVENTORY_CONTROL_MANUAL ? ( + + setOpenNewTransaction(true)} + onChange={(_, val) => { setManualFillPercent(val as number); setManualBushels((val as number / 100) * bin.bushelCapacity()); }} + min={0} max={100} sx={{ + color: "#4caf50", + py: 0, + mt: 0, + mb: 0, + height: 4, + "& .MuiSlider-root": { py: 0 }, + "& .MuiSlider-thumb": { width: 16, height: 16 }, + "& .MuiSlider-rail": { backgroundColor: "rgba(255,255,255,0.1)" }, + }} /> + + ) : ( + + )} + + + ); + + const inventorySummaryDesktop = () => { + return ( + + + + {/* Grain Type */} + + + Grain Type + + setOpenGrainDialog(true)} + sx={{ + cursor: "pointer", + mt: 0.5, + px: 1, + py: 0.5, + borderRadius: 1, + border: "1px solid", + borderColor: grey[700], + "&:hover": { + borderColor: grey[500], + backgroundColor: "rgba(255,255,255,0.05)", + }, + }} + > + + {bin.grainName()} + + + + {/* Bin Fill */} + + + Bin Fill + + + {/* hidden measuring span, renders off-screen */} + + + {currentFill()}/{bin.grainCapacity(user)} + + {bin.inventoryControl() === pond.BinInventoryControl.BIN_INVENTORY_CONTROL_MANUAL ? + { + setOpenNewTransaction(true) + }} + onChange={(_, val) => { + let fillPercent = val as number + setManualFillPercent(fillPercent) + let newBushels = (fillPercent/100) * bin.bushelCapacity() + setManualBushels(newBushels) + //this does casue the 3d bin to fill as you drag it but it throws off the transaction and the reset if you cancel + // let clone = cloneDeep(bin) + // let inventory = clone.settings.inventory ?? pond.BinInventory.create() + // inventory.grainBushels = newBushels + // if(setBin){ + // setBin(clone) + // } + }} + min={0} + max={100} + sx={{ + flexGrow: 1, + color: "#4caf50", + "& .MuiSlider-thumb": { + width: 16, + height: 16, + }, + "& .MuiSlider-rail": { + backgroundColor: "rgba(255,255,255,0.1)", + }, + }} + /> + : + + } + + {bin.inventoryControl() === pond.BinInventoryControl.BIN_INVENTORY_CONTROL_MANUAL ? manualFillPercent : bin.fillPercent()}% + + + + + {/* Last Updated */} + + + Last Updated + + + + + + + {moment(bin.status.timestamp).fromNow()} + + + {activity(bin.status.timestamp)} + + + + + + ); + }; + + return ( + + { + //this resets all of the state variables used + setOpenNewTransaction(false); + if(!confirmed){ + setManualBushels(bin.bushels()) + setManualFillPercent(bin.fillPercent()) + }else{ + let clone = cloneDeep(bin) + let inventory = clone.settings.inventory ?? pond.BinInventory.create() + inventory.grainBushels = manualBushels + if(setBin){ + setBin(clone) + } + } + + }} + /> + setOpenGrainDialog(false)} permissions={permissions} updateBin={updateBinCallback}/> + {loading ? : isMobile ? inventorySummaryMobile() : inventorySummaryDesktop()} + + {!isMobile && + + {loading ? + + : + + + {setBin && + + + + } + + } + + } + + {loading ? + + : + + + + } + + + {loading ? + + : + + + + } + + + + + ) +} \ No newline at end of file diff --git a/src/bin/binSummary/components/binAlerts.tsx b/src/bin/binSummary/components/binAlerts.tsx new file mode 100644 index 0000000..f8c1bac --- /dev/null +++ b/src/bin/binSummary/components/binAlerts.tsx @@ -0,0 +1,137 @@ +import { LinearProgress } from "@mui/material"; +import { Bin, Component, Device, Interaction } from "models"; +import Alerts, { Alert } from "objects/objectInteractions/Alerts"; +import NewObjectInteraction from "objects/objectInteractions/NewObjectInteraction"; +import { extension } from "pbHelpers/ComponentType"; +import { pond } from "protobuf-ts/pond"; +import { useGlobalState, useInteractionsAPI } from "providers"; +import React, { useCallback, useEffect, useState } from "react"; + +interface Props { + linkedComponents: Map; //the component key to the component object + componentDevices: Map; + permissions: pond.Permission[] +} + +export default function BinAlerts(props: Props){ + const {linkedComponents, componentDevices, permissions} = props + const [{as}] = useGlobalState(); + const interactionsAPI = useInteractionsAPI(); + + //list of alerts, each alert contains a list of interactions with matching conditions + const [alerts, setAlerts] = useState([]); + const [loading, setLoading] = useState(false) + const [newAlert, setNewAlert] = useState(false) + + const matchConditions = (interaction: Interaction, set: Alert) => { + //if the number of conditions are not the same they are different + if (interaction.settings.conditions.length !== set.conditions.length) { + return false; + } + //continue with the comparison + let matching = true; + interaction.settings.conditions.forEach((condition, i) => { + if ( + condition.comparison !== set.conditions[i].comparison || + condition.measurementType !== set.conditions[i].measurementType || + condition.value !== set.conditions[i].value + ) { + matching = false; + } + }); + return matching; + }; + + const load = useCallback(()=>{ + if(!loading){ + //load the interactions for the linked components + setLoading(true) + const newInteractions: Interaction[] = []; + const interactionSourceMap = new Map(); + const sinkOptions: Component[] = []; + const run = async () => { + // Run all component API fetches in parallel + await Promise.all( + [...linkedComponents].map(async ([key, comp]) => { + const device = componentDevices.get(key); + + if (device) { + const resp = await interactionsAPI.listInteractionsByComponent( + device, + comp.location(), + undefined, + as + ); + + resp.forEach(interaction => interactionSourceMap.set(interaction.key(), key)); + newInteractions.push(...resp); + } + + // Collect controller components + if (extension(comp.type()).isController) { + sinkOptions.push(comp); + } + }) + ); + }; + + run().then(() => { + newInteractions.forEach(interaction => { + //alert and control are not mutally exclusive, it is possible to be both if the control is sending notifications + if (interaction.isAlert()) { + // Find matching alert + let similarAlertIndex = alerts.findIndex(alert => + matchConditions(interaction, alert) + ); + + const compKey = interactionSourceMap.get(interaction.key()); + const component = compKey ? linkedComponents.get(compKey) : undefined; + + if (component) { + if (similarAlertIndex === -1) { + alerts.push({ + conditions: interaction.settings.conditions, + sourceComponents: [component], + }); + } else { + alerts[similarAlertIndex].sourceComponents.push(component); + } + } + + } + }); + setAlerts(alerts); + }).catch(err => { + console.error("Interaction fetch error:", err) + }).finally(() => { + setLoading(false) + }) + } + },[linkedComponents, interactionsAPI, componentDevices, as]) + + useEffect(()=>{ + load() + },[load]) + + + + return ( + + { + setNewAlert(false) + if(refresh){ + load() + } + }} + linkedComponents={linkedComponents} + componentDevices={componentDevices}/> + {loading ? + + : + {setNewAlert(true)}}/> + } + + ) +} \ No newline at end of file diff --git a/src/bin/binSummary/components/binAnalysisGraphs.tsx b/src/bin/binSummary/components/binAnalysisGraphs.tsx new file mode 100644 index 0000000..cfb4a12 --- /dev/null +++ b/src/bin/binSummary/components/binAnalysisGraphs.tsx @@ -0,0 +1,410 @@ +import { Avatar, Box, Button, CardHeader, Checkbox, FormControlLabel, Grid2, Theme, Tooltip, Typography } from "@mui/material"; +import { useMobile, useThemeType } from "hooks"; +import VPDDark from "assets/products/Ag/dryingDark.png"; +import VPDLight from "assets/products/Ag/dryingLight.png"; +import TrendLight from "assets/products/Ag/trendingLight.png"; +import TrendDark from "assets/products/Ag/trendingDark.png"; +import { useEffect, useState } from "react"; +import { makeStyles } from "@mui/styles"; +import moment, { Moment } from "moment"; +import { blue, orange, teal } from "@mui/material/colors"; +import { GrainDryingPoint } from "charts/GrainDryingChart"; +import { GrainCable } from "models/GrainCable"; +import { Plenum } from "models/Plenum"; +import BinGraphsVPD from "bin/graphs/BinGraphsVPD"; +import { UnitMeasurement } from "models/UnitMeasurement"; +import { Bin } from "models"; +import { useBinAPI, useGlobalState } from "providers"; +import TimeBar from "common/time/TimeBar"; +import { GetDefaultDateRange } from "common/time/DateRange"; +import { ZoomOut } from "@mui/icons-material"; +import BinGraphsTrending from "bin/graphs/BinGraphsTrending"; +import { DataPoint, TrendPoint } from "charts/TrendingChart"; +import WaterLight from "assets/products/Ag/waterContentLight.png"; +import WaterDark from "assets/products/Ag/waterContentDark.png"; +import { Pressure } from "models/Pressure"; +import { DataPoint as WaterPoint } from "charts/WaterLevelChart"; +import BinWaterLevel from "bin/graphs/BinWaterLevel"; +import { Controller } from "models/Controller"; +import { pond } from "protobuf-ts/pond"; + +interface Props { + cables: GrainCable[] + plenums: Plenum[] + componentDevices: Map + bin: Bin +} + +const useStyles = makeStyles((theme: Theme) =>{ + return ({ + root: { + display: "flex", + flexDirection: "column", + height: "100%", + overflow: "hidden", + }, + toolbar: { + flexShrink: 0, + }, + scrollContent: { + flex: 1, + minHeight: 0, + overflowY: "auto", + }, + card: { + position: "relative", + display: "flex", + height: "100%", + flexDirection: "column", + overflow: "visible" + }, + cardHeader: { + padding: theme.spacing(1), + paddingLeft: theme.spacing(2), + marginRight: 10 + }, + avatarIcon: { + width: 33, + height: 33 + } + }) + }); + +export default function BinAnalysisGraphs(props: Props){ + const {cables, plenums, componentDevices, bin} = props + const themeType = useThemeType() + const classes = useStyles() + const [{user, as, showErrors}, dispatch] = useGlobalState() + const isMobile = useMobile() + const [xDomain, setXDomain] = useState(["dataMin", "dataMax"]); + const [zoomed, setZoomed] = useState(false); + const [recentVPD, setRecentVPD] = useState(); + const [loading, setLoading] = useState(false) + // map using the component key and the unitmeasurements for that component + const [compMeasurements, setCompMeasurements] = useState>( + new Map() + ); + const binAPI = useBinAPI() + const defaultDateRange = GetDefaultDateRange() + const [startDate, setStartDate] = useState(defaultDateRange.start); + const [endDate, setEndDate] = useState(defaultDateRange.end); + const [recentPlenumTrend, setRecentPlenumTrend] = useState(); + const [recentCableTrend, setRecentCableTrend] = useState(); + const [recentWaterContent, setRecentWaterContent] = useState(); + + useEffect(() => { + let measurementMap: Map = new Map(); + if (!loading) { + setLoading(true); + //check if the bin has a fan to use the cfm in the drying graph + // if (bin.settings.fan?.type !== pond.FanType.FAN_TYPE_UNKNOWN) { + // setIncludeCFM(true); + // } + binAPI + .listBinComponentsMeasurements( + bin.key(), + startDate.toISOString(), + endDate.toISOString(), + showErrors, + showErrors, + as + ) + .then(resp => { + resp.data.measurements.forEach((um: any) => { + let unitMeasurement = UnitMeasurement.any(um, user); + let entry = measurementMap.get(unitMeasurement.componentId); + if (entry) { + entry.push(unitMeasurement); + } else { + measurementMap.set(unitMeasurement.componentId, [unitMeasurement]); + } + }); + setCompMeasurements(measurementMap); + setLoading(false); + }); + } + }, [bin, binAPI, startDate, endDate, user, as]); // eslint-disable-line react-hooks/exhaustive-deps + + const zoomOut = () => { + setXDomain(["dataMin", "dataMax"]); + setZoomed(false); + }; + + const zoomIn = (domain: string[] | number[]) => { + if (!isMobile) { + setXDomain(domain); + setZoomed(true); + } + }; + + const updateDateRange = (newStartDate: any, newEndDate: any) => { + let range = GetDefaultDateRange(); + range.start = newStartDate; + range.end = newEndDate; + setStartDate(newStartDate); + setEndDate(newEndDate); + }; + + //this uses the components found in the bins status + const waterGraph = () => { + let moistureCables: pond.GrainCable[] = []; + bin.status.grainCables.forEach(cable => { + if (cable.relativeHumidity.length > 0) { + moistureCables.push(cable); + } + }); + if (bin.status.plenums[0] && moistureCables[0] && bin.status.pressures[0] && bin.supportedGrain()) { + return ( + + 0 + ? componentDevices.get(bin.status.fans[0].key) + ":" + bin.status.fans[0].key + : undefined + } + newXDomain={xDomain} + multiGraphZoom={zoomIn} + multiGraphZoomOut + returnLast={lastWater => { + setRecentWaterContent(lastWater); + }} + /> + + ); + } else { + return ( + + + Plenum with pressure and moisture cable as well as an initial moisture and supported + grain type set in the bin settings required to calculate Water Content + + + ); + } + }; + + return ( + + + + + + + {zoomed && ( + + + + )} + { + //setShowErrors(!showErrors); + dispatch({ key: "showErrors", value: !showErrors }); + }} + /> + } + /> + + + + + } + title={ + + + + Drying vs. Hydrating + + + + } + subheader={ + recentVPD ? ( + + + + 0 ? orange[500] : blue[500] }}> + {recentVPD.dryScore > 0 ? "drying" : "hydrating"} + + {" : "} + 0 ? orange[500] : blue[500], + fontWeight: 500 + }}> + {recentVPD.dryScore.toFixed(2)} + +
+
+
+ + + {moment(recentVPD.timestamp).fromNow()} + + +
+ ) : ( + + No Data + + ) + } + /> + + {cables.length > 0 && plenums.length > 0 ? ( + { + setRecentVPD(lastVPD); + }} + /> + ) : ( + + + Plenum and moisture cable required to calculate VPD + + + )} + + + } + title={ + Moisture Trending + } + subheader={ + recentPlenumTrend && recentCableTrend ? ( + + + + {"Plenum Moisture: "} + + {recentPlenumTrend.trend.toFixed(2)} + +
+
+ + {"Grain Moisture: "} + + {recentCableTrend.moisture.toString()} + +
+
+
+ + + {recentPlenumTrend.timestamp > recentCableTrend.timestamp + ? moment(recentPlenumTrend.timestamp).fromNow() + : moment(recentCableTrend.timestamp).fromNow()} + + +
+ ) : ( + + No Data + + ) + } + /> + + {cables.length > 0 && plenums.length > 0 ? ( + { + setRecentCableTrend(lastData); + setRecentPlenumTrend(lastTrend); + }} + /> + ) : ( + + + Plenum and moisture cable required to calculate trending data + + + )} + + + } + title={ + Grain Water Content + } + subheader={ + recentWaterContent && + bin.settings.inventory && + bin.settings.inventory.initialMoisture > 0 ? ( + + + + {"Water Content: "} + + {recentWaterContent.liters && !isNaN(recentWaterContent.liters) + ? recentWaterContent.liters.toFixed(2) + : ""} + +
+
+
+ + + {moment(recentWaterContent.timestamp).fromNow()} + + +
+ ) : ( + + No Data + + ) + } + /> + + {waterGraph()} + +
+
+ ) +} \ No newline at end of file diff --git a/src/bin/binSummary/components/binControls.tsx b/src/bin/binSummary/components/binControls.tsx new file mode 100644 index 0000000..a1a4cde --- /dev/null +++ b/src/bin/binSummary/components/binControls.tsx @@ -0,0 +1,188 @@ +import { LinearProgress } from "@mui/material"; +import { Bin, Component, Device, Interaction } from "models"; +import Controls, { Control } from "objects/objectInteractions/Controls"; +import NewObjectInteraction from "objects/objectInteractions/NewObjectInteraction"; +import { sameComponentID } from "pbHelpers/Component"; +import { extension } from "pbHelpers/ComponentType"; +import { pond } from "protobuf-ts/pond"; +import { quack } from "protobuf-ts/quack"; +import { useGlobalState } from "providers"; +import interactionsAPI, { useInteractionsAPI } from "providers/pond/interactionsAPI"; +import React, { useCallback, useEffect, useState } from "react"; + +interface Props { + linkedComponents: Map; //the component key to the component object + componentDevices: Map; + devices: Device[]; + permissions: pond.Permission[] +} + +export default function BinControls(props: Props) { + const {linkedComponents, componentDevices, devices, permissions} = props + const [{as}] = useGlobalState() + const interactionsAPI = useInteractionsAPI() + const [controls, setControls] = useState([]); + const [selectedDevice, setSelectedDevice] = useState(undefined) + const [openNewInteraction, setOpenNewInteraction] = useState(false) + const [loading, setLoading] = useState(false) + + + const findDevice = (deviceID: number) => { + for (let device of devices) { + if (device.id() === deviceID) return device + } + } + const findSinkComponent = (sinks: Component[], interactionSink: quack.ComponentID, sourceDevice: number) => { + for (let component of sinks) { + if (sameComponentID(component.location(), interactionSink) && sourceDevice === componentDevices.get(component.key())){ + return component + } + } + } + + const matchConditions = (interaction: Interaction, set: Control) => { + //if the number of conditions are not the same they are different + if (interaction.settings.conditions.length !== set.conditions.length) { + return false; + } + //continue with the comparison + let matching = true; + interaction.settings.conditions.forEach((condition, i) => { + if ( + condition.comparison !== set.conditions[i].comparison || + condition.measurementType !== set.conditions[i].measurementType || + condition.value !== set.conditions[i].value + ) { + matching = false; + } + }); + return matching; + }; + + const matchResult = (interaction: Interaction, set: Control) => { + let interactionResult = interaction.settings.result + let setResult = set.result + let matching = true + // if anything in the result for the interaction is different from the set make matching false + if(interactionResult?.type !== setResult?.type || + interactionResult?.mode !== setResult?.mode || + interactionResult?.value !== setResult?.value || + interactionResult?.dutyCycle !== setResult?.dutyCycle + ){ + matching = false + } + return matching + } + const load = useCallback(()=>{ + if(!loading){ + setLoading(true) + const newInteractions: Interaction[] = []; + const interactionSourceMap = new Map(); + const sinkOptions: Component[] = []; + const controls: Control[] = []; + + const run = async () => { + // Run all component API fetches in parallel + await Promise.all( + [...linkedComponents].map(async ([key, comp]) => { + const device = componentDevices.get(key); + + if (device) { + const resp = await interactionsAPI.listInteractionsByComponent( + device, + comp.location(), + undefined, + as + ); + + resp.forEach(interaction => interactionSourceMap.set(interaction.key(), key)); + newInteractions.push(...resp); + } + + // Collect controller components + if (extension(comp.type()).isController) { + sinkOptions.push(comp); + } + }) + ); + }; + + run().then(() => { + newInteractions.forEach(interaction => { + if (interaction.isControl()) { + if (!interaction.settings.sink) return //if there is no sink it cant be a control so move on to the next + const compKey = interactionSourceMap.get(interaction.key()); + if (!compKey) return //we have to have a valid component key + const component = linkedComponents.get(compKey); + const deviceID = componentDevices.get(compKey); + if (!deviceID) return //we have to know which device it is for + const controlDevice = findDevice(deviceID) + if (!controlDevice) return //failed to get the device from the array + const sinkComponent = findSinkComponent(sinkOptions, interaction.settings.sink, deviceID) + if (!sinkComponent) return //failed to get the correct sink component + + let similarControlIndex = controls.findIndex(control => + matchConditions(interaction, control) && + matchResult(interaction, control) && + sameComponentID(interaction.settings.sink, control.sinkComponent.location()) && //if the sink for the interaction is the same address as the existing control + deviceID === control.device.id() //if the device id for source component is the same as the device id in the control + ); + + if (component && interaction.settings.result) { + if (similarControlIndex === -1) { + controls.push({ + conditions: interaction.settings.conditions, + result: interaction.settings.result, + sourceComponents: [component], + sinkComponent: sinkComponent, + device: controlDevice + }); + } else { + controls[similarControlIndex].sourceComponents.push(component); + } + } + } + }); + setControls(controls); + }).catch(err => { + console.error("Interaction fetch error:", err) + }).finally(() => { + setLoading(false) + }) + } + },[linkedComponents, interactionsAPI, componentDevices, as]) + + useEffect(() => { + load() + }, [load]); + + return ( + + { + setOpenNewInteraction(false) + if(refresh){ + load() + } + }} + linkedComponents={linkedComponents} + componentDevices={componentDevices} + device={selectedDevice}/> + {loading ? + + : + { + console.log("new control") + setSelectedDevice(device) + setOpenNewInteraction(true) + }} + /> + } + + ) +} \ No newline at end of file diff --git a/src/bin/binSummary/components/binDetails.tsx b/src/bin/binSummary/components/binDetails.tsx new file mode 100644 index 0000000..c4acfca --- /dev/null +++ b/src/bin/binSummary/components/binDetails.tsx @@ -0,0 +1,130 @@ +import { Box, Tab, Tabs } from "@mui/material"; +import React from "react"; +import { useState } from "react"; +import BinTableView from "../../binTableView"; +import { Bin, Component, Device } from "models"; +import Alerts from "objects/objectInteractions/Alerts"; +import BinAlerts from "./binAlerts"; +import { pond } from "protobuf-ts/pond"; +import BinControls from "./binControls"; +import BinAnalysisGraphs from "./binAnalysisGraphs"; +import { GrainCable } from "models/GrainCable"; +import { Plenum } from "models/Plenum"; +import { Controller } from "models/Controller"; +import { useMobile } from "hooks"; +import Bin3dVisualizer from "bin/bin3dVisualizer"; +import BinPlayer from "bin/BinPlayer"; + +interface Props { + bin: Bin + updateBinCallback?: (bin: Bin) => void + linkedComponents: Map; //the component key to the component object + componentDevices: Map; + devices: Device[]; + permissions: pond.Permission[] + cables: GrainCable[] + plenums: Plenum[] + showBinTab?: boolean + fans?: Controller[] + heaters?: Controller[] + componentMap: Map + binPrefs?: Map + setBin?: React.Dispatch>; +} + +interface TabPanelProps { + children?: React.ReactNode; + index: any; + value: any; +} + +function TabPanelMine(props: TabPanelProps) { + const { children, value, index, ...other } = props; + + return ( + + ); + } + +export default function BinDetails (props: Props) { + const {bin, updateBinCallback, linkedComponents, componentDevices, devices, permissions, cables, plenums, showBinTab, fans, heaters, componentMap, binPrefs, setBin} = props + const isMobile = useMobile() + const [currentTab, setCurrentTab] = useState((isMobile || showBinTab) ? "bin" : "table") + + //this is where we will have the tabs and tab panels for the table view, alerts, controls, and analysis + + return ( + + setCurrentTab(value)} + indicatorColor="primary" + textColor="primary" + variant={isMobile ? "scrollable" : "fullWidth"} + scrollButtons="auto" + allowScrollButtonsMobile + sx={{ + flexShrink: 0, + '& .MuiTabs-scroller': { + overflowX: 'auto !important', + } + }}> + {isMobile && } + + + + + + + {(isMobile || showBinTab) && + + + {setBin && + + + + } + + } + + + {setBin && isMobile && + + + + } + + + + + + + + + + + + + ) +} \ No newline at end of file diff --git a/src/bin/binSummary/components/nodeControls.tsx b/src/bin/binSummary/components/nodeControls.tsx new file mode 100644 index 0000000..2a8966a --- /dev/null +++ b/src/bin/binSummary/components/nodeControls.tsx @@ -0,0 +1,406 @@ +import { AppBar, Box, Button, Card, CardActionArea, Checkbox, DialogActions, DialogContent, DialogTitle, FormControlLabel, Grid2, IconButton, Typography } from "@mui/material"; +import { green } from "@mui/material/colors"; +import { makeStyles } from "@mui/styles"; +import { CableData } from "bin/3dView/Data/BuildCableData"; +import { NodeData } from "bin/3dView/Data/BuildNodeData"; +import ResponsiveDialog from "common/ResponsiveDialog"; +import HumidityIcon from "component/HumidityIcon"; +import TemperatureIcon from "component/TemperatureIcon"; +import { useComponentAPI, useMobile, useSnackbar } from "hooks"; +import InteractionsOverview from "interactions/InteractionsOverview"; +import { Bin, Component, Device, Interaction } from "models"; +import moment from "moment"; +import AddIcon from "@mui/icons-material/AddCircle"; +import GraphIcon from "products/CommonIcons/graphIcon"; +import { pond } from "protobuf-ts/pond"; +import { useBinAPI, useGlobalState, useInteractionsAPI } from "providers"; +import React from "react"; +import { useEffect, useState } from "react"; +import { useNavigate } from "react-router-dom"; +import { canWrite } from "pbHelpers/Permission"; +import InteractionSettings from "interactions/InteractionSettings"; + +const useStyles = makeStyles(() => { + return ({ + dialog: { + maxWidth: 350 + }, + appBar: { + position: "static", + borderRadius: 30 + }, + readingCard: { + padding: 10 + }, + greenButton: { + color: green["600"], + padding: 0 + } + }); + }); + +interface Props { + open: boolean + onClose: () => void + node: NodeData + cable: CableData + device: Device + bin: Bin + /** + * the possible options for controllers when creating new interactions, these controllers must be on the same device as the cable for interactions to work + */ + filteredComponents?: Component[] + componentMap: Map + permissions: pond.Permission[] + /** + * callback function for updating the cable with a new top node or excluded node + * @returns void + */ + updateComponentCallback?: () => void +} + +export default function NodeControls(props: Props){ + const {open, onClose, node, cable, device, bin, filteredComponents, permissions, updateComponentCallback, componentMap} = props + const classes = useStyles() + const [isTopNode, setIsTopNode] = useState(false) + const [isExcluded, setIsExcluded] = useState(false) + const [cableComponent, setCableComponent] = useState(Component.create()) + const [cableInteractions, setCableInteractions] = useState([]) + const isMobile = useMobile() + const navigate = useNavigate() + const [{as, user}] = useGlobalState() + const interactionAPI = useInteractionsAPI() + const binAPI = useBinAPI() + const componentAPI = useComponentAPI() + const {openSnack} = useSnackbar() + const [newInteraction, setNewInteraction] = useState(false); + + //will need to list the interactions for the cable + useEffect(() => { + let component = componentMap.get(cable.grainCable.key) ?? Component.create() + setCableComponent(component) + interactionAPI.listInteractionsByComponent(device.id(), cableComponent.location(), undefined, as).then(resp => { + setCableInteractions(resp); + }); + },[cable, device, interactionAPI]) + + //determine if the node is excluded/the top node + useEffect(()=>{ + if(node.topNode !== undefined){ + setIsTopNode(node.topNode) + } + if(cable.grainCable.excludedNodes.includes(node.nodeIndex)){ + setIsExcluded(true) + }else( + setIsExcluded(false) + ) + },[node, cable]) + + //navigation function to go to the component page + const goToComponent = () => { + navigate("/devices/" + device.id() + "/components/" + cable.grainCable.key); + } + + const close = ()=>{ + onClose() + } + + const setEMC = () => { + let settings = cableComponent.settings; + //make sure the mutation is not there first + if(!settings.defaultMutations.includes(pond.Mutator.MUTATOR_EMC)){ + settings.defaultMutations.push(pond.Mutator.MUTATOR_EMC) + } + settings.grainType = bin.grain(); + settings.customGrain = bin.customGrain(); + componentAPI + .update(device.id(), settings, [bin.key()], ["bin"], as) + .then(resp => { + openSnack("EMC set on cable " + cableComponent.name()); + }) + .catch(err => {}); + } + + const submit = () => { + //should update the component and then update the bin prefs if successful + componentAPI.update(device.id(), cableComponent.settings).then(resp => { + let pref = pond.BinComponentPreferences.create({ + type: pond.BinComponent.BIN_COMPONENT_GRAIN_CABLE, + node: cableComponent.settings.grainFilledTo + }); + //update the bins preferences to have the new top node for the cable + binAPI + .updateComponentPreferences(bin.key(), cableComponent.key(), pref, as) + .then(resp => { + openSnack("Changes will be reflected once the bins status updates") + if(updateComponentCallback){ + updateComponentCallback() + } + }) + .catch(err => {}); + }).catch(err => { + + }) + close() + } + + const updateTopNode = (checked: boolean) => { + if (isTopNode && !checked) { + cableComponent.settings.grainFilledTo = 0; + cableInteractions.forEach(interaction => { + interaction.settings.subtype = 0; + interaction.settings.nodeOne = 0; + interaction.settings.nodeTwo = 0; + }); + } else if (checked) { + cableComponent.settings.grainFilledTo = node.nodeIndex+1; + cableInteractions.forEach(interaction => { + interaction.settings.subtype = Interaction.upToSubtype(node.nodeIndex+1); + interaction.settings.nodeOne = node.nodeIndex+1; + }); + } + setIsTopNode(checked); + } + + const updateNodeExclusion = (checked: boolean) => { + if (checked) { + cableComponent.settings.excludedNodes.push(node.nodeIndex) + } else { + cableComponent.settings.excludedNodes.splice(cableComponent.settings.excludedNodes.indexOf(node.nodeIndex), 1) + } + setIsExcluded(checked) + } + + const displayTemp = () => { + let isF = user.settings.temperatureUnit === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT + let tempFinal = node.celcius ?? 0; + if (isF) { + tempFinal = (tempFinal * 1.8 + 32); + } + return tempFinal.toFixed(2) + (isF ? " F" : "C"); + }; + + const latestReading = () => { + return ( + + Latest Reading + {moment(cable.grainCable.lastRead).fromNow()} + + + + + + + {displayTemp()} + + + + Temperature + + + + + + + + + {node.humidity} % + + + + Humidity + + + + + {/* only show the emc if the bin grain type and the cable grain type match */} + {node.moisture ? ( + + + + + {node.moisture} % + + + + Grain EMC + + + ) : ( + + { + setEMC(); + }}> + + + + + Set EMC + + + + )} + + + + goToComponent()}> + + + + + See Graphs + + + + + + + ); + }; + + const nodeControl = () => { + return ( + + Node Control + { + updateNodeExclusion(e.target.checked); + }} + name="excludedNode" + /> + } + label={ + + + Exclude Node + + + If checked this will set the node to be disabled and will not be used for any calculations done for the bin + + + } + /> + { + updateTopNode(e.target.checked); + }} + name="topNode" + /> + } + label={ + + + Set as top node in grain + + + If checked this will set interactions to ignore all nodes above it. Interactions can + still be adjusted manually to use all nodes + + + } + /> + + ); + }; + + const interactionDisplay = () => { + return ( + + Interactions + + { + interactionAPI + .listInteractionsByComponent(device.id(), cableComponent.location(), undefined, as) + .then(resp => { + setCableInteractions(resp); + }); + }} + /> + + + { + setNewInteraction(true); + }} + className={classes.greenButton}> + + + + + ); + }; + + return ( + + + + + {cable.grainCable.name} + + + + + Node {node.nodeIndex+1} + + + + + + {latestReading()} + {nodeControl()} + {interactionDisplay()} + {/* + */} + + + + + + + { + setNewInteraction(false); + }} + refreshCallback={() => { + interactionAPI.listInteractionsByComponent(device.id(), cableComponent.location(), undefined, as).then(resp => { + setCableInteractions(resp); + }); + }} + canEdit={canWrite(permissions)} + /> + + ) +} \ No newline at end of file diff --git a/src/bin/binTableView.tsx b/src/bin/binTableView.tsx new file mode 100644 index 0000000..0659335 --- /dev/null +++ b/src/bin/binTableView.tsx @@ -0,0 +1,466 @@ +import { Edit, GppGood, Info, Save } from "@mui/icons-material"; +import { Box, Button, darken, DialogActions, IconButton, Table, TableBody, TableCell, TableHead, TableRow, TextField, Theme, Tooltip, Typography, useTheme } from "@mui/material"; +import { green, grey, orange, red, yellow } from "@mui/material/colors"; +import { makeStyles } from "@mui/styles"; +import ResponsiveDialog from "common/ResponsiveDialog"; +import HumidityIcon from "component/HumidityIcon"; +import TemperatureIcon from "component/TemperatureIcon"; +import { cloneDeep } from "lodash"; +import { Bin } from "models"; +import { pond } from "protobuf-ts/pond"; +import { useGlobalState } from "providers"; +import React, { useEffect, useRef, useState } from "react"; +import { useMemo } from "react"; +import { avg, celsiusToFahrenheit } from "utils"; +import BinTableExpanded from "./BinTableExpanded"; +import { useMobile } from "hooks"; + +const useStyles = makeStyles((theme: Theme) => ({ + tableStyle: { + borderCollapse: "separate", + borderSpacing: 0, // removes the default gap that "separate" introduces + }, + headerCellStyle: { + fontWeight: 650, + backgroundColor: darken(theme.palette.background.paper, 0.3), + textAlign: "center", + padding: 10 + }, + mobileHeaderCellStyle: { + fontWeight: 650, + backgroundColor: darken(theme.palette.background.paper, 0.3), + textAlign: "center", + padding: 2 + }, + targetCellStyle: { + textAlign: "center", + backgroundColor: theme.palette.background.paper + }, + mobileTargetCellStyle: { + textAlign: "center", + backgroundColor: theme.palette.background.paper, + padding: 2 + }, + defaultCellStyle: { + padding: 2, + fontSize: 15, + textAlign: "center", + backgroundColor: darken(theme.palette.background.paper, 0.1), + borderTop: "1px solid " + darken(theme.palette.background.paper, 0.4), + borderBottom: "none" + }, + colouredCellStyle: { + padding: 2, + borderTop: "1px solid " + darken(theme.palette.background.paper, 0.4), + // fontWeight: 650, + fontSize: 15, + textAlign: "center", + borderBottom: "none" + } + }) +); + +interface Props { + bin: Bin + updateBinCallback?: (bin: Bin) => void +} + +interface BinLevel { + grainTemps: number[] + airTemps: number[] + grainMoistures: number[] + airMoistures: number[] +} + + +export default function BinTableView(props: Props) { + const classes = useStyles() + const {bin, updateBinCallback} = props + const [{user}] = useGlobalState() + const theme = useTheme() + const [enterTemp, setEnterTemp] = useState(false) + const [enterMoisture, setEnterMoisture] = useState(false) + const [tempTarget, setTempTarget] = useState(0) + const [tempEntry, setTempEntry] = useState("") + const [moistureEntry, setMoistureEntry] = useState("") + const [moistureTarget, setMoistureTarget] = useState(0) + const [openExpandedCables, setOpenExpandedCables] = useState(false) + const isMobile = useMobile() + const inBounds = green[600] + const caution = yellow[800] + const warning = red[700] + const headerRow1Ref = useRef(null) + const [firstRowHeight, setFirstRowHeight] = useState(0) + + useEffect(() => { + if (headerRow1Ref.current) { + setFirstRowHeight(headerRow1Ref.current.getBoundingClientRect().height) + } + }, [enterTemp, enterMoisture]) // re-measure when the row height might change due to TextField appearing + + useEffect(()=>{ + let val = bin.targetTemp() + if(user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT){ + val = bin.targetTemp() * (9/5) + 32 + } + setTempTarget(val) + setTempEntry(val.toFixed(2)) + setMoistureTarget(bin.targetMoisture()) + setMoistureEntry(bin.targetMoisture().toFixed(2)) + },[bin]) + + const binLevels = useMemo(() => { + const cables = bin.status.grainCables + let levels: BinLevel[] = [] + //note for future self, the first item in the measurement arrays is the lowest node on the cable + //the zones we are creating here will match with the node number because most cables will either have the same number of nodes or only have a difference of 1 or 2 + //example: cable 1 has 5 nodes cable 2 has 7 nodes, the first five nodes of the cables will match up and average together for each zone + //and then zones 6 and 7 will be made using only cable 2 because cable 1 doesn't have them + cables.forEach(cable => { + cable.celcius.forEach((c, index) => { + //remember index will be 0 based but the top node starts at 1 for the lowest cable + let inGrain = index < cable.topNode + if (levels[index]){ + if(cable.excludedNodes.includes(index+1)) return + if(inGrain){ + levels[index].grainTemps.push(c) + //need to check that the cable not only has the moisture mutation on it, but also that it reads humidity + //cables that dont read humidity return an array of 0 values so if the average of all of the values is 0 then it is a temp only cable + if(cable.moisture.length > 0 && avg(cable.moisture) > 0){ + //based on all the other checks and the fact that the indexes between the array should match this should never be 0 but put a guard here just in case + //also note that we are only doing moisture and not humidity, it seems like users dont care about humidity + levels[index].grainMoistures.push(cable.moisture[index] ?? 0) + } + }else{ + levels[index].airTemps.push(c) + //need to check that the cable not only has the moisture mutation on it, but also that it reads humidity + //cables that dont read humidity return an array of 0 values so if the average of all of the values is 0 then it is a temp only cable + if(cable.moisture.length > 0 && avg(cable.moisture) > 0){ + //based on all the other checks and the fact that the indexes between the array should match this should never be 0 but put a guard here just in case + levels[index].airMoistures.push(cable.moisture[index] ?? 0) + } + } + }else{ + let newlevel: BinLevel = { + grainTemps: [], + grainMoistures: [], + airTemps: [], + airMoistures: [] + } + if(!cable.excludedNodes.includes(index)){ + if(inGrain){ + newlevel.grainTemps.push(c) + if(cable.moisture.length > 0 && avg(cable.moisture) > 0){ + newlevel.grainMoistures.push(cable.moisture[index] ?? 0) + } + }else{ + newlevel.airTemps.push(c) + if(cable.moisture.length > 0 && avg(cable.moisture) > 0){ + newlevel.airMoistures.push(cable.moisture[index] ?? 0) + } + } + } + levels.push(newlevel) + } + + }) + }) + //flip the levels so that the highest nodes are on the top + levels.reverse() + return levels + },[bin]) + + const levelDisplay = (level: BinLevel, lastRow?: boolean) => { + let tempDisplay = "--" + let moistureDisplay = "--" + let lvlTemp + let lvlMoisture + let tempColour: string = darken(theme.palette.background.paper, 0.1) + let moistureColour: string = darken(theme.palette.background.paper, 0.1) + + //determine the temp + if(level.grainTemps.length > 0){ + lvlTemp = avg(level.grainTemps) + //if the average temp is 5 degrees above the bins threshold + if(lvlTemp > (bin.targetTemp() + 10)){ + tempColour = warning + }else if(lvlTemp > bin.targetTemp() + 5){ + //if the average temp is greater than 5 degrees over + tempColour = caution + }else { + tempColour = inBounds + } + }else if (level.airTemps.length > 0){ + lvlTemp = avg(level.airTemps) + } + if (lvlTemp){ + if(user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT){ + lvlTemp = celsiusToFahrenheit(lvlTemp) + } + tempDisplay = lvlTemp.toFixed(2) + } + + //determine the moisture to show + if(level.grainMoistures.length > 0){ + lvlMoisture = avg(level.grainMoistures) + if(lvlMoisture > (bin.targetMoisture() + 1.5)){ + moistureColour = warning + }else if(lvlMoisture > bin.targetMoisture() + 0.5){ + moistureColour = caution + }else { + moistureColour = inBounds + } + }else if (level.airMoistures.length > 0){ + lvlMoisture = avg(level.airMoistures) + } + if(lvlMoisture){ + moistureDisplay = lvlMoisture.toFixed(2) + } + return ( + + {tempDisplay} + {moistureDisplay} + + ) + } + + const update = () => { + let temp = tempTarget + if(user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT){ + //convert to c + temp = (temp - 32) * (5 / 9); + + } + let clone = cloneDeep(bin) + if(clone.settings.inventory && updateBinCallback){ + clone.settings.inventory.targetTemperature = temp + clone.settings.inventory.targetMoisture = moistureTarget + updateBinCallback(clone) + } + } + + const tempThreshDisplay = (hideUnit?: boolean) => { + if(user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT){ + return tempTarget.toFixed(2) + (hideUnit ? "" : " °F") + } + return tempTarget.toFixed(2) + (hideUnit ? "" : " °C") + } + + const LegendSwatch = ({ color }: { color: string }) => ( + + ) + + + const updateTempEntry = () => { + return ( + { + let val = parseFloat(e.target.value) + if(!isNaN(val)){ + setTempTarget(val) + } + setTempEntry(e.target.value) + }} + /> + ) + } + + const updateMoistureEntry = () => { + return ( + { + let val = parseFloat(e.target.value) + if(!isNaN(val)){ + setMoistureTarget(val) + } + setMoistureEntry(e.target.value) + }} + /> + ) + } + + const expandedTableDialog = () => { + return ( + {setOpenExpandedCables(false)}}> + + + + + + ) + } + + + + return ( + + {expandedTableDialog()} + {/* Level Table */} + + Grain Table + + + + + + + + + {/* this box is to make the whole table scrollable */} + + + + + {/* "Targets" cell — hide on mobile when either field is being edited */} + {!(isMobile && (enterTemp || enterMoisture)) && ( + + + + {!isMobile && + + Targets + + } + + + )} + + {/* Temperature cell */} + {!(isMobile && enterMoisture) && ( + + + + {enterTemp ? updateTempEntry() : ( + + {tempThreshDisplay(isMobile)} + + )} + {enterTemp ? ( + { setEnterTemp(false); update(); }}> + + + ) : ( + setEnterTemp(true)}> + + + )} + + + )} + {/* Moisture cell — hide on mobile when temperature is being edited */} + {!(isMobile && enterTemp) && ( + + + + {enterMoisture ? updateMoistureEntry() : ( + + {bin.targetMoisture()} + + )} + {enterMoisture ? ( + { setEnterMoisture(false); update(); }}> + + + ) : ( + setEnterMoisture(true)}> + + + )} + + + )} + + + + Level + + + {isMobile ? "T" : "Temperature"}{(user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT ? " (°F)" : " (°C)")} + + + EMC (%) + + + + + + {binLevels.map((level, i) => ( + + {binLevels.length - i} + {levelDisplay(level, i === binLevels.length-1)} + + ))} + +
+
+ {/* Table Legend */} + + + + On target + + + + {user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT ? "~10 °F" : "+5 °C"} (0.5%) above + + + + {user.tempUnit() === pond.TemperatureUnit.TEMPERATURE_UNIT_FAHRENHEIT ? "~20 °F" : "+10 °C"} (1.5%) above + + +
+ ) +} \ No newline at end of file diff --git a/src/bin/graphs/BinGraphsVPD.tsx b/src/bin/graphs/BinGraphsVPD.tsx index 037bf2d..f4fe68c 100644 --- a/src/bin/graphs/BinGraphsVPD.tsx +++ b/src/bin/graphs/BinGraphsVPD.tsx @@ -4,6 +4,7 @@ import { GrainCable } from "models/GrainCable"; import { Plenum } from "models/Plenum"; import { UnitMeasurement } from "models/UnitMeasurement"; import moment from "moment"; +import { pond } from "protobuf-ts/pond"; import { quack } from "protobuf-ts/quack"; import React, { useEffect, useState } from "react"; import { avg } from "utils"; diff --git a/src/bin/graphs/BinSensorGraph.tsx b/src/bin/graphs/BinSensorGraph.tsx new file mode 100644 index 0000000..443e49e --- /dev/null +++ b/src/bin/graphs/BinSensorGraph.tsx @@ -0,0 +1,292 @@ +import { Avatar, Box, Card, CircularProgress, IconButton, Paper, Typography, useTheme } from "@mui/material"; +import moment, { Moment } from "moment"; +import { Component } from "models"; +import { useComponentAPI, useGlobalState } from "providers"; +import { useEffect, useMemo, useState } from "react"; +import { UnitMeasurement } from "models/UnitMeasurement"; +import { quack } from "protobuf-ts/quack"; +import { + Legend, + Line, + LineChart, + ResponsiveContainer, + Tooltip, + TooltipProps, + XAxis, + YAxis +} from "recharts"; +import { avg, roundTo } from "utils"; +import { MoreVert } from "@mui/icons-material"; + +interface Props { + device: number; + icon?: string; + title?: string; + tag?: string; + onMenuClick?: (event: React.MouseEvent) => void; + component: Component; + startDate: Moment; + endDate: Moment; + customHeight?: string | number; + /** + * this will cause all of the readings for a cable to be used in the average, + * by default it will filter any excluded nodes and only use nodes below the top node + */ + allNodes?: boolean +} + +/** Grain-cable nodes to include when averaging (matches GrainCable.filter indexing). */ +function valuesForAveraging( + nodeValues: number[], + component: Component, + allNodes?: boolean +): number[] { + if (allNodes) { + return nodeValues.filter(v => !isNaN(v)); + } + + const grainFilledTo = component.settings.grainFilledTo ?? 0; + const excludedNodes = component.settings.excludedNodes ?? []; + const included: number[] = []; + + nodeValues.forEach((v, index) => { + if (isNaN(v)) { + return; + } + if (excludedNodes.includes(index)) { + return; + } + if (grainFilledTo > 0 && index >= grainFilledTo) { + return; + } + included.push(v); + }); + + return included; +} + +interface MeasurementMeta { + value: number; + unit: string; + label: string; +} + +interface ChartPoint { + timestamp: number; + _meta: Record; + [seriesKey: string]: number | Record | undefined; +} + +interface SeriesInfo { + key: string; + colour: string; + unit: string; + label: string; +} + +function normalizeValue(value: number, min: number, max: number): number { + if (max === min) { + return 50; + } + return ((value - min) / (max - min)) * 100; +} + +function buildChartData( + measurements: UnitMeasurement[], + component: Component, + allNodes?: boolean +): { + data: ChartPoint[]; + series: SeriesInfo[]; +} { + const rawSeries = measurements + .filter(um => um.timestamps.length > 0 && um.values.length > 0) + .map(um => { + const points: { timestamp: number; value: number }[] = []; + um.values.forEach((valArray, i) => { + if (valArray.error || !um.timestamps[i]) { + return; + } + const nodeValues = valuesForAveraging(valArray.values, component, allNodes); + if (nodeValues.length === 0) { + return; + } + points.push({ + timestamp: moment(um.timestamps[i]).valueOf(), + value: avg(nodeValues) + }); + }); + const actualValues = points.map(p => p.value); + const min = actualValues.length > 0 ? Math.min(...actualValues) : 0; + const max = actualValues.length > 0 ? Math.max(...actualValues) : 100; + return { um, points, min, max, key: um.label }; + }) + .filter(s => s.points.length > 0); + + const timestampMap = new Map(); + rawSeries.forEach(({ um, points, min, max, key }) => { + points.forEach(({ timestamp, value }) => { + let point = timestampMap.get(timestamp); + if (!point) { + point = { timestamp, _meta: {} }; + timestampMap.set(timestamp, point); + } + point[key] = normalizeValue(value, min, max); + point._meta[key] = { value, unit: um.unit, label: um.label }; + }); + }); + + const data = Array.from(timestampMap.values()).sort((a, b) => a.timestamp - b.timestamp); + const series = rawSeries.map(({ um, key }) => ({ + key, + colour: um.colour, + unit: um.unit, + label: um.label + })); + + return { data, series }; +} + +function SensorGraphTooltip(props: TooltipProps) { + const { active, label, payload } = props; + if (!active || !payload?.length) { + return null; + } + + return ( + + + {payload.map(p => { + const dataKey = String(p.dataKey); + const meta = (p.payload as ChartPoint)._meta?.[dataKey]; + return ( + + {meta?.label ?? dataKey} + {": "} + + {meta ? `${roundTo(meta.value, 2)} ${meta.unit}` : p.value} + + + ); + })} + + {moment(label).format("lll")} + + + + ); +} + +export default function BinSensorGraph(props: Props) { + const { device, icon, title, tag, component, startDate, endDate, customHeight = 350, onMenuClick, allNodes } = props; + const [measurements, setMeasurements] = useState([]); + const [loading, setLoading] = useState(false); + const componentAPI = useComponentAPI(); + const [{ user }] = useGlobalState(); + const theme = useTheme(); + const now = moment(); + + useEffect(() => { + setLoading(true); + componentAPI + .sampleUnitMeasurements(device, component.key(), startDate, endDate, 1000, undefined, undefined, undefined, undefined, true) + .then(res => { + setMeasurements(res.data.measurements.map(um => UnitMeasurement.any(um, user))); + }) + .catch(() => { + setMeasurements([]); + }) + .finally(() => { + setLoading(false); + }); + }, [device, component, startDate, endDate, componentAPI, user]); + + const { data, series } = useMemo( + () => buildChartData(measurements, component, allNodes), + [measurements, component, allNodes] + ); + + return ( + + + + {icon && + + } + {title} + {tag && - {tag}} + + {onMenuClick && + + + + } + + + {loading ? ( + + + + ) : data.length === 0 || series.length === 0 ? ( + + No measurement data + + ) : ( + + + { + const t = moment(timestamp); + return now.isSame(t, "day") ? t.format("LT") : t.format("MMM DD"); + }} + scale="time" + type="number" + tick={{ fill: theme.palette.text.primary }} + stroke={theme.palette.divider} + interval="preserveStartEnd" + /> + {/* */} + + + {series.map(s => ( + + ))} + + + )} + + + ); +} diff --git a/src/grain/ChangeGrainDialog.tsx b/src/grain/ChangeGrainDialog.tsx new file mode 100644 index 0000000..2910b25 --- /dev/null +++ b/src/grain/ChangeGrainDialog.tsx @@ -0,0 +1,175 @@ +import { Box, Button, DialogActions, DialogContent, DialogTitle, Grid2, Switch, TextField } from "@mui/material"; +import ResponsiveDialog from "common/ResponsiveDialog"; +import SearchSelect, { Option } from "common/SearchSelect"; +import { Bin } from "models"; +import { pond } from "protobuf-ts/pond"; +import GrainDescriber, { GrainOptions, ToGrainOption } from "grain/GrainDescriber"; +import { useEffect, useMemo, useState } from "react"; +import React from "react"; +import CustomGrainSelector from "./CustomGrainSelector"; +import { cloneDeep } from "lodash"; +import { useBinAPI, useSnackbar } from "providers"; + +interface Props { + bin: Bin + open: boolean + closeDialog: () => void + permissions: pond.Permission[] + /** + * this function can be passed in if you want to just return a new bin with the changes and handle the actual update in the parent, + * it will stop the component from doing the update itself + * @param bin the bin with the new changes + * @returns + */ + updateBin?: (bin: Bin) => void + /** + * this function can be passed in as a callback function if the component handles the update + * @param updated whether the bin api was used to update the bin + * @returns + */ + updateCallback?: (bin: Bin) => void +} + +export default function ChangeGrainDialog(props: Props){ + const { bin, open, permissions, closeDialog, updateBin, updateCallback } = props + const canEdit = useMemo(()=>{ + return permissions ? permissions.includes(pond.Permission.PERMISSION_WRITE) : false; + },[permissions]) + + const [isCustom, setIsCustom] = useState(false) + const grainOptions = GrainOptions(); + const [grainOption, setGrainOption] = useState