Three.js

Three.js

Константы

Анимационные константы

Цикличные режимы (loop modes)

однократное воспроизведение клипа');" onmouseout="hide()">THREE.LoopOnce

клип проигрывается выбранное количество
раз (указанное в параметре repetitions),
всякий раз переходя с конца клипа
непосредственно на его начало');" onmouseout="hide()">THREE.LoopRepeat

воспроизводится выбранное количество раз
(указанное в параметре repetitions),
проигрывая его поочередно вперед и назад');" onmouseout="hide()">THREE.LoopPingPong

Режимы интерполяции (interpolation modes)

THREE.InterpolateDiscrete
THREE.InterpolateLinear
THREE.InterpolateSmooth

Режимы окончания (ending modes)

THREE.ZeroCurvatureEnding
THREE.ZeroSlopeEnding
THREE.WrapAroundEnding

Исходники



Константы ядра

Номер версии (revision number)

THREE.REV
Номер текущей версии three.js.

Кнопки мышки (mouse buttons)

THREE.MOUSE.LEFT
THREE.MOUSE.MIDDLE
THREE.MOUSE.RIGHT

Исходники



Константы настраиваемых уравнений смешивания

Пример

materials / blending / custom

Применение

Константы работают со всеми типами материалов. Вначале устанавливается режим смешивания материалов (THREE.CustomBlending), затем устанавливается желаемые уравнение смешивания (Blending Equation), исходный фактор (Source Factor) и целевой фактор (Destination Factor).
var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} );
material.blending = THREE.CustomBlending;
material.blendEquation = THREE.AddEquation; // по умолчанию
material.blendSrc = THREE.SrcAlphaFactor; // по умолчанию
material.blendDst = THREE.OneMinusDstAlphaFactor; // по умолчанию

Уравнения смешивания (blending equations)

THREE.AddEquation
THREE.SubtractEquation
THREE.ReverseSubtractEquation
THREE.MinEquation
THREE.MaxEquation

Исходные факторы (source factors)

THREE.ZeroFactor
THREE.OneFactor
THREE.SrcColorFactor
THREE.OneMinusSrcColorFactor
THREE.SrcAlphaFactor
THREE.OneMinusSrcAlphaFactor
THREE.DstAlphaFactor
THREE.OneMinusDstAlphaFactor
THREE.DstColorFactor
THREE.OneMinusDstColorFactor
THREE.SrcAlphaSaturateFactor

Целевые факторы (destination factors)

Все исходные факторы работают и как целевые, за исключением THREE.SrcAlphaSaturateFactor.

Исходники



Константы режима рисования

Это действующие значения для свойства Mesh.drawMode, и управляют тем, как список вершин будет интерпретирован после отправки в графический процессор (GPU).
Обратите внимание, что это все работает только когда Mesh.geometry является BufferGeometry. Изменение констант, когда Mesh.geometry является Geometry, не окажет никакого влияния.

Режимы рисования (draw modes)

THREE.TrianglesDrawMode
Этот режим устанавливается по умолчанию и приводит к тому, что каждые три последовательные вершины (v0, v1, v2), (v2, v3, v5), ... будут интерпретированы как отдельный треугольник.
Если число вершин не кратно 3, избыточные вершины игнорируются.
THREE.TriangleStripDrawMode
Этот режим приведет к последовательности треугольников, соединенных в ленту, представленную как (v0, v1, v2), (v2, v1, v3), (v2, v3, v4), ... так что каждый предыдущий треугольник имеет две общие вершины с предыдущим треугольником.
THREE.TriangleFanDrawMode
В результате этого режима появятся последовательности треугольников, в каждом из которых имеется одна общая вершина (подобно лопастям вентилятора - fan), представленные как (v0, v1, v2), (v0, v2, v3), (v0, v3, v4), и т.д.
Примечание: Этот режим не поддерживается DirectX10. (Вот DirectX10 на русском языке.) Браузеры Chrome и Firefox представляют WebGL на Windows при помощи ANGLE, преобразовывая внутри себя этот режим в поддерживаемый, что, скорее всего приведет к снижению производительности этих браузеров.
Примечание переводчика: ANGLE (Almost Native Graphics Layer Engine - практически встроенный движок графического слоя, а перевод самой аббревиатуры ANGLE - угол) это графический движок слоя абстракций, разработанный компанией Google, с открытым исходным кодом под лицензией BSD. Этот API в основном предназначен для обеспечения высокопроизводительной совместимости OpenGL с компьютерами Windows и веб-браузерами вроде Chromium, путем перевода вызовов OpenGL в Direct3D, который гораздо лучше поддерживается драйверами. Для ANGLE существует два внутренних визуализатора: самый старый использует Direct3D 9.0c, в то время как новый использует Direct3D 11.
из вышеприведенной статьи англ. Википедии, перевод мой.

