Skip to content

Instantly share code, notes, and snippets.

@yiwenl
yiwenl / sort-chars.js
Last active December 8, 2023 14:16
Sorting characters with number of transparent pixels
// Create a canvas element
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = 64;
canvas.height = 64;
// Function to calculate non-transparent pixels
function countNonTransparentPixels(character) {
// Clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
@yiwenl
yiwenl / doTrianglesIntersect.js
Last active September 5, 2023 20:21
Triangle intersection check
// Triangle format: [[x, y], [x, y], [x, y]]
function doTrianglesIntersect(triangle1, triangle2) {
function doEdgesIntersect(edge1, edge2) {
// Check if two line segments (edges) intersect
const [x1, y1] = edge1[0];
const [x2, y2] = edge1[1];
const [x3, y3] = edge2[0];
const [x4, y4] = edge2[1];
@yiwenl
yiwenl / Bezier - 2D
Last active September 24, 2023 16:46
Bezier Curve with gl-matrix
import { vec2 } from "gl-matrix";
export const bezier = (mPoints, t) => {
if (mPoints.length === 2) {
const p = vec2.create();
vec2.lerp(p, mPoints[0], mPoints[1], t);
return p;
}
const a = [];
// add any configs you like
export default {
value:0.5,
autoSave: false,
};
uniform float zNear = 0.1;
uniform float zFar = 500.0;
// depthSample from depthTexture.r, for instance
float linearDepth(float depthSample)
{
depthSample = 2.0 * depthSample - 1.0;
float zLinear = 2.0 * zNear * zFar / (zFar + zNear - depthSample * (zFar - zNear));
return zLinear;
}
vec3 align(vec3 pos, vec3 dir) {
vec3 initDir = vec3(1.0, 0.0, 0.0);
vec3 axis = cross(dir, initDir);
float angle = acos(dot(dir, initDir));
return rotate(pos, axis, angle);
}
@yiwenl
yiwenl / bezier.glsl
Last active May 31, 2023 18:47
Bezier curve in GLSL
// bezier curve with 2 control points
// A is the starting point, B, C are the control points, D is the destination
// t from 0 ~ 1
vec3 bezier(vec3 A, vec3 B, vec3 C, vec3 D, float t) {
vec3 E = mix(A, B, t);
vec3 F = mix(B, C, t);
vec3 G = mix(C, D, t);
vec3 H = mix(E, F, t);
vec3 I = mix(F, G, t);
@yiwenl
yiwenl / map.glsl
Last active October 15, 2019 14:07
Mapping function
float map(float value, float start, float end, float newStart, float newEnd) {
float percent = (value - start) / (end - start);
if (percent < 0.0) {
percent = 0.0;
}
if (percent > 1.0) {
percent = 1.0;
}
float newValue = newStart + (newEnd - newStart) * percent;
return newValue;
// fov in Radians, camera position in [x, y, z]
const fovHeight = Math.tan(camera.fov / 2) * camera.position[2]
const fovWidth = fovHeight * camera.aspectRatio
// saveImage.js
const dataURLtoBlob = (dataurl) => {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}