How to generate random numbers biased towards one value in a range? - javascript

Say, if I wanted to generate an unbiased random number between min and max, I'd do:
var rand = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
But what if I want to generate a random number between min and max but more biased towards a value N between min and max to a degree D? It's best to illustrate it with a probability curve:

Here is one way:
Get a random number in the min-max range
Get a random normalized mix value
Mix random with bias based on random mix
Ie., in pseudo:
Variables:
min = 0
max = 100
bias = 67 (N)
influence = 1 (D) [0.0, 1.0]
Formula:
rnd = random() x (max - min) + min
mix = random() x influence
value = rnd x (1 - mix) + bias x mix
The mix factor can be reduced with a secondary factor to set how much it should influence (ie. mix * factor where factor is [0, 1]).
Demo
This will plot a biased random range. The upper band has 1 as influence, the bottom 0.75 influence. Bias is here set to be at 2/3 position in the range.
The bottom band is without (deliberate) bias for comparison.
var ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "red"; ctx.fillRect(399,0,2,110); // draw bias target
ctx.fillStyle = "rgba(0,0,0,0.07)";
function getRndBias(min, max, bias, influence) {
var rnd = Math.random() * (max - min) + min, // random in range
mix = Math.random() * influence; // random mixer
return rnd * (1 - mix) + bias * mix; // mix full range and bias
}
// plot biased result
(function loop() {
for(var i = 0; i < 5; i++) { // just sub-frames (speedier plot)
ctx.fillRect( getRndBias(0, 600, 400, 1.00), 4, 2, 50);
ctx.fillRect( getRndBias(0, 600, 400, 0.75), 55, 2, 50);
ctx.fillRect( Math.random() * 600 ,115, 2, 35);
}
requestAnimationFrame(loop);
})();
<canvas width=600></canvas>

Fun: use the image as the density function. Sample random pixels until you get a black one, then take the x co-ordinate.
Code:
getPixels = require("get-pixels"); // npm install get-pixels
getPixels("distribution.png", function(err, pixels) {
var height, r, s, width, x, y;
if (err) {
return;
}
width = pixels.shape[0];
height = pixels.shape[1];
while (pixels.get(x, y, 0) !== 0) {
r = Math.random();
s = Math.random();
x = Math.floor(r * width);
y = Math.floor(s * height);
}
return console.log(r);
});
Example output:
0.7892316638026386
0.8595335511490703
0.5459279934875667
0.9044852438382804
0.35129814594984055
0.5352215224411339
0.8271261665504426
0.4871773284394294
0.8202084102667868
0.39301465335302055
Scale to taste.

