Ultra-Water README

README проекта с github.com/Humpalumps/Ultra-Water. Одним файлом markdown: README.md.

Ultra Water

Real-time ocean renderer for three.js (WebGL2), with a demo island scene.

npm install
npm run dev

Open the printed localhost URL. Orbit with the mouse (or a finger: phones get their own profile, see Phones and tablets). It opens on the Lagoon shot. Pick others from the camera dropdown (they also set the sun). The performance panel (top left) shows the GPU, render size, fps, ms per frame and a 20 s graph. Its Uncap FPS button switches the loop off the display's refresh: frames then render back-to-back, with at most three in flight on the GPU, so the counter shows what the machine can do while the scene keeps running live. The screen still updates at its own rate. Cap to display switches back. Run benchmark (also benchmark (uncapped) in the settings) renders 300 frames back-to-back with the render loop paused and times them to GPU completion with a fence. The screen freezes for about a second while it runs, so it only runs when asked.

Performance

Measured with the in-page benchmark on an RTX 3060 (Chrome, ANGLE/D3D11), 4× MSAA, all features on, at 1954×1692 (3.3 MP, the pixel count of 1440p; devicePixelRatio 2 on the browser window):

Shot ms / frame fps (uncapped)
Open ocean 3.30 ~303
Golden hour 4.35 ~230
Aerial 4.90 ~204
Underwater 4.93 ~203
Breakers 4.95 ~202
Lagoon 5.32 ~188
Flotsam (10 floating props) 5.79 ~173
Surf rock 5.92 ~169

Per pass in Breakers: water 1.90 ms, opaque (island, rocks, props) 1.63, post 0.38, caustics 0.22, FFT sim ~0.45 (independent of resolution). Caustics cost more under a low sun (about 0.37 ms in Golden hour), because the refracted rays fold more. Lagoon, Flotsam and Surf rock look down into the shallows, where nearly every water pixel runs the shore waves, foam and swash, so their water pass is 2.6–3.0 ms.

Earlier versions of this README quoted numbers 2–4× lower. Those came from a benchmark that synced with readPixels/finish, which ANGLE doesn't wait on. The fence-based benchmark is the one to trust. The HUD's GPU timer-query numbers read high while vsync-capped, because the GPU downclocks between frames.

Phones and tablets

The same build spots phones and tablets (a finger as the main pointer, matchMedia('(pointer: coarse)')) and starts them on a lighter profile. Desktop is unchanged. Add ?mobile or ?desktop to the URL to force either.

The mobile profile is resolution 0.6 (of the device pixel ratio, capped at 2), 2× MSAA, reflections at 0.35 scale and no bloom. On a phone the cost is mostly the number of render passes Chrome's GPU process has to translate, not pixels, so dropping bloom's 12 passes did more than lowering resolution. Auto resolution (auto resolution in the Quality folder) steps down by 0.05, to a floor of 0.5, when more than 4% of frames miss vsync over 2 s. It climbs back to 0.6 once frames are clean, and locks to a steady 30 fps if the floor still misses more than a quarter.

Measured before the shore update (surf rock, clear shallows, wet sand), on a OnePlus Nord 4 (Snapdragon 7+ Gen 3, Adreno 732, Chrome 156, which runs pages at 60 Hz on it), portrait, 424×782:

Shot live fps missed frames fps (uncapped)
Open ocean 60 0% 142
Aerial 60 0% 118
Underwater 60 0% 103
Lagoon 60 0% 102
Flotsam 60 0% 101
Golden hour 60 0% 99
Breakers 60 0% 95

With the desktop settings (708×1304, 4× MSAA, bloom) the same phone ran 41–50 fps live, missing up to a third of its frames, and 62 fps uncapped on average. Phone numbers move with temperature. These were taken warm (thermal status 1) while charging over USB.

What's in it

Waves (src/water/OceanSim.js)

Surface (src/water/OceanSurface.js)

Caustics (src/water/Caustics.js)

Underwater (src/water/UnderwaterPass.js, underside branch in OceanSurface.js)

Floating objects (src/water/WaterQuery.js, src/scene/floaters.js, src/scene/floaterMeshes.js, src/scene/floaterShadow.js)

