Узнайте, как использовать оценку освещенности в своих приложениях.
Предварительные требования
Прежде чем продолжить, убедитесь, что вы понимаете основные концепции дополненной реальности и как настроить сессию ARCore .
Настраивайте API один раз за сессию, выбрав соответствующий режим.
Настраивайте расчет освещенности один раз за сессию для того режима, который вы хотите использовать.
Java
// Configure the session with the Lighting Estimation API in ENVIRONMENTAL_HDR mode.
Config config = session.getConfig();
config.setLightEstimationMode(LightEstimationMode.ENVIRONMENTAL_HDR);
session.configure(config);
// Configure the session with the Lighting Estimation API in AMBIENT_INTENSITY mode.
Config config = session.getConfig();
config.setLightEstimationMode(LightEstimationMode.AMBIENT_INTENSITY);
session.configure(config);
// Configure the session with the Lighting Estimation API turned off.
Config config = session.getConfig();
config.setLightEstimationMode(LightEstimationMode.DISABLED);
session.configure(config);
Котлин
// Configure the session with the Lighting Estimation API in ENVIRONMENTAL_HDR mode.
Config config = session.config
config.lightEstimationMode = LightEstimationMode.ENVIRONMENTAL_HDR
session.configure(config)
// Configure the session with the Lighting Estimation API in AMBIENT_INTENSITY mode.
Config config = session.config
config.lightEstimationMode = LightEstimationMode.AMBIENT_INTENSITY
session.configure(config)
// Configure the session with the Lighting Estimation API turned off.
Config config = session.config
config.lightEstimationMode = LightEstimationMode.DISABLED
session.configure(config)
Configure ENVIRONMENTAL_HDR mode
To configure ENVIRONMENTAL_HDR mode, get the light estimate for each frame, then get the environmental HDR lighting components you want to use.
Java
void update() {
// Get the current frame.
Frame frame = session.update();
// Get the light estimate for the current frame.
LightEstimate lightEstimate = frame.getLightEstimate();
// Get intensity and direction of the main directional light from the current light estimate.
float[] intensity = lightEstimate.getEnvironmentalHdrMainLightIntensity(); // note - currently only out param.
float[] direction = lightEstimate.getEnvironmentalHdrMainLightDirection();
app.setDirectionalLightValues(intensity, direction); // app-specific code.
// Get ambient lighting as spherical harmonics coefficients.
float[] harmonics = lightEstimate.getEnvironmentalHdrAmbientSphericalHarmonics();
app.setAmbientSphericalHarmonicsLightValues(harmonics); // app-specific code.
// Get HDR environmental lighting as a cubemap in linear color space.
Image[] lightmaps = lightEstimate.acquireEnvironmentalHdrCubeMap();
for (int i = 0; i < lightmaps.length /*should be 6*/; ++i) {
app.uploadToTexture(i, lightmaps[i]); // app-specific code.
}
}
Котлин
fun update() {
// Get the current frame.
val frame = session.update()
// Get the light estimate for the current frame.
val lightEstimate = frame.lightEstimate
// Get intensity and direction of the main directional light from the current light estimate.
val intensity = lightEstimate.environmentalHdrMainLightIntensity
val direction = lightEstimate.environmentalHdrMainLightDirection
app.setDirectionalLightValues(intensity, direction) // app-specific code.
// Get ambient lighting as spherical harmonics coefficients.
val harmonics = lightEstimate.environmentalHdrAmbientSphericalHarmonics
app.ambientSphericalHarmonicsLightValues = harmonics // app-specific code.
// Get HDR environmental lighting as a cubemap in linear color space.
val lightMaps = lightEstimate.acquireEnvironmentalHdrCubeMap();
for ((index, lightMap) in lightMaps.withIndex()) { // 6 maps total.
app.uploadToTexture(index, lightMap); // app-specific code.
}
}
Configure AMBIENT_INTENSITY mode
Если вы планируете использовать компонент цветокоррекции в режиме AMBIENT_INTENSITY , сначала избегайте выделения памяти для цветокоррекции на каждом кадре, повторно используя общее выделение памяти.
Java
// Avoid allocation on every frame.
float[] colorCorrection = new float[4];
Котлин
val colorCorrection = floatArrayOf(0.0f, 0.0f, 0.0f, 0.0f)
Получите приблизительную оценку освещенности для каждого кадра, а затем определите компоненты интенсивности окружающего освещения, которые вы хотите использовать.
Java
void update() {
// Get the current frame.
Frame frame = session.update();
// Get the light estimate for the current frame.
LightEstimate lightEstimate = frame.getLightEstimate();
// Get the pixel intensity of AMBIENT_INTENSITY mode.
float pixelIntensity = lightEstimate.getPixelIntensity();
// Read the pixel color correction of AMBIENT_INTENSITY mode into colorCorrection.
lightEstimate.getColorCorrection(colorCorrection, 0);
}
Котлин
fun update() {
// Get the current frame.
val frame = session.update()
// Get the light estimate for the current frame.
val lightEstimate = frame.lightEstimate
// Get the pixel intensity of AMBIENT_INTENSITY mode.
val pixelIntensity = lightEstimate.pixelIntensity
// Read the pixel color correction of AMBIENT_INTENSITY mode into colorCorrection.
lightEstimate.getColorCorrection(colorCorrection, 0)
}
Обеспечение энергосбережения с помощью API-интерфейсов Environmental HDR.
Принцип сохранения энергии гласит, что свет, отраженный от поверхности, никогда не станет интенсивнее, чем был до того, как достиг поверхности. Это правило соблюдается в физически корректном рендеринге, но обычно игнорируется в устаревших конвейерах рендеринга, используемых в видеоиграх и мобильных приложениях.
Если вы используете конвейер физически корректного рендеринга с оценкой освещения Environmental HDR, просто убедитесь, что в ваших виртуальных объектах используются физически корректные материалы.
Однако, если вы не используете конвейер обработки данных, основанный на физических принципах, у вас есть несколько вариантов:
Наиболее оптимальным решением в этом случае является переход на конвейер обработки данных, основанный на физическом принципе.
Однако, если это невозможно, хорошим обходным путем является умножение значения альбедо для материала, не основанного на физических принципах, на коэффициент сохранения энергии. Это может гарантировать, что, по крайней мере, модель затенения BRDF может быть преобразована в физически обоснованную. Каждая модель BRDF имеет свой коэффициент — например, для диффузного отражения он равен 1/Pi.