- 本篇文章將要繪制一個具有動畫效果的galaxy登颓,關于galaxy的實現(xiàn)可以參考之前的這篇筆記 Galaxy趾断,我們在此基礎上做了部分修改
- We saw that animating each particles is a bad idea, animating the geometry buffer attribute on each frame is a bad idea, it must be have frame rate issue
- so we're going to animate each particles by using vertex shader
-
Set up
<script setup>
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import * as dat from 'dat.gui'
/**
* scene
*/
const scene = new THREE.Scene()
/**
* Camera
*/
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
100
)
camera.position.set(3, 3, 3)
/**
* Renderer
*/
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
document.body.appendChild(renderer.domElement)
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})
/**
* control
*/
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
/**
* render
*/
const clock = new THREE.Clock()
function tick () {
let elapsedTime = clock.getElapsedTime()
controls.update()
requestAnimationFrame(tick)
renderer.render(scene, camera)
}
tick()
</script>
-
基于之前已實現(xiàn)的 Galaxy 修改后的 Galaxy神年,添加對應屬性的
gui
/**
* Galaxy
*/
// 參數(shù)
const parameters = {
count: 200000,
size: 0.005,
radius: 5, // 星系半徑
branches: 3, // 星系分支闰蛔,平分星系角度
spin: 1, // 旋轉(zhuǎn)系數(shù)褒翰,geometry距離原點越遠旋轉(zhuǎn)角度越大
randomness: 0.5, // 隨機性
randomnessPower: 3, // 隨機性系數(shù)苍狰,可控制曲線變化
insideColor: '#ff6030',
outsideColor: '#1b3984',
}
let geometry = null
let material = null
let points = null
const generateGalaxy = () => {
if(points !== null) {
geometry.dispose()
material.dispose()
scene.remove(points)
}
// geometry
geometry = new THREE.BufferGeometry()
const positions = new Float32Array(parameters.count * 3)
const colors = new Float32Array(parameters.count * 3)
const colorInside = new THREE.Color(parameters.insideColor)
const colorOutside = new THREE.Color(parameters.outsideColor)
for(let i = 0; i < parameters.count; i++) {
const i3 = i * 3
// Position
const radius = Math.random() * parameters.radius
const branchAngle = (i % parameters.branches) / parameters.branches * Math.PI * 2
const randomX = Math.pow(Math.random(), parameters.randomnessPower) * (Math.random() < 0.5 ? 1 : - 1) * parameters.randomness * radius
const randomY = Math.pow(Math.random(), parameters.randomnessPower) * (Math.random() < 0.5 ? 1 : - 1) * parameters.randomness * radius
const randomZ = Math.pow(Math.random(), parameters.randomnessPower) * (Math.random() < 0.5 ? 1 : - 1) * parameters.randomness * radius
positions[i3] = Math.cos(branchAngle) * radius + randomX
positions[i3 + 1] = randomY
positions[i3 + 2] = Math.sin(branchAngle) * radius + randomZ
// Color
const mixedColor = colorInside.clone()
mixedColor.lerp(colorOutside, radius / parameters.radius)
colors[i3] = mixedColor.r
colors[i3 + 1] = mixedColor.g
colors[i3 + 2] = mixedColor.b
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3))
// material
material = new THREE.PointsMaterial({
size: parameters.size,
sizeAttenuation: true,
depthWrite: false,
blending: THREE.AdditiveBlending,
vertexColors: true,
})
// Points
points = new THREE.Points(geometry, material)
scene.add(points)
}
generateGalaxy()
/**
* gui
*/
const gui = new dat.GUI()
gui.add(parameters, 'count')
.min(100)
.max(1000000)
.step(100)
.onFinishChange(generateGalaxy)
gui.add(parameters, 'radius')
.min(0.01)
.max(20)
.step(0.01)
.onFinishChange(generateGalaxy)
gui.add(parameters, 'branches')
.min(2)
.max(20)
.step(1)
.onFinishChange(generateGalaxy)
gui.add(parameters, 'randomness')
.min(0)
.max(2)
.step(0.001)
.onFinishChange(generateGalaxy)
gui.add(parameters, 'randomnessPower')
.min(1)
.max(10)
.step(0.001)
.onFinishChange(generateGalaxy)
gui.addColor(parameters, 'insideColor').onFinishChange(generateGalaxy)
gui.addColor(parameters, 'outsideColor').onFinishChange(generateGalaxy)
修改后的最初的galaxy.png
-
The first, we're going to create our own shader, we're going to replace
PointsMaterial
byShaderMaterial
- we get a warning telling us that the
ShaderMaterial
supports neithersize
norsizeAttenuation
, so remove these properties
- we get a warning telling us that the
// material
material = new THREE.ShaderMaterial({
depthWrite: false,
blending: THREE.AdditiveBlending,
vertexColors: true,
})
warning.png
ShaderMaterial.png
-
Shader
import vertexShader from './animated-galaxy/vertex.glsl'
import fragmentShader from './animated-galaxy/fragment.glsl'
// material
material = new THREE.ShaderMaterial({
depthWrite: false,
blending: THREE.AdditiveBlending,
vertexColors: true,
vertexShader,
fragmentShader,
})
// vertex.glsl
void main () {
// Position
vec4 modelPosition = modelMatrix * vec4(position, 1.0);
vec4 viewPosition = viewMatrix * modelPosition;
vec4 projectedPosition = projectionMatrix * viewPosition;
gl_Position = projectedPosition;
// Size
gl_PointSize = 2.0; // 內(nèi)置變量露筒,fragment size
}
// fragment.glsl
void main () {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
shader.png
-
Handle the Size
- because we're not use the
PointsMaterial
, we need to redo the color, the size, the size attenuation...
// material material = new THREE.ShaderMaterial({ ... uniforms: { uSize: {value: 8} } })
// vertex.glsl uniform float uSize; void main () { // Position ... // Size gl_PointSize = uSize; // fragment size }
- in real life, stars have different sizes, we can send a random value in the attributes
const generateGalaxy = () => { ... ... const scales = new Float32Array(parameters.count) for(let i = 0; i < parameters.count; i++) { ... ... // Size scales[i] = Math.random() } ... geometry.setAttribute('aScale', new THREE.BufferAttribute(scales, 1)) }
- because we're not use the
// vertex.glsl
uniform float uSize;
attribute float aScale;
void main () {
// Position
...
// Size
gl_PointSize = uSize * aScale; // fragment size
}
Size.png
-
Fix the pixel ratio
- the
gl_PointSize
means thefragment
size(這里最好要理解下設備像素比的概念耻涛, 即物理像素/邏輯像素) - if you have a screen with a pixel ratio of 1, the particles will look 2 times larger than if the screen with a pixel ratio of 2
- 瀏覽器獲取設備像素比的方法是
window.devicePixelRatio
废酷,但我們在構造render的部分已經(jīng)設置過了renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
- the
// material
material = new THREE.ShaderMaterial({
...
uniforms: {
uSize: {value: 8 * renderer.getPixelRatio()}
}
})
/**
* Renderer
*/
...
window.addEventListener('resize', () => {
...
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})
generateGalaxy() // 將調(diào)用移動至renderer后面,防止上面在獲取renderer變量時報錯
-
Size Attenuation
- 當我們只關注一顆particle時抹缕,會發(fā)現(xiàn)不管頁面放大或是縮小澈蟆,particle始終保持著相同大小
- 我們當前使用的
perspectiveCamera
,呈現(xiàn)效果應當是particle距離camera越遠歉嗓,尺寸越小丰介,這就是size attenuation - 原先使用
PointsMaterial
時,直接設置sizeAttenuation: true
就可以了鉴分,但在shader
中我們需要自己實現(xiàn)這一部分 - we're going to take the code from the three.js depedency哮幢,PointsMaterial的頂點著色器文件路徑: /node_modules/three/src/renderers/shaders/ShaderLib/points.glsl.js,我們需要關注的就是以下這段
#ifdef USE_SIZEATTENUATION // 只有在perspectiveCamera下才會工作 bool isPerspective = isPerspectiveMatrix( projectionMatrix ); // scale is a value related to the renderer hight // particle的大小會根據(jù)屏幕的高度拉伸志珍,這樣不管是在大屏幕還是小屏幕橙垢,看到的particle都會差不多 // mvPosition correspond to the position of the vertex once the modelMatrix and the viewMatrix // in our case, it's viewPosition if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif
- 基于以上的代碼來修改我們自己的,然后就會發(fā)現(xiàn)距離camare近的particle尺寸相對遠的較大伦糯,這就是size attenuation柜某,但我們在這部分并不想讓particle隨著屏幕大小的改變而拉伸
// vertex.glsl ... void main () { ... ... // Size gl_PointSize = uSize * aScale; // fragment size gl_PointSize *= ( 1.0 / - viewPosition.z ); }
Size attenuation.png
-
To draw our particle pattern
- 通常是可以使用
Mesh
的uv
屬性來實現(xiàn)一些圖案的,但在這里敛纲,我們使用的是new THREE.Points()
喂击,Points
對象是用于渲染大量的點的對象,他不具有uv
屬性淤翔,uv
屬性通常與Mesh
一起使用翰绊,用于紋理映射 - 在當前文件結構里,我們每一個
vertex
就代表一個particle
旁壮,fragment
當然也一樣监嗜,所以我們使用了內(nèi)置變量gl_PointCoord
-
gl_PointCoord
是一個二維向量,x 和 y 的取值范圍都是[0, 1]抡谐,表示當前片段在 Point Spirit 上的歸一化坐標位置 - 如下裁奇,在fragment中測試一下,看看得到的結果麦撵,同時再繼續(xù)實現(xiàn)更多的形狀
// fragment.glsl void main () { gl_FragColor = vec4(gl_PointCoord, 1.0, 1.0); }
- 通常是可以使用
gl_PointCoord.png
- Disc Pattern刽肠,邊緣清晰的圓形
// fragment.glsl
void main () {
// disc
float strength = distance(gl_PointCoord, vec2(0.5)); // 計算當前片段與圓心(0.5, 0.5)的距離
strength = step(0.5, strength);
strength = 1.0 - strength;
gl_FragColor = vec4(vec3(strength), 1.0);
}
Disc Pattern.png
- Diffuse Point Pattern溃肪,邊緣擴散的particle
// fragment.glsl
void main () {
// diffuse point
float strength = distance(gl_PointCoord, vec2(0.5));
strength *= 2.0;
strength = 1.0 - strength;
gl_FragColor = vec4(vec3(strength), 1.0);
}
Diffuse Point Pattern.png
- Light Point Pattern
// fragment.glsl
void main () {
// light point
float strength = distance(gl_PointCoord, vec2(0.5));
strength = 1.0 - strength;
strength = pow(strength, 10.0);
gl_FragColor = vec4(vec3(strength), 1.0);
}
material = new THREE.ShaderMaterial({
...
...
uniforms: {
uSize: {value: 30 * renderer.getPixelRatio()}
}
})
Light Point Pattern.png
-
Handle the Color
// vertex.glsl
...
varying vec3 vColor;
void main () {
...
...
// Color
vColor = color;
}
// fragmrnt.glsl
varying vec3 vColor;
void main () {
// light point
float strength = distance(gl_PointCoord, vec2(0.5));
strength = 1.0 - strength;
strength = pow(strength, 10.0);
// Color
vec3 color = mix(vec3(0.0), vColor, strength); // 將黑色與color混合
gl_FragColor = vec4(color, 1.0);
}
Handle the Color.png
-
Animate
- we only need to rotate the particles on
x
andz
- we calculate the particle angle and its distance to the center 我們計算particle和x軸之間的夾角以及particle到中心點的距離
- we increase that angle according to the
uTime
anddistance
- we can use
atan()
to retrieve the angle 用于計算給定數(shù)值的反正切值
- we only need to rotate the particles on
// material
material = new THREE.ShaderMaterial({
...
uniforms: {
uSize: {value: 30 * renderer.getPixelRatio()},
uTime: {value: 0}
}
})
/**
* render
*/
const clock = new THREE.Clock()
function tick () {
let elapsedTime = clock.getElapsedTime()
// update material
material.uniforms.uTime.value = elapsedTime
...
}
tick()
// vertex.glsl
uniform float uSize;
uniform float uTime;
...
void main () {
// Position
vec4 modelPosition = modelMatrix * vec4(position, 1.0);
float angle = atan(modelPosition.x, modelPosition.z);
float distanceToCenter = length(modelPosition.xz);
float angleOffset = (1.0 / distanceToCenter) * uTime * 0.2;
angle += angleOffset;
modelPosition.x = cos(angle) * distanceToCenter;
modelPosition.z = sin(angle) * distanceToCenter;
...
...
}
Animate.png
-
增加旋轉(zhuǎn)后的隨機性
- 在創(chuàng)建galaxy時設置了一個參數(shù)
randomness
,只在設置初始position
時使用了音五,旋轉(zhuǎn)過程中卻沒有使用 - 旋轉(zhuǎn)過程中particle分布的隨機性不好的話乍惊,就容易變得越來越線條,particle不能很好的分布在軸線附近放仗,可以對比上下兩張圖,還是較為直觀的
- 在創(chuàng)建galaxy時設置了一個參數(shù)
const generateGalaxy = () => {
...
...
const randomness = new Float32Array(parameters.count * 3)
...
for(let i = 0; i < parameters.count; i++) {
...
// Position
const radius = Math.random() * parameters.radius
const branchAngle = (i % parameters.branches) / parameters.branches * Math.PI * 2
positions[i3] = Math.cos(branchAngle) * radius
positions[i3 + 1] = 0
positions[i3 + 2] = Math.sin(branchAngle) * radius
// random
const randomX = Math.pow(Math.random(), parameters.randomnessPower) * (Math.random() < 0.5 ? 1 : - 1) * parameters.randomness * radius
const randomY = Math.pow(Math.random(), parameters.randomnessPower) * (Math.random() < 0.5 ? 1 : - 1) * parameters.randomness * radius
const randomZ = Math.pow(Math.random(), parameters.randomnessPower) * (Math.random() < 0.5 ? 1 : - 1) * parameters.randomness * radius
randomness[i3] = randomX
randomness[i3 + 1] = randomY
randomness[i3 + 2] = randomZ
...
...
}
...
geometry.setAttribute('aRandomness', new THREE.BufferAttribute(randomness, 3))
...
...
}
// vertex.glsl
...
attribute vec3 aRandomness;
...
void main () {
// Position
...
...
// random
modelPosition.xyz += aRandomness;
...
...
}
randomness.png