Spaces:
Running on Zero

Shenhan commited on
Commit
a863b67
·
verified ·
1 Parent(s): 58f596e

Flow4RT demo

Browse files
Files changed (45) hide show
  1. .gitattributes +10 -0
  2. LICENSE +11 -0
  3. NOTICE +110 -0
  4. README.md +16 -4
  5. __pycache__/app.cpython-311.pyc +0 -0
  6. __pycache__/visualize.cpython-311.pyc +0 -0
  7. app.py +277 -0
  8. examples/CREDITS.md +17 -0
  9. examples/bmx_bowl.mp4 +3 -0
  10. examples/car_turn.mp4 +3 -0
  11. examples/forest_car.mp4 +3 -0
  12. examples/horsejump_high.mp4 +3 -0
  13. examples/kite_surf.mp4 +3 -0
  14. examples/parkour.mp4 +3 -0
  15. examples/rollerblade.mp4 +3 -0
  16. examples/soapbox.mp4 +3 -0
  17. examples/swing.mp4 +3 -0
  18. examples/toy_car.mp4 +3 -0
  19. flow4rt/__init__.py +3 -0
  20. flow4rt/__pycache__/__init__.cpython-311.pyc +0 -0
  21. flow4rt/__pycache__/inference.cpython-311.pyc +0 -0
  22. flow4rt/inference.py +130 -0
  23. flow4rt/model/__init__.py +3 -0
  24. flow4rt/model/__pycache__/__init__.cpython-311.pyc +0 -0
  25. flow4rt/model/__pycache__/dpt_head.cpython-311.pyc +0 -0
  26. flow4rt/model/__pycache__/flow4rt.cpython-311.pyc +0 -0
  27. flow4rt/model/__pycache__/geometry.cpython-311.pyc +0 -0
  28. flow4rt/model/__pycache__/geometry_blocks.cpython-311.pyc +0 -0
  29. flow4rt/model/__pycache__/layers.cpython-311.pyc +0 -0
  30. flow4rt/model/__pycache__/motion_blocks.cpython-311.pyc +0 -0
  31. flow4rt/model/dpt_head.py +184 -0
  32. flow4rt/model/flow4rt.py +107 -0
  33. flow4rt/model/geometry.py +66 -0
  34. flow4rt/model/geometry_blocks.py +145 -0
  35. flow4rt/model/layers.py +245 -0
  36. flow4rt/model/motion_blocks.py +66 -0
  37. requirements.txt +8 -0
  38. viewer/template.html +134 -0
  39. viewer/vendor/LineMaterial.js +640 -0
  40. viewer/vendor/LineSegments2.js +318 -0
  41. viewer/vendor/LineSegmentsGeometry.js +203 -0
  42. viewer/vendor/OrbitControls.js +1106 -0
  43. viewer/vendor/three.min.js +0 -0
  44. viewer/viewer.js +379 -0
  45. visualize.py +250 -0