Применение

var geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vector3( -10, 10, 0 ), new THREE.Vector3( -10, -10, 0 ), new THREE.Vector3( 10, -10, 0 ), ... ); geometry.faces.push( new THREE.Face3( 0, 1, 2 ), ... );
var material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
var mesh = new THREE.Mesh( geometry, material ); mesh.drawMode = THREE.TrianglesDrawMode; // default (по умолчанию)
scene.add( mesh );

Исходники


Константы материалов

Эти константы определяют свойства, общие для всех типов материала, за исключением операций комбинирования текстур (Texture Combine Operations), которые применяются только к MeshBasicMaterial, MeshLambertMaterial и MeshPhongMaterial.

Сторона (side)

THREE.FrontSide
THREE.BackSide
THREE.DoubleSide
Эти константы определяют какая сторона грани будет отображаться - передняя (front), задняя (back) или обе. По умолчанию используется FrontSide.

Цвета (colors)

THREE.NoColors
THREE.FaceColors
THREE.VertexColors
NoColors используется по умолчанию и применяет ко всем граням (поверхностям) цвет материала.
FaceColors окрашивает грани (т.е. ячейки каркаса) в соответствии со значением цвета color каждой треугольной грани Face3.
VertexColors окрашивает грани в соответствии со значением vertexColors каждой из вершин грани Face3. Это массив из трех значений color, по одному для каждой вершины грани.
Смотрите пример geometry / colors.

Режим смешивания (blending mode)

THREE.NoBlending
THREE.NormalBlending
THREE.AdditiveBlending
THREE.SubtractiveBlending
THREE.MultiplyBlending
THREE.CustomBlending
Эти константы управляют исходным и целевым уравнениями для RGB и Alpha материала These control the source and destination blending equations for the material's RGB and Alpha sent to the WebGLRenderer for use by WebGL.
NormalBlending используется по умолчанию.
Обратите внимание, что CustomBlending должен быть установлен для использования Custom Blending Equations.
Смотрите пример materials / blending.

Режим глубины (depth mode)

