当我在youtube上观看了Coding Train上有关分形树的视频后,我尝试自己建造一个。效果很好,我使用一些变量来获得不同的结果。
我很乐意看到树被风吹动。我尝试了一些不同的方法,例如稍微旋转分支或一些次要的物理实现,但是失败了。
所以我的问题是:什么是渲染分形树并赋予它某种“生命”(如风的轻微摇晃)的最佳方法?
有什么好的参考资料吗?
我需要物理学吗? ->如果是这样,我该在哪里看?
如果没有->我怎么能伪造这种效果?
我为能获得的所有帮助感到高兴。
创意来源:https://www.youtube.com/watch?v=0jjeOYMjmDU
最佳答案
树在风中。
以下是在风中弯曲树枝的一些短点。由于整个解决方案很复杂,因此您将不得不从代码中获得最大的收益。
该代码包括种子随机数函数。随机递归树渲染器,质量较差的随机风力生成器,均使用动画循环在画布上绘制。
风
要施加风,您需要向每个分支施加与分支与风的角度成比例的弯曲力。
因此,如果在方向dir
上有一个分支,而在方向wDir
上有风,则弯曲力所需的缩放比例为
var x = Math.cos(dir); // get normalize vector for the branch
var y = Math.sin(dir);
var wx = Math.cos(wDir); // get normalize vector for the wind
var wy = Math.sin(wDir);
var forceScale = x * wy - y * wx;
分支的长度也会影响力的大小,包括将分支的矢量加长成正比于其长度的力
var x = Math.cos(dir) * length; // get normalize vector for the branch
var y = Math.sin(dir) * length;
var wx = Math.cos(wDir); // get normalize vector for the wind
var wy = Math.sin(wDir);
var forceScale = x * wy - y * wx;
使用此方法可确保分支不会弯曲成风。
还有分支的厚度,这是与横截面积有关的多项式关系。这是未知的,因此缩放到树的最大厚度(此近似值假定树的基础不能弯曲,但是末端分支可以弯曲很多。)
然后,弯曲分支的弹力将具有将分支移回其正常位置的力。这就像弹簧一样,与风力非常相似。由于计算和内存负载将开始使CPU不堪重负,我们可以作弊,并且还可以随风弹起,弹起一点点弹性。
还有那棵树。
该树需要是随机的,但由于它是分形的,所以您不想存储每个分支。因此,您还需要一个种子随机生成器,可以在每次渲染过程开始时将其重置。每次迭代都会随机渲染该树,但是因为每次获得同一棵树时随机数都从相同的种子开始。
这个例子
阵风中随机抽出树木和风。风是随机的,因此树可能不会立即移动。
单击树图像以重新设定树的随机种子值。
我没有看视频,但是这些东西是非常标准的,因此递归功能不应与您可能拥有的东西相去甚远。我确实看到了youTube封面图片,看起来好像树没有随机性。要消除随机性,请将
leng
,ang
,width
最小值,最大值设置为相同。例如,angMin = angMax = 0.4;
将删除随机的分支角度。风的强度将最大达到旋风强度(在美国为飓风),以达到最大效果。
有无数的魔术数字,最重要的是带有注释的常量。
const ctx = canvas.getContext("2d");
// click function to reseed random tree
canvas.addEventListener("click",()=> {
treeSeed = Math.random() * 10000 | 0;
treeGrow = 0.1; // regrow tree
});
/* Seeded random functions
randSeed(int) int is a seed value
randSI() random integer 0 or 1
randSI(max) random integer from 0 <= random < max
randSI(min, max) random integer from min <= random < max
randS() like Math.random
randS(max) random float 0 <= random < max
randS(min, max) random float min <= random < max
*/
const seededRandom = (() => {
var seed = 1;
return { max : 2576436549074795, reseed (s) { seed = s }, random () { return seed = ((8765432352450986 * seed) + 8507698654323524) % this.max }}
})();
const randSeed = (seed) => seededRandom.reseed(seed|0);
const randSI = (min = 2, max = min + (min = 0)) => (seededRandom.random() % (max - min)) + min;
const randS = (min = 1, max = min + (min = 0)) => (seededRandom.random() / seededRandom.max) * (max - min) + min;
/* TREE CONSTANTS all angles in radians and lengths/widths are in pixels */
const angMin = 0.01; // branching angle min and max
const angMax= 0.6;
const lengMin = 0.8; // length reduction per branch min and max
const lengMax = 0.9;
const widthMin = 0.6; // width reduction per branch min max
const widthMax = 0.8;
const trunkMin = 6; // trunk base width ,min and max
const trunkMax = 10;
const maxBranches = 200; // max number of branches
const windX = -1; // wind direction vector
const windY = 0;
const bendability = 8; // greater than 1. The bigger this number the more the thin branches will bend first
// the canvas height you are scaling up or down to a different sized canvas
const windStrength = 0.01 * bendability * ((200 ** 2) / (canvas.height ** 2)); // wind strength
// The wind is used to simulate branch spring back the following
// two number control that. Note that the sum on the two following should
// be below 1 or the function will oscillate out of control
const windBendRectSpeed = 0.01; // how fast the tree reacts to the wing
const windBranchSpring = 0.98; // the amount and speed of the branch spring back
const gustProbability = 1/100; // how often there is a gust of wind
// Values trying to have a gusty wind effect
var windCycle = 0;
var windCycleGust = 0;
var windCycleGustTime = 0;
var currentWind = 0;
var windFollow = 0;
var windActual = 0;
// The seed value for the tree
var treeSeed = Math.random() * 10000 | 0;
// Vars to build tree with
var branchCount = 0;
var maxTrunk = 0;
var treeGrow = 0.01; // this value should not be zero
// Starts a new tree
function drawTree(seed) {
branchCount = 0;
treeGrow += 0.02;
randSeed(seed);
maxTrunk = randSI(trunkMin, trunkMax);
drawBranch(canvas.width / 2, canvas.height, -Math.PI / 2, canvas.height / 5, maxTrunk);
}
// Recusive tree
function drawBranch(x, y, dir, leng, width) {
branchCount ++;
const treeGrowVal = (treeGrow > 1 ? 1 : treeGrow < 0.1 ? 0.1 : treeGrow) ** 2 ;
// get wind bending force and turn branch direction
const xx = Math.cos(dir) * leng * treeGrowVal;
const yy = Math.sin(dir) * leng * treeGrowVal;
const windSideWayForce = windX * yy - windY * xx;
// change direction by addition based on the wind and scale to
// (windStrength * windActual) the wind force
// ((1 - width / maxTrunk) ** bendability) the amount of bending due to branch thickness
// windSideWayForce the force depending on the branch angle to the wind
dir += (windStrength * windActual) * ((1 - width / maxTrunk) ** bendability) * windSideWayForce;
// draw the branch
ctx.lineWidth = width;
ctx.beginPath();
ctx.lineTo(x, y);
x += Math.cos(dir) * leng * treeGrowVal;
y += Math.sin(dir) * leng * treeGrowVal;
ctx.lineTo(x, y);
ctx.stroke();
// if not to thing, not to short and not to many
if (branchCount < maxBranches && leng > 5 && width > 1) {
// to stop recusive bias (due to branch count limit)
// random select direction of first recusive bend
const rDir = randSI() ? -1 : 1;
treeGrow -= 0.2;
drawBranch(
x,y,
dir + randS(angMin, angMax) * rDir,
leng * randS(lengMin, lengMax),
width * randS(widthMin, widthMax)
);
// bend next branch the other way
drawBranch(
x,y,
dir + randS(angMin, angMax) * -rDir,
leng * randS(lengMin, lengMax),
width * randS(widthMin, widthMax)
);
treeGrow += 0.2;
}
}
// Dont ask this is a quick try at wind gusts
// Wind needs a spacial component this sim does not include that.
function updateWind() {
if (Math.random() < gustProbability) {
windCycleGustTime = (Math.random() * 10 + 1) | 0;
}
if (windCycleGustTime > 0) {
windCycleGustTime --;
windCycleGust += windCycleGustTime/20
} else {
windCycleGust *= 0.99;
}
windCycle += windCycleGust;
currentWind = (Math.sin(windCycle/40) * 0.6 + 0.4) ** 2;
currentWind = currentWind < 0 ? 0 : currentWind;
windFollow += (currentWind - windActual) * windBendRectSpeed;
windFollow *= windBranchSpring ;
windActual += windFollow;
}
requestAnimationFrame(update);
function update() {
ctx.clearRect(0,0,canvas.width,canvas.height);
updateWind();
drawTree(treeSeed);
requestAnimationFrame(update);
}
body {
font-family : arial;
}
<canvas id="canvas" width="250" heigth="200"></canvas>
Click tree to reseed.
更新资料
我只是注意到风和分支的长度是绝对的,因此在较大的画布上绘制树会产生太大的弯曲力,并且分支会弯曲超过风矢量。
要放大sim,要么通过全局比例转换来完成,要么将
windStrength
常数减小为较小的值。您将不得不将值用作其二阶多项式关系。我的猜测是将其乘以(200 ** 2) / (canvas.height ** 2)
,其中200是示例画布的大小,而canvas.height
是新画布的大小。我已将计算结果添加到示例中,但它并不完美,因此在缩放时,如果弯曲太远或不足,则必须向下或向上更改值
windStrength
(第一个数字)。