.gitattributes CHANGED
@@ -33,3 +33,13 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/bmx_bowl.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ examples/car_turn.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ examples/forest_car.mp4 filter=lfs diff=lfs merge=lfs -text
39
+ examples/horsejump_high.mp4 filter=lfs diff=lfs merge=lfs -text
40
+ examples/kite_surf.mp4 filter=lfs diff=lfs merge=lfs -text
41
+ examples/parkour.mp4 filter=lfs diff=lfs merge=lfs -text
42
+ examples/rollerblade.mp4 filter=lfs diff=lfs merge=lfs -text
43
+ examples/soapbox.mp4 filter=lfs diff=lfs merge=lfs -text
44
+ examples/swing.mp4 filter=lfs diff=lfs merge=lfs -text
45
+ examples/toy_car.mp4 filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flow4RT, Copyright (c) 2026 the Flow4RT authors, is licensed under the Creative Commons
2
+ Attribution-NonCommercial-ShareAlike 4.0 International license (CC BY-NC-SA 4.0).
3
+
4
+ A summary of the CC BY-NC-SA 4.0 license is located here:
5
+ https://creativecommons.org/licenses/by-nc-sa/4.0/
6
+
7
+ The CC BY-NC-SA 4.0 license is located here:
8
+ https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
9
+
10
+ This project contains components derived from third-party works, which remain subject to
11
+ their own licenses. See NOTICE.
NOTICE ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Flow4RT
2
+ Copyright (c) 2026 the Flow4RT authors
3
+
4
+ This project contains subcomponents with separate copyright notices and license terms.
5
+ Your use of the source code for these subcomponents is subject to the terms and conditions
6
+ of the following licenses. Each derived file names its source(s) in its header.
7
+
8
+ ====
9
+
10
+ naver/dust3r
11
+ https://github.com/naver/dust3r
12
+ Copyright (C) 2024-present Naver Corporation
13
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0
14
+ Used in: flow4rt/inference.py (frame loading/resizing), flow4rt/model/geometry.py,
15
+ flow4rt/training/, flow4rt/data/
16
+
17
+ ====
18
+
19
+ CUT3R/CUT3R
20
+ https://github.com/CUT3R/CUT3R
21
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0
22
+ Used in: flow4rt/data/ (dataset loaders of TartanAir, UnrealStereo4K, DL3DV, Map-free, ScanNet,
23
+ Hypersim, Virtual KITTI 2, Point Odyssey, Dynamic Replica), datasets_preprocess/ (TartanAir,
24
+ Dynamic Replica, Point Odyssey, Map-free scripts)
25
+
26
+ ====
27
+
28
+ Luo-Yihang/4RC
29
+ https://github.com/Luo-Yihang/4RC
30
+ Used in: flow4rt/model/ (backbone, motion tracker, layers, DPT head)
31
+
32
+ S-Lab License 1.0
33
+ Copyright 2026 S-Lab
34
+
35
+ Redistribution and use for non-commercial purpose in source and binary forms, with or without
36
+ modification, are permitted provided that the following conditions are met:
37
+ 1. Redistributions of source code must retain the above copyright notice, this list of
38
+ conditions and the following disclaimer.
39
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of
40
+ conditions and the following disclaimer in the documentation and/or other materials
41
+ provided with the distribution.
42
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to
43
+ endorse or promote products derived from this software without specific prior written
44
+ permission.
45
+
46
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
47
+ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
48
+ FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
49
+ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
51
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
52
+ IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
53
+ OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
54
+
55
+ In the event that redistribution and/or use for commercial purpose in source or binary forms,
56
+ with or without modification is required, please contact the contributor(s) of the work.
57
+
58
+ ====
59
+
60
+ ByteDance-Seed/Depth-Anything-3
61
+ https://github.com/ByteDance-Seed/Depth-Anything-3
62
+ Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
63
+ Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
64
+ Used in: flow4rt/model/backbone.py, flow4rt/model/layers.py, flow4rt/model/dpt_head.py
65
+
66
+ ====
67
+
68
+ facebookresearch/dinov2
69
+ https://github.com/facebookresearch/dinov2
70
+ Copyright (c) Meta Platforms, Inc. and affiliates.
71
+ Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
72
+ Used in: flow4rt/model/backbone.py, flow4rt/model/layers.py
73
+
74
+ ====
75
+
76
+ facebookresearch/vggt
77
+ https://github.com/facebookresearch/vggt
78
+ Copyright (c) Meta Platforms, Inc. and affiliates.
79
+ Licensed under the license found in the LICENSE file of that repository.
80
+ Used in: flow4rt/model/dpt_head.py (via 4RC)
81
+
82
+ ====
83
+
84
+ microsoft/MoGe
85
+ https://github.com/microsoft/moge
86
+ MIT License
87
+ Used in: flow4rt/model/dpt_head.py (create_uv_grid)
88
+
89
+ ====
90
+
91
+ Junyi42/monst3r
92
+ https://github.com/Junyi42/monst3r
93
+ Creative Commons Attribution-NonCommercial-ShareAlike 4.0
94
+ Used in: benchmarks/video_depth_pose/ (ground-truth depth readers and evaluation settings of
95
+ depth_metric.ipynb, TUM pose conversion of cloud_opt/base_opt.py)
96
+
97
+ ====
98
+
99
+ mrdoob/three.js (r147)
100
+ https://github.com/mrdoob/three.js
101
+ Copyright 2010-2022 Three.js Authors
102
+ MIT License
103
+ Used in: viewer/vendor/ (three.min.js and the examples OrbitControls, LineSegmentsGeometry,
104
+ LineMaterial, LineSegments2), inlined into the HTML files written by visualize.py
105
+
106
+ ====
107
+
108
+ Not redistributed: the benchmarks import code from official repositories that are cloned by
109
+ third_party/clone.sh (St4RTrack, https://github.com/HavenFeng/St4RTrack; MonST3R) and remain under
110
+ their own licenses.
README.md CHANGED
@@ -1,13 +1,25 @@
1
  ---
2
  title: Flow4RT
3
- emoji: 😻
4
  colorFrom: blue
5
- colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Flow4RT
3
+ emoji: 🌀
4
  colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
+ python_version: "3.11"
9
  app_file: app.py
10
  pinned: false
11
+ license: cc-by-nc-sa-4.0
12
+ short_description: 4D reconstruction and world-space 3D tracking from video
13
  ---
14
 
15
+ # Flow4RT: Seeing Motion through Geometry
16
+
17
+ Upload a video (up to 64 frames) or pick an example, and explore the reconstruction and the
18
+ world-space 3D tracks in the interactive 4D viewer. The viewer can be downloaded as a
19
+ self-contained HTML file.
20
+
21
+ [Project page](https://shenhanqian.github.io/flow4rt) ·
22
+ [Code](https://github.com/ShenhanQian/Flow4RT) ·
23
+ [Model](https://huggingface.co/Shenhan/Flow4RT)
24
+
25
+ The example clips and their licenses are listed in [examples/CREDITS.md](examples/CREDITS.md).
__pycache__/app.cpython-311.pyc ADDED
Binary file (23.8 kB). View file
 
__pycache__/visualize.cpython-311.pyc ADDED
Binary file (30.4 kB). View file
 
app.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Flow4RT web demo (Gradio): upload a video and explore the result in the interactive 4D viewer.
2
+
3
+ pip install -e .[app]
4
+ python app.py # http://localhost:7860; --share for a public link
5
+
6
+ Also runs as a Hugging Face Space (ZeroGPU if the `spaces` package is present).
7
+ """
8
+
9
+ import argparse
10
+ import os
11
+ import re
12
+ import shutil
13
+ import tempfile
14
+ import threading
15
+ import time
16
+ import uuid
17
+
18
+ import gradio as gr
19
+ import torch
20
+
21
+ from flow4rt.inference import frames_to_tensor, load_model, predict, read_frames
22
+ from visualize import write_viewer
23
+
24
+ try:
25
+ import spaces # Hugging Face ZeroGPU
26
+ gpu = spaces.GPU(duration=120)
27
+ except ImportError:
28
+ gpu = lambda fn: fn
29
+
30
+ ROOT = os.path.dirname(os.path.abspath(__file__))
31
+ WEIGHTS = os.path.join(ROOT, "checkpoints", "flow4rt.safetensors")
32
+ OUTPUTS = os.path.join(tempfile.gettempdir(), "flow4rt_app")
33
+ # The clips of the project page, in its order (sources in examples/CREDITS.md).
34
+ EXAMPLES = ["bmx_bowl", "parkour", "soapbox", "forest_car", "toy_car", "rollerblade", "swing", "kite_surf",
35
+ "horsejump_high", "car_turn"]
36
+ EXAMPLE_DIR = os.path.join(ROOT, "examples")
37
+ MAX_FRAMES = 64
38
+ KEEP_HOURS = 6 # results older than this are deleted
39
+
40
+ # The viewer's design tokens (viewer/template.html), applied to the Gradio page.
41
+ FONT = ["-apple-system", "BlinkMacSystemFont", "Segoe UI", "Roboto", "Helvetica", "Arial", "sans-serif"]
42
+ ACCENT, ACCENT_INK, ACCENT_SOFT = "#1a73e8", "#0f57b8", "#e8f0fe"
43
+ TEXT, INK, SOFT, LINE, LINE_STRONG, TRACK = "#1d232c", "#14181f", "#586272", "#e2e7ee", "#cfd7e2", "#e9edf3"
44
+ SHADOW = "0 1px 2px rgba(16,24,40,.05), 0 6px 20px rgba(16,24,40,.06)"
45
+
46
+ THEME = gr.themes.Base(font=FONT, font_mono=["ui-monospace", "SFMono-Regular", "Menlo", "monospace"]).set(
47
+ body_background_fill="#fff", body_text_color=TEXT, body_text_color_subdued=SOFT,
48
+ background_fill_primary="#fff", background_fill_secondary="#fff", border_color_primary=LINE,
49
+ block_background_fill="#fff", block_border_color=LINE, block_border_width="1px", block_radius="14px",
50
+ block_shadow=SHADOW, block_padding="14px", block_label_background_fill="#fff", block_label_text_color=SOFT,
51
+ block_label_border_color=LINE, block_title_text_color=SOFT, block_title_text_weight="500",
52
+ block_label_text_weight="500", layout_gap="16px", panel_background_fill="#fff", panel_border_width="0px",
53
+ input_background_fill="#fff", input_border_color=LINE_STRONG, input_border_color_focus=ACCENT,
54
+ input_radius="10px", input_shadow_focus="0 0 0 3px rgba(26,115,232,.28)",
55
+ slider_color=ACCENT, color_accent=ACCENT, color_accent_soft=ACCENT_SOFT, loader_color=ACCENT,
56
+ button_large_radius="999px", button_medium_radius="999px", button_small_radius="999px",
57
+ button_large_text_weight="600", button_primary_background_fill=ACCENT,
58
+ button_primary_background_fill_hover=ACCENT_INK, button_primary_border_color=ACCENT,
59
+ button_primary_text_color="#fff", button_primary_shadow="0 1px 2px rgba(15,87,184,.35), 0 2px 8px rgba(26,115,232,.28)",
60
+ button_secondary_background_fill="#fff", button_secondary_background_fill_hover=ACCENT_SOFT,
61
+ button_secondary_border_color=LINE_STRONG, button_secondary_text_color=INK,
62
+ button_secondary_text_color_hover=ACCENT_INK,
63
+ )
64
+
65
+ CSS = f"""
66
+ .gradio-container {{ width: 100% !important; max-width: 1480px !important; margin: 0 auto !important;
67
+ padding: 20px 16px 8px !important; }}
68
+ footer {{ display: none !important; }}
69
+ #header {{ display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px 24px;
70
+ padding: 4px 2px 6px; }}
71
+ #header h1 {{ margin: 0; font-size: 1.6rem; line-height: 1.2; font-weight: 700; color: {INK}; letter-spacing: -.01em; }}
72
+ #header h1 i {{ font-style: normal; color: {ACCENT}; }}
73
+ #header h1 span {{ color: {SOFT}; font-weight: 500; }}
74
+ #header .links {{ display: flex; gap: 8px; }}
75
+ #header .links a {{ display: inline-flex; align-items: center; height: 30px; padding: 0 13px; border-radius: 999px;
76
+ border: 1px solid {LINE_STRONG}; background: #fff; color: {INK}; font-size: .85rem; font-weight: 500;
77
+ text-decoration: none; transition: background .16s, border-color .16s, color .16s; }}
78
+ #header .links a:hover {{ background: {ACCENT_SOFT}; color: {ACCENT_INK}; border-color: #bcd3f8; }}
79
+ /* One card for the settings, examples and the Run button; the blocks inside it are flat. */
80
+ #settings {{ border: 1px solid {LINE}; border-radius: 14px; box-shadow: {SHADOW}; background: #fff;
81
+ padding: 14px 16px 16px; gap: 14px; }}
82
+ #settings .block, #settings .form {{ border: 0 !important; box-shadow: none !important; padding: 0 !important;
83
+ background: none !important; overflow: visible !important; }}
84
+ #settings .form {{ gap: 14px !important; flex: none !important; }}
85
+ /* Examples: a vertical list of clips left of the video, played while hovered. */
86
+ #examples {{ border: 1px solid {LINE}; border-radius: 14px; box-shadow: {SHADOW}; background: #fff; padding: 12px;
87
+ gap: 8px; }}
88
+ #examples .html-container, #examples .prose, #examples .block {{ padding: 0 !important; border: 0 !important;
89
+ box-shadow: none !important; background: none !important; }}
90
+ .card-title {{ font-size: .85rem; font-weight: 500; color: {SOFT}; margin: 0 2px; line-height: 1.2; }}
91
+ .ex-list {{ display: grid; grid-template-columns: 1fr 1fr; align-content: start; gap: 8px; height: 330px; margin-top: 8px; overflow-y: auto; padding-right: 2px; }}
92
+ .ex {{ position: relative; display: block; width: 100%; height: 0; padding: 0 0 56.25%; border-radius: 10px; overflow: hidden;
93
+ border: 1px solid {LINE}; background: {TRACK}; box-shadow: none; cursor: pointer;
94
+ transition: border-color .16s, box-shadow .16s; }}
95
+ .ex:hover {{ border-color: {ACCENT}; }}
96
+ .ex.on {{ border-color: {ACCENT}; box-shadow: 0 0 0 2px {ACCENT}; }}
97
+ .ex video {{ position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; display: block;
98
+ pointer-events: none; }}
99
+ #example-pick {{ display: none !important; }}
100
+ #run {{ margin-top: auto; flex: none; height: 44px; min-height: 44px; }}
101
+ /* The download: a round arrow button at the bottom right of the viewer's canvas column, in the last line of
102
+ its controls (the viewer: 16px padding, a 260px side panel and an 18px gap). */
103
+ #result {{ position: relative; gap: 0; }}
104
+ #download {{ position: absolute; bottom: 16px; right: 278px; z-index: 5; width: 30px !important; min-width: 0 !important;
105
+ height: 30px; padding: 0 !important; border-radius: 50% !important; font-size: 0 !important; flex: none;
106
+ background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%231a73e8' stroke-width='2.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 4v11M7 10.5l5 5 5-5M5 20h14'/%3E%3C/svg%3E") center / 16px no-repeat !important;
107
+ border: 1px solid {LINE_STRONG} !important; box-shadow: none !important; }}
108
+ #download:hover {{ background-color: {ACCENT_SOFT} !important; border-color: #bcd3f8 !important; }}
109
+ /* The viewer brings its own 16px padding and canvas card: align its canvas with the cards above. */
110
+ #viewer, #viewer .html-container, #viewer .prose {{ padding: 0 !important; margin: 0 !important;
111
+ overflow: visible !important; max-width: none !important; }}
112
+ #viewer iframe {{ display: block; width: calc(100% + 32px); margin: 0 -16px; height: min(820px, 90vh); border: 0; }}
113
+ .empty {{ height: 360px; display: flex; flex-direction: column; align-items: center;
114
+ justify-content: center; gap: 4px; color: {SOFT}; text-align: center; padding: 0 24px;
115
+ border: 1.5px dashed {LINE_STRONG}; border-radius: 14px; background: #fafbfd; }}
116
+ .empty b {{ color: {INK}; font-size: 1.05rem; }}
117
+ .empty .dots {{ display: flex; gap: 6px; margin-bottom: 10px; }}
118
+ .empty .dots i {{ width: 8px; height: 8px; border-radius: 50%; background: {LINE_STRONG}; }}
119
+ .empty .dots i:nth-child(2) {{ background: #bcd3f8; }} .empty .dots i:nth-child(3) {{ background: {ACCENT}; }}
120
+ """
121
+
122
+ # Narrow windows, in <head>: Gradio rewrites the selectors inside the @media rules of `css`.
123
+ HEAD = """<style>
124
+ /* Narrow windows: the viewer stacks its side panel under the canvas (below 900px) and the page sizes the
125
+ iframe to it; the download goes under the viewer. */
126
+ @media (max-width: 900px) {
127
+ .main.fillable { padding-left: 0 !important; padding-right: 0 !important; }
128
+ .gradio-container { padding: 12px 12px 8px !important; }
129
+ #viewer iframe { width: 100% !important; margin: 0 !important; height: 1000px; }
130
+ #download { position: static !important; align-self: flex-end; margin-top: 4px; }
131
+ #video { height: 240px !important; }
132
+ #header h1 { font-size: 1.3rem !important; }
133
+ .ex-list { height: 236px !important; }
134
+ }
135
+ </style>"""
136
+
137
+ # The viewer is light-only: keep the page light as well.
138
+ JS = """() => { const u = new URL(location.href);
139
+ if (u.searchParams.get('__theme') !== 'light') { u.searchParams.set('__theme', 'light'); location.replace(u.href); return; }
140
+ // Example clips: play while hovered; a click passes the clip's name to the hidden #example-pick textbox.
141
+ document.addEventListener('mouseover', e => { const v = e.target.closest('.ex')?.querySelector('video');
142
+ if (v && v.paused) v.play().catch(() => {}); });
143
+ document.addEventListener('mouseout', e => { const b = e.target.closest('.ex');
144
+ if (b && !b.contains(e.relatedTarget)) { const v = b.querySelector('video'); v.pause(); v.currentTime = 0; } });
145
+ document.addEventListener('click', e => { const b = e.target.closest('.ex'); if (!b) return;
146
+ document.querySelectorAll('.ex').forEach(x => x.classList.toggle('on', x === b));
147
+ const box = document.querySelector('#example-pick textarea, #example-pick input');
148
+ box.value = b.dataset.clip; box.dispatchEvent(new Event('input', { bubbles: true })); });
149
+ // In a narrow window the viewer is as tall as its content: size its iframe to it.
150
+ document.addEventListener('load', e => { const f = e.target;
151
+ if (f.tagName !== 'IFRAME' || !f.closest('#viewer')) return;
152
+ const fit = () => { if (innerWidth <= 900) f.style.height = f.contentDocument.documentElement.scrollHeight + 'px';
153
+ else f.style.height = ''; };
154
+ new ResizeObserver(fit).observe(f.contentDocument.body); addEventListener('resize', fit); fit(); }, true);
155
+ }"""
156
+
157
+ HEADER = """<div id="header"><div>
158
+ <h1>Flow<i>4RT</i>: <span>Seeing Motion through Geometry</span></h1>
159
+ </div><div class="links">
160
+ <a href="https://shenhanqian.github.io/flow4rt" target="_blank">Project page</a>
161
+ <a href="https://github.com/ShenhanQian/Flow4RT" target="_blank">Code</a>
162
+ <a href="https://huggingface.co/Shenhan/Flow4RT" target="_blank">Model</a>
163
+ </div></div>"""
164
+
165
+ EMPTY = """<div class="empty"><div class="dots"><i></i><i></i><i></i></div>
166
+ <b>The 4D viewer appears here</b>
167
+ <span>Upload a video or pick an example, then press Run.</span></div>"""
168
+
169
+
170
+ def weights_path() -> str:
171
+ if os.path.exists(WEIGHTS):
172
+ return WEIGHTS
173
+ from huggingface_hub import hf_hub_download
174
+ return hf_hub_download("Shenhan/Flow4RT", "flow4rt.safetensors")
175
+
176
+
177
+ _model, _model_lock = None, threading.Lock()
178
+
179
+
180
+ def get_model():
181
+ global _model
182
+ with _model_lock:
183
+ if _model is None:
184
+ _model = load_model(weights_path(), device="cuda" if torch.cuda.is_available() else "cpu")
185
+ return _model
186
+
187
+
188
+ @gpu
189
+ def infer(frames):
190
+ model = get_model()
191
+ pred = predict(model, frames_to_tensor(frames).to(next(model.parameters()).device))
192
+ return {k: v.cpu().numpy() for k, v in pred.items()}
193
+
194
+
195
+ def example_list() -> str:
196
+ """The example clips as muted videos, with their first frame as the poster."""
197
+ os.makedirs(os.path.join(OUTPUTS, "thumbs"), exist_ok=True)
198
+ items = []
199
+ for clip in EXAMPLES:
200
+ poster = os.path.join(OUTPUTS, "thumbs", f"{clip}.jpg")
201
+ if not os.path.exists(poster):
202
+ frame = read_frames(os.path.join(EXAMPLE_DIR, f"{clip}.mp4"), max_frames=1)[0]
203
+ frame.thumbnail((480, 480))
204
+ frame.save(poster, quality=85)
205
+ items.append(f'<button class="ex" data-clip="{clip}" aria-label="{clip}"><video muted loop playsinline '
206
+ f'preload="none" poster="/gradio_api/file={poster}" '
207
+ f'src="/gradio_api/file={os.path.join(EXAMPLE_DIR, clip)}.mp4"></video></button>')
208
+ return '<div class="ex-list">' + "".join(items) + "</div>"
209
+
210
+
211
+ def pick_example(clip):
212
+ return os.path.join(EXAMPLE_DIR, f"{clip}.mp4") if clip in EXAMPLES else gr.skip()
213
+
214
+
215
+ def clean_old_results():
216
+ for d in os.listdir(OUTPUTS):
217
+ path = os.path.join(OUTPUTS, d)
218
+ if d != "thumbs" and time.time() - os.path.getmtime(path) > KEEP_HOURS * 3600:
219
+ shutil.rmtree(path, ignore_errors=True)
220
+
221
+
222
+ def run(video, max_frames, stride, progress=gr.Progress()):
223
+ if video is None:
224
+ raise gr.Error("Upload a video or pick an example first.")
225
+ t0 = time.time()
226
+ progress(0.05, desc="Reading frames")
227
+ frames = read_frames(video, max_frames=int(max_frames), stride=int(stride))
228
+ if len(frames) < 2:
229
+ raise gr.Error("The video needs at least two frames.")
230
+ progress(0.15, desc=f"Running Flow4RT on {len(frames)} frames")
231
+ t1 = time.time()
232
+ pred = infer(frames)
233
+ t2 = time.time()
234
+
235
+ progress(0.75, desc="Building the viewer")
236
+ clean_old_results()
237
+ out = os.path.join(OUTPUTS, uuid.uuid4().hex)
238
+ os.makedirs(out)
239
+ name = re.sub(r"[^\w.-]+", "_", os.path.splitext(os.path.basename(video))[0])
240
+ page = write_viewer(pred, os.path.join(out, f"flow4rt_{name}.html"), name, max_inline=float("inf"))
241
+ print(f"{name}: {len(frames)} frames, read {t1 - t0:.1f} s, model {t2 - t1:.1f} s, viewer {time.time() - t2:.1f} s")
242
+ iframe = f'<iframe src="/gradio_api/file={page}" allowfullscreen></iframe>'
243
+ return iframe, gr.update(value=page, visible=True)
244
+
245
+
246
+ with gr.Blocks(title="Flow4RT") as app:
247
+ gr.HTML(HEADER)
248
+ with gr.Row(elem_id="inputs", equal_height=True):
249
+ with gr.Column(scale=4, min_width=260, elem_id="examples"):
250
+ gr.HTML('<div class="card-title">Examples</div>' + example_list(), padding=False)
251
+ pick = gr.Textbox(elem_id="example-pick", show_label=False, container=False)
252
+ video = gr.Video(label="Video", sources=["upload"], height=380, scale=6, elem_id="video")
253
+ with gr.Column(scale=3, min_width=260, elem_id="settings"):
254
+ max_frames = gr.Slider(2, MAX_FRAMES, value=48, step=1, label="Frames", info="from the start of the video")
255
+ stride = gr.Slider(1, 4, value=1, step=1, label="Frame stride", info="use every n-th frame")
256
+ button = gr.Button("Run", variant="primary", size="lg", elem_id="run")
257
+ with gr.Column(elem_id="result"):
258
+ viewer = gr.HTML(EMPTY, elem_id="viewer", padding=False)
259
+ download = gr.DownloadButton("Download", visible=False, elem_id="download")
260
+ pick.change(pick_example, pick, video)
261
+ button.click(run, [video, max_frames, stride], [viewer, download])
262
+
263
+
264
+ if __name__ == "__main__":
265
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
266
+ parser.add_argument("--host", default=os.environ.get("GRADIO_SERVER_NAME", "127.0.0.1"))
267
+ parser.add_argument("--port", type=int, default=7860)
268
+ parser.add_argument("--share", action="store_true", help="create a public gradio.live link")
269
+ args = parser.parse_args()
270
+ os.makedirs(OUTPUTS, exist_ok=True)
271
+ if os.environ.get("SPACE_ID"):
272
+ get_model() # ZeroGPU expects the model on "cuda" at startup, in the main process
273
+ else:
274
+ threading.Thread(target=get_model, daemon=True).start() # load the weights while the page starts
275
+ app.queue(default_concurrency_limit=1).launch(
276
+ server_name=args.host, server_port=args.port, share=args.share, allowed_paths=[OUTPUTS, EXAMPLE_DIR],
277
+ theme=THEME, css=CSS, js=JS, head=HEAD)
examples/CREDITS.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Example clips
2
+
3
+ | file | source | license |
4
+ |---|---|---|
5
+ | `bmx_bowl.mp4` | [Pexels, video 7935583](https://www.pexels.com/video/7935583/) | [Pexels license](https://www.pexels.com/license/) |
6
+ | `parkour.mp4` | [DAVIS 2017](https://davischallenge.org), sequence `parkour` | CC BY 4.0 |
7
+ | `soapbox.mp4` | [DAVIS 2017](https://davischallenge.org), sequence `soapbox` | CC BY 4.0 |
8
+ | `forest_car.mp4` | [Pexels](https://www.pexels.com) | [Pexels license](https://www.pexels.com/license/) |
9
+ | `toy_car.mp4` | [SA-V](https://ai.meta.com/datasets/segment-anything-video/), video `sav_021651` | CC BY 4.0 |
10
+ | `rollerblade.mp4` | [DAVIS 2017](https://davischallenge.org), sequence `rollerblade` | CC BY 4.0 |
11
+ | `swing.mp4` | [DAVIS 2017](https://davischallenge.org), sequence `swing` | CC BY 4.0 |
12
+ | `kite_surf.mp4` | [DAVIS 2017](https://davischallenge.org), sequence `kite-surf` | CC BY 4.0 |
13
+ | `horsejump_high.mp4` | [DAVIS 2017](https://davischallenge.org), sequence `horsejump-high` | CC BY 4.0 |
14
+ | `car_turn.mp4` | [DAVIS 2017](https://davischallenge.org), sequence `car-turn` | CC BY 4.0 |
15
+
16
+ The clips are those of the project page. Each is downscaled to a width of 960 pixels and has 48 frames;
17
+ the DAVIS clips take 48 frames spread evenly over the sequence, as in the paper (`rollerblade.mp4`: all 35).
examples/bmx_bowl.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01764f89fcf547c5ecdc198643376fa51231980d4395c273b1e4411d0b8187b9
3
+ size 783382
examples/car_turn.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:24abf65c70ca83fcaf912da437b1495aff57f20bebf2ee66387198c27df41a9f
3
+ size 2163804
examples/forest_car.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5130df8be0a83c47a491f419342b3622fc0756368486be1c392294ecbb39d111
3
+ size 2533027
examples/horsejump_high.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dc81c39dfbeae93bfd669ae5d637fb85abada9567fdbf0041b542f0830b61a35
3
+ size 1682461
examples/kite_surf.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f45601bf365e907dee39f2b153af9c552d4a251f89ef4a307101e2c7188dbf6
3
+ size 2461071
examples/parkour.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:196e4402f3cbfb2072ff6ba6631ebd150cc78485931c819e0a8a05fa155ce007
3
+ size 3062837
examples/rollerblade.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:94881a89b87b72f7c9c6387a331ee54db818bc7ccd5189e795c1b472a6efe91a
3
+ size 880331
examples/soapbox.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f69db66985abac593480a62d5bae5e7c014270d2fbb777e798645f3946a0ebc8
3
+ size 2069625
examples/swing.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5e166c76656578fe26e0281647b53592ed6f7400613acaffe7a876d7cd444fb
3
+ size 2075109
examples/toy_car.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:718e090d78bbb178060a57c04210f4d94e0c102f4e3ea24646a3faa617f6c7a3
3
+ size 1680861
flow4rt/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .model import Flow4RT
2
+
3
+ __all__ = ["Flow4RT"]
flow4rt/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (310 Bytes). View file
 
flow4rt/__pycache__/inference.cpython-311.pyc ADDED
Binary file (10.4 kB). View file
 
flow4rt/inference.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Running Flow4RT on a video or a list of frames.
2
+
3
+ Frame reading and resizing follow `load_images` / `crop_img` of DUSt3R
4
+ (https://github.com/naver/dust3r, Copyright (C) 2024-present Naver Corporation, CC BY-NC-SA 4.0).
5
+ """
6
+
7
+ import os
8
+ from typing import Dict, List, Sequence, Union
9
+
10
+ import cv2
11
+ import numpy as np
12
+ import PIL.Image
13
+ import torch
14
+ from PIL.ImageOps import exif_transpose
15
+
16
+ from .model import Flow4RT
17
+ from .model.geometry import focal_length_from_pointmap
18
+
19
+ IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png")
20
+ VIDEO_EXTENSIONS = (".mp4", ".avi", ".mov")
21
+
22
+ Frames = Union[str, Sequence[Union[str, PIL.Image.Image]]]
23
+
24
+
25
+ # --------------------------------------------------------------------------------------
26
+ # Input
27
+ # --------------------------------------------------------------------------------------
28
+
29
+ def read_frames(inputs: Frames, max_frames: int = None, stride: int = 1, start: int = 0) -> List[PIL.Image.Image]:
30
+ """Reads RGB frames from a video file, a directory of images, or a list of image paths /
31
+ PIL images. Frames are taken as `[start::stride][:max_frames]`."""
32
+ if isinstance(inputs, str) and inputs.lower().endswith(VIDEO_EXTENSIONS):
33
+ cap = cv2.VideoCapture(inputs)
34
+ if not cap.isOpened():
35
+ raise IOError(f"Cannot open video {inputs}")
36
+ frames = []
37
+ idx = 0
38
+ while True:
39
+ ok, frame = cap.read()
40
+ if not ok:
41
+ break
42
+ if idx >= start and (idx - start) % stride == 0:
43
+ frames.append(PIL.Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)))
44
+ if max_frames is not None and len(frames) >= max_frames:
45
+ break
46
+ idx += 1
47
+ cap.release()
48
+ return frames
49
+
50
+ if isinstance(inputs, str):
51
+ if not os.path.isdir(inputs):
52
+ raise ValueError(f"{inputs} is neither a video nor a directory")
53
+ inputs = sorted(os.path.join(inputs, f) for f in os.listdir(inputs) if f.lower().endswith(IMAGE_EXTENSIONS))
54
+
55
+ inputs = list(inputs)[start::stride][:max_frames]
56
+ return [exif_transpose(f if isinstance(f, PIL.Image.Image) else PIL.Image.open(f)).convert("RGB") for f in inputs]
57
+
58
+
59
+ def resize_frame(img: PIL.Image.Image, long_edge: int = 518, patch_size: int = Flow4RT.PATCH_SIZE,
60
+ crop: bool = False) -> PIL.Image.Image:
61
+ """Resizes the long edge to `long_edge`, then brings both sides to multiples of `patch_size`
62
+ by resizing (default) or by a center crop."""
63
+ S = max(img.size)
64
+ interp = PIL.Image.LANCZOS if S > long_edge else PIL.Image.BICUBIC
65
+ img = img.resize(tuple(int(round(x * long_edge / S)) for x in img.size), interp)
66
+ W, H = img.size
67
+ halfw, halfh = (W // patch_size) * patch_size // 2, (H // patch_size) * patch_size // 2
68
+ if crop:
69
+ cx, cy = W // 2, H // 2
70
+ return img.crop((cx - halfw, cy - halfh, cx + halfw, cy + halfh))
71
+ return img.resize((2 * halfw, 2 * halfh), PIL.Image.LANCZOS)
72
+
73
+
74
+ def frames_to_tensor(frames: Sequence[PIL.Image.Image], long_edge: int = 518, crop: bool = False) -> torch.Tensor:
75
+ """PIL frames -> (V, 3, H, W) tensor in [-1, 1] at the model resolution."""
76
+ imgs = [np.asarray(resize_frame(f, long_edge, crop=crop), dtype=np.float32) / 255.0 for f in frames]
77
+ return (torch.from_numpy(np.stack(imgs)).permute(0, 3, 1, 2) - 0.5) / 0.5
78
+
79
+
80
+ # --------------------------------------------------------------------------------------
81
+ # Inference
82
+ # --------------------------------------------------------------------------------------
83
+
84
+ def load_model(path: str, device: Union[str, torch.device] = "cuda") -> Flow4RT:
85
+ return Flow4RT.from_pretrained(path, device=device)
86
+
87
+
88
+ @torch.no_grad()
89
+ def predict(model: Flow4RT, images: torch.Tensor, anchor: int = 0, amp: bool = True) -> Dict[str, torch.Tensor]:
90
+ """Runs Flow4RT on all frames in a single forward pass, with every frame paired with the
91
+ anchor frame. The world coordinate frame is the camera of the anchor frame.
92
+
93
+ Args:
94
+ images: (V, 3, H, W) in [-1, 1], e.g. from `frames_to_tensor`.
95
+ Returns a dict of tensors (on the model device):
96
+ images (V, H, W, 3) input frames in [0, 1]
97
+ pts3d (V, H, W, 3) pointmap of frame i in its own camera
98
+ depth (V, H, W) z of `pts3d`
99
+ conf (V, H, W) confidence of `pts3d`
100
+ rigidity (V, H, W) rigidity map of frame i w.r.t. the anchor (sums to 1 per frame)
101
+ cam2world (V, 4, 4) camera-to-world pose of frame i
102
+ points (V, H, W, 3) pointmap of frame i in world coordinates (reconstruction)
103
+ tracks (V, H, W, 3) the anchor frame's pixels at the time of frame i, in world
104
+ coordinates (world-space 3D tracks / scene flow)
105
+ focal (V,) focal length in pixels, from `pts3d`
106
+ """
107
+ device = next(model.parameters()).device
108
+ V = images.shape[0]
109
+ views = {
110
+ "img": images[None].to(device),
111
+ "target_idx": torch.full((1, V), anchor, dtype=torch.long, device=device),
112
+ }
113
+ dtype = torch.bfloat16 if device.type != "cuda" or torch.cuda.is_bf16_supported() else torch.float16
114
+ with torch.autocast(device_type=device.type, dtype=dtype, enabled=amp):
115
+ pred_src, pred_tgt = model(views) # frame i toward the anchor; the anchor toward frame i
116
+
117
+ def get(pred, key):
118
+ return pred[key][0].float()
119
+
120
+ return {
121
+ "images": ((images.permute(0, 2, 3, 1) + 1) / 2).to(device),
122
+ "pts3d": get(pred_src, "pts3d"),
123
+ "depth": get(pred_src, "pts3d")[..., 2],
124
+ "conf": get(pred_src, "conf"),
125
+ "rigidity": get(pred_src, "rigidity"),
126
+ "cam2world": get(pred_src, "camera_pose"),
127
+ "points": get(pred_src, "pts3d_v"),
128
+ "tracks": get(pred_tgt, "pts3d_t"),
129
+ "focal": focal_length_from_pointmap(get(pred_src, "pts3d")),
130
+ }
flow4rt/model/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .flow4rt import Flow4RT
2
+
3
+ __all__ = ["Flow4RT"]
flow4rt/model/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (318 Bytes). View file
 
flow4rt/model/__pycache__/dpt_head.cpython-311.pyc ADDED
Binary file (17.4 kB). View file
 
flow4rt/model/__pycache__/flow4rt.cpython-311.pyc ADDED
Binary file (8.67 kB). View file
 
flow4rt/model/__pycache__/geometry.cpython-311.pyc ADDED
Binary file (6.14 kB). View file
 
flow4rt/model/__pycache__/geometry_blocks.cpython-311.pyc ADDED
Binary file (10.5 kB). View file
 
flow4rt/model/__pycache__/layers.cpython-311.pyc ADDED
Binary file (23.1 kB). View file
 
flow4rt/model/__pycache__/motion_blocks.cpython-311.pyc ADDED
Binary file (5.38 kB). View file
 
flow4rt/model/dpt_head.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DPT head predicting a pointmap and a confidence map from multi-level ViT tokens.
2
+ #
3
+ # Adapted from VGGT (https://github.com/facebookresearch/vggt) and Depth Anything 3
4
+ # (https://github.com/ByteDance-Seed/Depth-Anything-3, Apache-2.0); both inspired by
5
+ # Depth Anything V2 (https://github.com/DepthAnything/Depth-Anything-V2).
6
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
7
+ #
8
+ # Changes w.r.t. the sources: the output convolutions are replaced by the memory-efficient
9
+ # variant of VGGT-Omega (a 1x1 projection to sub-pixels at the fused resolution followed by
10
+ # pixel shuffle; the low-channel logits are then resized to the image size since Flow4RT
11
+ # uses 14x14 patches); fusion blocks are gradient-checkpointed during training.
12
+
13
+ from typing import List, Tuple
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.nn.functional as F
18
+ from torch.utils.checkpoint import checkpoint
19
+
20
+
21
+ class DPTHead(nn.Module):
22
+ """Decodes tokens of 4 read-out layers into a point map (B, H, W, 3) and a raw per-pixel
23
+ scalar (B, H, W), whose activation depends on the branch (confidence or rigidity)."""
24
+
25
+ def __init__(self, dim_in: int, patch_size: int = 14, output_dim: int = 4, features: int = 256,
26
+ out_channels: List[int] = (256, 512, 1024, 1024)) -> None:
27
+ super().__init__()
28
+ self.patch_size = patch_size
29
+ self.output_dim = output_dim
30
+
31
+ self.norm = nn.LayerNorm(dim_in)
32
+ self.projects = nn.ModuleList([nn.Conv2d(dim_in, oc, kernel_size=1) for oc in out_channels])
33
+ self.resize_layers = nn.ModuleList([
34
+ nn.ConvTranspose2d(out_channels[0], out_channels[0], kernel_size=4, stride=4),
35
+ nn.ConvTranspose2d(out_channels[1], out_channels[1], kernel_size=2, stride=2),
36
+ nn.Identity(),
37
+ nn.Conv2d(out_channels[3], out_channels[3], kernel_size=3, stride=2, padding=1),
38
+ ])
39
+
40
+ self.scratch = nn.Module()
41
+ for i, oc in enumerate(out_channels):
42
+ setattr(self.scratch, f"layer{i + 1}_rn", nn.Conv2d(oc, features, kernel_size=3, padding=1, bias=False))
43
+ # in-place ReLUs would overwrite checkpointed inputs before recomputation
44
+ self.scratch.refinenet1 = FeatureFusionBlock(features)
45
+ self.scratch.refinenet2 = FeatureFusionBlock(features)
46
+ self.scratch.refinenet3 = FeatureFusionBlock(features)
47
+ self.scratch.refinenet4 = FeatureFusionBlock(features, has_residual=False)
48
+
49
+ self.shuffle_factor = max(1, patch_size // 4)
50
+ self.scratch.output_conv2 = nn.Conv2d(features, output_dim * self.shuffle_factor**2, kernel_size=1)
51
+
52
+ def forward(self, tokens_list: List[torch.Tensor], image_size: Tuple[int, int],
53
+ frames_chunk_size: int = 8) -> Tuple[torch.Tensor, torch.Tensor]:
54
+ """tokens_list: 4 tensors (B, P, C) from different levels; processed in chunks of frames."""
55
+ B = tokens_list[0].shape[0]
56
+ if frames_chunk_size is None or frames_chunk_size >= B:
57
+ return self._forward_impl(tokens_list, image_size)
58
+ preds = [self._forward_impl([t[s:s + frames_chunk_size] for t in tokens_list], image_size)
59
+ for s in range(0, B, frames_chunk_size)]
60
+ return tuple(torch.cat(p, dim=0) for p in zip(*preds))
61
+
62
+ def _forward_impl(self, tokens_list, image_size):
63
+ H, W = image_size
64
+ patch_h, patch_w = H // self.patch_size, W // self.patch_size
65
+
66
+ out = []
67
+ for i, x in enumerate(tokens_list):
68
+ x = self.norm(x)
69
+ x = x.permute(0, 2, 1).reshape(x.shape[0], x.shape[-1], patch_h, patch_w)
70
+ x = self.projects[i](x)
71
+ x = _apply_pos_embed(x, W, H)
72
+ x = self.resize_layers[i](x)
73
+ out.append(x)
74
+
75
+ out = self._fuse(out)
76
+ out = _apply_pos_embed(out, W, H)
77
+ out = self.scratch.output_conv2(out)
78
+ out = F.pixel_shuffle(out, self.shuffle_factor)
79
+ out = custom_interpolate(out, (patch_h * self.patch_size, patch_w * self.patch_size))
80
+ out = out.permute(0, 2, 3, 1) # B, H, W, C
81
+
82
+ pts3d, scalar = out.split([3, 1], dim=-1)
83
+ return norm_exp_transform(pts3d), scalar.squeeze(-1)
84
+
85
+ def _fuse(self, features: List[torch.Tensor]) -> torch.Tensor:
86
+ layers_rn = [getattr(self.scratch, f"layer{i + 1}_rn")(f) for i, f in enumerate(features)]
87
+ sizes = [x.shape[2:] for x in layers_rn]
88
+ s = self.scratch
89
+
90
+ out = self._run(lambda x: s.refinenet4(x, size=sizes[2]), layers_rn[3])
91
+ out = self._run(lambda x, r: s.refinenet3(x, r, size=sizes[1]), out, layers_rn[2])
92
+ out = self._run(lambda x, r: s.refinenet2(x, r, size=sizes[0]), out, layers_rn[1])
93
+ out = self._run(lambda x, r: s.refinenet1(x, r, size=sizes[0]), out, layers_rn[0])
94
+ return out
95
+
96
+ def _run(self, fn, *args):
97
+ if self.training:
98
+ return checkpoint(fn, *args, use_reentrant=False)
99
+ return fn(*args)
100
+
101
+
102
+ def norm_exp_transform(x: torch.Tensor) -> torch.Tensor:
103
+ """Maps the network output to a point: keeps the direction, exponentiates the norm."""
104
+ d = x.norm(dim=-1, keepdim=True).clamp(min=1e-8)
105
+ return x / d * torch.expm1(d)
106
+
107
+
108
+ class ResidualConvUnit(nn.Module):
109
+ def __init__(self, features: int):
110
+ super().__init__()
111
+ self.conv1 = nn.Conv2d(features, features, kernel_size=3, padding=1, bias=True)
112
+ self.conv2 = nn.Conv2d(features, features, kernel_size=3, padding=1, bias=True)
113
+ self.activation = nn.ReLU(inplace=False)
114
+
115
+ def forward(self, x):
116
+ out = self.conv1(self.activation(x))
117
+ out = self.conv2(self.activation(out))
118
+ return out + x
119
+
120
+
121
+ class FeatureFusionBlock(nn.Module):
122
+ def __init__(self, features: int, has_residual: bool = True):
123
+ super().__init__()
124
+ self.out_conv = nn.Conv2d(features, features, kernel_size=1, bias=True)
125
+ self.has_residual = has_residual
126
+ if has_residual:
127
+ self.resConfUnit1 = ResidualConvUnit(features)
128
+ self.resConfUnit2 = ResidualConvUnit(features)
129
+
130
+ def forward(self, x, residual=None, size=None):
131
+ if self.has_residual:
132
+ x = x + self.resConfUnit1(residual)
133
+ x = self.resConfUnit2(x)
134
+ x = custom_interpolate(x, size)
135
+ return self.out_conv(x)
136
+
137
+
138
+ def custom_interpolate(x: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
139
+ """Bilinear interpolation (align_corners=True), chunked to avoid INT_MAX issues."""
140
+ INT_MAX = 1610612736
141
+ input_elements = size[0] * size[1] * x.shape[0] * x.shape[1]
142
+ if input_elements > INT_MAX:
143
+ chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0)
144
+ return torch.cat([F.interpolate(c, size=size, mode="bilinear", align_corners=True) for c in chunks]).contiguous()
145
+ return F.interpolate(x, size=size, mode="bilinear", align_corners=True)
146
+
147
+
148
+ def _apply_pos_embed(x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor:
149
+ patch_h, patch_w = x.shape[-2:]
150
+ pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device)
151
+ pos_embed = position_grid_to_embed(pos_embed, x.shape[1]) * ratio
152
+ return x + pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1)
153
+
154
+
155
+ def position_grid_to_embed(pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100) -> torch.Tensor:
156
+ """(H, W, 2) grid -> (H, W, embed_dim) sinusoidal embedding."""
157
+ H, W, _ = pos_grid.shape
158
+ pos_flat = pos_grid.reshape(-1, 2)
159
+ emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0)
160
+ emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0)
161
+ return torch.cat([emb_x, emb_y], dim=-1).view(H, W, embed_dim)
162
+
163
+
164
+ def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor:
165
+ device = pos.device
166
+ omega = torch.arange(embed_dim // 2, dtype=torch.float32 if device.type == "mps" else torch.double, device=device)
167
+ omega /= embed_dim / 2.0
168
+ omega = 1.0 / omega_0**omega
169
+ out = torch.einsum("m,d->md", pos.reshape(-1), omega)
170
+ return torch.cat([torch.sin(out), torch.cos(out)], dim=1).float()
171
+
172
+
173
+ def create_uv_grid(width: int, height: int, aspect_ratio: float, dtype=None, device=None) -> torch.Tensor:
174
+ """(width, height, 2) UV grid spanning the image plane normalized by its diagonal
175
+ (from MoGe, https://github.com/microsoft/moge)."""
176
+ diag_factor = (aspect_ratio**2 + 1.0) ** 0.5
177
+ span_x = aspect_ratio / diag_factor
178
+ span_y = 1.0 / diag_factor
179
+ left_x, right_x = -span_x * (width - 1) / width, span_x * (width - 1) / width
180
+ top_y, bottom_y = -span_y * (height - 1) / height, span_y * (height - 1) / height
181
+ x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device)
182
+ y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device)
183
+ uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy")
184
+ return torch.stack((uu, vv), dim=-1)
flow4rt/model/flow4rt.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Tuple
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+ from .dpt_head import DPTHead
7
+ from .geometry import geotrf, solve_transfm
8
+ from .geometry_blocks import GeometryBlocks
9
+ from .motion_blocks import MotionBlocks
10
+
11
+
12
+ class Flow4RT(nn.Module):
13
+ """Flow4RT.
14
+
15
+ Geometry blocks (a ViT-g) process all views jointly. At each of four read-out layers, motion
16
+ blocks map the tokens of a source view toward its target view (viewpoint and time). A shared
17
+ DPT head decodes the geometry branch into a local point map P with confidence C, and the
18
+ motion branch into a displaced point map P_vt with rigidity W. The rigidity-weighted rigid
19
+ alignment of P to P_vt gives the relative camera pose T, which separates scene flow into
20
+ camera motion and object motion.
21
+ """
22
+
23
+ PATCH_SIZE = 14
24
+
25
+ def __init__(self, motion_depth: int = 8):
26
+ super().__init__()
27
+ self.geometry_blocks = GeometryBlocks()
28
+ self.motion_blocks = MotionBlocks(dim=1536, depth=motion_depth)
29
+ self.head = DPTHead(dim_in=1536, output_dim=4)
30
+
31
+ @classmethod
32
+ def from_pretrained(cls, path: str, device="cpu", **kwargs) -> "Flow4RT":
33
+ """Loads weights from a `.safetensors` file or a training checkpoint (`.pth`)."""
34
+ model = cls(**kwargs)
35
+ if path.endswith(".safetensors"):
36
+ from safetensors.torch import load_file
37
+ state_dict = load_file(path)
38
+ else:
39
+ state_dict = torch.load(path, map_location="cpu", weights_only=False, mmap=True)
40
+ state_dict = state_dict.get("model", state_dict)
41
+ model.load_state_dict(state_dict, strict=True)
42
+ return model.to(device).eval()
43
+
44
+ def forward(self, views: Dict[str, torch.Tensor]) -> Tuple[Dict[str, torch.Tensor], Dict[str, torch.Tensor]]:
45
+ """
46
+ Args:
47
+ views: dict with
48
+ img: (B, V, 3, H, W) images in [-1, 1]; H and W multiples of 14.
49
+ target_idx: (B, V) long, the target view of each view.
50
+ Returns:
51
+ (pred_src, pred_tgt), dicts of (B, V, ...) tensors. For view i with target j:
52
+ pred_src: view i as the source, toward j; pred_tgt: view j as the source, toward i.
53
+ Names follow the paper's notation (P, C, P_vt, W, T, P_v, P_t).
54
+ pts3d P local point map: source viewpoint, source time
55
+ conf C confidence of P
56
+ pts3d_vt P_vt displaced point map: target viewpoint, target time
57
+ rigidity W rigidity map, sums to 1 over the pixels of each view
58
+ camera_pose T (B, V, 4, 4) relative pose (source -> target camera), solved
59
+ from P, P_vt and W by weighted rigid alignment
60
+ pts3d_v P_v target viewpoint, source time (T P)
61
+ pts3d_t P_t source viewpoint, target time (T^-1 P_vt)
62
+ """
63
+ images = views["img"]
64
+ target_idx = views["target_idx"]
65
+ B, V, _, H, W = images.shape
66
+ x = (images + 1) / 2 # the geometry blocks take images in [0, 1]
67
+
68
+ geometry_tokens, motion_tokens = [], []
69
+ for level, (patches, cls_token, time_token) in enumerate(self.geometry_blocks(x)):
70
+ geometry_tokens.append(patches.flatten(0, 1)) # (B*V, P, C)
71
+ tokens = torch.cat([cls_token.unsqueeze(2), time_token.unsqueeze(2), patches], dim=2)
72
+ motion_tokens.append(self.motion_blocks(tokens, target_idx, level)) # (B*2V, P, C)
73
+
74
+ with torch.autocast(device_type=images.device.type, dtype=torch.float32):
75
+ pts3d, conf = self.head(geometry_tokens, (H, W)) # geometry branch, per view
76
+ pts3d_vt, rigidity = self.head(motion_tokens, (H, W)) # motion branch, per (source, target)
77
+
78
+ def with_target(t): # (B*V, ...) -> (B*2V, ...): views followed by their targets
79
+ t = t.reshape(B, V, *t.shape[1:])
80
+ idx = target_idx.reshape(B, V, *([1] * (t.ndim - 2))).expand_as(t)
81
+ return torch.cat([t, torch.gather(t, dim=1, index=idx)], dim=1).flatten(0, 1)
82
+
83
+ out = {
84
+ "pts3d": with_target(pts3d),
85
+ "conf": with_target(1 + torch.exp(conf)),
86
+ "pts3d_vt": pts3d_vt,
87
+ "rigidity": rigidity.flatten(1).softmax(dim=1).view_as(rigidity), # sums to 1 over pixels
88
+ }
89
+ pred_src, pred_tgt = {}, {}
90
+ for k, v in out.items():
91
+ pred_src[k], pred_tgt[k] = v.reshape(B, 2, V, *v.shape[1:]).unbind(dim=1)
92
+ return self._postprocess(pred_src), self._postprocess(pred_tgt)
93
+
94
+ @staticmethod
95
+ def _postprocess(pred: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
96
+ pts = pred["pts3d"].detach()
97
+ pts_vt = pred["pts3d_vt"]
98
+ rigidity = pred["rigidity"]
99
+
100
+ # relative camera pose: rigidity-weighted alignment of the two pointmaps of the same pixels
101
+ trf_cam = solve_transfm(pts.flatten(-3, -2), pts_vt.flatten(-3, -2).detach(), rigidity.flatten(-2, -1))
102
+ pts_v = geotrf(trf_cam, pts)
103
+ pts_t = geotrf(trf_cam.inverse(), pts_vt)
104
+ pred["camera_pose"] = trf_cam # (B, V, 4, 4): source camera -> target camera
105
+ pred["pts3d_v"] = pts_v
106
+ pred["pts3d_t"] = pts_t
107
+ return pred
flow4rt/model/geometry.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Geometry utilities. `geotrf` and `Rt_to_T` are adapted from DUSt3R
2
+ # (https://github.com/naver/dust3r, Copyright (C) 2024-present Naver Corporation, CC BY-NC-SA 4.0).
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+
7
+
8
+ def Rt_to_T(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
9
+ """(..., 3, 3), (..., 3) -> (..., 4, 4) homogeneous transform."""
10
+ T = torch.cat((R, t.unsqueeze(-1)), dim=-1)
11
+ T = F.pad(T, (0, 0, 0, 1), value=0)
12
+ T[..., -1, -1] = 1
13
+ return T
14
+
15
+
16
+ def geotrf(T: torch.Tensor, pts: torch.Tensor) -> torch.Tensor:
17
+ """Applies (..., 4, 4) transforms to points (..., *, 3) with matching leading dims."""
18
+ Tt = T.swapaxes(-1, -2)
19
+ p = pts.reshape(*T.shape[:-2], -1, 3)
20
+ return (p @ Tt[..., :3, :3] + Tt[..., 3:, :3]).reshape(pts.shape)
21
+
22
+
23
+ def solve_transfm(p: torch.Tensor, q: torch.Tensor, w: torch.Tensor = None) -> torch.Tensor:
24
+ """Weighted rigid (Kabsch) alignment: the (..., 4, 4) transform T minimizing
25
+ sum_n w_n |T p_n - q_n|^2, for points p, q of shape (..., N, 3) and weights w (..., N)."""
26
+ N = p.shape[-2]
27
+ if w is None:
28
+ w = torch.ones_like(p[..., :1]) / N
29
+ elif w.ndim == p.ndim - 1:
30
+ w = w.unsqueeze(-1)
31
+
32
+ mean_p = torch.sum(w * p, dim=-2, keepdim=True)
33
+ mean_q = torch.sum(w * q, dim=-2, keepdim=True)
34
+ H = torch.einsum("...ni,...nj->...ij", w * (p - mean_p), q - mean_q)
35
+ U, _, Vt = torch.linalg.svd(H)
36
+ R = torch.matmul(Vt.transpose(-2, -1), U.transpose(-2, -1))
37
+
38
+ # ensure a proper rotation (det(R) = 1)
39
+ mask = torch.det(R) < 0
40
+ mask_lastrow = mask[..., None, None].repeat(mask.ndim * [1] + [3, 3])
41
+ mask_lastrow[..., :-1, :] = False
42
+ Vt_new = Vt.clone()
43
+ Vt_new[mask_lastrow] *= -1
44
+ R[mask] = torch.matmul(Vt_new[mask].transpose(-2, -1), U[mask].transpose(-2, -1))
45
+
46
+ t = (mean_q - torch.matmul(R, mean_p.transpose(-2, -1)).transpose(-2, -1)).squeeze(-2)
47
+ return Rt_to_T(R, t)
48
+
49
+
50
+ def focal_length_from_pointmap(pts3d: torch.Tensor, conf: torch.Tensor = None) -> torch.Tensor:
51
+ """Least-squares focal length (principal point at the image center) of (..., H, W, 3)
52
+ pointmaps in camera coordinates. Returns (...,); NaN where it cannot be estimated."""
53
+ H, W = pts3d.shape[-3:-1]
54
+ yy, xx = torch.meshgrid(torch.arange(H, device=pts3d.device), torch.arange(W, device=pts3d.device), indexing="ij")
55
+ du = (xx - W / 2.0).reshape(1, -1)
56
+ dv = (yy - H / 2.0).reshape(1, -1)
57
+
58
+ X, Y, Z = (pts3d[..., i].reshape(*pts3d.shape[:-3], -1) for i in range(3))
59
+ valid = Z > 1e-6
60
+ Xn = torch.where(valid, X / Z, torch.zeros_like(X))
61
+ Yn = torch.where(valid, Y / Z, torch.zeros_like(Y))
62
+ w = valid.float() if conf is None else conf.reshape(*pts3d.shape[:-3], -1) * valid
63
+
64
+ f = (w * (du * Xn + dv * Yn)).sum(dim=-1) / (w * (Xn**2 + Yn**2)).sum(dim=-1)
65
+ f[f <= 0] = torch.nan
66
+ return f
flow4rt/model/geometry_blocks.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Geometry blocks: the DINOv2 ViT-g backbone with alternating frame-wise / global attention of
2
+ # Depth Anything 3 and 4RC.
3
+ #
4
+ # Adapted from DINOv2 (https://github.com/facebookresearch/dinov2, Apache-2.0),
5
+ # Depth Anything 3 (https://github.com/ByteDance-Seed/Depth-Anything-3, Apache-2.0)
6
+ # and 4RC (https://github.com/Luo-Yihang/4RC, S-Lab License 1.0).
7
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
8
+ #
9
+ # Changes w.r.t. 4RC: no camera token and no reference-view selection/reordering (the
10
+ # input frame order is kept); intermediate layers are returned without concatenating
11
+ # frame-wise tokens; generic ViT sizes, register tokens, masking and drop-path removed; the
12
+ # `pretrained` wrapper module is dropped (weight names `backbone.pretrained.*` -> `geometry_blocks.*`).
13
+
14
+ import math
15
+ from typing import List, Tuple
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ from einops import rearrange
20
+ from torch.utils.checkpoint import checkpoint
21
+
22
+ from .layers import Block, PatchEmbed, PositionGetter, RotaryPositionEmbedding2D, SwiGLUFFN
23
+
24
+
25
+ class GeometryBlocks(nn.Module):
26
+ """ViT-g/14. Blocks with index >= `alt_start` alternate between within-view (even) and
27
+ cross-view (odd) attention; a learned time token is inserted at `alt_start`.
28
+
29
+ Input: images (B, S, 3, H, W) in [0, 1].
30
+ Output: for each read-out layer, a tuple
31
+ (patch_tokens (B, S, P, C) after the final norm, cls_token (B, S, C), time_token (B, S, C)).
32
+ """
33
+
34
+ patch_start_idx = 2 # [cls, time, patches...]
35
+
36
+ def __init__(self, readout_layers: List[int] = (19, 27, 33, 39), alt_start: int = 13, qknorm_start: int = 13,
37
+ rope_start: int = 13, rope_freq: float = 100, img_size: int = 518, patch_size: int = 14,
38
+ embed_dim: int = 1536, depth: int = 40, num_heads: int = 24, mlp_ratio: float = 4.0,
39
+ interpolate_offset: float = 0.1):
40
+ super().__init__()
41
+ self.readout_layers = list(readout_layers)
42
+ self.embed_dim = embed_dim
43
+ self.patch_size = patch_size
44
+ self.alt_start = alt_start
45
+ self.rope_start = rope_start
46
+ self.interpolate_offset = interpolate_offset
47
+
48
+ self.patch_embed = PatchEmbed(img_size=img_size, patch_size=patch_size, embed_dim=embed_dim)
49
+ num_patches = self.patch_embed.num_patches
50
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
51
+ self.time_token = nn.Parameter(torch.randn(1, 1, embed_dim))
52
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
53
+
54
+ self.rope = RotaryPositionEmbedding2D(frequency=rope_freq)
55
+ self.position_getter = PositionGetter()
56
+ self.blocks = nn.ModuleList([
57
+ Block(
58
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, ffn_layer=SwiGLUFFN, init_values=1.0,
59
+ qk_norm=i >= qknorm_start, rope=self.rope if i >= rope_start else None, ln_eps=1e-6,
60
+ )
61
+ for i in range(depth)
62
+ ])
63
+ self.norm = nn.LayerNorm(embed_dim)
64
+
65
+ def interpolate_pos_encoding(self, x, h, w):
66
+ previous_dtype = x.dtype
67
+ npatch = x.shape[1] - 1
68
+ N = self.pos_embed.shape[1] - 1
69
+ if npatch == N and w == h:
70
+ return self.pos_embed
71
+ pos_embed = self.pos_embed.float()
72
+ class_pos_embed = pos_embed[:, 0]
73
+ patch_pos_embed = pos_embed[:, 1:]
74
+ dim = x.shape[-1]
75
+ h0, w0 = h // self.patch_size, w // self.patch_size
76
+ M = int(math.sqrt(N))
77
+ assert N == M * M
78
+ # DINOv2 adds a small offset to avoid floating point errors in the interpolation
79
+ scale_factor = (float(h0 + self.interpolate_offset) / M, float(w0 + self.interpolate_offset) / M)
80
+ patch_pos_embed = nn.functional.interpolate(
81
+ patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2),
82
+ mode="bicubic", antialias=False, scale_factor=scale_factor,
83
+ )
84
+ assert (h0, w0) == patch_pos_embed.shape[-2:]
85
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
86
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
87
+
88
+ def prepare_tokens(self, x):
89
+ B, S, _, H, W = x.shape
90
+ x = self.patch_embed(x.flatten(0, 1))
91
+ x = torch.cat((self.cls_token.expand(B * S, -1, -1), x), dim=1)
92
+ x = x + self.interpolate_pos_encoding(x, H, W)
93
+ return rearrange(x, "(b s) n c -> b s n c", b=B, s=S)
94
+
95
+ def prepare_rope(self, B, S, H, W, device):
96
+ """Positions for frame-wise attention (patch grid) and global attention (all patches
97
+ share one position, so RoPE only separates special tokens from patches)."""
98
+ pos = self.position_getter(B * S, H // self.patch_size, W // self.patch_size, device=device)
99
+ pos = rearrange(pos, "(b s) n c -> b s n c", b=B)
100
+ pos_special = torch.zeros(B, S, self.patch_start_idx, 2, device=device, dtype=pos.dtype)
101
+ pos_local = torch.cat([pos_special, pos + 1], dim=2)
102
+ pos_global = torch.cat([pos_special, torch.ones_like(pos)], dim=2)
103
+ return pos_local, pos_global
104
+
105
+ def run_block(self, x, block, attn_type, pos):
106
+ b, s = x.shape[:2]
107
+ if attn_type == "local":
108
+ x, pos = x.flatten(0, 1), pos.flatten(0, 1) if pos is not None else None
109
+ else:
110
+ x, pos = x.flatten(1, 2), pos.flatten(1, 2) if pos is not None else None
111
+
112
+ if self.training:
113
+ x = checkpoint(block, x, pos, use_reentrant=False)
114
+ else:
115
+ x = block(x, pos=pos)
116
+
117
+ if attn_type == "local":
118
+ return rearrange(x, "(b s) n c -> b s n c", b=b, s=s)
119
+ return rearrange(x, "b (s n) c -> b s n c", b=b, s=s)
120
+
121
+ def forward(self, x: torch.Tensor) -> List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
122
+ B, S, _, H, W = x.shape
123
+ x = self.prepare_tokens(x)
124
+ pos_local, pos_global = self.prepare_rope(B, S, H, W, x.device)
125
+
126
+ outputs = []
127
+ for i, blk in enumerate(self.blocks):
128
+ if i == self.alt_start: # insert the time token after the cls token
129
+ time_token = self.time_token.expand(B, S, -1).unsqueeze(2)
130
+ x = torch.cat([x[:, :, :1], time_token, x[:, :, 1:]], dim=2)
131
+
132
+ use_rope = i >= self.rope_start
133
+ if i >= self.alt_start and i % 2 == 1:
134
+ x = self.run_block(x, blk, "global", pos_global if use_rope else None)
135
+ else:
136
+ x = self.run_block(x, blk, "local", pos_local if use_rope else None)
137
+
138
+ if i in self.readout_layers:
139
+ outputs.append(x)
140
+
141
+ # special tokens are returned before the final norm, patch tokens after
142
+ return [
143
+ (self.norm(out)[:, :, self.patch_start_idx:], out[:, :, 0], out[:, :, 1])
144
+ for out in outputs
145
+ ]
flow4rt/model/layers.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Transformer building blocks shared by the geometry blocks and the motion blocks.
2
+ #
3
+ # Adapted from DINOv2 (https://github.com/facebookresearch/dinov2, Apache-2.0),
4
+ # Depth Anything 3 (https://github.com/ByteDance-Seed/Depth-Anything-3, Apache-2.0)
5
+ # and 4RC (https://github.com/Luo-Yihang/4RC, S-Lab License 1.0).
6
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
7
+ #
8
+ # Changes w.r.t. the sources: merged into one file, removed options that are unused by
9
+ # Flow4RT (dropout, drop-path / stochastic depth, xFormers, LoRA, attention masks,
10
+ # returning attention weights, RoPE in cross-attention).
11
+
12
+ from typing import Dict, Optional, Tuple
13
+
14
+ import torch
15
+ import torch.nn.functional as F
16
+ from torch import Tensor, nn
17
+
18
+
19
+ class Mlp(nn.Module):
20
+ def __init__(self, in_features: int, hidden_features: int, bias: bool = True) -> None:
21
+ super().__init__()
22
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
23
+ self.act = nn.GELU()
24
+ self.fc2 = nn.Linear(hidden_features, in_features, bias=bias)
25
+
26
+ def forward(self, x: Tensor) -> Tensor:
27
+ return self.fc2(self.act(self.fc1(x)))
28
+
29
+
30
+ class SwiGLUFFN(nn.Module):
31
+ """SwiGLU FFN with the hidden size rounding of DINOv2's `SwiGLUFFNFused`."""
32
+
33
+ def __init__(self, in_features: int, hidden_features: int, bias: bool = True) -> None:
34
+ super().__init__()
35
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
36
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
37
+ self.w3 = nn.Linear(hidden_features, in_features, bias=bias)
38
+
39
+ def forward(self, x: Tensor) -> Tensor:
40
+ x1, x2 = self.w12(x).chunk(2, dim=-1)
41
+ return self.w3(F.silu(x1) * x2)
42
+
43
+
44
+ class LayerScale(nn.Module):
45
+ def __init__(self, dim: int, init_values: float) -> None:
46
+ super().__init__()
47
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
48
+
49
+ def forward(self, x: Tensor) -> Tensor:
50
+ return x * self.gamma
51
+
52
+
53
+ class PatchEmbed(nn.Module):
54
+ """(B, 3, H, W) image -> (B, H*W / patch_size**2, D) patch tokens."""
55
+
56
+ def __init__(self, img_size: int, patch_size: int, in_chans: int = 3, embed_dim: int = 768) -> None:
57
+ super().__init__()
58
+ self.patch_size = patch_size
59
+ self.num_patches = (img_size // patch_size) ** 2
60
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
61
+
62
+ def forward(self, x: Tensor) -> Tensor:
63
+ H, W = x.shape[-2:]
64
+ assert H % self.patch_size == 0 and W % self.patch_size == 0, \
65
+ f"Image size {H}x{W} is not a multiple of the patch size {self.patch_size}"
66
+ return self.proj(x).flatten(2).transpose(1, 2)
67
+
68
+
69
+ # --------------------------------------------------------------------------------------
70
+ # 2D rotary position embedding
71
+ # --------------------------------------------------------------------------------------
72
+
73
+ class PositionGetter:
74
+ """Generates and caches the (y, x) grid positions of patches."""
75
+
76
+ def __init__(self):
77
+ self.position_cache: Dict[Tuple[int, int], Tensor] = {}
78
+
79
+ def __call__(self, batch_size: int, height: int, width: int, device: torch.device) -> Tensor:
80
+ if (height, width) not in self.position_cache:
81
+ y_coords = torch.arange(height, device=device)
82
+ x_coords = torch.arange(width, device=device)
83
+ self.position_cache[height, width] = torch.cartesian_prod(y_coords, x_coords)
84
+ positions = self.position_cache[height, width]
85
+ return positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone()
86
+
87
+
88
+ class RotaryPositionEmbedding2D(nn.Module):
89
+ """2D RoPE: the first half of the channels encodes y, the second half x."""
90
+
91
+ def __init__(self, frequency: float = 100.0):
92
+ super().__init__()
93
+ self.base_frequency = frequency
94
+ self.frequency_cache: Dict[Tuple, Tuple[Tensor, Tensor]] = {}
95
+
96
+ def _compute_frequency_components(self, dim, seq_len, device, dtype):
97
+ cache_key = (dim, seq_len, device, dtype)
98
+ if cache_key not in self.frequency_cache:
99
+ exponents = torch.arange(0, dim, 2, device=device).float() / dim
100
+ inv_freq = 1.0 / (self.base_frequency**exponents)
101
+ positions = torch.arange(seq_len, device=device, dtype=inv_freq.dtype)
102
+ angles = torch.einsum("i,j->ij", positions, inv_freq).to(dtype)
103
+ angles = torch.cat((angles, angles), dim=-1)
104
+ self.frequency_cache[cache_key] = (angles.cos().to(dtype), angles.sin().to(dtype))
105
+ return self.frequency_cache[cache_key]
106
+
107
+ @staticmethod
108
+ def _rotate_features(x: Tensor) -> Tensor:
109
+ x1, x2 = x.chunk(2, dim=-1)
110
+ return torch.cat((-x2, x1), dim=-1)
111
+
112
+ def _apply_1d_rope(self, tokens, positions, cos_comp, sin_comp):
113
+ cos = F.embedding(positions, cos_comp)[:, None, :, :]
114
+ sin = F.embedding(positions, sin_comp)[:, None, :, :]
115
+ return (tokens * cos) + (self._rotate_features(tokens) * sin)
116
+
117
+ def forward(self, tokens: Tensor, positions: Tensor) -> Tensor:
118
+ """tokens: (B, heads, N, C); positions: (B, N, 2) integer (y, x)."""
119
+ feature_dim = tokens.size(-1) // 2
120
+ max_position = int(positions.max()) + 1
121
+ cos_comp, sin_comp = self._compute_frequency_components(feature_dim, max_position, tokens.device, tokens.dtype)
122
+ vertical, horizontal = tokens.chunk(2, dim=-1)
123
+ vertical = self._apply_1d_rope(vertical, positions[..., 0], cos_comp, sin_comp)
124
+ horizontal = self._apply_1d_rope(horizontal, positions[..., 1], cos_comp, sin_comp)
125
+ return torch.cat((vertical, horizontal), dim=-1)
126
+
127
+
128
+ # --------------------------------------------------------------------------------------
129
+ # Attention
130
+ # --------------------------------------------------------------------------------------
131
+
132
+ class Attention(nn.Module):
133
+ def __init__(self, dim: int, num_heads: int, qkv_bias: bool = True, qk_norm: bool = False, rope=None) -> None:
134
+ super().__init__()
135
+ self.num_heads = num_heads
136
+ head_dim = dim // num_heads
137
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
138
+ self.q_norm = nn.LayerNorm(head_dim) if qk_norm else nn.Identity()
139
+ self.k_norm = nn.LayerNorm(head_dim) if qk_norm else nn.Identity()
140
+ self.proj = nn.Linear(dim, dim)
141
+ self.rope = rope
142
+
143
+ def forward(self, x: Tensor, pos: Optional[Tensor] = None) -> Tensor:
144
+ B, N, C = x.shape
145
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
146
+ q, k, v = qkv[0], qkv[1], qkv[2]
147
+ q, k = self.q_norm(q), self.k_norm(k)
148
+ if self.rope is not None and pos is not None:
149
+ q = self.rope(q, pos)
150
+ k = self.rope(k, pos)
151
+ x = F.scaled_dot_product_attention(q, k, v)
152
+ x = x.transpose(1, 2).reshape(B, N, C)
153
+ return self.proj(x)
154
+
155
+
156
+ class CrossAttention(nn.Module):
157
+ def __init__(self, dim: int, num_heads: int, qkv_bias: bool = True, qk_norm: bool = False) -> None:
158
+ super().__init__()
159
+ self.num_heads = num_heads
160
+ self.head_dim = dim // num_heads
161
+ self.toq = nn.Linear(dim, dim, bias=qkv_bias)
162
+ self.tok = nn.Linear(dim, dim, bias=qkv_bias)
163
+ self.tov = nn.Linear(dim, dim, bias=qkv_bias)
164
+ self.q_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity()
165
+ self.k_norm = nn.LayerNorm(self.head_dim) if qk_norm else nn.Identity()
166
+ self.proj = nn.Linear(dim, dim)
167
+
168
+ def forward(self, x: Tensor, y: Tensor) -> Tensor:
169
+ B, Nx, C = x.shape
170
+ Ny = y.shape[1]
171
+ q = self.toq(x).reshape(B, Nx, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
172
+ k = self.tok(y).reshape(B, Ny, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
173
+ v = self.tov(y).reshape(B, Ny, self.num_heads, self.head_dim).permute(0, 2, 1, 3)
174
+ q, k = self.q_norm(q), self.k_norm(k)
175
+ x = F.scaled_dot_product_attention(q, k, v)
176
+ x = x.transpose(1, 2).reshape(B, Nx, C)
177
+ return self.proj(x)
178
+
179
+
180
+ # --------------------------------------------------------------------------------------
181
+ # Transformer blocks
182
+ # --------------------------------------------------------------------------------------
183
+
184
+ class Block(nn.Module):
185
+ """Pre-norm self-attention block with LayerScale (DINOv2)."""
186
+
187
+ def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, ffn_layer=Mlp, init_values=None,
188
+ qk_norm: bool = False, rope=None, ln_eps: float = 1e-5) -> None:
189
+ super().__init__()
190
+ self.norm1 = nn.LayerNorm(dim, eps=ln_eps)
191
+ self.attn = Attention(dim, num_heads=num_heads, qk_norm=qk_norm, rope=rope)
192
+ self.ls1 = LayerScale(dim, init_values) if init_values else nn.Identity()
193
+ self.norm2 = nn.LayerNorm(dim, eps=ln_eps)
194
+ self.mlp = ffn_layer(dim, int(dim * mlp_ratio))
195
+ self.ls2 = LayerScale(dim, init_values) if init_values else nn.Identity()
196
+
197
+ def forward(self, x: Tensor, pos: Optional[Tensor] = None) -> Tensor:
198
+ x = x + self.ls1(self.attn(self.norm1(x), pos=pos))
199
+ x = x + self.ls2(self.mlp(self.norm2(x)))
200
+ return x
201
+
202
+
203
+ def modulate(x: Tensor, shift: Tensor, scale: Tensor) -> Tensor:
204
+ return x * (1 + scale.unsqueeze(-2)) + shift.unsqueeze(-2)
205
+
206
+
207
+ class AdaLNBlock(nn.Module):
208
+ """Self-attention block whose LayerNorms are modulated by a condition vector (DiT-style adaLN-Zero)."""
209
+
210
+ def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, qk_norm: bool = False) -> None:
211
+ super().__init__()
212
+ self.norm1 = nn.LayerNorm(dim)
213
+ self.attn = Attention(dim, num_heads=num_heads, qk_norm=qk_norm)
214
+ self.norm2 = nn.LayerNorm(dim)
215
+ self.mlp = Mlp(dim, int(dim * mlp_ratio))
216
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True))
217
+ nn.init.zeros_(self.adaLN_modulation[-1].weight)
218
+ nn.init.zeros_(self.adaLN_modulation[-1].bias)
219
+
220
+ def forward(self, x: Tensor, cond: Tensor) -> Tensor:
221
+ """x: (B, N, C); cond: (B, C)."""
222
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(cond).chunk(6, dim=-1)
223
+ x = x + gate_msa.unsqueeze(-2) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa))
224
+ x = x + gate_mlp.unsqueeze(-2) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
225
+ return x
226
+
227
+
228
+ class CrossBlock(nn.Module):
229
+ """Pre-norm cross-attention block: tokens `x` attend to tokens `y`."""
230
+
231
+ def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, init_values: float = 0.01,
232
+ qk_norm: bool = False) -> None:
233
+ super().__init__()
234
+ self.norm1 = nn.LayerNorm(dim)
235
+ self.normy = nn.LayerNorm(dim)
236
+ self.attn = CrossAttention(dim, num_heads=num_heads, qk_norm=qk_norm)
237
+ self.ls1 = LayerScale(dim, init_values)
238
+ self.norm2 = nn.LayerNorm(dim)
239
+ self.mlp = Mlp(dim, int(dim * mlp_ratio))
240
+ self.ls2 = LayerScale(dim, init_values)
241
+
242
+ def forward(self, x: Tensor, y: Tensor) -> Tensor:
243
+ x = x + self.ls1(self.attn(self.norm1(x), self.normy(y)))
244
+ x = x + self.ls2(self.mlp(self.norm2(x)))
245
+ return x
flow4rt/model/motion_blocks.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Motion blocks: map the tokens of a source view toward a target view (its viewpoint and time).
2
+ #
3
+ # Adapted from the MotionDecoder of 4RC (https://github.com/Luo-Yihang/4RC, S-Lab License 1.0).
4
+ #
5
+ # Changes w.r.t. 4RC: the blocks operate on all geometry tokens (cls, time, patches) rather than
6
+ # on patches only, have no positional embedding, are conditioned (AdaLN) on the time token of the
7
+ # target view, and are split into groups, one per read-out layer of the geometry blocks. Both
8
+ # directions of every (source, target) pair are evaluated in one batch.
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from torch.utils.checkpoint import checkpoint
13
+
14
+ from .layers import AdaLNBlock, CrossBlock
15
+
16
+
17
+ class MotionBlock(nn.Module):
18
+ """Cross-attention from the source tokens to the target tokens, then self-attention with
19
+ AdaLN modulated by the target's time token."""
20
+
21
+ def __init__(self, dim: int, num_heads: int, mlp_ratio: float = 4.0, init_values: float = 0.01):
22
+ super().__init__()
23
+ self.cross_attn = CrossBlock(dim, num_heads, mlp_ratio=mlp_ratio, init_values=init_values, qk_norm=True)
24
+ self.self_attn = AdaLNBlock(dim, num_heads, mlp_ratio=mlp_ratio, qk_norm=True)
25
+
26
+ def forward(self, src: torch.Tensor, tgt: torch.Tensor, time_cond: torch.Tensor) -> torch.Tensor:
27
+ if self.training:
28
+ src = checkpoint(self.cross_attn, src, tgt, use_reentrant=False)
29
+ return checkpoint(self.self_attn, src, time_cond, use_reentrant=False)
30
+ return self.self_attn(self.cross_attn(src, tgt), time_cond)
31
+
32
+
33
+ class MotionBlocks(nn.ModuleList):
34
+ """`depth` motion blocks, `depth // num_levels` per read-out layer.
35
+
36
+ Given the tokens of S views and the target of each view, returns tokens for 2S queries:
37
+ [ view i toward target_idx[i] ] for i in 0..S-1, then
38
+ [ view target_idx[i] toward i ] for i in 0..S-1.
39
+ """
40
+
41
+ def __init__(self, dim: int = 1536, depth: int = 8, num_heads: int = 16, mlp_ratio: float = 4.0,
42
+ init_values: float = 0.01, num_levels: int = 4):
43
+ assert depth % num_levels == 0
44
+ super().__init__([MotionBlock(dim, num_heads, mlp_ratio, init_values) for _ in range(depth)])
45
+ self.blocks_per_level = depth // num_levels
46
+
47
+ def forward(self, tokens: torch.Tensor, target_idx: torch.Tensor, level: int,
48
+ patch_start_idx: int = 2) -> torch.Tensor:
49
+ """
50
+ Args:
51
+ tokens: (B, S, N, C) geometry tokens [cls, time, patches...] of one read-out layer.
52
+ target_idx: (B, S) long, the target view of each view.
53
+ level: index of the read-out layer.
54
+ Returns:
55
+ (B*2S, P, C) motion tokens of the patches.
56
+ """
57
+ B, S, N, C = tokens.shape
58
+ tokens_tgt = torch.gather(tokens, dim=1, index=target_idx[:, :, None, None].expand(-1, -1, N, C))
59
+ src = torch.cat([tokens, tokens_tgt], dim=1).flatten(0, 1) # (B*2S, N, C) the views to move
60
+ tgt = torch.cat([tokens_tgt, tokens], dim=1) # (B, 2S, N, C) the views to move toward
61
+ time_cond = tgt[:, :, patch_start_idx - 1].flatten(0, 1) # time token of the target, (B*2S, C)
62
+ tgt = tgt.flatten(0, 1)
63
+
64
+ for i in range(self.blocks_per_level * level, self.blocks_per_level * (level + 1)):
65
+ src = self[i](src, tgt, time_cond)
66
+ return src[:, patch_start_idx:].contiguous()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ numpy
3
+ einops
4
+ safetensors
5
+ huggingface_hub
6
+ opencv-python-headless
7
+ pillow
8
+ spaces
viewer/template.html ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <!-- Flow4RT 4D viewer, written by visualize.py; styles follow the project page. -->
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="utf-8">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7
+ <title>{{TITLE}} · Flow4RT</title>
8
+ <style>
9
+ :root {
10
+ --text: #1d232c; --ink: #14181f; --text-soft: #586272; --line: #e2e7ee; --line-strong: #cfd7e2;
11
+ --accent: #1a73e8; --accent-ink: #0f57b8; --accent-soft: #e8f0fe; --track: #e9edf3;
12
+ --shadow: 0 1px 2px rgba(16, 24, 40, .05), 0 6px 20px rgba(16, 24, 40, .06);
13
+ --radius: 14px; --ctl: 36px; --ctl-sm: 30px;
14
+ --ring: 0 0 0 3px rgba(26, 115, 232, .28);
15
+ --ease: .16s cubic-bezier(.2, .7, .3, 1);
16
+ }
17
+ * { box-sizing: border-box; }
18
+ body { margin: 0; background: #fff; color: var(--text); -webkit-font-smoothing: antialiased;
19
+ font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
20
+ button { font: inherit; }
21
+ :is(button, input):focus { outline: none; }
22
+ button:focus-visible { box-shadow: var(--ring); }
23
+ img { max-width: 100%; display: block; }
24
+
25
+ .btn { display: inline-flex; align-items: center; height: var(--ctl-sm); padding: 0 13px; border-radius: 999px; cursor: pointer;
26
+ background: #fff; color: var(--ink); border: 1px solid var(--line-strong); font-size: .85rem; font-weight: 500; white-space: nowrap;
27
+ transition: background var(--ease), border-color var(--ease), color var(--ease); }
28
+ .btn:hover { background: var(--accent-soft); color: var(--accent-ink); border-color: #bcd3f8; }
29
+ .icon-btn { flex: none; width: var(--ctl); height: var(--ctl); border-radius: 50%; padding: 0; cursor: pointer;
30
+ display: inline-flex; align-items: center; justify-content: center; background: var(--accent); color: #fff; border: 1px solid var(--accent);
31
+ transition: background var(--ease), transform var(--ease); }
32
+ .icon-btn:hover { background: var(--accent-ink); }
33
+ .icon-btn:active { transform: scale(.94); }
34
+ .icon-btn svg { width: 16px; height: 16px; }
35
+
36
+ /* Sliders: a thin track filled up to the thumb (--p, kept by the script at the end). */
37
+ input[type=range] { -webkit-appearance: none; appearance: none; height: 20px; margin: 0; background: transparent; cursor: pointer; --p: 0%; }
38
+ input[type=range]::-webkit-slider-runnable-track { height: 4px; border-radius: 999px;
39
+ background: linear-gradient(to right, var(--accent) var(--p), var(--track) var(--p)); }
40
+ input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; margin-top: -5px; border-radius: 50%;
41
+ background: #fff; border: 2px solid var(--accent); box-shadow: 0 1px 3px rgba(16, 24, 40, .2); }
42
+ input[type=range]::-moz-range-track { height: 4px; border-radius: 999px; background: var(--track); }
43
+ input[type=range]::-moz-range-progress { height: 4px; border-radius: 999px; background: var(--accent); }
44
+ input[type=range]::-moz-range-thumb { width: 10px; height: 10px; border-radius: 50%; background: #fff; border: 2px solid var(--accent); }
45
+
46
+ .seg { display: inline-flex; gap: 2px; padding: 3px; border-radius: 999px; background: var(--track); }
47
+ .seg button { border: 0; background: transparent; color: var(--text-soft); font-weight: 500; font-size: .85rem; line-height: 1;
48
+ height: calc(var(--ctl-sm) - 6px); padding: 0 13px; border-radius: 999px; cursor: pointer; white-space: nowrap;
49
+ transition: background var(--ease), color var(--ease); }
50
+ .seg button:hover { color: var(--ink); }
51
+ .seg button.on { background: var(--accent); color: #fff; font-weight: 600;
52
+ box-shadow: 0 1px 2px rgba(15, 87, 184, .35), 0 2px 8px rgba(26, 115, 232, .28); }
53
+ .ctl { display: flex; align-items: center; gap: 8px; font-size: .85rem; }
54
+ .ctl > .lab { color: var(--text-soft); font-weight: 500; white-space: nowrap; }
55
+ .ctl input[type=range] { width: 110px; }
56
+ .ctl .val { min-width: 34px; color: var(--text-soft); font-variant-numeric: tabular-nums; }
57
+ /* On / off options as chips. */
58
+ .check { display: inline-flex; gap: 7px; align-items: center; height: var(--ctl-sm); padding: 0 13px 0 9px; border-radius: 999px;
59
+ border: 1px solid var(--line-strong); background: #fff; color: var(--text-soft); font-size: .85rem; font-weight: 500;
60
+ cursor: pointer; user-select: none; transition: background var(--ease), border-color var(--ease), color var(--ease); }
61
+ .check:hover { color: var(--ink); }
62
+ .check input { -webkit-appearance: none; appearance: none; flex: none; width: 14px; height: 14px; margin: 0; border-radius: 50%;
63
+ border: 1.5px solid #b3bdcb; background: #fff center / 10px no-repeat; cursor: inherit; }
64
+ .check input:checked { border-color: var(--accent); background-color: var(--accent);
65
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2.5 6.2l2.4 2.4 4.6-5' fill='none' stroke='white' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); }
66
+ .check:has(input:checked) { background: var(--accent-soft); border-color: #bcd3f8; color: var(--accent-ink); }
67
+ .check.off { opacity: .4; cursor: not-allowed; }
68
+
69
+ .viewer { display: grid; grid-template-columns: minmax(0, 1fr) 260px; gap: 18px; padding: 16px; height: 100vh; }
70
+ .main { display: flex; flex-direction: column; min-height: 0; }
71
+ .canvas-box { position: relative; flex: 1; min-height: 240px; border-radius: var(--radius); overflow: hidden;
72
+ background: #fff; border: 1px solid var(--line); box-shadow: var(--shadow); }
73
+ .canvas-box canvas { width: 100%; height: 100%; display: block; cursor: grab; }
74
+ .canvas-box canvas:active { cursor: grabbing; }
75
+ .overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
76
+ background: rgba(255, 255, 255, .78); color: #333; font-weight: 600; font-size: .95rem; text-align: center; padding: 0 20px; }
77
+ .overlay .spin { width: 22px; height: 22px; border: 3px solid #d3dae3; border-top-color: var(--accent); border-radius: 50%;
78
+ animation: spin .8s linear infinite; margin-right: 10px; flex: none; }
79
+ @keyframes spin { to { transform: rotate(360deg); } }
80
+ .hint { position: absolute; bottom: 8px; right: 12px; font-size: .75rem; color: #7b8594; pointer-events: none; }
81
+ .timeline { display: flex; align-items: center; gap: 12px; margin-top: 12px; }
82
+ .timeline input[type=range] { flex: 1; }
83
+ .tlabel { min-width: 70px; text-align: right; font-size: .8rem; color: var(--text-soft); font-variant-numeric: tabular-nums; }
84
+ .controls { display: flex; flex-wrap: wrap; gap: 12px 22px; align-items: center; margin-top: 14px; }
85
+ .side { display: flex; flex-direction: column; gap: 12px; overflow-y: auto; }
86
+ .side figure { margin: 0; }
87
+ .side figcaption { font-size: .78rem; color: var(--text-soft); margin-bottom: 3px; }
88
+ .imgbox { position: relative; border-radius: 8px; overflow: hidden; border: 1px solid var(--line); background: #000; }
89
+ .imgbox img { width: 100%; }
90
+ .imgbox canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
91
+ .scene-title { font-weight: 700; font-size: 1.05rem; color: var(--ink); }
92
+ .scene-sub { color: var(--text-soft); font-size: .85rem; }
93
+ @media (max-width: 900px) {
94
+ .viewer { grid-template-columns: minmax(0, 1fr); height: auto; }
95
+ .canvas-box { flex: none; aspect-ratio: 4 / 3; }
96
+ .side { display: grid; grid-template-columns: 1fr 1fr; }
97
+ }
98
+ </style>
99
+ </head>
100
+ <body>
101
+ <div class="viewer">
102
+ <div class="main">
103
+ <div class="canvas-box">
104
+ <canvas class="gl"></canvas>
105
+ <div class="overlay"><div class="spin"></div>Loading…</div>
106
+ <span class="hint">drag: orbit · scroll: zoom · right-drag: pan</span>
107
+ </div>
108
+ <div class="timeline">
109
+ <button class="icon-btn playbtn" aria-label="Pause"></button>
110
+ <input type="range" min="0" max="1" value="0" aria-label="Frame">
111
+ <span class="tlabel"></span>
112
+ </div>
113
+ <div class="controls">
114
+ <div class="seg seg-mode"><button data-v="track">Tracking</button><button data-v="recon">Reconstruction</button></div>
115
+ <label class="ctl"><span class="lab">Confidence ≥</span><input type="range" id="opt-conf" min="0" max="90" step="5" value="20"><span class="val"></span></label>
116
+ <label class="ctl"><span class="lab">Point size</span><input type="range" id="opt-size" min="0.3" max="2.5" step="0.05" value="1"></label>
117
+ <button class="btn reset">Reset view</button>
118
+ <label class="check"><input type="checkbox" id="opt-trails" checked> Tracks</label>
119
+ <label class="check"><input type="checkbox" id="opt-moving" checked> Dynamic only</label>
120
+ <label class="check"><input type="checkbox" id="opt-current" checked> Current frame</label>
121
+ <label class="check"><input type="checkbox" id="opt-accum"> Accumulate frames</label>
122
+ <label class="check"><input type="checkbox" id="opt-cams" checked> Cameras</label>
123
+ </div>
124
+ </div>
125
+ <aside class="side">
126
+ <div><div class="scene-title">{{TITLE}}</div><div class="scene-sub"></div></div>
127
+ <figure class="frame0"><figcaption>Anchor frame · track queries</figcaption><div class="imgbox"><img alt="Anchor frame"><canvas></canvas></div></figure>
128
+ <figure class="framet"><figcaption>Frame 1</figcaption><div class="imgbox"><img alt="Current frame"></div></figure>
129
+ </aside>
130
+ </div>
131
+ <script>window.F4RT = { parts: [], add(p) { this.parts.push(p); } };</script>
132
+ {{SCRIPTS}}
133
+ </body>
134
+ </html>
viewer/vendor/LineMaterial.js ADDED
@@ -0,0 +1,640 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * three.js r147, examples/js/lines/LineMaterial.js
3
+ * Copyright 2010-2022 Three.js Authors
4
+ * SPDX-License-Identifier: MIT
5
+ */
6
+ ( function () {
7
+
8
+ /**
9
+ * parameters = {
10
+ * color: <hex>,
11
+ * linewidth: <float>,
12
+ * dashed: <boolean>,
13
+ * dashScale: <float>,
14
+ * dashSize: <float>,
15
+ * dashOffset: <float>,
16
+ * gapSize: <float>,
17
+ * resolution: <Vector2>, // to be set by renderer
18
+ * }
19
+ */
20
+ THREE.UniformsLib.line = {
21
+ worldUnits: {
22
+ value: 1
23
+ },
24
+ linewidth: {
25
+ value: 1
26
+ },
27
+ resolution: {
28
+ value: new THREE.Vector2( 1, 1 )
29
+ },
30
+ dashOffset: {
31
+ value: 0
32
+ },
33
+ dashScale: {
34
+ value: 1
35
+ },
36
+ dashSize: {
37
+ value: 1
38
+ },
39
+ gapSize: {
40
+ value: 1
41
+ } // todo FIX - maybe change to totalSize
42
+ };
43
+
44
+ THREE.ShaderLib[ 'line' ] = {
45
+ uniforms: THREE.UniformsUtils.merge( [ THREE.UniformsLib.common, THREE.UniformsLib.fog, THREE.UniformsLib.line ] ),
46
+ vertexShader: /* glsl */`
47
+ #include <common>
48
+ #include <color_pars_vertex>
49
+ #include <fog_pars_vertex>
50
+ #include <logdepthbuf_pars_vertex>
51
+ #include <clipping_planes_pars_vertex>
52
+
53
+ uniform float linewidth;
54
+ uniform vec2 resolution;
55
+
56
+ attribute vec3 instanceStart;
57
+ attribute vec3 instanceEnd;
58
+
59
+ attribute vec3 instanceColorStart;
60
+ attribute vec3 instanceColorEnd;
61
+
62
+ #ifdef WORLD_UNITS
63
+
64
+ varying vec4 worldPos;
65
+ varying vec3 worldStart;
66
+ varying vec3 worldEnd;
67
+
68
+ #ifdef USE_DASH
69
+
70
+ varying vec2 vUv;
71
+
72
+ #endif
73
+
74
+ #else
75
+
76
+ varying vec2 vUv;
77
+
78
+ #endif
79
+
80
+ #ifdef USE_DASH
81
+
82
+ uniform float dashScale;
83
+ attribute float instanceDistanceStart;
84
+ attribute float instanceDistanceEnd;
85
+ varying float vLineDistance;
86
+
87
+ #endif
88
+
89
+ void trimSegment( const in vec4 start, inout vec4 end ) {
90
+
91
+ // trim end segment so it terminates between the camera plane and the near plane
92
+
93
+ // conservative estimate of the near plane
94
+ float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
95
+ float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
96
+ float nearEstimate = - 0.5 * b / a;
97
+
98
+ float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
99
+
100
+ end.xyz = mix( start.xyz, end.xyz, alpha );
101
+
102
+ }
103
+
104
+ void main() {
105
+
106
+ #ifdef USE_COLOR
107
+
108
+ vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
109
+
110
+ #endif
111
+
112
+ #ifdef USE_DASH
113
+
114
+ vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
115
+ vUv = uv;
116
+
117
+ #endif
118
+
119
+ float aspect = resolution.x / resolution.y;
120
+
121
+ // camera space
122
+ vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
123
+ vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
124
+
125
+ #ifdef WORLD_UNITS
126
+
127
+ worldStart = start.xyz;
128
+ worldEnd = end.xyz;
129
+
130
+ #else
131
+
132
+ vUv = uv;
133
+
134
+ #endif
135
+
136
+ // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
137
+ // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
138
+ // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
139
+ // perhaps there is a more elegant solution -- WestLangley
140
+
141
+ bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
142
+
143
+ if ( perspective ) {
144
+
145
+ if ( start.z < 0.0 && end.z >= 0.0 ) {
146
+
147
+ trimSegment( start, end );
148
+
149
+ } else if ( end.z < 0.0 && start.z >= 0.0 ) {
150
+
151
+ trimSegment( end, start );
152
+
153
+ }
154
+
155
+ }
156
+
157
+ // clip space
158
+ vec4 clipStart = projectionMatrix * start;
159
+ vec4 clipEnd = projectionMatrix * end;
160
+
161
+ // ndc space
162
+ vec3 ndcStart = clipStart.xyz / clipStart.w;
163
+ vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
164
+
165
+ // direction
166
+ vec2 dir = ndcEnd.xy - ndcStart.xy;
167
+
168
+ // account for clip-space aspect ratio
169
+ dir.x *= aspect;
170
+ dir = normalize( dir );
171
+
172
+ #ifdef WORLD_UNITS
173
+
174
+ // get the offset direction as perpendicular to the view vector
175
+ vec3 worldDir = normalize( end.xyz - start.xyz );
176
+ vec3 offset;
177
+ if ( position.y < 0.5 ) {
178
+
179
+ offset = normalize( cross( start.xyz, worldDir ) );
180
+
181
+ } else {
182
+
183
+ offset = normalize( cross( end.xyz, worldDir ) );
184
+
185
+ }
186
+
187
+ // sign flip
188
+ if ( position.x < 0.0 ) offset *= - 1.0;
189
+
190
+ float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
191
+
192
+ // don't extend the line if we're rendering dashes because we
193
+ // won't be rendering the endcaps
194
+ #ifndef USE_DASH
195
+
196
+ // extend the line bounds to encompass endcaps
197
+ start.xyz += - worldDir * linewidth * 0.5;
198
+ end.xyz += worldDir * linewidth * 0.5;
199
+
200
+ // shift the position of the quad so it hugs the forward edge of the line
201
+ offset.xy -= dir * forwardOffset;
202
+ offset.z += 0.5;
203
+
204
+ #endif
205
+
206
+ // endcaps
207
+ if ( position.y > 1.0 || position.y < 0.0 ) {
208
+
209
+ offset.xy += dir * 2.0 * forwardOffset;
210
+
211
+ }
212
+
213
+ // adjust for linewidth
214
+ offset *= linewidth * 0.5;
215
+
216
+ // set the world position
217
+ worldPos = ( position.y < 0.5 ) ? start : end;
218
+ worldPos.xyz += offset;
219
+
220
+ // project the worldpos
221
+ vec4 clip = projectionMatrix * worldPos;
222
+
223
+ // shift the depth of the projected points so the line
224
+ // segments overlap neatly
225
+ vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
226
+ clip.z = clipPose.z * clip.w;
227
+
228
+ #else
229
+
230
+ vec2 offset = vec2( dir.y, - dir.x );
231
+ // undo aspect ratio adjustment
232
+ dir.x /= aspect;
233
+ offset.x /= aspect;
234
+
235
+ // sign flip
236
+ if ( position.x < 0.0 ) offset *= - 1.0;
237
+
238
+ // endcaps
239
+ if ( position.y < 0.0 ) {
240
+
241
+ offset += - dir;
242
+
243
+ } else if ( position.y > 1.0 ) {
244
+
245
+ offset += dir;
246
+
247
+ }
248
+
249
+ // adjust for linewidth
250
+ offset *= linewidth;
251
+
252
+ // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
253
+ offset /= resolution.y;
254
+
255
+ // select end
256
+ vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
257
+
258
+ // back to clip space
259
+ offset *= clip.w;
260
+
261
+ clip.xy += offset;
262
+
263
+ #endif
264
+
265
+ gl_Position = clip;
266
+
267
+ vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
268
+
269
+ #include <logdepthbuf_vertex>
270
+ #include <clipping_planes_vertex>
271
+ #include <fog_vertex>
272
+
273
+ }
274
+ `,
275
+ fragmentShader: /* glsl */`
276
+ uniform vec3 diffuse;
277
+ uniform float opacity;
278
+ uniform float linewidth;
279
+
280
+ #ifdef USE_DASH
281
+
282
+ uniform float dashOffset;
283
+ uniform float dashSize;
284
+ uniform float gapSize;
285
+
286
+ #endif
287
+
288
+ varying float vLineDistance;
289
+
290
+ #ifdef WORLD_UNITS
291
+
292
+ varying vec4 worldPos;
293
+ varying vec3 worldStart;
294
+ varying vec3 worldEnd;
295
+
296
+ #ifdef USE_DASH
297
+
298
+ varying vec2 vUv;
299
+
300
+ #endif
301
+
302
+ #else
303
+
304
+ varying vec2 vUv;
305
+
306
+ #endif
307
+
308
+ #include <common>
309
+ #include <color_pars_fragment>
310
+ #include <fog_pars_fragment>
311
+ #include <logdepthbuf_pars_fragment>
312
+ #include <clipping_planes_pars_fragment>
313
+
314
+ vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
315
+
316
+ float mua;
317
+ float mub;
318
+
319
+ vec3 p13 = p1 - p3;
320
+ vec3 p43 = p4 - p3;
321
+
322
+ vec3 p21 = p2 - p1;
323
+
324
+ float d1343 = dot( p13, p43 );
325
+ float d4321 = dot( p43, p21 );
326
+ float d1321 = dot( p13, p21 );
327
+ float d4343 = dot( p43, p43 );
328
+ float d2121 = dot( p21, p21 );
329
+
330
+ float denom = d2121 * d4343 - d4321 * d4321;
331
+
332
+ float numer = d1343 * d4321 - d1321 * d4343;
333
+
334
+ mua = numer / denom;
335
+ mua = clamp( mua, 0.0, 1.0 );
336
+ mub = ( d1343 + d4321 * ( mua ) ) / d4343;
337
+ mub = clamp( mub, 0.0, 1.0 );
338
+
339
+ return vec2( mua, mub );
340
+
341
+ }
342
+
343
+ void main() {
344
+
345
+ #include <clipping_planes_fragment>
346
+
347
+ #ifdef USE_DASH
348
+
349
+ if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
350
+
351
+ if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
352
+
353
+ #endif
354
+
355
+ float alpha = opacity;
356
+
357
+ #ifdef WORLD_UNITS
358
+
359
+ // Find the closest points on the view ray and the line segment
360
+ vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
361
+ vec3 lineDir = worldEnd - worldStart;
362
+ vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
363
+
364
+ vec3 p1 = worldStart + lineDir * params.x;
365
+ vec3 p2 = rayEnd * params.y;
366
+ vec3 delta = p1 - p2;
367
+ float len = length( delta );
368
+ float norm = len / linewidth;
369
+
370
+ #ifndef USE_DASH
371
+
372
+ #ifdef USE_ALPHA_TO_COVERAGE
373
+
374
+ float dnorm = fwidth( norm );
375
+ alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
376
+
377
+ #else
378
+
379
+ if ( norm > 0.5 ) {
380
+
381
+ discard;
382
+
383
+ }
384
+
385
+ #endif
386
+
387
+ #endif
388
+
389
+ #else
390
+
391
+ #ifdef USE_ALPHA_TO_COVERAGE
392
+
393
+ // artifacts appear on some hardware if a derivative is taken within a conditional
394
+ float a = vUv.x;
395
+ float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
396
+ float len2 = a * a + b * b;
397
+ float dlen = fwidth( len2 );
398
+
399
+ if ( abs( vUv.y ) > 1.0 ) {
400
+
401
+ alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
402
+
403
+ }
404
+
405
+ #else
406
+
407
+ if ( abs( vUv.y ) > 1.0 ) {
408
+
409
+ float a = vUv.x;
410
+ float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
411
+ float len2 = a * a + b * b;
412
+
413
+ if ( len2 > 1.0 ) discard;
414
+
415
+ }
416
+
417
+ #endif
418
+
419
+ #endif
420
+
421
+ vec4 diffuseColor = vec4( diffuse, alpha );
422
+
423
+ #include <logdepthbuf_fragment>
424
+ #include <color_fragment>
425
+
426
+ gl_FragColor = vec4( diffuseColor.rgb, alpha );
427
+
428
+ #include <tonemapping_fragment>
429
+ #include <encodings_fragment>
430
+ #include <fog_fragment>
431
+ #include <premultiplied_alpha_fragment>
432
+
433
+ }
434
+ `
435
+ };
436
+ class LineMaterial extends THREE.ShaderMaterial {
437
+
438
+ constructor( parameters ) {
439
+
440
+ super( {
441
+ type: 'LineMaterial',
442
+ uniforms: THREE.UniformsUtils.clone( THREE.ShaderLib[ 'line' ].uniforms ),
443
+ vertexShader: THREE.ShaderLib[ 'line' ].vertexShader,
444
+ fragmentShader: THREE.ShaderLib[ 'line' ].fragmentShader,
445
+ clipping: true // required for clipping support
446
+ } );
447
+
448
+ this.isLineMaterial = true;
449
+ Object.defineProperties( this, {
450
+ color: {
451
+ enumerable: true,
452
+ get: function () {
453
+
454
+ return this.uniforms.diffuse.value;
455
+
456
+ },
457
+ set: function ( value ) {
458
+
459
+ this.uniforms.diffuse.value = value;
460
+
461
+ }
462
+ },
463
+ worldUnits: {
464
+ enumerable: true,
465
+ get: function () {
466
+
467
+ return 'WORLD_UNITS' in this.defines;
468
+
469
+ },
470
+ set: function ( value ) {
471
+
472
+ if ( value === true ) {
473
+
474
+ this.defines.WORLD_UNITS = '';
475
+
476
+ } else {
477
+
478
+ delete this.defines.WORLD_UNITS;
479
+
480
+ }
481
+
482
+ }
483
+ },
484
+ linewidth: {
485
+ enumerable: true,
486
+ get: function () {
487
+
488
+ return this.uniforms.linewidth.value;
489
+
490
+ },
491
+ set: function ( value ) {
492
+
493
+ this.uniforms.linewidth.value = value;
494
+
495
+ }
496
+ },
497
+ dashed: {
498
+ enumerable: true,
499
+ get: function () {
500
+
501
+ return Boolean( 'USE_DASH' in this.defines );
502
+
503
+ },
504
+ set( value ) {
505
+
506
+ if ( Boolean( value ) !== Boolean( 'USE_DASH' in this.defines ) ) {
507
+
508
+ this.needsUpdate = true;
509
+
510
+ }
511
+
512
+ if ( value === true ) {
513
+
514
+ this.defines.USE_DASH = '';
515
+
516
+ } else {
517
+
518
+ delete this.defines.USE_DASH;
519
+
520
+ }
521
+
522
+ }
523
+ },
524
+ dashScale: {
525
+ enumerable: true,
526
+ get: function () {
527
+
528
+ return this.uniforms.dashScale.value;
529
+
530
+ },
531
+ set: function ( value ) {
532
+
533
+ this.uniforms.dashScale.value = value;
534
+
535
+ }
536
+ },
537
+ dashSize: {
538
+ enumerable: true,
539
+ get: function () {
540
+
541
+ return this.uniforms.dashSize.value;
542
+
543
+ },
544
+ set: function ( value ) {
545
+
546
+ this.uniforms.dashSize.value = value;
547
+
548
+ }
549
+ },
550
+ dashOffset: {
551
+ enumerable: true,
552
+ get: function () {
553
+
554
+ return this.uniforms.dashOffset.value;
555
+
556
+ },
557
+ set: function ( value ) {
558
+
559
+ this.uniforms.dashOffset.value = value;
560
+
561
+ }
562
+ },
563
+ gapSize: {
564
+ enumerable: true,
565
+ get: function () {
566
+
567
+ return this.uniforms.gapSize.value;
568
+
569
+ },
570
+ set: function ( value ) {
571
+
572
+ this.uniforms.gapSize.value = value;
573
+
574
+ }
575
+ },
576
+ opacity: {
577
+ enumerable: true,
578
+ get: function () {
579
+
580
+ return this.uniforms.opacity.value;
581
+
582
+ },
583
+ set: function ( value ) {
584
+
585
+ this.uniforms.opacity.value = value;
586
+
587
+ }
588
+ },
589
+ resolution: {
590
+ enumerable: true,
591
+ get: function () {
592
+
593
+ return this.uniforms.resolution.value;
594
+
595
+ },
596
+ set: function ( value ) {
597
+
598
+ this.uniforms.resolution.value.copy( value );
599
+
600
+ }
601
+ },
602
+ alphaToCoverage: {
603
+ enumerable: true,
604
+ get: function () {
605
+
606
+ return Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines );
607
+
608
+ },
609
+ set: function ( value ) {
610
+
611
+ if ( Boolean( value ) !== Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines ) ) {
612
+
613
+ this.needsUpdate = true;
614
+
615
+ }
616
+
617
+ if ( value === true ) {
618
+
619
+ this.defines.USE_ALPHA_TO_COVERAGE = '';
620
+ this.extensions.derivatives = true;
621
+
622
+ } else {
623
+
624
+ delete this.defines.USE_ALPHA_TO_COVERAGE;
625
+ this.extensions.derivatives = false;
626
+
627
+ }
628
+
629
+ }
630
+ }
631
+ } );
632
+ this.setValues( parameters );
633
+
634
+ }
635
+
636
+ }
637
+
638
+ THREE.LineMaterial = LineMaterial;
639
+
640
+ } )();
viewer/vendor/LineSegments2.js ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * three.js r147, examples/js/lines/LineSegments2.js
3
+ * Copyright 2010-2022 Three.js Authors
4
+ * SPDX-License-Identifier: MIT
5
+ */
6
+ ( function () {
7
+
8
+ const _start = new THREE.Vector3();
9
+ const _end = new THREE.Vector3();
10
+ const _start4 = new THREE.Vector4();
11
+ const _end4 = new THREE.Vector4();
12
+ const _ssOrigin = new THREE.Vector4();
13
+ const _ssOrigin3 = new THREE.Vector3();
14
+ const _mvMatrix = new THREE.Matrix4();
15
+ const _line = new THREE.Line3();
16
+ const _closestPoint = new THREE.Vector3();
17
+ const _box = new THREE.Box3();
18
+ const _sphere = new THREE.Sphere();
19
+ const _clipToWorldVector = new THREE.Vector4();
20
+ let _ray, _instanceStart, _instanceEnd, _lineWidth;
21
+
22
+ // Returns the margin required to expand by in world space given the distance from the camera,
23
+ // line width, resolution, and camera projection
24
+ function getWorldSpaceHalfWidth( camera, distance, resolution ) {
25
+
26
+ // transform into clip space, adjust the x and y values by the pixel width offset, then
27
+ // transform back into world space to get world offset. Note clip space is [-1, 1] so full
28
+ // width does not need to be halved.
29
+ _clipToWorldVector.set( 0, 0, - distance, 1.0 ).applyMatrix4( camera.projectionMatrix );
30
+ _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
31
+ _clipToWorldVector.x = _lineWidth / resolution.width;
32
+ _clipToWorldVector.y = _lineWidth / resolution.height;
33
+ _clipToWorldVector.applyMatrix4( camera.projectionMatrixInverse );
34
+ _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
35
+ return Math.abs( Math.max( _clipToWorldVector.x, _clipToWorldVector.y ) );
36
+
37
+ }
38
+
39
+ function raycastWorldUnits( lineSegments, intersects ) {
40
+
41
+ const matrixWorld = lineSegments.matrixWorld;
42
+ for ( let i = 0, l = _instanceStart.count; i < l; i ++ ) {
43
+
44
+ _line.start.fromBufferAttribute( _instanceStart, i );
45
+ _line.end.fromBufferAttribute( _instanceEnd, i );
46
+ _line.applyMatrix4( matrixWorld );
47
+ const pointOnLine = new THREE.Vector3();
48
+ const point = new THREE.Vector3();
49
+ _ray.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
50
+ const isInside = point.distanceTo( pointOnLine ) < _lineWidth * 0.5;
51
+ if ( isInside ) {
52
+
53
+ intersects.push( {
54
+ point,
55
+ pointOnLine,
56
+ distance: _ray.origin.distanceTo( point ),
57
+ object: lineSegments,
58
+ face: null,
59
+ faceIndex: i,
60
+ uv: null,
61
+ uv2: null
62
+ } );
63
+
64
+ }
65
+
66
+ }
67
+
68
+ }
69
+
70
+ function raycastScreenSpace( lineSegments, camera, intersects ) {
71
+
72
+ const projectionMatrix = camera.projectionMatrix;
73
+ const material = lineSegments.material;
74
+ const resolution = material.resolution;
75
+ const matrixWorld = lineSegments.matrixWorld;
76
+ const geometry = lineSegments.geometry;
77
+ const instanceStart = geometry.attributes.instanceStart;
78
+ const instanceEnd = geometry.attributes.instanceEnd;
79
+ const near = - camera.near;
80
+
81
+ //
82
+
83
+ // pick a point 1 unit out along the ray to avoid the ray origin
84
+ // sitting at the camera origin which will cause "w" to be 0 when
85
+ // applying the projection matrix.
86
+ _ray.at( 1, _ssOrigin );
87
+
88
+ // ndc space [ - 1.0, 1.0 ]
89
+ _ssOrigin.w = 1;
90
+ _ssOrigin.applyMatrix4( camera.matrixWorldInverse );
91
+ _ssOrigin.applyMatrix4( projectionMatrix );
92
+ _ssOrigin.multiplyScalar( 1 / _ssOrigin.w );
93
+
94
+ // screen space
95
+ _ssOrigin.x *= resolution.x / 2;
96
+ _ssOrigin.y *= resolution.y / 2;
97
+ _ssOrigin.z = 0;
98
+ _ssOrigin3.copy( _ssOrigin );
99
+ _mvMatrix.multiplyMatrices( camera.matrixWorldInverse, matrixWorld );
100
+ for ( let i = 0, l = instanceStart.count; i < l; i ++ ) {
101
+
102
+ _start4.fromBufferAttribute( instanceStart, i );
103
+ _end4.fromBufferAttribute( instanceEnd, i );
104
+ _start4.w = 1;
105
+ _end4.w = 1;
106
+
107
+ // camera space
108
+ _start4.applyMatrix4( _mvMatrix );
109
+ _end4.applyMatrix4( _mvMatrix );
110
+
111
+ // skip the segment if it's entirely behind the camera
112
+ const isBehindCameraNear = _start4.z > near && _end4.z > near;
113
+ if ( isBehindCameraNear ) {
114
+
115
+ continue;
116
+
117
+ }
118
+
119
+ // trim the segment if it extends behind camera near
120
+ if ( _start4.z > near ) {
121
+
122
+ const deltaDist = _start4.z - _end4.z;
123
+ const t = ( _start4.z - near ) / deltaDist;
124
+ _start4.lerp( _end4, t );
125
+
126
+ } else if ( _end4.z > near ) {
127
+
128
+ const deltaDist = _end4.z - _start4.z;
129
+ const t = ( _end4.z - near ) / deltaDist;
130
+ _end4.lerp( _start4, t );
131
+
132
+ }
133
+
134
+ // clip space
135
+ _start4.applyMatrix4( projectionMatrix );
136
+ _end4.applyMatrix4( projectionMatrix );
137
+
138
+ // ndc space [ - 1.0, 1.0 ]
139
+ _start4.multiplyScalar( 1 / _start4.w );
140
+ _end4.multiplyScalar( 1 / _end4.w );
141
+
142
+ // screen space
143
+ _start4.x *= resolution.x / 2;
144
+ _start4.y *= resolution.y / 2;
145
+ _end4.x *= resolution.x / 2;
146
+ _end4.y *= resolution.y / 2;
147
+
148
+ // create 2d segment
149
+ _line.start.copy( _start4 );
150
+ _line.start.z = 0;
151
+ _line.end.copy( _end4 );
152
+ _line.end.z = 0;
153
+
154
+ // get closest point on ray to segment
155
+ const param = _line.closestPointToPointParameter( _ssOrigin3, true );
156
+ _line.at( param, _closestPoint );
157
+
158
+ // check if the intersection point is within clip space
159
+ const zPos = THREE.MathUtils.lerp( _start4.z, _end4.z, param );
160
+ const isInClipSpace = zPos >= - 1 && zPos <= 1;
161
+ const isInside = _ssOrigin3.distanceTo( _closestPoint ) < _lineWidth * 0.5;
162
+ if ( isInClipSpace && isInside ) {
163
+
164
+ _line.start.fromBufferAttribute( instanceStart, i );
165
+ _line.end.fromBufferAttribute( instanceEnd, i );
166
+ _line.start.applyMatrix4( matrixWorld );
167
+ _line.end.applyMatrix4( matrixWorld );
168
+ const pointOnLine = new THREE.Vector3();
169
+ const point = new THREE.Vector3();
170
+ _ray.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
171
+ intersects.push( {
172
+ point: point,
173
+ pointOnLine: pointOnLine,
174
+ distance: _ray.origin.distanceTo( point ),
175
+ object: lineSegments,
176
+ face: null,
177
+ faceIndex: i,
178
+ uv: null,
179
+ uv2: null
180
+ } );
181
+
182
+ }
183
+
184
+ }
185
+
186
+ }
187
+
188
+ class LineSegments2 extends THREE.Mesh {
189
+
190
+ constructor( geometry = new THREE.LineSegmentsGeometry(), material = new THREE.LineMaterial( {
191
+ color: Math.random() * 0xffffff
192
+ } ) ) {
193
+
194
+ super( geometry, material );
195
+ this.isLineSegments2 = true;
196
+ this.type = 'LineSegments2';
197
+
198
+ }
199
+
200
+ // for backwards-compatibility, but could be a method of THREE.LineSegmentsGeometry...
201
+
202
+ computeLineDistances() {
203
+
204
+ const geometry = this.geometry;
205
+ const instanceStart = geometry.attributes.instanceStart;
206
+ const instanceEnd = geometry.attributes.instanceEnd;
207
+ const lineDistances = new Float32Array( 2 * instanceStart.count );
208
+ for ( let i = 0, j = 0, l = instanceStart.count; i < l; i ++, j += 2 ) {
209
+
210
+ _start.fromBufferAttribute( instanceStart, i );
211
+ _end.fromBufferAttribute( instanceEnd, i );
212
+ lineDistances[ j ] = j === 0 ? 0 : lineDistances[ j - 1 ];
213
+ lineDistances[ j + 1 ] = lineDistances[ j ] + _start.distanceTo( _end );
214
+
215
+ }
216
+
217
+ const instanceDistanceBuffer = new THREE.InstancedInterleavedBuffer( lineDistances, 2, 1 ); // d0, d1
218
+
219
+ geometry.setAttribute( 'instanceDistanceStart', new THREE.InterleavedBufferAttribute( instanceDistanceBuffer, 1, 0 ) ); // d0
220
+ geometry.setAttribute( 'instanceDistanceEnd', new THREE.InterleavedBufferAttribute( instanceDistanceBuffer, 1, 1 ) ); // d1
221
+
222
+ return this;
223
+
224
+ }
225
+ raycast( raycaster, intersects ) {
226
+
227
+ const worldUnits = this.material.worldUnits;
228
+ const camera = raycaster.camera;
229
+ if ( camera === null && ! worldUnits ) {
230
+
231
+ console.error( 'LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.' );
232
+
233
+ }
234
+
235
+ const threshold = raycaster.params.Line2 !== undefined ? raycaster.params.Line2.threshold || 0 : 0;
236
+ _ray = raycaster.ray;
237
+ const matrixWorld = this.matrixWorld;
238
+ const geometry = this.geometry;
239
+ const material = this.material;
240
+ _lineWidth = material.linewidth + threshold;
241
+ _instanceStart = geometry.attributes.instanceStart;
242
+ _instanceEnd = geometry.attributes.instanceEnd;
243
+
244
+ // check if we intersect the sphere bounds
245
+ if ( geometry.boundingSphere === null ) {
246
+
247
+ geometry.computeBoundingSphere();
248
+
249
+ }
250
+
251
+ _sphere.copy( geometry.boundingSphere ).applyMatrix4( matrixWorld );
252
+
253
+ // increase the sphere bounds by the worst case line screen space width
254
+ let sphereMargin;
255
+ if ( worldUnits ) {
256
+
257
+ sphereMargin = _lineWidth * 0.5;
258
+
259
+ } else {
260
+
261
+ const distanceToSphere = Math.max( camera.near, _sphere.distanceToPoint( _ray.origin ) );
262
+ sphereMargin = getWorldSpaceHalfWidth( camera, distanceToSphere, material.resolution );
263
+
264
+ }
265
+
266
+ _sphere.radius += sphereMargin;
267
+ if ( _ray.intersectsSphere( _sphere ) === false ) {
268
+
269
+ return;
270
+
271
+ }
272
+
273
+ // check if we intersect the box bounds
274
+ if ( geometry.boundingBox === null ) {
275
+
276
+ geometry.computeBoundingBox();
277
+
278
+ }
279
+
280
+ _box.copy( geometry.boundingBox ).applyMatrix4( matrixWorld );
281
+
282
+ // increase the box bounds by the worst case line width
283
+ let boxMargin;
284
+ if ( worldUnits ) {
285
+
286
+ boxMargin = _lineWidth * 0.5;
287
+
288
+ } else {
289
+
290
+ const distanceToBox = Math.max( camera.near, _box.distanceToPoint( _ray.origin ) );
291
+ boxMargin = getWorldSpaceHalfWidth( camera, distanceToBox, material.resolution );
292
+
293
+ }
294
+
295
+ _box.expandByScalar( boxMargin );
296
+ if ( _ray.intersectsBox( _box ) === false ) {
297
+
298
+ return;
299
+
300
+ }
301
+
302
+ if ( worldUnits ) {
303
+
304
+ raycastWorldUnits( this, intersects );
305
+
306
+ } else {
307
+
308
+ raycastScreenSpace( this, camera, intersects );
309
+
310
+ }
311
+
312
+ }
313
+
314
+ }
315
+
316
+ THREE.LineSegments2 = LineSegments2;
317
+
318
+ } )();
viewer/vendor/LineSegmentsGeometry.js ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * three.js r147, examples/js/lines/LineSegmentsGeometry.js
3
+ * Copyright 2010-2022 Three.js Authors
4
+ * SPDX-License-Identifier: MIT
5
+ */
6
+ ( function () {
7
+
8
+ const _box = new THREE.Box3();
9
+ const _vector = new THREE.Vector3();
10
+ class LineSegmentsGeometry extends THREE.InstancedBufferGeometry {
11
+
12
+ constructor() {
13
+
14
+ super();
15
+ this.isLineSegmentsGeometry = true;
16
+ this.type = 'LineSegmentsGeometry';
17
+ const positions = [ - 1, 2, 0, 1, 2, 0, - 1, 1, 0, 1, 1, 0, - 1, 0, 0, 1, 0, 0, - 1, - 1, 0, 1, - 1, 0 ];
18
+ const uvs = [ - 1, 2, 1, 2, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 2, 1, - 2 ];
19
+ const index = [ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ];
20
+ this.setIndex( index );
21
+ this.setAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
22
+ this.setAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) );
23
+
24
+ }
25
+ applyMatrix4( matrix ) {
26
+
27
+ const start = this.attributes.instanceStart;
28
+ const end = this.attributes.instanceEnd;
29
+ if ( start !== undefined ) {
30
+
31
+ start.applyMatrix4( matrix );
32
+ end.applyMatrix4( matrix );
33
+ start.needsUpdate = true;
34
+
35
+ }
36
+
37
+ if ( this.boundingBox !== null ) {
38
+
39
+ this.computeBoundingBox();
40
+
41
+ }
42
+
43
+ if ( this.boundingSphere !== null ) {
44
+
45
+ this.computeBoundingSphere();
46
+
47
+ }
48
+
49
+ return this;
50
+
51
+ }
52
+ setPositions( array ) {
53
+
54
+ let lineSegments;
55
+ if ( array instanceof Float32Array ) {
56
+
57
+ lineSegments = array;
58
+
59
+ } else if ( Array.isArray( array ) ) {
60
+
61
+ lineSegments = new Float32Array( array );
62
+
63
+ }
64
+
65
+ const instanceBuffer = new THREE.InstancedInterleavedBuffer( lineSegments, 6, 1 ); // xyz, xyz
66
+
67
+ this.setAttribute( 'instanceStart', new THREE.InterleavedBufferAttribute( instanceBuffer, 3, 0 ) ); // xyz
68
+ this.setAttribute( 'instanceEnd', new THREE.InterleavedBufferAttribute( instanceBuffer, 3, 3 ) ); // xyz
69
+
70
+ //
71
+
72
+ this.computeBoundingBox();
73
+ this.computeBoundingSphere();
74
+ return this;
75
+
76
+ }
77
+ setColors( array ) {
78
+
79
+ let colors;
80
+ if ( array instanceof Float32Array ) {
81
+
82
+ colors = array;
83
+
84
+ } else if ( Array.isArray( array ) ) {
85
+
86
+ colors = new Float32Array( array );
87
+
88
+ }
89
+
90
+ const instanceColorBuffer = new THREE.InstancedInterleavedBuffer( colors, 6, 1 ); // rgb, rgb
91
+
92
+ this.setAttribute( 'instanceColorStart', new THREE.InterleavedBufferAttribute( instanceColorBuffer, 3, 0 ) ); // rgb
93
+ this.setAttribute( 'instanceColorEnd', new THREE.InterleavedBufferAttribute( instanceColorBuffer, 3, 3 ) ); // rgb
94
+
95
+ return this;
96
+
97
+ }
98
+ fromWireframeGeometry( geometry ) {
99
+
100
+ this.setPositions( geometry.attributes.position.array );
101
+ return this;
102
+
103
+ }
104
+ fromEdgesGeometry( geometry ) {
105
+
106
+ this.setPositions( geometry.attributes.position.array );
107
+ return this;
108
+
109
+ }
110
+ fromMesh( mesh ) {
111
+
112
+ this.fromWireframeGeometry( new THREE.WireframeGeometry( mesh.geometry ) );
113
+
114
+ // set colors, maybe
115
+
116
+ return this;
117
+
118
+ }
119
+ fromLineSegments( lineSegments ) {
120
+
121
+ const geometry = lineSegments.geometry;
122
+ this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
123
+
124
+ // set colors, maybe
125
+
126
+ return this;
127
+
128
+ }
129
+ computeBoundingBox() {
130
+
131
+ if ( this.boundingBox === null ) {
132
+
133
+ this.boundingBox = new THREE.Box3();
134
+
135
+ }
136
+
137
+ const start = this.attributes.instanceStart;
138
+ const end = this.attributes.instanceEnd;
139
+ if ( start !== undefined && end !== undefined ) {
140
+
141
+ this.boundingBox.setFromBufferAttribute( start );
142
+ _box.setFromBufferAttribute( end );
143
+ this.boundingBox.union( _box );
144
+
145
+ }
146
+
147
+ }
148
+ computeBoundingSphere() {
149
+
150
+ if ( this.boundingSphere === null ) {
151
+
152
+ this.boundingSphere = new THREE.Sphere();
153
+
154
+ }
155
+
156
+ if ( this.boundingBox === null ) {
157
+
158
+ this.computeBoundingBox();
159
+
160
+ }
161
+
162
+ const start = this.attributes.instanceStart;
163
+ const end = this.attributes.instanceEnd;
164
+ if ( start !== undefined && end !== undefined ) {
165
+
166
+ const center = this.boundingSphere.center;
167
+ this.boundingBox.getCenter( center );
168
+ let maxRadiusSq = 0;
169
+ for ( let i = 0, il = start.count; i < il; i ++ ) {
170
+
171
+ _vector.fromBufferAttribute( start, i );
172
+ maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector ) );
173
+ _vector.fromBufferAttribute( end, i );
174
+ maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector ) );
175
+
176
+ }
177
+
178
+ this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
179
+ if ( isNaN( this.boundingSphere.radius ) ) {
180
+
181
+ console.error( 'THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this );
182
+
183
+ }
184
+
185
+ }
186
+
187
+ }
188
+ toJSON() {
189
+
190
+ // todo
191
+ }
192
+ applyMatrix( matrix ) {
193
+
194
+ console.warn( 'THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().' );
195
+ return this.applyMatrix4( matrix );
196
+
197
+ }
198
+
199
+ }
200
+
201
+ THREE.LineSegmentsGeometry = LineSegmentsGeometry;
202
+
203
+ } )();
viewer/vendor/OrbitControls.js ADDED
@@ -0,0 +1,1106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * three.js r147, examples/js/controls/OrbitControls.js
3
+ * Copyright 2010-2022 Three.js Authors
4
+ * SPDX-License-Identifier: MIT
5
+ */
6
+ ( function () {
7
+
8
+ // This set of controls performs orbiting, dollying (zooming), and panning.
9
+ // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
10
+ //
11
+ // Orbit - left mouse / touch: one-finger move
12
+ // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
13
+ // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
14
+
15
+ const _changeEvent = {
16
+ type: 'change'
17
+ };
18
+ const _startEvent = {
19
+ type: 'start'
20
+ };
21
+ const _endEvent = {
22
+ type: 'end'
23
+ };
24
+ class OrbitControls extends THREE.EventDispatcher {
25
+
26
+ constructor( object, domElement ) {
27
+
28
+ super();
29
+ this.object = object;
30
+ this.domElement = domElement;
31
+ this.domElement.style.touchAction = 'none'; // disable touch scroll
32
+
33
+ // Set to false to disable this control
34
+ this.enabled = true;
35
+
36
+ // "target" sets the location of focus, where the object orbits around
37
+ this.target = new THREE.Vector3();
38
+
39
+ // How far you can dolly in and out ( PerspectiveCamera only )
40
+ this.minDistance = 0;
41
+ this.maxDistance = Infinity;
42
+
43
+ // How far you can zoom in and out ( OrthographicCamera only )
44
+ this.minZoom = 0;
45
+ this.maxZoom = Infinity;
46
+
47
+ // How far you can orbit vertically, upper and lower limits.
48
+ // Range is 0 to Math.PI radians.
49
+ this.minPolarAngle = 0; // radians
50
+ this.maxPolarAngle = Math.PI; // radians
51
+
52
+ // How far you can orbit horizontally, upper and lower limits.
53
+ // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
54
+ this.minAzimuthAngle = - Infinity; // radians
55
+ this.maxAzimuthAngle = Infinity; // radians
56
+
57
+ // Set to true to enable damping (inertia)
58
+ // If damping is enabled, you must call controls.update() in your animation loop
59
+ this.enableDamping = false;
60
+ this.dampingFactor = 0.05;
61
+
62
+ // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
63
+ // Set to false to disable zooming
64
+ this.enableZoom = true;
65
+ this.zoomSpeed = 1.0;
66
+
67
+ // Set to false to disable rotating
68
+ this.enableRotate = true;
69
+ this.rotateSpeed = 1.0;
70
+
71
+ // Set to false to disable panning
72
+ this.enablePan = true;
73
+ this.panSpeed = 1.0;
74
+ this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
75
+ this.keyPanSpeed = 7.0; // pixels moved per arrow key push
76
+
77
+ // Set to true to automatically rotate around the target
78
+ // If auto-rotate is enabled, you must call controls.update() in your animation loop
79
+ this.autoRotate = false;
80
+ this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
81
+
82
+ // The four arrow keys
83
+ this.keys = {
84
+ LEFT: 'ArrowLeft',
85
+ UP: 'ArrowUp',
86
+ RIGHT: 'ArrowRight',
87
+ BOTTOM: 'ArrowDown'
88
+ };
89
+
90
+ // Mouse buttons
91
+ this.mouseButtons = {
92
+ LEFT: THREE.MOUSE.ROTATE,
93
+ MIDDLE: THREE.MOUSE.DOLLY,
94
+ RIGHT: THREE.MOUSE.PAN
95
+ };
96
+
97
+ // Touch fingers
98
+ this.touches = {
99
+ ONE: THREE.TOUCH.ROTATE,
100
+ TWO: THREE.TOUCH.DOLLY_PAN
101
+ };
102
+
103
+ // for reset
104
+ this.target0 = this.target.clone();
105
+ this.position0 = this.object.position.clone();
106
+ this.zoom0 = this.object.zoom;
107
+
108
+ // the target DOM element for key events
109
+ this._domElementKeyEvents = null;
110
+
111
+ //
112
+ // public methods
113
+ //
114
+
115
+ this.getPolarAngle = function () {
116
+
117
+ return spherical.phi;
118
+
119
+ };
120
+
121
+ this.getAzimuthalAngle = function () {
122
+
123
+ return spherical.theta;
124
+
125
+ };
126
+
127
+ this.getDistance = function () {
128
+
129
+ return this.object.position.distanceTo( this.target );
130
+
131
+ };
132
+
133
+ this.listenToKeyEvents = function ( domElement ) {
134
+
135
+ domElement.addEventListener( 'keydown', onKeyDown );
136
+ this._domElementKeyEvents = domElement;
137
+
138
+ };
139
+
140
+ this.saveState = function () {
141
+
142
+ scope.target0.copy( scope.target );
143
+ scope.position0.copy( scope.object.position );
144
+ scope.zoom0 = scope.object.zoom;
145
+
146
+ };
147
+
148
+ this.reset = function () {
149
+
150
+ scope.target.copy( scope.target0 );
151
+ scope.object.position.copy( scope.position0 );
152
+ scope.object.zoom = scope.zoom0;
153
+ scope.object.updateProjectionMatrix();
154
+ scope.dispatchEvent( _changeEvent );
155
+ scope.update();
156
+ state = STATE.NONE;
157
+
158
+ };
159
+
160
+ // this method is exposed, but perhaps it would be better if we can make it private...
161
+ this.update = function () {
162
+
163
+ const offset = new THREE.Vector3();
164
+
165
+ // so camera.up is the orbit axis
166
+ const quat = new THREE.Quaternion().setFromUnitVectors( object.up, new THREE.Vector3( 0, 1, 0 ) );
167
+ const quatInverse = quat.clone().invert();
168
+ const lastPosition = new THREE.Vector3();
169
+ const lastQuaternion = new THREE.Quaternion();
170
+ const twoPI = 2 * Math.PI;
171
+ return function update() {
172
+
173
+ const position = scope.object.position;
174
+ offset.copy( position ).sub( scope.target );
175
+
176
+ // rotate offset to "y-axis-is-up" space
177
+ offset.applyQuaternion( quat );
178
+
179
+ // angle from z-axis around y-axis
180
+ spherical.setFromVector3( offset );
181
+ if ( scope.autoRotate && state === STATE.NONE ) {
182
+
183
+ rotateLeft( getAutoRotationAngle() );
184
+
185
+ }
186
+
187
+ if ( scope.enableDamping ) {
188
+
189
+ spherical.theta += sphericalDelta.theta * scope.dampingFactor;
190
+ spherical.phi += sphericalDelta.phi * scope.dampingFactor;
191
+
192
+ } else {
193
+
194
+ spherical.theta += sphericalDelta.theta;
195
+ spherical.phi += sphericalDelta.phi;
196
+
197
+ }
198
+
199
+ // restrict theta to be between desired limits
200
+
201
+ let min = scope.minAzimuthAngle;
202
+ let max = scope.maxAzimuthAngle;
203
+ if ( isFinite( min ) && isFinite( max ) ) {
204
+
205
+ if ( min < - Math.PI ) min += twoPI; else if ( min > Math.PI ) min -= twoPI;
206
+ if ( max < - Math.PI ) max += twoPI; else if ( max > Math.PI ) max -= twoPI;
207
+ if ( min <= max ) {
208
+
209
+ spherical.theta = Math.max( min, Math.min( max, spherical.theta ) );
210
+
211
+ } else {
212
+
213
+ spherical.theta = spherical.theta > ( min + max ) / 2 ? Math.max( min, spherical.theta ) : Math.min( max, spherical.theta );
214
+
215
+ }
216
+
217
+ }
218
+
219
+ // restrict phi to be between desired limits
220
+ spherical.phi = Math.max( scope.minPolarAngle, Math.min( scope.maxPolarAngle, spherical.phi ) );
221
+ spherical.makeSafe();
222
+ spherical.radius *= scale;
223
+
224
+ // restrict radius to be between desired limits
225
+ spherical.radius = Math.max( scope.minDistance, Math.min( scope.maxDistance, spherical.radius ) );
226
+
227
+ // move target to panned location
228
+
229
+ if ( scope.enableDamping === true ) {
230
+
231
+ scope.target.addScaledVector( panOffset, scope.dampingFactor );
232
+
233
+ } else {
234
+
235
+ scope.target.add( panOffset );
236
+
237
+ }
238
+
239
+ offset.setFromSpherical( spherical );
240
+
241
+ // rotate offset back to "camera-up-vector-is-up" space
242
+ offset.applyQuaternion( quatInverse );
243
+ position.copy( scope.target ).add( offset );
244
+ scope.object.lookAt( scope.target );
245
+ if ( scope.enableDamping === true ) {
246
+
247
+ sphericalDelta.theta *= 1 - scope.dampingFactor;
248
+ sphericalDelta.phi *= 1 - scope.dampingFactor;
249
+ panOffset.multiplyScalar( 1 - scope.dampingFactor );
250
+
251
+ } else {
252
+
253
+ sphericalDelta.set( 0, 0, 0 );
254
+ panOffset.set( 0, 0, 0 );
255
+
256
+ }
257
+
258
+ scale = 1;
259
+
260
+ // update condition is:
261
+ // min(camera displacement, camera rotation in radians)^2 > EPS
262
+ // using small-angle approximation cos(x/2) = 1 - x^2 / 8
263
+
264
+ if ( zoomChanged || lastPosition.distanceToSquared( scope.object.position ) > EPS || 8 * ( 1 - lastQuaternion.dot( scope.object.quaternion ) ) > EPS ) {
265
+
266
+ scope.dispatchEvent( _changeEvent );
267
+ lastPosition.copy( scope.object.position );
268
+ lastQuaternion.copy( scope.object.quaternion );
269
+ zoomChanged = false;
270
+ return true;
271
+
272
+ }
273
+
274
+ return false;
275
+
276
+ };
277
+
278
+ }();
279
+ this.dispose = function () {
280
+
281
+ scope.domElement.removeEventListener( 'contextmenu', onContextMenu );
282
+ scope.domElement.removeEventListener( 'pointerdown', onPointerDown );
283
+ scope.domElement.removeEventListener( 'pointercancel', onPointerCancel );
284
+ scope.domElement.removeEventListener( 'wheel', onMouseWheel );
285
+ scope.domElement.removeEventListener( 'pointermove', onPointerMove );
286
+ scope.domElement.removeEventListener( 'pointerup', onPointerUp );
287
+ if ( scope._domElementKeyEvents !== null ) {
288
+
289
+ scope._domElementKeyEvents.removeEventListener( 'keydown', onKeyDown );
290
+
291
+ }
292
+
293
+ //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
294
+
295
+ };
296
+
297
+ //
298
+ // internals
299
+ //
300
+
301
+ const scope = this;
302
+ const STATE = {
303
+ NONE: - 1,
304
+ ROTATE: 0,
305
+ DOLLY: 1,
306
+ PAN: 2,
307
+ TOUCH_ROTATE: 3,
308
+ TOUCH_PAN: 4,
309
+ TOUCH_DOLLY_PAN: 5,
310
+ TOUCH_DOLLY_ROTATE: 6
311
+ };
312
+ let state = STATE.NONE;
313
+ const EPS = 0.000001;
314
+
315
+ // current position in spherical coordinates
316
+ const spherical = new THREE.Spherical();
317
+ const sphericalDelta = new THREE.Spherical();
318
+ let scale = 1;
319
+ const panOffset = new THREE.Vector3();
320
+ let zoomChanged = false;
321
+ const rotateStart = new THREE.Vector2();
322
+ const rotateEnd = new THREE.Vector2();
323
+ const rotateDelta = new THREE.Vector2();
324
+ const panStart = new THREE.Vector2();
325
+ const panEnd = new THREE.Vector2();
326
+ const panDelta = new THREE.Vector2();
327
+ const dollyStart = new THREE.Vector2();
328
+ const dollyEnd = new THREE.Vector2();
329
+ const dollyDelta = new THREE.Vector2();
330
+ const pointers = [];
331
+ const pointerPositions = {};
332
+ function getAutoRotationAngle() {
333
+
334
+ return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
335
+
336
+ }
337
+
338
+ function getZoomScale() {
339
+
340
+ return Math.pow( 0.95, scope.zoomSpeed );
341
+
342
+ }
343
+
344
+ function rotateLeft( angle ) {
345
+
346
+ sphericalDelta.theta -= angle;
347
+
348
+ }
349
+
350
+ function rotateUp( angle ) {
351
+
352
+ sphericalDelta.phi -= angle;
353
+
354
+ }
355
+
356
+ const panLeft = function () {
357
+
358
+ const v = new THREE.Vector3();
359
+ return function panLeft( distance, objectMatrix ) {
360
+
361
+ v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix
362
+ v.multiplyScalar( - distance );
363
+ panOffset.add( v );
364
+
365
+ };
366
+
367
+ }();
368
+ const panUp = function () {
369
+
370
+ const v = new THREE.Vector3();
371
+ return function panUp( distance, objectMatrix ) {
372
+
373
+ if ( scope.screenSpacePanning === true ) {
374
+
375
+ v.setFromMatrixColumn( objectMatrix, 1 );
376
+
377
+ } else {
378
+
379
+ v.setFromMatrixColumn( objectMatrix, 0 );
380
+ v.crossVectors( scope.object.up, v );
381
+
382
+ }
383
+
384
+ v.multiplyScalar( distance );
385
+ panOffset.add( v );
386
+
387
+ };
388
+
389
+ }();
390
+
391
+ // deltaX and deltaY are in pixels; right and down are positive
392
+ const pan = function () {
393
+
394
+ const offset = new THREE.Vector3();
395
+ return function pan( deltaX, deltaY ) {
396
+
397
+ const element = scope.domElement;
398
+ if ( scope.object.isPerspectiveCamera ) {
399
+
400
+ // perspective
401
+ const position = scope.object.position;
402
+ offset.copy( position ).sub( scope.target );
403
+ let targetDistance = offset.length();
404
+
405
+ // half of the fov is center to top of screen
406
+ targetDistance *= Math.tan( scope.object.fov / 2 * Math.PI / 180.0 );
407
+
408
+ // we use only clientHeight here so aspect ratio does not distort speed
409
+ panLeft( 2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix );
410
+ panUp( 2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix );
411
+
412
+ } else if ( scope.object.isOrthographicCamera ) {
413
+
414
+ // orthographic
415
+ panLeft( deltaX * ( scope.object.right - scope.object.left ) / scope.object.zoom / element.clientWidth, scope.object.matrix );
416
+ panUp( deltaY * ( scope.object.top - scope.object.bottom ) / scope.object.zoom / element.clientHeight, scope.object.matrix );
417
+
418
+ } else {
419
+
420
+ // camera neither orthographic nor perspective
421
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' );
422
+ scope.enablePan = false;
423
+
424
+ }
425
+
426
+ };
427
+
428
+ }();
429
+ function dollyOut( dollyScale ) {
430
+
431
+ if ( scope.object.isPerspectiveCamera ) {
432
+
433
+ scale /= dollyScale;
434
+
435
+ } else if ( scope.object.isOrthographicCamera ) {
436
+
437
+ scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom * dollyScale ) );
438
+ scope.object.updateProjectionMatrix();
439
+ zoomChanged = true;
440
+
441
+ } else {
442
+
443
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
444
+ scope.enableZoom = false;
445
+
446
+ }
447
+
448
+ }
449
+
450
+ function dollyIn( dollyScale ) {
451
+
452
+ if ( scope.object.isPerspectiveCamera ) {
453
+
454
+ scale *= dollyScale;
455
+
456
+ } else if ( scope.object.isOrthographicCamera ) {
457
+
458
+ scope.object.zoom = Math.max( scope.minZoom, Math.min( scope.maxZoom, scope.object.zoom / dollyScale ) );
459
+ scope.object.updateProjectionMatrix();
460
+ zoomChanged = true;
461
+
462
+ } else {
463
+
464
+ console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' );
465
+ scope.enableZoom = false;
466
+
467
+ }
468
+
469
+ }
470
+
471
+ //
472
+ // event callbacks - update the object state
473
+ //
474
+
475
+ function handleMouseDownRotate( event ) {
476
+
477
+ rotateStart.set( event.clientX, event.clientY );
478
+
479
+ }
480
+
481
+ function handleMouseDownDolly( event ) {
482
+
483
+ dollyStart.set( event.clientX, event.clientY );
484
+
485
+ }
486
+
487
+ function handleMouseDownPan( event ) {
488
+
489
+ panStart.set( event.clientX, event.clientY );
490
+
491
+ }
492
+
493
+ function handleMouseMoveRotate( event ) {
494
+
495
+ rotateEnd.set( event.clientX, event.clientY );
496
+ rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
497
+ const element = scope.domElement;
498
+ rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
499
+
500
+ rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
501
+ rotateStart.copy( rotateEnd );
502
+ scope.update();
503
+
504
+ }
505
+
506
+ function handleMouseMoveDolly( event ) {
507
+
508
+ dollyEnd.set( event.clientX, event.clientY );
509
+ dollyDelta.subVectors( dollyEnd, dollyStart );
510
+ if ( dollyDelta.y > 0 ) {
511
+
512
+ dollyOut( getZoomScale() );
513
+
514
+ } else if ( dollyDelta.y < 0 ) {
515
+
516
+ dollyIn( getZoomScale() );
517
+
518
+ }
519
+
520
+ dollyStart.copy( dollyEnd );
521
+ scope.update();
522
+
523
+ }
524
+
525
+ function handleMouseMovePan( event ) {
526
+
527
+ panEnd.set( event.clientX, event.clientY );
528
+ panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
529
+ pan( panDelta.x, panDelta.y );
530
+ panStart.copy( panEnd );
531
+ scope.update();
532
+
533
+ }
534
+
535
+ function handleMouseWheel( event ) {
536
+
537
+ if ( event.deltaY < 0 ) {
538
+
539
+ dollyIn( getZoomScale() );
540
+
541
+ } else if ( event.deltaY > 0 ) {
542
+
543
+ dollyOut( getZoomScale() );
544
+
545
+ }
546
+
547
+ scope.update();
548
+
549
+ }
550
+
551
+ function handleKeyDown( event ) {
552
+
553
+ let needsUpdate = false;
554
+ switch ( event.code ) {
555
+
556
+ case scope.keys.UP:
557
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
558
+
559
+ rotateUp( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
560
+
561
+ } else {
562
+
563
+ pan( 0, scope.keyPanSpeed );
564
+
565
+ }
566
+
567
+ needsUpdate = true;
568
+ break;
569
+ case scope.keys.BOTTOM:
570
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
571
+
572
+ rotateUp( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
573
+
574
+ } else {
575
+
576
+ pan( 0, - scope.keyPanSpeed );
577
+
578
+ }
579
+
580
+ needsUpdate = true;
581
+ break;
582
+ case scope.keys.LEFT:
583
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
584
+
585
+ rotateLeft( 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
586
+
587
+ } else {
588
+
589
+ pan( scope.keyPanSpeed, 0 );
590
+
591
+ }
592
+
593
+ needsUpdate = true;
594
+ break;
595
+ case scope.keys.RIGHT:
596
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
597
+
598
+ rotateLeft( - 2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight );
599
+
600
+ } else {
601
+
602
+ pan( - scope.keyPanSpeed, 0 );
603
+
604
+ }
605
+
606
+ needsUpdate = true;
607
+ break;
608
+
609
+ }
610
+
611
+ if ( needsUpdate ) {
612
+
613
+ // prevent the browser from scrolling on cursor keys
614
+ event.preventDefault();
615
+ scope.update();
616
+
617
+ }
618
+
619
+ }
620
+
621
+ function handleTouchStartRotate() {
622
+
623
+ if ( pointers.length === 1 ) {
624
+
625
+ rotateStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY );
626
+
627
+ } else {
628
+
629
+ const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX );
630
+ const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY );
631
+ rotateStart.set( x, y );
632
+
633
+ }
634
+
635
+ }
636
+
637
+ function handleTouchStartPan() {
638
+
639
+ if ( pointers.length === 1 ) {
640
+
641
+ panStart.set( pointers[ 0 ].pageX, pointers[ 0 ].pageY );
642
+
643
+ } else {
644
+
645
+ const x = 0.5 * ( pointers[ 0 ].pageX + pointers[ 1 ].pageX );
646
+ const y = 0.5 * ( pointers[ 0 ].pageY + pointers[ 1 ].pageY );
647
+ panStart.set( x, y );
648
+
649
+ }
650
+
651
+ }
652
+
653
+ function handleTouchStartDolly() {
654
+
655
+ const dx = pointers[ 0 ].pageX - pointers[ 1 ].pageX;
656
+ const dy = pointers[ 0 ].pageY - pointers[ 1 ].pageY;
657
+ const distance = Math.sqrt( dx * dx + dy * dy );
658
+ dollyStart.set( 0, distance );
659
+
660
+ }
661
+
662
+ function handleTouchStartDollyPan() {
663
+
664
+ if ( scope.enableZoom ) handleTouchStartDolly();
665
+ if ( scope.enablePan ) handleTouchStartPan();
666
+
667
+ }
668
+
669
+ function handleTouchStartDollyRotate() {
670
+
671
+ if ( scope.enableZoom ) handleTouchStartDolly();
672
+ if ( scope.enableRotate ) handleTouchStartRotate();
673
+
674
+ }
675
+
676
+ function handleTouchMoveRotate( event ) {
677
+
678
+ if ( pointers.length == 1 ) {
679
+
680
+ rotateEnd.set( event.pageX, event.pageY );
681
+
682
+ } else {
683
+
684
+ const position = getSecondPointerPosition( event );
685
+ const x = 0.5 * ( event.pageX + position.x );
686
+ const y = 0.5 * ( event.pageY + position.y );
687
+ rotateEnd.set( x, y );
688
+
689
+ }
690
+
691
+ rotateDelta.subVectors( rotateEnd, rotateStart ).multiplyScalar( scope.rotateSpeed );
692
+ const element = scope.domElement;
693
+ rotateLeft( 2 * Math.PI * rotateDelta.x / element.clientHeight ); // yes, height
694
+
695
+ rotateUp( 2 * Math.PI * rotateDelta.y / element.clientHeight );
696
+ rotateStart.copy( rotateEnd );
697
+
698
+ }
699
+
700
+ function handleTouchMovePan( event ) {
701
+
702
+ if ( pointers.length === 1 ) {
703
+
704
+ panEnd.set( event.pageX, event.pageY );
705
+
706
+ } else {
707
+
708
+ const position = getSecondPointerPosition( event );
709
+ const x = 0.5 * ( event.pageX + position.x );
710
+ const y = 0.5 * ( event.pageY + position.y );
711
+ panEnd.set( x, y );
712
+
713
+ }
714
+
715
+ panDelta.subVectors( panEnd, panStart ).multiplyScalar( scope.panSpeed );
716
+ pan( panDelta.x, panDelta.y );
717
+ panStart.copy( panEnd );
718
+
719
+ }
720
+
721
+ function handleTouchMoveDolly( event ) {
722
+
723
+ const position = getSecondPointerPosition( event );
724
+ const dx = event.pageX - position.x;
725
+ const dy = event.pageY - position.y;
726
+ const distance = Math.sqrt( dx * dx + dy * dy );
727
+ dollyEnd.set( 0, distance );
728
+ dollyDelta.set( 0, Math.pow( dollyEnd.y / dollyStart.y, scope.zoomSpeed ) );
729
+ dollyOut( dollyDelta.y );
730
+ dollyStart.copy( dollyEnd );
731
+
732
+ }
733
+
734
+ function handleTouchMoveDollyPan( event ) {
735
+
736
+ if ( scope.enableZoom ) handleTouchMoveDolly( event );
737
+ if ( scope.enablePan ) handleTouchMovePan( event );
738
+
739
+ }
740
+
741
+ function handleTouchMoveDollyRotate( event ) {
742
+
743
+ if ( scope.enableZoom ) handleTouchMoveDolly( event );
744
+ if ( scope.enableRotate ) handleTouchMoveRotate( event );
745
+
746
+ }
747
+
748
+ //
749
+ // event handlers - FSM: listen for events and reset state
750
+ //
751
+
752
+ function onPointerDown( event ) {
753
+
754
+ if ( scope.enabled === false ) return;
755
+ if ( pointers.length === 0 ) {
756
+
757
+ scope.domElement.setPointerCapture( event.pointerId );
758
+ scope.domElement.addEventListener( 'pointermove', onPointerMove );
759
+ scope.domElement.addEventListener( 'pointerup', onPointerUp );
760
+
761
+ }
762
+
763
+ //
764
+
765
+ addPointer( event );
766
+ if ( event.pointerType === 'touch' ) {
767
+
768
+ onTouchStart( event );
769
+
770
+ } else {
771
+
772
+ onMouseDown( event );
773
+
774
+ }
775
+
776
+ }
777
+
778
+ function onPointerMove( event ) {
779
+
780
+ if ( scope.enabled === false ) return;
781
+ if ( event.pointerType === 'touch' ) {
782
+
783
+ onTouchMove( event );
784
+
785
+ } else {
786
+
787
+ onMouseMove( event );
788
+
789
+ }
790
+
791
+ }
792
+
793
+ function onPointerUp( event ) {
794
+
795
+ removePointer( event );
796
+ if ( pointers.length === 0 ) {
797
+
798
+ scope.domElement.releasePointerCapture( event.pointerId );
799
+ scope.domElement.removeEventListener( 'pointermove', onPointerMove );
800
+ scope.domElement.removeEventListener( 'pointerup', onPointerUp );
801
+
802
+ }
803
+
804
+ scope.dispatchEvent( _endEvent );
805
+ state = STATE.NONE;
806
+
807
+ }
808
+
809
+ function onPointerCancel( event ) {
810
+
811
+ removePointer( event );
812
+
813
+ }
814
+
815
+ function onMouseDown( event ) {
816
+
817
+ let mouseAction;
818
+ switch ( event.button ) {
819
+
820
+ case 0:
821
+ mouseAction = scope.mouseButtons.LEFT;
822
+ break;
823
+ case 1:
824
+ mouseAction = scope.mouseButtons.MIDDLE;
825
+ break;
826
+ case 2:
827
+ mouseAction = scope.mouseButtons.RIGHT;
828
+ break;
829
+ default:
830
+ mouseAction = - 1;
831
+
832
+ }
833
+
834
+ switch ( mouseAction ) {
835
+
836
+ case THREE.MOUSE.DOLLY:
837
+ if ( scope.enableZoom === false ) return;
838
+ handleMouseDownDolly( event );
839
+ state = STATE.DOLLY;
840
+ break;
841
+ case THREE.MOUSE.ROTATE:
842
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
843
+
844
+ if ( scope.enablePan === false ) return;
845
+ handleMouseDownPan( event );
846
+ state = STATE.PAN;
847
+
848
+ } else {
849
+
850
+ if ( scope.enableRotate === false ) return;
851
+ handleMouseDownRotate( event );
852
+ state = STATE.ROTATE;
853
+
854
+ }
855
+
856
+ break;
857
+ case THREE.MOUSE.PAN:
858
+ if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
859
+
860
+ if ( scope.enableRotate === false ) return;
861
+ handleMouseDownRotate( event );
862
+ state = STATE.ROTATE;
863
+
864
+ } else {
865
+
866
+ if ( scope.enablePan === false ) return;
867
+ handleMouseDownPan( event );
868
+ state = STATE.PAN;
869
+
870
+ }
871
+
872
+ break;
873
+ default:
874
+ state = STATE.NONE;
875
+
876
+ }
877
+
878
+ if ( state !== STATE.NONE ) {
879
+
880
+ scope.dispatchEvent( _startEvent );
881
+
882
+ }
883
+
884
+ }
885
+
886
+ function onMouseMove( event ) {
887
+
888
+ switch ( state ) {
889
+
890
+ case STATE.ROTATE:
891
+ if ( scope.enableRotate === false ) return;
892
+ handleMouseMoveRotate( event );
893
+ break;
894
+ case STATE.DOLLY:
895
+ if ( scope.enableZoom === false ) return;
896
+ handleMouseMoveDolly( event );
897
+ break;
898
+ case STATE.PAN:
899
+ if ( scope.enablePan === false ) return;
900
+ handleMouseMovePan( event );
901
+ break;
902
+
903
+ }
904
+
905
+ }
906
+
907
+ function onMouseWheel( event ) {
908
+
909
+ if ( scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE ) return;
910
+ event.preventDefault();
911
+ scope.dispatchEvent( _startEvent );
912
+ handleMouseWheel( event );
913
+ scope.dispatchEvent( _endEvent );
914
+
915
+ }
916
+
917
+ function onKeyDown( event ) {
918
+
919
+ if ( scope.enabled === false || scope.enablePan === false ) return;
920
+ handleKeyDown( event );
921
+
922
+ }
923
+
924
+ function onTouchStart( event ) {
925
+
926
+ trackPointer( event );
927
+ switch ( pointers.length ) {
928
+
929
+ case 1:
930
+ switch ( scope.touches.ONE ) {
931
+
932
+ case THREE.TOUCH.ROTATE:
933
+ if ( scope.enableRotate === false ) return;
934
+ handleTouchStartRotate();
935
+ state = STATE.TOUCH_ROTATE;
936
+ break;
937
+ case THREE.TOUCH.PAN:
938
+ if ( scope.enablePan === false ) return;
939
+ handleTouchStartPan();
940
+ state = STATE.TOUCH_PAN;
941
+ break;
942
+ default:
943
+ state = STATE.NONE;
944
+
945
+ }
946
+
947
+ break;
948
+ case 2:
949
+ switch ( scope.touches.TWO ) {
950
+
951
+ case THREE.TOUCH.DOLLY_PAN:
952
+ if ( scope.enableZoom === false && scope.enablePan === false ) return;
953
+ handleTouchStartDollyPan();
954
+ state = STATE.TOUCH_DOLLY_PAN;
955
+ break;
956
+ case THREE.TOUCH.DOLLY_ROTATE:
957
+ if ( scope.enableZoom === false && scope.enableRotate === false ) return;
958
+ handleTouchStartDollyRotate();
959
+ state = STATE.TOUCH_DOLLY_ROTATE;
960
+ break;
961
+ default:
962
+ state = STATE.NONE;
963
+
964
+ }
965
+
966
+ break;
967
+ default:
968
+ state = STATE.NONE;
969
+
970
+ }
971
+
972
+ if ( state !== STATE.NONE ) {
973
+
974
+ scope.dispatchEvent( _startEvent );
975
+
976
+ }
977
+
978
+ }
979
+
980
+ function onTouchMove( event ) {
981
+
982
+ trackPointer( event );
983
+ switch ( state ) {
984
+
985
+ case STATE.TOUCH_ROTATE:
986
+ if ( scope.enableRotate === false ) return;
987
+ handleTouchMoveRotate( event );
988
+ scope.update();
989
+ break;
990
+ case STATE.TOUCH_PAN:
991
+ if ( scope.enablePan === false ) return;
992
+ handleTouchMovePan( event );
993
+ scope.update();
994
+ break;
995
+ case STATE.TOUCH_DOLLY_PAN:
996
+ if ( scope.enableZoom === false && scope.enablePan === false ) return;
997
+ handleTouchMoveDollyPan( event );
998
+ scope.update();
999
+ break;
1000
+ case STATE.TOUCH_DOLLY_ROTATE:
1001
+ if ( scope.enableZoom === false && scope.enableRotate === false ) return;
1002
+ handleTouchMoveDollyRotate( event );
1003
+ scope.update();
1004
+ break;
1005
+ default:
1006
+ state = STATE.NONE;
1007
+
1008
+ }
1009
+
1010
+ }
1011
+
1012
+ function onContextMenu( event ) {
1013
+
1014
+ if ( scope.enabled === false ) return;
1015
+ event.preventDefault();
1016
+
1017
+ }
1018
+
1019
+ function addPointer( event ) {
1020
+
1021
+ pointers.push( event );
1022
+
1023
+ }
1024
+
1025
+ function removePointer( event ) {
1026
+
1027
+ delete pointerPositions[ event.pointerId ];
1028
+ for ( let i = 0; i < pointers.length; i ++ ) {
1029
+
1030
+ if ( pointers[ i ].pointerId == event.pointerId ) {
1031
+
1032
+ pointers.splice( i, 1 );
1033
+ return;
1034
+
1035
+ }
1036
+
1037
+ }
1038
+
1039
+ }
1040
+
1041
+ function trackPointer( event ) {
1042
+
1043
+ let position = pointerPositions[ event.pointerId ];
1044
+ if ( position === undefined ) {
1045
+
1046
+ position = new THREE.Vector2();
1047
+ pointerPositions[ event.pointerId ] = position;
1048
+
1049
+ }
1050
+
1051
+ position.set( event.pageX, event.pageY );
1052
+
1053
+ }
1054
+
1055
+ function getSecondPointerPosition( event ) {
1056
+
1057
+ const pointer = event.pointerId === pointers[ 0 ].pointerId ? pointers[ 1 ] : pointers[ 0 ];
1058
+ return pointerPositions[ pointer.pointerId ];
1059
+
1060
+ }
1061
+
1062
+ //
1063
+
1064
+ scope.domElement.addEventListener( 'contextmenu', onContextMenu );
1065
+ scope.domElement.addEventListener( 'pointerdown', onPointerDown );
1066
+ scope.domElement.addEventListener( 'pointercancel', onPointerCancel );
1067
+ scope.domElement.addEventListener( 'wheel', onMouseWheel, {
1068
+ passive: false
1069
+ } );
1070
+
1071
+ // force an update at start
1072
+
1073
+ this.update();
1074
+
1075
+ }
1076
+
1077
+ }
1078
+
1079
+ // This set of controls performs orbiting, dollying (zooming), and panning.
1080
+ // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
1081
+ // This is very similar to OrbitControls, another set of touch behavior
1082
+ //
1083
+ // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
1084
+ // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
1085
+ // Pan - left mouse, or arrow keys / touch: one-finger move
1086
+
1087
+ class MapControls extends OrbitControls {
1088
+
1089
+ constructor( object, domElement ) {
1090
+
1091
+ super( object, domElement );
1092
+ this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up
1093
+
1094
+ this.mouseButtons.LEFT = THREE.MOUSE.PAN;
1095
+ this.mouseButtons.RIGHT = THREE.MOUSE.ROTATE;
1096
+ this.touches.ONE = THREE.TOUCH.PAN;
1097
+ this.touches.TWO = THREE.TOUCH.DOLLY_ROTATE;
1098
+
1099
+ }
1100
+
1101
+ }
1102
+
1103
+ THREE.MapControls = MapControls;
1104
+ THREE.OrbitControls = OrbitControls;
1105
+
1106
+ } )();
viewer/vendor/three.min.js ADDED
The diff for this file is too large to render. See raw diff
 