Just for fun, here's a version that relies on the Gaussian function, as mentioned in SpiderPig's comment to your question. The Gaussian function is applied to a random number between 1 and 100, where the height of the bell indicates how close the final value will be to N. I interpreted the degree D to mean how likely the final value is to be close to N, and so D corresponds to the width of the bell - the smaller D is, the less likely is the bias. Clearly, the example could be further calibrated.
(I copied Ken Fyrstenberg's canvas method to demonstrate the function.)
function randBias(min, max, N, D) {
var a = 1,
b = 50,
c = D;
var influence = Math.floor(Math.random() * (101)),
x = Math.floor(Math.random() * (max - min + 1)) + min;
return x > N
? x + Math.floor(gauss(influence) * (N - x))
: x - Math.floor(gauss(influence) * (x - N));
function gauss(x) {
return a * Math.exp(-(x - b) * (x - b) / (2 * c * c));
}
}
var ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(399, 0, 2, 110);
ctx.fillStyle = "rgba(0,0,0,0.07)";
(function loop() {
for (var i = 0; i < 5; i++) {
ctx.fillRect(randBias(0, 600, 400, 50), 4, 2, 50);
ctx.fillRect(randBias(0, 600, 400, 10), 55, 2, 50);
ctx.fillRect(Math.random() * 600, 115, 2, 35);
}
requestAnimationFrame(loop);
})();
<canvas width=600></canvas>

Say when you use Math.floor(Math.random() * (max - min + 1)) + min;, you are actually creating a Uniform distribution. To get the data distribution in your chart, what you need is a distribution with non-zero skewness.
There are different techniques to get those kinds of distributions. Here is an example of beta distribution found on stackoverflow.
Here is the example summarized from the link:
unif = Math.random() // The original uniform distribution.
And we can transfer it into beta distribution by doing
beta = sin(unif*pi/2)^2 // The standard beta distribution
To get the skewness shown in your chart,
beta_right = (beta > 0.5) ? 2*beta-1 : 2*(1-beta)-1;
You can change the value 1 to any else to have it skew to other value.

Related

Need help visualizing some data with an open processing sketch

The project that i have put together here called Swellcloud. The animation was forked from here. This code connects to a wave buoy just off my local beach and the animation is relevant to the live conditions. If the 'swell' is high, I would like the peaks & troughs to be large, the swell data has a range of min 0.1m = smallest swell so low troughs & peaks in the animation. And maximum 10m large waves so large troughs & peaks... then the surf 'period' data which has a range of 0s to 20s would reflect the 'smoothness' of the animation, so high period nice straight lines on the animation, and low period would be choppy/ragged lines.
I have managed to get the data to 'speed' up the animation if the swell data is large but i cant control the height of the waves on the animation or the period
Does anyone have any pointers?
We make these variables global so we know when they have loaded:
let surfheight, surfperiod;
fetch(
"https://data.channelcoast.org/observations/waves/latest?key='my key"
)
.then(function (resp) {
return resp.text();
})
.then(function (data) {
//console.log(data);
let parser = new DOMParser(),
xmlDoc = parser.parseFromString(data, "text/xml");
//console.log(xmlDoc.getElementsByTagName('ms:hs')[36].innerHTML); //76=Perran,36 Porthleven
surfheight = xmlDoc.getElementsByTagName("ms:hs")[36].innerHTML;
surfperiod = xmlDoc.getElementsByTagName("ms:tp")[36].innerHTML;
// you can set the surf variable here, because the sketch will start only after the data loads,
// also make sure to first convert it to a number like "Number(surfheight)" otherwise it won't work
surfht = Number(surfheight);
surfpd = Number(surfperiod);
document.getElementById("surfheight").textContent = surfheight;
document.getElementById("surfperiod").textContent = surfperiod;
});
var yoff = 0; // 2nd dimension of perlin noise
var waveColor, waveColor2, waveColor3;
var waveColorArr;
var controls, waveSpeed;
var canvas;
let surfht;
let surfpd;
function setup() {
canvas = createCanvas(windowWidth, windowHeight);
waveColor = color(0, 50, 120, 100);
waveColor2 = color(0, 100, 150, 100);
waveColor3 = color(0, 200, 250, 100);
noiseDetail(2, 0.2);
waveColorArr = [waveColor, waveColor, waveColor2, waveColor2, waveColor3, waveColor3];
}
function draw() {
// after these load, the sketch starts
if (!surfperiod && !surfheight) {
return;
}
background(0);
noStroke();
const amp = map(surfht, 0, 10, 0, 1);
//const amp = map(surfpd, 0, 10, 0, 1);
for (var i = 0; i <= 5; i++) {
// We are going to draw a polygon out of the wave points
beginShape();
fill(waveColorArr[i]);
var xoff = 0;
for (var x = 0; x <= width + 500; x += 100) {
var y = map(
noise(xoff, yoff - 0.5 * i),
0,
1,
(height / 10) * (i + 1),
height - height / 10 + (height / 10) * i
);
vertex(x, y);
// i've extracted this into a variable for cleaner code
const inc = map(surfpd, 0, 20, 0.01, 0.5);
xoff += inc + 0.5 / 10000.0;
}
vertex(width, height);
vertex(0, height);
endShape(CLOSE);
}
const inc = map(surfht, 0, 10, 0, 0.025);
yoff += 0.007 + inc + 0.5 / 10000.0;
}
function windowResized() {
resizeCanvas(window.innerWidth, window.innerHeight);
}
This is a the bit of code that mainly draws a single wave:
// We are going to draw a polygon out of the wave points
beginShape();
fill(waveColorArr[i]);
var xoff = 0;
for (var x = 0; x <= width + 500; x += 100) {
var y = map(
noise(xoff, yoff - 0.5 * i),
0,
1,
(height / 10) * (i + 1),
height - height / 10 + (height / 10) * i
);
vertex(x, y);
// i've extracted this into a variable for cleaner code
const inc = map(surfpd, 0, 20, 0.01, 0.5);
xoff += inc + 0.5 / 10000.0;
}
vertex(width, height);
vertex(0, height);
endShape(CLOSE);
You've already figured out how to map() the inc value.
Similar notice y is mapped as well, from 0.0 -> 1.0 range to (height / 10) * (i + 1)
to height - height / 10 + (height / 10) * i range.
A quick and hacky way to do it is to multiply those values by a value which would scale the wave height.
Better yet, you could encapsulate the instructions into a re-usable function, configurable with parameters.
You can also have a look at this detailed answer on drawing sine waves and remember that you can add/multiply waves together to get different shapes.

With HTML5 canvas, how to calculate the final point coordinates with an offset?

On a HTML5 canvas object, I have to subtract a distance from a destination point, to give the final destination on the same line.
So, first I have calculated the distance between the source and target points, with the Pythagorean theorem, but my memories of Thales's theorem are too faulty to find the final point (on same line), with the right x and y attributes.
function getDistance (from, to){
return Math.hypot(to.x - from.x, to.y - from.y);
}
function getFinalTo (from, to, distanceToSubstract){
//with Pythagore we obtain the distance between the 2 points
var originalDistance = getDistance(from, to);
var finalDistance = originalDistance - distanceToSubstract;
//Now, I was thinking about Thales but all my tries are wrong
//Here some of ones, I need to get finalTo properties to draw an arrow to a node without
var finalTo = new Object;
finalTo.x = ((1 - finalDistance) * from.x) + (finalDistance * to.x);
finalTo.y = ((1 - finalDistance) * from.y) + (finalDistance * to.y);
return finalTo;
}
Indeed, the arrowhead be hidden by the round node that can be about 100 pixels of radius, so I try to get the final point.
Thanks a lot.
Regards,
Will depend on the line cap. For "butt" there is no change, for "round" and "square" you the line extends by half the width at each end
The following function shortens the line to fit depending on the line cap.
drawLine(x1,y1,x2,y2){
// get vector from start to end
var x = x2-x1;
var y = y2-y1;
// get length
const len = Math.hypot(x,y) * 2; // *2 because we want half the width
// normalise vector
x /= len;
y /= len;
if(ctx.lineCap !== "butt"){
// shorten both ends to fit the length
const lw = ctx.lineWidth;
x1 += x * lw;
y1 += y * lw;
x2 -= x * lw;
y2 -= y * lw;
}
ctx.beginPath()
ctx.lineTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
For miter joins the following answer will help https://stackoverflow.com/a/41184052/3877726
You can use simple proportion by distance ratio:
(I did not account for round cap)
ratio = finalDistance / originalDistance
finalTo.x = from.x + (to.x - from.x) * ratio;
finalTo.y = from.y + (to.y - from.y) * ratio;
Your approach was attempt to use linear interpolation, but you erroneously mixed distances (in pixels, meters etc) with ratios (dimensionless - is this term right?)
ratio = finalDistance / originalDistance
finalTo.x = ((1 - ratio) * from.x) + (ratio * to.x);
finalTo.y = ((1 - ratio) * from.y) + (ratio * to.y);
Note that both approaches is really the same formula.

HTML5 Canvas hue-rotate changing saturation and lightness

I am working on a relatively simple app that will generate differently colored version of the same .SVG image (modified by HSL values).
Right now I'm implementing hue changes. I am using a generated list of colors. Before drawing the color variations a base color is selected. In this case I used a dead simple .SVG of a green square (hsl(137,100%,82%)).
This is what my code looks like:
for(let i = 0; i < nColors; i++){
ctx.filter = 'hue-rotate('+(palette[i].h-hStart)+'deg)';
ctx.drawImage(img, i*100, 0, 100, 100);
ctx.filter = "none";
}
where:
nColors is the amount of colors in the array
palette is an array of objects with properties h, s and l - cointains the colors
hStart is the base hue of my image (in this case 137)
I'm calculating the hue difference between the current color and the base color and rotating the canvas drawing hue by that number, then drawing the squares side by side. Unfortunately, here are my results.
The list at the top contains the actual colors I want to impose on my .SVG, the squares at the bottom are my canvas.
As you can see, the color diverts more and more with each iteration. I've checked the exact colors in Photoshop (I know Photoshop uses HSB but I converted the values) and the S&L differences are really big and somewhat regular (the first one is correct).
100,82
100,82
100,89
83,100
52,100
53,100
60,100
62,100
Now, I did read somewhere that different browsers may render colors differently so I checked the colors with getPixelData and the results matched my Photoshop readings, therefore I believe that the issue indeed lies in the hue-rotate filter.
I could achieve the same results by reading all the pixel data and changing it "manually", but in the end I'd like to paint each new image to an invisible, large canvas and export high resolution .PNGs - it would be rather CPU intensive and take a long time.
Is it actually a bug/feature of hue-rotate or am I making a mistake somewhere? Is there any way to fix it? Is there any other way to achieve the same results while keeping it relatively simple and sticking to vectors?
EDIT: here's a fiddle
This is not really a bug.
Canvas 2DContext's filter = CSSFilterFunc will produce the same result as the CSS filter: CSSFilterFunc, and the hue-rotate(angle) function does only approximate this hue-rotation : it doesn't convert all your RGBA pixels to their HSL values. So yes, you'll have wrong results.
But, you may try to approximate this using SVGFilterMatrix instead. The original hue-rotate will produce a similar result than the CSSFunc one, but we can calculate the hue rotation and apply it to a colorMatrix.
If you want to write it, here is a paper explaining how to do it : http://www.graficaobscura.com/matrix/index.html
I don't really have time right now to do it, so I'll borrow an already written js implementation of a better approximation than the default one found in this Q/A, written by pixi.js mates and will only show you how to apply it on your canvas, thanks to an SVGFilter.
Note that as correctly pointed by #RobertLongson, you also need to set the color-interpolation-filters property of the feColorMatrix element to sRGB since it defaults to linear-sRGB.
// set our SVGfilter's colorMatrix's values
document.getElementById('matrix').setAttribute('values', hueRotate(100));
var cssCtx = CSSFiltered.getContext('2d');
var svgCtx = SVGFiltered.getContext('2d');
var reqctx = requiredRes.getContext('2d');
cssCtx.fillStyle = svgCtx.fillStyle = reqctx.fillStyle = 'hsl(100, 50%, 50%)';
cssCtx.fillRect(0, 0, 100, 100);
svgCtx.fillRect(0, 0, 100, 100);
reqctx.fillRect(0, 0, 100, 100);
// CSSFunc
cssCtx.filter = "hue-rotate(100deg)";
// url func pointing to our SVG Filter
svgCtx.filter = "url(#hue-rotate)";
reqctx.fillStyle = 'hsl(200, 50%, 50%)';
cssCtx.fillRect(100, 0, 100, 100);
svgCtx.fillRect(100, 0, 100, 100);
reqctx.fillRect(100, 0, 100, 100);
var reqdata = reqctx.getImageData(150, 50, 1, 1).data;
var reqHSL = rgbToHsl(reqdata);
console.log('required result : ', 'rgba(' + reqdata.join() + '), hsl(' + reqHSL + ')');
var svgData = svgCtx.getImageData(150, 50, 1, 1).data;
var svgHSL = rgbToHsl(svgData);
console.log('SVGFiltered : ', 'rgba(' + svgData.join() + '), , hsl(' + svgHSL + ')');
// this one throws an security error in Firefox < 52
var cssData = cssCtx.getImageData(150, 50, 1, 1).data;
var cssHSL = rgbToHsl(cssData);
console.log('CSSFiltered : ', 'rgba(' + cssData.join() + '), hsl(' + cssHSL + ')');
// hueRotate will create a colorMatrix with the hue rotation applied to it
// taken from https://pixijs.github.io/docs/filters_colormatrix_ColorMatrixFilter.js.html
// and therefore from https://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751
function hueRotate(rotation) {
rotation = (rotation || 0) / 180 * Math.PI;
var cosR = Math.cos(rotation),
sinR = Math.sin(rotation),
sqrt = Math.sqrt;
var w = 1 / 3,
sqrW = sqrt(w);
var a00 = cosR + (1.0 - cosR) * w;
var a01 = w * (1.0 - cosR) - sqrW * sinR;
var a02 = w * (1.0 - cosR) + sqrW * sinR;
var a10 = w * (1.0 - cosR) + sqrW * sinR;
var a11 = cosR + w * (1.0 - cosR);
var a12 = w * (1.0 - cosR) - sqrW * sinR;
var a20 = w * (1.0 - cosR) - sqrW * sinR;
var a21 = w * (1.0 - cosR) + sqrW * sinR;
var a22 = cosR + w * (1.0 - cosR);
var matrix = [
a00, a01, a02, 0, 0,
a10, a11, a12, 0, 0,
a20, a21, a22, 0, 0,
0, 0, 0, 1, 0,
];
return matrix.join(' ');
}
function rgbToHsl(arr) {
var r = arr[0] / 255,
g = arr[1] / 255,
b = arr[2] / 255;
var max = Math.max(r, g, b),
min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if (max == min) {
h = s = 0;
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [
Math.round(h * 360),
Math.round(s * 100),
Math.round(l * 100)
];
}
body{ margin-bottom: 100px}
<!-- this is our filter, we'll add the values by js -->
<svg height="0" width="0">
<filter id="hue-rotate">
<feColorMatrix in="SourceGraphic" id="matrix" type="matrix" color-interpolation-filters="sRGB" />
</filter>
</svg>
<p>CSS Filtered :
<br>
<canvas id="CSSFiltered" width="200" height="100"></canvas>
</p>
<p>SVG Filtered :
<br>
<canvas id="SVGFiltered" width="200" height="100"></canvas>
</p>
<p>Required Result :
<br>
<canvas id="requiredRes" width="200" height="100"></canvas>
</p>

How can I create a WebGL basic firework

I kinda have like a fountain of particles, but I want to make them ''explode'' making more of them where I click like a firework.
var nFireworks = 10000;
function initParticleSystem() {
var particlesData = [];
for (var i= 0; i < nFireworks; i++) {
// angulos del cono
var theta = Math.PI / 6.0 * Math.random();
var phi = 5.0 * Math.PI * Math.random();
// direccion
var x1 = Math.sin(theta) * Math.cos(phi) ;
var y1 = velocity;
var z1 = 0.0;
// velocidad
var alpha = Math.random();
var velocity = (1.4 * alpha) + (0.80 * (1.0 - alpha));
particlesData[i * 4 + 0] = x1 * velocity;
particlesData[i * 4 + 1] = y1 * velocity;
particlesData[i * 4 + 2] = z1 * velocity;
particlesData[i * 4 + 3] = i * 0.095;
}
}
Your code is a bit odd, it uses velocity before it defines it, and you don't actually show the step function or anything else, but hey, I'll give it a go.
Your code (probably) generates a cone of particles where they all move along y at a constant velocity, and the x velocity is spread randomly in a PI/6 wide cone. If you want your particles to spread out in all directions randomly I would suggest starting by changing it like this:
before your for loop, set velocity to a constant first instead of all that nonsense:
var velocity = 5;
Then, you want particles to move outwards from the point in all equally random x and y directions, so change your x and y values to:
var x1 = ((Math.random() - 0.5) * velocity) * 2;
var y1 = ((Math.random() - 0.5) * velocity) * 2;
to form particles where their x and y velocities are random between -velocity and +velocity
Then, I don't know why your code generates particle data in a single array like that, I would make it
particleData.push([x1,y1,z1,i]);
and then reference each particle that way, or a possibly less performant but much more readable:
particleData.push({x: x1, y: y1, z: z1, brightness: i]};
(I'm just going to guess that i is brightness there).
Good luck buddy, it's not really a WebGL question, it's just you asking someone how to write your code for you, but hopefully that helps.

Make and animate wave in canvas

I’m looking for a way to create a wave in a shape designed in canvas. After much research I found something that is pretty close to what I want:
var c = document.getElementById('c'),
ctx = c.getContext('2d'),
cw = c.width = window.innerWidth,
ch = c.height = window.innerHeight,
points = [],
tick = 0,
opt = {
count: 5,
range: {
x: 20,
y: 80
},
duration: {
min: 20,
max: 40
},
thickness: 10,
strokeColor: '#444',
level: .35,
curved: true
},
rand = function(min, max) {
return Math.floor((Math.random() * (max - min + 1)) + min);
},
ease = function(t, b, c, d) {
if ((t /= d / 2) < 1) return c / 2 * t * t + b;
return -c / 2 * ((--t) * (t - 2) - 1) + b;
};
ctx.lineJoin = 'round';
ctx.lineWidth = opt.thickness;
ctx.strokeStyle = opt.strokeColor;
var Point = function(config) {
this.anchorX = config.x;
this.anchorY = config.y;
this.x = config.x;
this.y = config.y;
this.setTarget();
};
Point.prototype.setTarget = function() {
this.initialX = this.x;
this.initialY = this.y;
this.targetX = this.anchorX + rand(0, opt.range.x * 2) - opt.range.x;
this.targetY = this.anchorY + rand(0, opt.range.y * 2) - opt.range.y;
this.tick = 0;
this.duration = rand(opt.duration.min, opt.duration.max);
}
Point.prototype.update = function() {
var dx = this.targetX - this.x;
var dy = this.targetY - this.y;
var dist = Math.sqrt(dx * dx + dy * dy);
if (Math.abs(dist) <= 0) {
this.setTarget();
} else {
var t = this.tick;
var b = this.initialY;
var c = this.targetY - this.initialY;
var d = this.duration;
this.y = ease(t, b, c, d);
b = this.initialX;
c = this.targetX - this.initialX;
d = this.duration;
this.x = ease(t, b, c, d);
this.tick++;
}
};
Point.prototype.render = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, 3, 0, Math.PI * 2, false);
ctx.fillStyle = '#000';
ctx.fill();
};
var updatePoints = function() {
var i = points.length;
while (i--) {
points[i].update();
}
};
var renderPoints = function() {
var i = points.length;
while (i--) {
points[i].render();
}
};
var renderShape = function() {
ctx.beginPath();
var pointCount = points.length;
ctx.moveTo(points[0].x, points[0].y);
var i;
for (i = 0; i < pointCount - 1; i++) {
var c = (points[i].x + points[i + 1].x) / 2;
var d = (points[i].y + points[i + 1].y) / 2;
ctx.quadraticCurveTo(points[i].x, points[i].y, c, d);
}
ctx.lineTo(-opt.range.x - opt.thickness, ch + opt.thickness);
ctx.lineTo(cw + opt.range.x + opt.thickness, ch + opt.thickness);
ctx.closePath();
ctx.fillStyle = 'hsl(' + (tick / 2) + ', 80%, 60%)';
ctx.fill();
ctx.stroke();
};
var clear = function() {
ctx.clearRect(0, 0, cw, ch);
};
var loop = function() {
window.requestAnimFrame(loop, c);
tick++;
clear();
updatePoints();
renderShape();
//renderPoints();
};
var i = opt.count + 2;
var spacing = (cw + (opt.range.x * 2)) / (opt.count - 1);
while (i--) {
points.push(new Point({
x: (spacing * (i - 1)) - opt.range.x,
y: ch - (ch * opt.level)
}));
}
window.requestAnimFrame = function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(a) {
window.setTimeout(a, 1E3 / 60)
}
}();
loop();
canvas {
display: block;
}
<canvas id="c"></canvas>
http://codepen.io/jackrugile/pen/BvLHg
The problem is that the movement of the wave appears a bit unreal. I'd like to keep this notion of random motion and not have a shape that repeats itself by moving from left to right but it will be great if I found a way to create a ‘realistic’ water movement (good fluid dynamics, collisions of this wave with the edges of its container (custom shape)).
I think I'm asking a lot but ... A small line of research could help :)
Interference
You can make a more realistic wave using interference.
Have one big wave (swell) running slowly with a big motion
Have another one or two smaller sine waves running (oscillators)
All with random amplitudes
Mix the waves horizontally using average and calculate the various points
Draw the result using a cardinal spline (or if the resolution is high you can just draw simple lines between the points instead).
Use various parameters so you can adjust it live to find a good combination.
You can also add oscillators to represent the z axis to make it more realistic in case you want to layer the waves to make a pseudo-3D wave.
Example
I cannot give you wave collision, fluid dynamics - that would be a bit too broad for SO but I can give you a fluid-ish wave example (as you have the point of each segment you can use that for collision detection).
And example would be to create an oscillator object which you could set the various settings on such as amplitude, rotation speed (phase) etc.
Then have a mixer function which mixes the result of these oscillators that you use.
Live demo here (full-screen version here)
The oscillator object in this demo look like this:
function osc() {
/// various settings
this.variation = 0.4; /// how much variation between random and max
this.max = 100; /// max amplitude (radius)
this.speed = 0.02; /// rotation speed (for radians)
var me = this, /// keep reference to 'this' (getMax)
a = 0, /// current angle
max = getMax(); /// create a temp. current max
/// this will be called by mixer
this.getAmp = function() {
a += this.speed; /// add to rotation angle
if (a >= 2.0) { /// at break, reset (see note)
a = 0;
max = getMax();
}
/// calculate y position
return max * Math.sin(a * Math.PI) + this.horizon;
}
function getMax() {
return Math.random() * me.max * me.variation +
me.max * (1 - me.variation);
}
return this;
}
This do all the setup and calculations for us and all we need to do is to call the getAmp() to get a new value for each frame.
Instead of doing it manually we can use a "mixer". This mixer allows us to add as many oscillators we want to the mix:
function mixer() {
var d = arguments.length, /// number of arguments
i = d, /// initialize counter
sum = 0; /// sum of y-points
if (d < 1) return horizon; /// if none, return
while(i--) sum += arguments[i].getAmp(); /// call getAmp and sum
return sum / d + horizon; /// get average and add horizon
}
Putting this in a loop with a point recorder which shifts the point in one direction will create a fluid looking wave.
The demo above uses three oscillators. (A tip in that regard is to keep the rotation speed lower than the big swell or else you will get small bumps on it.)
NOTE: The way I create a new random max is not the best way as I use a break point (but simple for demo purpose). You can instead replace this with something better.
Since you are searching for a realistic effect, best idea might be to simulate the water. It is not that hard, in fact : water can be nicely enough approximated by a network of springs linked together.
Result is quite good, you can find it here :
http://jsfiddle.net/gamealchemist/Z7fs5/
So i assumed it was 2D effect and built an array holding, for each point of a water surface, its acceleration, speed, and position. I store them in a single array, at 3*i + 0, 3*i + 1, and 3*i+2.
Then on each update, i simply apply newton's laws with elasticity, and with some friction to get the movement to stop.
I influence each point so it goes to its stable state + get influenced by its right and left neighboor.
(If you want smoother animation, use also i-2 and i+2 points, and lower kFactor.)
var left = 0, y = -1;
var right = water[2];
for (pt = 0 ; pt < pointCount; pt++, i += 3) {
y = right;
right = (pt < pointCount - 1) ? water[i + 5] : 0;
if (right === undefined) alert('nooo');
// acceleration
water[i] = (-0.3 * y + (left - y) + (right - y)) * kFactor - water[i + 1] * friction;
// speed
water[i + 1] += water[i] * dt;
// height
water[i + 2] += water[i + 1] * dt;
left = y;
}
The draw is very simple : just iterate though the points and draw. But it's hard to get a smooth effect while drawing, since it's hard to have bezier and quadraticCurve to have their derivates match. I suggested a few drawing methods, you can switch if you want.
Then i added rain, so that the water can move in a random way. Here it's just very simple trajectory, then i compute if there's collision with the water, and, if so, i add some velocity and shift the point.
I'd like to create a ‘realistic’ water movement with good fluid dynamics, collisions of this wave with the edges of a custom
container..
Oh boy.. That is quite a mouthful.
You should probably ask your Question here: gamedev.stackexchange
Anyways, have you tried to program any sort of wave yet, or are you just looking for WaveCreator.js ?
Go and Google some Non-language-specific Guides on how to create 2D water.
If you are a beginner, then start with something simple to get the idea behind things.
How about creating a bunch of Boxes for "minecraft-style" water ?
Here every "line" of water could be represented as a position in an Array. Then loop through it and set the "height" of the water based on the previous Array Index.
(You could smooth the water out by either making the blocks very thin (More work for your program!) or by smoothing out the edges and giving them an angle based on the other Squares.
I think this could be a neat solution. Anyhow. Hope that gave you some ideas.

Categories