THREE.NeverDepth
THREE.AlwaysDepth
THREE.LessDepth
THREE.LessEqualDepth
THREE.GreaterEqualDepth
THREE.GreaterDepth
THREE.NotEqualDepth
Which depth function the material uses to compare incoming pixels Z-depth against the current Z-depth buffer value. Если результатом этого сравнения будет значение true, пиксель будет прорисован. If the result of the comparison is true, the pixel will be drawn.
[page:Materials NeverDepth will never return true.
[page:Materials AlwaysDepth will always return true.
[page:Materials LessDepth will return true if the incoming pixel Z-depth is less than the current buffer Z-depth.
[page:Materials LessEqualDepth is the default and will return true if the incoming pixel Z-depth is less than or equal to the current buffer Z-depth.
[page:Materials GreaterEqualDepth will return true if the incoming pixel Z-depth is greater than or equal to the current buffer Z-depth.
[page:Materials GreaterDepth will return true if the incoming pixel Z-depth is greater than the current buffer Z-depth.
[page:Materials NotEqualDepth will return true if the incoming pixel Z-depth is equal to the current buffer Z-depth.

Операции комбинирования (совмещения) текстур

THREE.MultiplyOperation
THREE.MixOperation
THREE.AddOperation
Эти операции определяют каков будет результат при совмещении цвета поверхности с картой цвета среды (если существует), для таких материалов как MeshBasicMaterial, MeshLambertMaterial и MeshPhongMaterial.
MultiplyOperation применяется по умолчанию и перемножает карту цвета среды и цвет поверхности.
MixOperation при смешивании двух цветов используется отражение.
AddOperation добавляет два цвета.

Исходники


Константы WebGLRenderer

Режимы выбраковки граней (cull face modes)

THREE.CullFaceNone
THREE.CullFaceBack
THREE.CullFaceFront
THREE.CullFaceFrontBack
Эти константы используются методом setFaceCulling WebGLRenderer'а.
CullFaceNone отключает выбраковку граней.
CullFaceBack отбрасываются задние грани (эта константа применяется по умолчанию).
CullFaceFront отбрасываются переднии грани.
CullFaceFrontBack отбрасываются обе грани, и передняя и задняя.

Направление передней грани Front Face Direction

THREE.FrontFaceDirectionCW
THREE.FrontFaceDirectionCCW
Эти константы используются методом setFaceCulling WebGLRenderer'а.
FrontFaceDirectionCW sets the winding order for polygons to clockwise.
FrontFaceDirectionCCW sets the winding order for polygons to counter-clockwise (default).

Типы тени Shadow Types

THREE.BasicShadowMap
THREE.PCFShadowMap
THREE.PCFSoftShadowMap
Эти константы определяют свойство shadowMap.type WebGLRenderer'а.
BasicShadowMap дает нефильтрованные карты теней - самые быстрые, но и самые низкокачественные. gives unfiltered shadow maps - fastest, but lowest quality.

тестов на затенение в окрестностях искомого фрагмента и для
затенения используется среднее значение этих тестов, таким
образом, граница тени будет более «мягкой».')"> PCFShadowMap
фильтры теневых карт используют алгоритм Percentage-Closer Filtering - PCF (значение по умолчанию).

реалистичными и приближенными к жизни. Очертания теней
растворяются по мере удаления от объекта, отбрасывающего
тень. Использование технологии PCSS позволяет сделать
очертания теней естественными и избежать «лесенок».')"> PCFSoftShadowMap
фильтры теневых карт используют алгоритм Percentage-Closer Soft Shadows (PCSS).

Tone Mapping

Отображение тонов цвета (tone mapping) - это процесс преобразования диапазона яркостей HDR к LDR диапазону, отображаемому устройством вывода, например, монитором или принтером, так как вывод HDR изображений на них потребует преобразования динамического диапазона и цветового охвата модели HDR в соответствующий динамический диапазон LDR, чаще всего модель RGB. Ведь диапазон яркости, представленный в HDR, очень широк, это несколько порядков абсолютного динамического диапазона единовременно, в одной сцене. А диапазон, который можно воспроизвести на привычных устройствах вывода (мониторах, телевизорах), составляет лишь около двух порядков динамического диапазона.

Преобразование из HDR в LDR и называется tone mapping, оно выполняется с потерями и имитирует свойства человеческого зрения.

THREE.NoToneMapping
THREE.LinearToneMapping
THREE.ReinhardToneMapping
THREE.Uncharted2ToneMapping
THREE.CineonToneMapping
Эти константы определяют свойство toneMapping WebGLRenderer'а. Они используются для приведения внешнего вида изображения в расширенном динамическом диапазоне (high dynamic range - HDR) к возможному отображению их в низком динамическом диапазоне (low dynamic range - LDR) стандартного компьютерного монитора или экрана мобильного устройства.

NoToneMapping отключает отображение тонов.
Значением по умолчанию является LinearToneMapping.
Смотрите пример отображения тонов.

Исходники


Константы текстур

Режимы картирования (Mapping Modes)

THREE.UVMapping
THREE.CubeReflectionMapping
THREE.CubeRefractionMapping
THREE.EquirectangularReflectionMapping
THREE.EquirectangularRefractionMapping
THREE.SphericalReflectionMapping
THREE.CubeUVReflectionMapping
THREE.CubeUVRefractionMapping
Эти константы определяют режим отображения текстуры.These define the texture's mapping mode.
Значением по умолчанию является THREE.UVMapping, при которой текстура накладывается на поверхность объекта в соответствии с координатами UV сетки (mesh).
Остальные константы определяют типы The rest define environment mapping types.
[page:Constant CubeReflectionMapping] and [page:Constant CubeRefractionMapping] are for use with a [page:CubeTexture CubeTexture], which is made up of six textures, one for each face of the cube.
[page:Constant CubeReflectionMapping] is the default for a [page:CubeTexture CubeTexture].

[page:Constant EquirectangularReflectionMapping] and [page:Constant EquirectangularRefractionMapping] are for use with an equirectangular environment map.

[page:Constant SphericalReflectionMapping] is for use with a spherical reflection map.

Смотрите пример materials / envmaps.

Режимы укладки текстур (Wrapping Modes)

THREE.RepeatWrapping
THREE.ClampToEdgeWrapping
THREE.MirroredRepeatWrapping
Эти константы определяют свойства текстур wrapS и wrapT, которые устанавливают стыковку текстур по горизонтали и вертикали.
С константой RepeatWrapping текстура будет попросту повторяться до бесконечности.
По умолчанию применяется константа ClampToEdgeWrapping. Последний пиксел текстуры растягивается до края сетки (mesh).
С константой MirroredRepeatWrapping текстура будет повторяться бесконечно, зеркально отображаясь при каждом повторе.

Фильтры увеличения (Magnification Filters)

THREE.NearestFilter
THREE.LinearFilter
For use with a texture's [page:Texture.magFilter magFilter] property, these define the texture magnification function to be used when the pixel being textured maps to an area less than or equal to one texture element (texel).

[page:constant NearestFilter] returns the value of the texture element that is nearest (in Manhattan distance) to the specified texture coordinates.

[page:constant LinearFilter] is the default and returns the weighted average of the four texture elements that are closest to the specified texture coordinates, and can include items wrapped or repeated from other parts of a texture, depending on the values of [page:Texture.wrapS wrapS] and [page:Texture.wrapT wrapT], and on the exact mapping.

Фильтры минимизации (Minification Filters)

THREE.NearestFilter
THREE.NearestMipMapNearestFilter
THREE.NearestMipMapLinearFilter
THREE.LinearFilter
THREE.LinearMipMapNearestFilter
THREE.LinearMipMapLinearFilter
For use with a texture's [page:Texture.minFilter minFilter] property, these define the texture minifying function that is used whenever the pixel being textured maps to an area greater than one texture element (texel).

In addition to [page:constant NearestFilter] and [page:constant LinearFilter], the following four functions can be used for minification:

[page:constant NearestMipMapNearestFilter] chooses the mipmap that most closely matches the size of the pixel being textured and uses the [page:constant NearestFilter] criterion (the texel nearest to the center of the pixel) to produce a texture value.

[page:constant NearestMipMapLinearFilter] chooses the two mipmaps that most closely match the size of the pixel being textured and uses the [page:constant NearestFilter] criterion to produce a texture value from each mipmap. The final texture value is a weighted average of those two values.

[page:constant LinearMipMapNearestFilter] chooses the mipmap that most closely matches the size of the pixel being textured and uses the [page:constant LinearFilter] criterion (a weighted average of the four texels that are closest to the center of the pixel) to produce a texture value.

[page:constant LinearMipMapLinearFilter] is the default and chooses the two mipmaps that most closely match the size of the pixel being textured and uses the [page:constant LinearFilter] criterion to produce a texture value from each mipmap. The final texture value is a weighted average of those two values.

See the [example:webgl_materials_texture_filters materials / texture / filters] example.

Типы

THREE.UnsignedByteType
THREE.ByteType
THREE.ShortType
THREE.UnsignedShortType
THREE.IntType
THREE.UnsignedIntType
THREE.FloatType
THREE.HalfFloatType
THREE.UnsignedShort4444Type
THREE.UnsignedShort5551Type
THREE.UnsignedShort565Type
THREE.UnsignedInt248Type
Для использования со свойством текстуры type, которое должно соответствовать правильному формату.
Значением по умолчанию является UnsignedByteType.

Форматы

THREE.AlphaFormat
THREE.RGBFormat
THREE.RGBAFormat
THREE.LuminanceFormat
THREE.LuminanceAlphaFormat
THREE.RGBEFormat
THREE.DepthFormat
THREE.DepthStencilFormat
For use with a texture's [page:Texture.format format] property, these define how elements of a 2d texture, or *texels*, are read by shaders.

[page:constant AlphaFormat] discards the red, green and blue components and reads just the alpha component. The [page:Texture.type type] must be [page:constant UnsignedByteType].

[page:constant RGBFormat] discards the alpha components and reads the red, green and blue components. The [page:Texture.type type] must be [page:constant UnsignedByteType] or [page:constant UnsignedShort565Type].

[page:constant RGBAFormat] is the default and reads the red, green, blue and alpha components. The [page:Texture.type type] must be [page:constant UnsignedByteType], [page:constant UnsignedShort4444Type] or [page:constant THREE.UnsignedShort5551Type].

[page:constant LuminanceFormat] reads each element as a single luminance component. This is then converted to a floating point, clamped to the range [0,1], and then assembled into an RGBA element by placing the luminance value in the red, green and blue channels, and attaching 1.0 to the alpha channel. The [page:Texture.type type] must be [page:constant UnsignedByteType].

[page:constant LuminanceAlphaFormat] reads each element as a luminance/alpha double. The same process occurs as for the [page:constant LuminanceFormat], except that the alpha channel may have values other than *1.0*. The [page:Texture.type type] must be [page:constant UnsignedByteType].

[page:constant RGBEFormat] is identical to [page:constant RGBAFormat].

[page:constant DepthFormat] reads each element as a single depth value, converts it to floating point, and clamps to the range [0,1]. The [page:Texture.type type] must be [page:constant UnsignedIntType] or [page:constant UnsignedShortType]. This is the default for [page:DepthTexture DepthTexture].

[page:constant DepthStencilFormat] reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as in [page:constant DepthFormat]. The stencil component is interpreted based on the depth + stencil internal format. The [page:Texture.type type] must be [page:constant UnsignedInt248Type].

Note that the texture must have the correct [page:Texture.type type] set, as described above. See this page for details.

DDS / ST3C Compressed Texture Formats

THREE.RGB_S3TC_DXT1_Format
THREE.RGBA_S3TC_DXT1_Format
THREE.RGBA_S3TC_DXT3_Format
THREE.RGBA_S3TC_DXT5_Format
For use with a [page:CompressedTexture CompressedTexture]'s [page:Texture.format format] property, these require support for the WEBGL_compressed_texture_s3tc extension.
According to WebglStats, as of February 2016 over 80% of WebGL enabled devices support this extension.

There are four S3TC formats available via this extension. These are:
[page:constant RGB_S3TC_DXT1_Format]: A DXT1-compressed image in an RGB image format.
[page:constant RGBA_S3TC_DXT1_Format]: A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
[page:constant RGBA_S3TC_DXT3_Format]: A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
[page:constant RGBA_S3TC_DXT5_Format]: A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3 compression in how the alpha compression is done.

PVRTC Compressed Texture Formats

THREE.RGB_PVRTC_4BPPV1_Format
THREE.RGB_PVRTC_2BPPV1_Format
THREE.RGBA_PVRTC_4BPPV1_Format
THREE.RGBA_PVRTC_2BPPV1_Format
For use with a [page:CompressedTexture CompressedTexture]'s [page:Texture.format format] property, these require support for the WEBGL_compressed_texture_pvrtc extension.
According to WebglStats, as of February 2016 less than 8% of WebGL enabled devices support this extenstion. PVRTC is typically only available on mobile devices with PowerVR chipsets, which are mainly Apple devices.

There are four PVRTC formats available via this extension. These are:
[page:constant RGB_PVRTC_4BPPV1_Format]: RGB compression in 4-bit mode. One block for each 4?4 pixels.
[page:constant RGB_PVRTC_2BPPV1_Format]: RGB compression in 2-bit mode. One block for each 8?4 pixels.
[page:constant RGBA_PVRTC_4BPPV1_Format]: RGBA compression in 4-bit mode. One block for each 4?4 pixels.
[page:constant RGBA_PVRTC_2BPPV1_Format]: RGBA compression in 2-bit mode. One block for each 8?4 pixels.

ETC Compressed Texture Format

THREE.RGB_ETC1_Format
For use with a [page:CompressedTexture CompressedTexture]'s [page:Texture.format format] property, these require support for the WEBGL_compressed_texture_etc1 extension.
According to WebglStats, as of February 2016 just over 13% of WebGL enabled devices support this extenstion.

Кодирование Encoding

LinearEncoding
THREE.sRGBEncoding
THREE.GammaEncoding
THREE.RGBEEncoding
THREE.LogLuvEncoding
THREE.RGBM7Encoding
THREE.RGBM16Encoding
THREE.RGBDEncoding
THREE.BasicDepthPacking
THREE.RGBADepthPacking
Для использования со свойством encoding Texture.

If the encoding type is changed after the texture has already been used by a material, you will need to set [page:Material.needsUpdate Material.needsUpdate] to *true* to make the material recompile.

Значением по умолчанию является LinearEncoding. Значения, отличные от данных, действительны только для карт материала, envMap и emissiveMap.

Исходники