viewer/viewer.js ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Flow4RT 4D viewer of one prediction, adapted from the project page's viewer.
2
+ *
3
+ * visualize.py embeds the data as F4RT.add({...}) calls before this script: the scene description
4
+ * (kind "meta"), the dense tracks ("track") and the point maps in chunks of frames ("recon").
5
+ * Arrays are int16/uint8, byte-shuffled and gzipped; positions are normalised to the scene radius.
6
+ */
7
+ (function () {
8
+ 'use strict';
9
+
10
+ const RADIUS_CLIP = 2.5; // positions are quantised to [-2.5, 2.5] scene radii
11
+ const FPS = 12;
12
+ const LOOP_PAUSE = 1000; // ms to hold the last frame before looping back
13
+ const TRACK_FADE = 0.6; // how far tracking-mode points are washed out towards white
14
+ const TRAIL_WIDTH = 2.5; // px
15
+
16
+ // ------------------------------------------------------------------ decoding
17
+ async function inflate(b64, Type) {
18
+ const bin = atob(b64);
19
+ const bytes = new Uint8Array(bin.length);
20
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
21
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'));
22
+ const buf = new Uint8Array(await new Response(stream).arrayBuffer());
23
+ const k = Type.BYTES_PER_ELEMENT;
24
+ if (k === 1) return new Type(buf.buffer);
25
+ const n = buf.length / k, out = new Uint8Array(buf.length);
26
+ for (let b = 0; b < k; b++) {
27
+ const off = b * n;
28
+ for (let i = 0; i < n; i++) out[i * k + b] = buf[off + i];
29
+ }
30
+ return new Type(out.buffer);
31
+ }
32
+
33
+ async function decode(parts) {
34
+ const meta = parts.find(p => p.kind === 'meta'), T = meta.T;
35
+ // Point maps: the chunks concatenated in frame order, so that frames 0..t are one draw range.
36
+ const chunks = parts.filter(p => p.kind === 'recon').sort((a, b) => a.first - b.first);
37
+ const counts = chunks.flatMap(c => c.counts), offsets = [0];
38
+ counts.forEach(c => offsets.push(offsets[offsets.length - 1] + c));
39
+ const n = offsets[T];
40
+ const recon = { counts, offsets, pos: new Int16Array(n * 3), col: new Uint8Array(n * 3), conf: new Uint8Array(n) };
41
+ for (const c of chunks) {
42
+ const o = offsets[c.first];
43
+ recon.pos.set(await inflate(c.pos, Int16Array), o * 3);
44
+ recon.col.set(await inflate(c.col, Uint8Array), o * 3);
45
+ recon.conf.set(await inflate(c.conf, Uint8Array), o);
46
+ }
47
+ // Dense tracks: frame-to-frame deltas, summed up (int16 wrap is exact).
48
+ const tp = parts.find(p => p.kind === 'track'), N = tp.n;
49
+ const delta = await inflate(tp.pos, Int16Array); // (T, 3, N)
50
+ const frames = new Int16Array(T * N * 3), cur = new Int16Array(N * 3);
51
+ for (let t = 0; t < T; t++) {
52
+ for (let c = 0; c < 3; c++) {
53
+ const base = (t * 3 + c) * N;
54
+ for (let i = 0; i < N; i++) cur[i * 3 + c] += delta[base + i];
55
+ }
56
+ frames.set(cur, t * N * 3);
57
+ }
58
+ const track = { n: N, frames, col: await inflate(tp.col, Uint8Array), conf: await inflate(tp.conf, Uint8Array) };
59
+ const trails = {};
60
+ for (const [name, s] of Object.entries(meta.trails)) {
61
+ const q = await inflate(s.pos, Int16Array); // (T, Q, 3)
62
+ const f = new Float32Array(q.length);
63
+ for (let i = 0; i < q.length; i++) f[i] = q[i] / 32767 * RADIUS_CLIP;
64
+ trails[name] = { traj: f, Q: s.colors.length, colors: s.colors, uv: s.uv };
65
+ }
66
+ return { meta, recon, track, trails };
67
+ }
68
+
69
+ // ------------------------------------------------------------------ helpers
70
+ let DISC = null;
71
+ function disc() {
72
+ if (DISC) return DISC;
73
+ const c = document.createElement('canvas');
74
+ c.width = c.height = 64;
75
+ const g = c.getContext('2d');
76
+ g.beginPath(); g.arc(32, 32, 30, 0, Math.PI * 2); g.fillStyle = '#fff'; g.fill();
77
+ // Nearest filtering without mipmaps: minified mip levels would blend the
78
+ // disc's transparent-black surround into small points and darken them.
79
+ DISC = new THREE.CanvasTexture(c);
80
+ DISC.generateMipmaps = false;
81
+ DISC.minFilter = DISC.magFilter = THREE.NearestFilter;
82
+ return DISC;
83
+ }
84
+
85
+ // Disc point sprites that drop points below the confidence percentile `u.thr` and are washed
86
+ // out towards the white background by `u.fade` in [0, 1].
87
+ function cloudMaterial(u) {
88
+ const mat = new THREE.PointsMaterial({ size: 0.01, vertexColors: true, map: disc(), alphaTest: 0.5, sizeAttenuation: true });
89
+ mat.onBeforeCompile = s => {
90
+ s.uniforms.fade = u.fade;
91
+ s.uniforms.thr = u.thr;
92
+ s.vertexShader = 'attribute float confq;\nuniform float thr;\n' + s.vertexShader.replace('#include <project_vertex>',
93
+ '#include <project_vertex>\n\tif (confq < thr) gl_Position = vec4(0.0, 0.0, 2.0, 1.0);');
94
+ s.fragmentShader = 'uniform float fade;\n' + s.fragmentShader.replace('#include <color_fragment>',
95
+ '#include <color_fragment>\n\tdiffuseColor.rgb = mix(diffuseColor.rgb, vec3(1.0), fade);');
96
+ };
97
+ mat.customProgramCacheKey = () => 'cloud';
98
+ return mat;
99
+ }
100
+
101
+ function cloud(pos, col, conf, mat) {
102
+ const g = new THREE.BufferGeometry();
103
+ g.setAttribute('position', pos);
104
+ g.setAttribute('color', new THREE.BufferAttribute(col, 3, true));
105
+ g.setAttribute('confq', new THREE.BufferAttribute(conf, 1));
106
+ const p = new THREE.Points(g, mat);
107
+ p.frustumCulled = false;
108
+ return p;
109
+ }
110
+
111
+ // The trajectory style of the paper figures: each curve widens and fades in from its old end,
112
+ // relative to the frame shown now. Every segment carries its frame index; `now` is set per frame.
113
+ const FADE_FLOOR = 0.12, FADE_GAMMA = 1.6, TAPER = 0.35;
114
+ function taperAndFade(g, m, T, Q) {
115
+ const ti = new Float32Array((T - 1) * Q);
116
+ for (let t = 0; t < T - 1; t++) ti.fill(t, t * Q, (t + 1) * Q);
117
+ g.setAttribute('instanceT', new THREE.InstancedBufferAttribute(ti, 1));
118
+ m.userData.now = { value: T - 1 };
119
+ m.onBeforeCompile = s => {
120
+ s.uniforms.now = m.userData.now;
121
+ s.vertexShader = s.vertexShader
122
+ .replace('attribute vec3 instanceColorStart;',
123
+ 'attribute vec3 instanceColorStart;\nattribute float instanceT;\nuniform float now;\nvarying float vFade;')
124
+ .replace('void main() {',
125
+ 'void main() {\n\tfloat ff = clamp((instanceT + 1.0) / max(now, 1.0), 0.0, 1.0);\n' +
126
+ `\tvFade = ${FADE_FLOOR.toFixed(3)} + ${(1 - FADE_FLOOR).toFixed(3)} * pow(ff, ${FADE_GAMMA.toFixed(2)});\n` +
127
+ `\tfloat taper = ${TAPER.toFixed(3)} + ${(1 - TAPER).toFixed(3)} * ff;`)
128
+ .replace('offset *= linewidth;', 'offset *= linewidth * taper;');
129
+ s.fragmentShader = 'varying float vFade;\n' + s.fragmentShader
130
+ .replace('#include <color_fragment>', '#include <color_fragment>\n\talpha *= vFade;');
131
+ };
132
+ m.customProgramCacheKey = () => 'trail-fade';
133
+ }
134
+
135
+ // Fat line segments, time-major so that `instanceCount = t * Q` reveals every trajectory up to
136
+ // frame t, and the heads of the trajectories as dots.
137
+ function trailObject(tr, T) {
138
+ const { traj, Q, colors } = tr;
139
+ const pos = new Float32Array((T - 1) * Q * 6), col = new Float32Array((T - 1) * Q * 6);
140
+ for (let t = 0; t < T - 1; t++) {
141
+ for (let q = 0; q < Q; q++) {
142
+ const s = (t * Q + q) * 6, a = (t * Q + q) * 3, b = ((t + 1) * Q + q) * 3;
143
+ pos.set(traj.subarray(a, a + 3), s); pos.set(traj.subarray(b, b + 3), s + 3);
144
+ const c = colors[q].map(v => v / 255);
145
+ col.set(c, s); col.set(c, s + 3);
146
+ }
147
+ }
148
+ const g = new THREE.LineSegmentsGeometry();
149
+ g.setPositions(pos); g.setColors(col);
150
+ const m = new THREE.LineMaterial({ linewidth: TRAIL_WIDTH, vertexColors: true, depthTest: false, transparent: true });
151
+ taperAndFade(g, m, T, Q);
152
+ const line = new THREE.LineSegments2(g, m);
153
+ line.renderOrder = 6;
154
+ line.frustumCulled = false;
155
+ const hg = new THREE.BufferGeometry();
156
+ const headPos = new THREE.BufferAttribute(new Float32Array(Q * 3), 3);
157
+ hg.setAttribute('position', headPos);
158
+ hg.setAttribute('color', new THREE.BufferAttribute(new Float32Array(colors.flat().map(v => v / 255)), 3));
159
+ const heads = new THREE.Points(hg, new THREE.PointsMaterial({ size: 6, sizeAttenuation: false,
160
+ vertexColors: true, map: disc(), alphaTest: 0.5, depthTest: false }));
161
+ heads.renderOrder = 7; heads.frustumCulled = false;
162
+ const group = new THREE.Group();
163
+ group.add(line, heads);
164
+ return {
165
+ group, line,
166
+ update(t) {
167
+ line.geometry.instanceCount = t * Q;
168
+ m.userData.now.value = t; // fade relative to this frame
169
+ headPos.array.set(traj.subarray(t * Q * 3, (t + 1) * Q * 3));
170
+ headPos.needsUpdate = true;
171
+ },
172
+ };
173
+ }
174
+
175
+ // Camera frustums as thin lines: apex to the four image corners, and the image rectangle.
176
+ function frustumObject(f) {
177
+ const idx = [0, 1, 0, 2, 0, 3, 0, 4, 1, 2, 2, 3, 3, 4, 4, 1];
178
+ const g = new THREE.BufferGeometry();
179
+ g.setAttribute('position', new THREE.Float32BufferAttribute(idx.flatMap(i => f[i]), 3));
180
+ return new THREE.LineSegments(g);
181
+ }
182
+
183
+ // ------------------------------------------------------------------ app
184
+ const ICON_PLAY = '<svg viewBox="0 0 16 16"><path fill="currentColor" d="M4.5 2.3v11.4c0 .5.5.8.9.5l8.6-5.7a.6.6 0 0 0 0-1L5.4 1.8c-.4-.3-.9 0-.9.5z"/></svg>';
185
+ const ICON_PAUSE = '<svg viewBox="0 0 16 16"><rect x="3.2" y="2" width="3.4" height="12" rx="1" fill="currentColor"/><rect x="9.4" y="2" width="3.4" height="12" rx="1" fill="currentColor"/></svg>';
186
+
187
+ async function main() {
188
+ const $ = sel => document.querySelector(sel);
189
+ const box = $('.canvas-box'), overlay = $('.overlay');
190
+ if (typeof DecompressionStream === 'undefined') {
191
+ overlay.textContent = 'This browser lacks DecompressionStream; please use a recent Chrome, Firefox, Safari or Edge.';
192
+ return;
193
+ }
194
+ const { meta, recon, track, trails } = await decode(window.F4RT.parts);
195
+ const T = meta.T;
196
+ const opt = id => $('#opt-' + id);
197
+ // Initial state from the URL, e.g. viewer.html?mode=recon&t=20&accum=1
198
+ const params = new URLSearchParams(location.search);
199
+ for (const [k, v] of params) if (opt(k) && opt(k).type === 'checkbox') opt(k).checked = v !== '0';
200
+ const state = { mode: params.get('mode') === 'recon' ? 'recon' : 'track', t: 0, playing: true };
201
+ if (params.has('t')) { state.t = Math.max(0, Math.min(T - 1, +params.get('t'))); state.playing = false; }
202
+
203
+ // preserveDrawingBuffer so that the canvas can be saved as an image or screenshotted.
204
+ const renderer = new THREE.WebGLRenderer({ canvas: $('canvas.gl'), antialias: true, preserveDrawingBuffer: true });
205
+ renderer.setClearColor(0xffffff, 1);
206
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
207
+ const camera = new THREE.PerspectiveCamera(36, 1.6, 0.01, 100);
208
+ const controls = new THREE.OrbitControls(camera, renderer.domElement);
209
+ controls.enableDamping = true;
210
+ controls.dampingFactor = 0.12;
211
+ controls.rotateSpeed = 0.7;
212
+ controls.zoomSpeed = 0.8;
213
+ let dirty = true;
214
+ controls.addEventListener('change', () => { dirty = true; });
215
+
216
+ // ---- scene
217
+ const scene = new THREE.Scene();
218
+ const group = new THREE.Group();
219
+ group.scale.setScalar(RADIUS_CLIP); // int16 normalised -> scene units
220
+ scene.add(group);
221
+ const u = { fade: { value: 0 }, thr: { value: 0 } };
222
+ const mat = cloudMaterial(u);
223
+ const reconPts = cloud(new THREE.BufferAttribute(recon.pos, 3, true), recon.col, recon.conf, mat);
224
+ const trackPos = new THREE.BufferAttribute(new Int16Array(track.n * 3), 3, true);
225
+ trackPos.setUsage(THREE.DynamicDrawUsage);
226
+ const trackPts = cloud(trackPos, track.col, track.conf, mat);
227
+ group.add(reconPts, trackPts);
228
+ const trailObjs = {};
229
+ for (const [name, tr] of Object.entries(trails)) {
230
+ if (!tr.Q) continue;
231
+ trailObjs[name] = trailObject(tr, T);
232
+ scene.add(trailObjs[name].group);
233
+ }
234
+ const frustums = meta.frustums.map(frustumObject);
235
+ const past = new THREE.LineBasicMaterial({ color: 0x9aa3ad }), current = new THREE.LineBasicMaterial({ color: 0xea7814 });
236
+ frustums.forEach(f => scene.add(f));
237
+
238
+ // ---- controls
239
+ const slider = $('.timeline input'), playBtn = $('.playbtn'), tlabel = $('.tlabel');
240
+ slider.max = T - 1;
241
+ $('.scene-sub').textContent = `${T} frames · ${meta.w}×${meta.h}`;
242
+ const markMode = () => document.querySelectorAll('.seg-mode button').forEach(b => b.classList.toggle('on', b.dataset.v === state.mode));
243
+ document.querySelectorAll('.seg-mode button').forEach(b => {
244
+ b.onclick = () => { state.mode = b.dataset.v; markMode(); update(); };
245
+ });
246
+ markMode();
247
+ ['trails', 'current', 'accum', 'cams'].forEach(id => { opt(id).onchange = update; });
248
+ opt('moving').onchange = () => { drawQueries(); update(); };
249
+ const confVal = $('#opt-conf + .val');
250
+ opt('conf').oninput = () => { u.thr.value = +opt('conf').value; confVal.textContent = opt('conf').value + '%'; dirty = true; };
251
+ opt('conf').oninput();
252
+ opt('size').oninput = () => { mat.size = meta.pointSize * opt('size').value; dirty = true; };
253
+ opt('size').oninput();
254
+ $('.reset').onclick = resetCamera;
255
+ slider.oninput = () => { state.t = +slider.value; state.playing = false; syncPlay(); update(); };
256
+ playBtn.onclick = () => { state.playing = !state.playing; syncPlay(); };
257
+ function syncPlay() {
258
+ playBtn.innerHTML = state.playing ? ICON_PAUSE : ICON_PLAY;
259
+ playBtn.setAttribute('aria-label', state.playing ? 'Pause' : 'Play');
260
+ }
261
+ syncPlay();
262
+
263
+ function resetCamera() {
264
+ camera.position.set(...meta.cam.pos);
265
+ controls.target.set(...meta.cam.target);
266
+ controls.update();
267
+ dirty = true;
268
+ }
269
+
270
+ function trailSet() { return opt('moving').checked ? 'moving' : 'all'; }
271
+
272
+ function drawQueries() {
273
+ const img = $('.frame0 img'), cv = $('.frame0 canvas');
274
+ const draw = () => {
275
+ const r = img.getBoundingClientRect(), dpr = window.devicePixelRatio || 1;
276
+ cv.width = r.width * dpr; cv.height = r.height * dpr;
277
+ const g = cv.getContext('2d');
278
+ g.scale(dpr, dpr);
279
+ const tr = trails[trailSet()];
280
+ tr.uv.forEach(([x, y], i) => {
281
+ const [R, G, B] = tr.colors[i];
282
+ g.beginPath(); g.arc(x * r.width, y * r.height, 2.4, 0, 7); g.fillStyle = '#222'; g.fill();
283
+ g.beginPath(); g.arc(x * r.width, y * r.height, 1.6, 0, 7); g.fillStyle = `rgb(${R},${G},${B})`; g.fill();
284
+ });
285
+ };
286
+ if (img.complete && img.naturalWidth) draw(); else img.onload = draw;
287
+ }
288
+ $('.frame0 img').src = meta.frames[meta.anchor];
289
+ drawQueries();
290
+
291
+ function update() {
292
+ const t = state.t, trackMode = state.mode === 'track';
293
+ const accum = !trackMode && opt('accum').checked;
294
+ // Options stay in place and are greyed out when they do not apply.
295
+ const avail = (id, on) => { opt(id).disabled = !on; opt(id).parentElement.classList.toggle('off', !on); };
296
+ ['trails', 'moving', 'current'].forEach(id => avail(id, trackMode));
297
+ avail('accum', !trackMode);
298
+ u.fade.value = trackMode ? TRACK_FADE : 0; // so the trajectories stand out
299
+ trackPts.visible = trackMode;
300
+ if (trackMode) {
301
+ trackPos.array.set(track.frames.subarray(t * track.n * 3, (t + 1) * track.n * 3));
302
+ trackPos.needsUpdate = true;
303
+ }
304
+ reconPts.visible = !trackMode || opt('current').checked;
305
+ const first = accum ? 0 : t;
306
+ reconPts.geometry.setDrawRange(recon.offsets[first], recon.offsets[t + 1] - recon.offsets[first]);
307
+ for (const [name, o] of Object.entries(trailObjs)) {
308
+ o.group.visible = trackMode && opt('trails').checked && name === trailSet();
309
+ o.update(t);
310
+ }
311
+ frustums.forEach((f, i) => {
312
+ f.visible = opt('cams').checked && (i === t || (accum && i < t));
313
+ f.material = i === t ? current : past;
314
+ });
315
+ slider.value = t;
316
+ tlabel.textContent = `${t + 1} / ${T}`;
317
+ $('.framet img').src = meta.frames[t];
318
+ $('.framet figcaption').textContent = `Frame ${t + 1}`;
319
+ dirty = true;
320
+ }
321
+
322
+ function resize() {
323
+ const w = box.clientWidth, h = box.clientHeight;
324
+ renderer.setSize(w, h, false);
325
+ camera.aspect = w / h;
326
+ camera.updateProjectionMatrix();
327
+ const pr = renderer.getPixelRatio();
328
+ Object.values(trailObjs).forEach(o => o.line.material.resolution.set(w * pr, h * pr));
329
+ dirty = true;
330
+ }
331
+ new ResizeObserver(resize).observe(box);
332
+ resize();
333
+ resetCamera();
334
+ update();
335
+ overlay.style.display = 'none';
336
+
337
+ let last = performance.now(), acc = 0;
338
+ function frame(now) {
339
+ requestAnimationFrame(frame);
340
+ const dt = Math.min(now - last, 100); last = now;
341
+ if (state.playing) {
342
+ acc += dt;
343
+ if (acc >= 1000 / FPS + (state.t === T - 1 ? LOOP_PAUSE : 0)) {
344
+ acc = 0;
345
+ state.t = (state.t + 1) % T;
346
+ update();
347
+ }
348
+ }
349
+ if (controls.update()) dirty = true;
350
+ if (!dirty) return;
351
+ dirty = false;
352
+ renderer.render(scene, camera);
353
+ }
354
+ requestAnimationFrame(frame);
355
+ }
356
+
357
+ // ------------------------------------------------------------------ sliders
358
+ // The filled part of every slider's track is a gradient up to --p, so --p follows the value,
359
+ // whether the user moves the thumb or the script sets it.
360
+ const value = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
361
+ document.querySelectorAll('input[type=range]').forEach(el => {
362
+ const paint = () => {
363
+ const lo = +el.min || 0, hi = +el.max;
364
+ el.style.setProperty('--p', (hi > lo ? 100 * (value.get.call(el) - lo) / (hi - lo) : 0) + '%');
365
+ };
366
+ Object.defineProperty(el, 'value', {
367
+ get() { return value.get.call(this); },
368
+ set(v) { value.set.call(this, v); paint(); },
369
+ });
370
+ el.addEventListener('input', paint);
371
+ new MutationObserver(paint).observe(el, { attributes: true, attributeFilter: ['min', 'max'] });
372
+ paint();
373
+ });
374
+
375
+ main().catch(e => {
376
+ document.querySelector('.overlay').textContent = 'Could not load the data: ' + e.message;
377
+ throw e;
378
+ });
379
+ })();
visualize.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write an interactive 4D viewer of the predictions of demo.py as one self-contained HTML file.
2
+
3
+ python visualize.py outputs/demo/predictions.npz [-o viewer.html]
4
+
5
+ Open the file in a browser; it needs neither a server nor Python. The scene is in the camera frame
6
+ of the anchor frame. Clips too long to embed are written as a folder (viewer.html + data/*.js).
7
+ """
8
+
9
+ import argparse
10
+ import base64
11
+ import colorsys
12
+ import gzip
13
+ import json
14
+ import os
15
+ import warnings
16
+
17
+ import cv2
18
+ import numpy as np
19
+
20
+ VIEWER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "viewer")
21
+ VENDOR = ["three.min.js", "OrbitControls.js", "LineSegmentsGeometry.js", "LineMaterial.js", "LineSegments2.js"]
22
+ RADIUS_CLIP = 2.5 # positions are quantised to [-2.5, 2.5] scene radii, as on the project page
23
+ MAX_INLINE = 25e6 # bytes of data embedded in a single file
24
+
25
+
26
+ def trajectory_colors(n: int) -> np.ndarray:
27
+ """One color per trajectory, as in the paper's figures: a full-saturation hue sweep from red to violet."""
28
+ t = np.linspace(0.0, 1.0, n) if n > 1 else np.array([0.5])
29
+ return (np.array([colorsys.hsv_to_rgb(0.78 * v, 1.0, 1.0) for v in t]).reshape(-1, 3) * 255).astype(np.uint8)
30
+
31
+
32
+ def b64gz(arr: np.ndarray) -> str:
33
+ """Byte-shuffle (all low bytes, then all high bytes) + gzip + base64, decoded by the viewer."""
34
+ raw = np.ascontiguousarray(arr)
35
+ if raw.dtype.itemsize > 1:
36
+ raw = raw.view(np.uint8).reshape(-1, raw.dtype.itemsize).T
37
+ return base64.b64encode(gzip.compress(np.ascontiguousarray(raw).tobytes(), 6, mtime=0)).decode()
38
+
39
+
40
+ def edge_keep(points: np.ndarray, tol: float = 0.05, grow: int = 5) -> np.ndarray:
41
+ """(T, H, W) mask of the pixels that are not flying pixels, i.e. where the log-distance to the
42
+ camera changes by less than `tol` per pixel, dilated by `grow` pixels as on the project page."""
43
+ keep = np.ones(points.shape[:3], bool)
44
+ for t, p in enumerate(points):
45
+ lr = np.log(np.linalg.norm(np.nan_to_num(p), axis=-1) + 1e-6).astype(np.float32)
46
+ g = np.hypot(cv2.Sobel(lr, cv2.CV_32F, 1, 0, ksize=3), cv2.Sobel(lr, cv2.CV_32F, 0, 1, ksize=3)) / 8
47
+ keep[t] = cv2.dilate((~(g <= tol)).astype(np.uint8), np.ones((grow, grow), np.uint8)) == 0
48
+ return keep
49
+
50
+
51
+ def conf_rank(conf: np.ndarray) -> np.ndarray:
52
+ """Per-pixel confidence percentile in [0, 100] (uint8), so the viewer can threshold by percentile."""
53
+ rank = np.empty(conf.size, np.float64)
54
+ rank[np.argsort(conf, axis=None, kind="stable")] = np.arange(conf.size)
55
+ return (100 * rank / max(conf.size - 1, 1)).reshape(conf.shape).astype(np.uint8)
56
+
57
+
58
+ def jpeg(img: np.ndarray, width: int = 360) -> str:
59
+ h, w = img.shape[:2]
60
+ img = cv2.resize((img * 255).astype(np.uint8), (width, round(h * width / w)), interpolation=cv2.INTER_AREA)
61
+ ok, buf = cv2.imencode(".jpg", cv2.cvtColor(img, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 82])
62
+ return "data:image/jpeg;base64," + base64.b64encode(buf.tobytes()).decode()
63
+
64
+
65
+ def coherent(disp, mask, max_dev, r=2):
66
+ """(h, w) mask of the tracks in `mask` whose displacements (T, h, w, 3) stay within `max_dev` of
67
+ their own travel from the median displacement of the masked tracks in a (2r+1)^2 neighborhood.
68
+ Rejects tracks that start on the boundary of a moving object and partly follow its background."""
69
+ d = np.where(mask[None, ..., None], disp, np.nan)
70
+ d = np.pad(d, ((0, 0), (r, r), (r, r), (0, 0)), constant_values=np.nan)
71
+ win = np.lib.stride_tricks.sliding_window_view(d, (2 * r + 1, 2 * r + 1), axis=(1, 2)) # (T, h, w, 3, k, k)
72
+ ys, xs = np.nonzero(mask) # only the masked tracks are tested
73
+ with warnings.catch_warnings():
74
+ warnings.simplefilter("ignore", RuntimeWarning) # all-NaN windows of tracks with NaN displacements
75
+ ref = np.nanmedian(win[:, ys, xs].reshape(len(win), len(ys), 3, -1), axis=-1)
76
+ dev = np.linalg.norm(disp[:, ys, xs] - ref, axis=-1).max(axis=0)
77
+ travel = np.linalg.norm(disp[:, ys, xs], axis=-1).max(axis=0)
78
+ keep = np.zeros_like(mask)
79
+ keep[ys, xs] = dev <= max_dev * travel
80
+ return keep
81
+
82
+
83
+ def select_tracks(tracks, conf, anchor, grid, max_tracks, min_motion, max_dev, min_group=10, min_conf=0.05):
84
+ """Pixels on a `grid` of confident anchor pixels, sampled to `max_tracks` in image order, either among
85
+ the moving ones (tracks travelling more than `min_motion` of their distance from the anchor camera and
86
+ moving coherently with their neighbors) or among all."""
87
+ H, W = conf.shape[1:]
88
+ ys, xs = np.mgrid[grid // 2:H:grid, grid // 2:W:grid]
89
+ # A low cut: small moving objects in front of a large textured background (rollerblade) can have most
90
+ # of their pixels in the lowest fifth of the confidence.
91
+ keep = conf[anchor, ys, xs] >= np.quantile(conf[anchor], min_conf)
92
+ xyz = tracks[:, ys, xs]
93
+ # Relative to each point's own distance from the anchor camera: depth errors grow with distance, and
94
+ # a far background that drifts by a few percent must not count as moving.
95
+ motion = np.linalg.norm(xyz - xyz[anchor], axis=-1).max(axis=0)
96
+ moving = keep & (motion > min_motion * np.linalg.norm(xyz[anchor], axis=-1))
97
+ moving = coherent(xyz - xyz[anchor], moving, max_dev)
98
+ padded = np.pad(moving, 1) # drop isolated pixels (depth edges): keep those with >= 5 of 8 moving neighbors
99
+ neighbors = sum(padded[1 + dy:padded.shape[0] - 1 + dy, 1 + dx:padded.shape[1] - 1 + dx]
100
+ for dy in (-1, 0, 1) for dx in (-1, 0, 1) if dy or dx)
101
+ moving = moving & (neighbors >= 5)
102
+ # and drop the small groups left over, e.g. from a drifting patch of sky
103
+ n, labels, stats, _ = cv2.connectedComponentsWithStats(moving.astype(np.uint8), connectivity=8)
104
+ moving = np.isin(labels, np.flatnonzero(stats[:, cv2.CC_STAT_AREA] >= min_group)) & moving
105
+ moving = moving[keep]
106
+ ys, xs = ys[keep], xs[keep]
107
+ print(f"{moving.sum()} of {len(ys)} candidate tracks are moving")
108
+ sets = {}
109
+ for name, sel in (("moving", np.flatnonzero(moving)), ("all", np.arange(len(ys)))):
110
+ sel = sel[np.linspace(0, len(sel) - 1, min(len(sel), max_tracks)).astype(int)] if len(sel) else sel
111
+ sets[name] = ys[sel], xs[sel] # image order, so neighboring queries get neighboring hues
112
+ return sets
113
+
114
+
115
+ def export(pred, args):
116
+ """The viewer's data as a list of payloads: the scene description, the dense tracks and the
117
+ per-frame point maps in chunks of frames."""
118
+ images, points, tracks, conf = pred["images"], pred["points"], pred["tracks"], pred["conf"]
119
+ T, H, W = conf.shape
120
+ a, s = args.anchor, args.stride
121
+
122
+ # Normalise to the scene's centre and radius and flip OpenCV (y down) to three.js (y up) axes.
123
+ ref = points[a][(conf[a] >= np.quantile(conf[a], 0.2)) & np.isfinite(points[a]).all(-1)]
124
+ center = np.median(ref, axis=0)
125
+ radius = float(np.percentile(np.linalg.norm(ref - center, axis=-1), 90))
126
+ to_view = lambda p: (p - center) / radius * np.array([1.0, -1.0, -1.0])
127
+ inside = lambda v: np.isfinite(v).all(-1) & (np.linalg.norm(v, axis=-1) < RADIUS_CLIP)
128
+ quant = lambda v: np.round(np.clip(np.nan_to_num(v) / RADIUS_CLIP, -1, 1) * 32767).astype(np.int16)
129
+
130
+ edge = edge_keep(points)[:, ::s, ::s].reshape(T, -1)
131
+ rank = np.stack([conf_rank(c[::s, ::s]) for c in conf]).reshape(T, -1)
132
+ rgb = (images[:, ::s, ::s] * 255).astype(np.uint8).reshape(T, -1, 3)
133
+
134
+ # Reconstruction: every frame's point map at the anchor's viewpoint.
135
+ recon = []
136
+ for t0 in range(0, T, args.chunk):
137
+ pos, col, cnf, counts = [], [], [], []
138
+ for t in range(t0, min(t0 + args.chunk, T)):
139
+ v = to_view(points[t, ::s, ::s].reshape(-1, 3))
140
+ keep = inside(v) & edge[t]
141
+ pos.append(quant(v[keep]))
142
+ col.append(rgb[t][keep])
143
+ cnf.append(rank[t][keep])
144
+ counts.append(int(keep.sum()))
145
+ recon.append(dict(kind="recon", first=t0, counts=counts, pos=b64gz(np.concatenate(pos)),
146
+ col=b64gz(np.concatenate(col)), conf=b64gz(np.concatenate(cnf))))
147
+
148
+ # Tracking: the anchor's pixels carried to every frame, as frame-to-frame deltas that are zero
149
+ # wherever the scene is static (int16 wraps exactly).
150
+ v = to_view(tracks[:, ::s, ::s].reshape(T, -1, 3))
151
+ keep = inside(v[a]) & edge[a] & np.isfinite(v).all(-1).all(0)
152
+ q = quant(v[:, keep])
153
+ delta = np.diff(q, axis=0, prepend=np.zeros_like(q[:1]))
154
+ track = dict(kind="track", n=int(keep.sum()), pos=b64gz(delta.transpose(0, 2, 1)), # (T, 3, N)
155
+ col=b64gz(rgb[a][keep]), conf=b64gz(rank[a][keep]))
156
+
157
+ # Trajectories of the displayed tracks, for the moving pixels only and for all of them.
158
+ sets = select_tracks(tracks, conf, a, args.track_grid, args.max_tracks, args.min_motion,
159
+ args.max_dev)
160
+ trails = {name: dict(uv=np.round(np.stack([xs / W, ys / H], 1), 4).tolist(),
161
+ colors=trajectory_colors(len(ys)).tolist(), pos=b64gz(quant(to_view(tracks[:, ys, xs]))))
162
+ for name, (ys, xs) in sets.items()}
163
+
164
+ # Camera frustums (apex and four image corners).
165
+ c2w, focal = pred["cam2world"].astype(np.float64), pred["focal"]
166
+ depth = 0.075 * radius
167
+ corners = np.array([[0, 0, 0], [-W / 2, -H / 2, 1], [W / 2, -H / 2, 1], [W / 2, H / 2, 1], [-W / 2, H / 2, 1]])
168
+ frustums = [to_view((corners * [depth / f, depth / f, depth]) @ c[:3, :3].T + c[:3, 3])
169
+ for c, f in zip(c2w, focal)]
170
+ # Initial view: behind, beside and above the anchor camera, looking at the moving points if any,
171
+ # otherwise at the median depth along the optical axis.
172
+ ys, xs = sets["moving"]
173
+ if len(ys):
174
+ target = to_view(np.nanmedian(tracks[:, ys, xs].reshape(-1, 3), axis=0))
175
+ else:
176
+ target = to_view(c2w[a, :3, 3] + c2w[a, :3, 2] * np.median(np.linalg.norm(ref, axis=-1)))
177
+ offset = to_view(c2w[a, :3, 3]) - target
178
+ offset *= max(1.6, 0.8 / np.linalg.norm(offset))
179
+ az, el = np.radians(-25), np.radians(-15)
180
+ offset = np.array([[np.cos(az), 0, np.sin(az)], [0, 1, 0], [-np.sin(az), 0, np.cos(az)]]) @ offset
181
+ offset = np.array([[1, 0, 0], [0, np.cos(el), -np.sin(el)], [0, np.sin(el), np.cos(el)]]) @ offset
182
+ # Point size: three.js draws a point of size p about 0.32 p wide (36 deg field of view), so 4x the
183
+ # spacing of the subsampled pixels closes the gaps between them.
184
+ pitch = s * np.median(np.linalg.norm(ref, axis=-1)) / np.median(focal) / radius
185
+
186
+ meta = dict(kind="meta", name=args.name, T=T, w=W, h=H, anchor=a, pointSize=round(float(4 * pitch), 5),
187
+ cam=dict(pos=np.round(target + offset, 4).tolist(), target=np.round(target, 4).tolist()),
188
+ frustums=np.round(np.stack(frustums), 4).tolist(), trails=trails,
189
+ frames=[jpeg(im) for im in images])
190
+ return [meta, track] + recon
191
+
192
+
193
+ def write_viewer(pred, out, name="", anchor=0, stride=2, track_grid=4, max_tracks=400, min_motion=0.3,
194
+ max_dev=0.25, chunk=16, max_inline=MAX_INLINE) -> str:
195
+ """Writes the viewer of the predictions to out; returns the path of the page (a folder's
196
+ viewer.html if the data is larger than max_inline bytes). The options are those of the command line."""
197
+ args = argparse.Namespace(name=name, anchor=anchor, stride=stride, track_grid=track_grid, max_tracks=max_tracks,
198
+ min_motion=min_motion, max_dev=max_dev, chunk=chunk)
199
+ payloads = [f"F4RT.add({json.dumps(p, separators=(',', ':'))});\n" for p in export(pred, args)]
200
+ read = lambda path: open(os.path.join(VIEWER, path)).read()
201
+ scripts = "".join(f"<script>\n{read(os.path.join('vendor', f))}</script>\n" for f in VENDOR)
202
+ scripts += f"<script>\n{read('viewer.js')}</script>\n"
203
+ page = read("template.html").replace("{{TITLE}}", name)
204
+
205
+ size = sum(map(len, payloads))
206
+ if size <= max_inline:
207
+ data = "".join(f"<script>{p}</script>\n" for p in payloads)
208
+ with open(out, "w") as f:
209
+ f.write(page.replace("{{SCRIPTS}}", data + scripts))
210
+ print(f"Wrote {out} ({os.path.getsize(out) / 1e6:.1f} MB); open it in a browser")
211
+ return out
212
+ # Too large to embed: a folder whose page loads the data by <script> tags, which work on file://.
213
+ folder = os.path.splitext(out)[0]
214
+ os.makedirs(os.path.join(folder, "data"), exist_ok=True)
215
+ tags = ""
216
+ for i, p in enumerate(payloads):
217
+ with open(os.path.join(folder, "data", f"{i:03d}.js"), "w") as f:
218
+ f.write(p)
219
+ tags += f'<script src="data/{i:03d}.js"></script>\n'
220
+ page_path = os.path.join(folder, "viewer.html")
221
+ with open(page_path, "w") as f:
222
+ f.write(page.replace("{{SCRIPTS}}", tags + scripts))
223
+ print(f"Data too large to embed ({size / 1e6:.0f} MB): wrote the folder {folder}/; open {page_path}")
224
+ return page_path
225
+
226
+
227
+ def main():
228
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
229
+ parser.add_argument("predictions", help="predictions.npz written by demo.py")
230
+ parser.add_argument("-o", "--output", help="output HTML file (default: viewer.html next to the predictions)")
231
+ parser.add_argument("--stride", type=int, default=2, help="pixel subsampling of the point clouds")
232
+ parser.add_argument("--track_grid", type=int, default=4, help="pixel spacing of the candidate tracks")
233
+ parser.add_argument("--max_tracks", type=int, default=400, help="number of displayed tracks")
234
+ parser.add_argument("--min_motion", type=float, default=0.3,
235
+ help="a track is moving if it travels more than this fraction of its distance from the "
236
+ "anchor camera")
237
+ parser.add_argument("--max_dev", type=float, default=0.25,
238
+ help="drop moving tracks that deviate from their neighbors by more than this fraction "
239
+ "of their travel (boundaries of moving objects)")
240
+ parser.add_argument("--anchor", type=int, default=0, help="the anchor frame used in demo.py")
241
+ parser.add_argument("--chunk", type=int, default=16, help="frames per point-map payload")
242
+ args = parser.parse_args()
243
+ out = args.output or os.path.join(os.path.dirname(os.path.abspath(args.predictions)), "viewer.html")
244
+ name = os.path.basename(os.path.dirname(os.path.abspath(args.predictions)))
245
+ opts = {k: v for k, v in vars(args).items() if k not in ("predictions", "output")}
246
+ write_viewer(np.load(args.predictions), out, name, **opts)
247
+
248
+
249
+ if __name__ == "__main__":
250
+ main()