Pipeline (src/main.js)

  1. Ingest the last water query, step the floaters, then:
    • render the floater shadow map;
    • update the impact rings;
    • run the FFT;
    • splat the caustics;
    • submit the next query.
  2. Planar reflection (half res, skipped underwater).
  3. Opaque pass into a single 4× MSAA HDR target.
  4. Water pass, depth-tested against the kept MSAA depth for correct per-sample edges.
  5. Underwater pass, when near or below the surface.
  6. Post (PostFX.js):
    • GPU auto exposure, metered in log space and adapted over time; the GUI value is compensation.
    • Dual-filter bloom with Karis average.
    • AgX.
    • Lens droplets.
    • TPDF dither.

Scene

The Water folder has a colour preset dropdown (clear, tropical, toxic green, purple, rust orange, murky brown). Each sets the absorption, in-scatter colour, thin-foam tint and underwater scattering together; clarity and scatter still adjust on top.

Camera presets: Golden hour, Breakers, Lagoon, Surf rock, Open ocean, Aerial, Flotsam and Underwater. Flotsam and Underwater spawn a field of floating props. The Floaters & underwater folder has spawn, drop and clear buttons, plus drag, buoyancy, scattering, shaft and meniscus controls.

Not in yet

The design was argued out with a second agent before building, and again for each round of upgrades.

License

MIT, see LICENSE. Code adapted from other projects is listed in THIRD_PARTY_NOTICES.md.

Ultra-Water (Humpalumps/Ultra-Water)

Ищем в базе…

Что это такое?Ultra Water — это рендерер океана в реальном времени на основе быстрого преобразования Фурье (FFT), созданный для three.js (WebGL2). Он охватывает прибойные волны у берега, пену, каустики, подводный рендеринг и плавучесть, и поставляется с демо-сценой острова, которая работает со скоростью 200+ fps.
Это готовое приложение или библиотека, которую я подключаю к своей сцене three.js?Это набор JS-модулей (OceanSim.js, OceanSurface.js, Caustics.js, UnderwaterPass.js, WaterQuery.js и др.), которые встраиваются в сцену three.js. В репозиторий также входит демо-страница для запуска, с островом, плавающими объектами и графическим интерфейсом (GUI) для их демонстрации.
Как попробовать демо?Запустите локальный сервер разработки проекта и откройте в браузере выведенный адрес localhost, затем вращайте камеру мышью (или пальцем на сенсорных устройствах).
Нужна ли дискретная видеокарта для хорошей производительности?Основные показатели (200–300+ fps) измерены на RTX 3060, но та же сборка работает и на телефонах, например на OnePlus Nord 4, поддерживая 60 fps в реальном времени за счёт автоматического масштабирования разрешения. Поэтому дискретная видеокарта не обязательна, достаточно браузера с поддержкой WebGL2.
Каких возможностей океана пока не хватает?Движущиеся объекты не оставляют следов в воде (плавающие объекты создают кольца брызг только при падении в воду), плавающие объекты не сталкиваются друг с другом, волны у берега только наклоняются, но никогда не закручиваются в полноценную трубу, а сетка поверхности прямо у камеры грубая.
Чем мобильный профиль отличается от десктопного?Он автоматически определяет сенсорный ввод и переключается на более лёгкий профиль (масштаб разрешения 0,6, 2x MSAA, отражения в масштабе 0,35, без bloom). Если кадры начинают пропускать вертикальную синхронизацию (vsync), разрешение снижается ещё сильнее. Параметры ?mobile или ?desktop в URL позволяют принудительно выбрать любой из режимов.
Как моделируются прибойные волны у берега?Они работают на поле времени распространения волны (эйконал), которое вычисляется методом быстрого обхода (fast sweeping) от берега. Поэтому фронты волн замедляются, сгущаются и преломляются вокруг батиметрии (рельефа дна), неравномерно разваливаются вдоль каждого гребня и затухают там, где фронты от разных участков берега сталкиваются, вместо того чтобы складываться в сплошные полотна.
Могу ли я сам проверить производительность?Да. Встроенная панель показывает GPU, размер рендера, fps и график времени кадра, а кнопка Run benchmark рендерит 300 кадров подряд. Время замеряется до завершения работы GPU с помощью fence, поэтому результаты надёжны.
Могу ли я изменить внешний вид воды?Выпадающий список цветовых пресетов переключает между чистой, тропической, токсично-зелёной, фиолетовой, ржаво-оранжевой и мутно-коричневой водой. Каждый пресет сразу задаёт поглощение, цвет рассеивания внутрь, оттенок пены и рассеивание под водой, а прозрачность и рассеивание остаются настраиваемыми поверх них.
Автор
Humpalumps
Размер
0.2 MB
Звёзды
679
Обновлён
КоммитNov 02
Возраст
21 д
Коммиты · 90 дней