diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 00000000..384cedbd --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,66 @@ +# Sample workflow for building and deploying a Hugo site to GitHub Pages +name: Deploy Hugo site to Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: ["main"] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow one concurrent deployment +concurrency: + group: "pages" + cancel-in-progress: true + +# Default to bash +defaults: + run: + shell: bash + +jobs: + # Build job + build: + runs-on: ubuntu-latest + env: + HUGO_VERSION: 0.99.0 + steps: + - name: Install Hugo CLI + run: | + wget -O ${{ runner.temp }}/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_Linux-64bit.deb \ + && sudo dpkg -i ${{ runner.temp }}/hugo.deb + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: recursive + - name: Setup Pages + id: pages + uses: actions/configure-pages@v1 + - name: Build with Hugo + run: | + hugo \ + --minify \ + --baseURL ${{ steps.pages.outputs.base_url }} + - name: Upload artifact + uses: actions/upload-pages-artifact@v1 + with: + path: ./public + + # Deployment job + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + needs: build + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v1 diff --git a/.gitignore b/.gitignore index 7220fb2e..4e5d0e86 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ # Logs *.log .hugo_build.lock +.DS_Store \ No newline at end of file diff --git a/.gitmodules b/.gitmodules index 1d95c411..eb663cee 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "themes/book"] path = themes/book url = https://github.com/alex-shpak/hugo-book +[submodule "themes/ananke"] + path = themes/ananke + url = https://github.com/theNewDynamic/gohugo-theme-ananke.git diff --git a/README.md b/README.md index 244e35f3..1dcc88b8 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,9 @@ -# Showcase Template +# Grupo de estudio +- Angela Cardenas +- Diego Carvajal +- Brayan Portela +- David Muñoz -Welcome to the [gohugo](https://gohugo.io/) template to create rich content [academic reports](https://www.wordy.com/writers-workshop/writing-an-academic-report/) having [p5.js](https://p5js.org/) sketches. - -## Hacking - -Install the [gohugo](https://gohugo.io/) [static site generator](https://jamstack.org/generators/) then: ```sh $git clone https://github.com/VisualComputing/showcase @@ -12,12 +11,3 @@ $cd showcase $git submodule update --init --recursive $hugo server -D --disableFastRender ``` - -Deploy with `$git push` after redefined `baseURL` in `config.toml` which should point to your actual public remote. - -### Remarks - -1. If you renamed the repo, say to `newreponame`, don't forget to update all url references of the markdown and js file sources, to reflect that change, i.e., look in all the [content folder](https://github.com/VisualComputing/showcase/tree/main/content) files for `showcase` occurrences and replace them by `newreponame`. -2. If you forked the repo don't forget to activate the [actions](https://github.com/VisualComputing/showcase/actions). -3. Don't forget to select the `gh-pages` branch as the one to serve your site from at the [pages section of your repo configuration page](https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site), if it is no so by default. -4. The **showcase** template uses the [hugo-book](https://github.com/alex-shpak/hugo-book) theme by default. Check the [hugo themes site](https://themes.gohugo.io/) if you wish to add other ones. \ No newline at end of file diff --git a/config.toml b/config.toml index 3a9cf553..7665fdf9 100644 --- a/config.toml +++ b/config.toml @@ -1,7 +1,7 @@ -baseURL = "https://visualcomputing.github.io/showcase" +baseURL = "https://dicarvajalb.github.io/visual_computing" languageCode = "en-us" -title = "Showcase Template" -theme = 'book' +title = "Grupo de estudio" +theme = "book" # Book configuration disablePathToLower = true @@ -22,7 +22,7 @@ enableGitInfo = true # Set source repository location. # Used for 'Last Modified' and 'Edit this page' links. - BookRepo = 'https://github.com/visualcomputing/showcase' + BookRepo = 'https://github.com/Dicarvajalb/visual_computing' # Configure the date format used on the pages # - In git information @@ -35,3 +35,4 @@ enableGitInfo = true # Theme will print warning if page referenced in markdown does not exists. BookPortableLinks = false + diff --git a/content/_index.md b/content/_index.md index 39001154..2264e864 100644 --- a/content/_index.md +++ b/content/_index.md @@ -3,37 +3,8 @@ title: Introduction type: docs --- -# Showcase Template - -Welcome to the [gohugo](https://gohugo.io/) template to create rich content [academic reports](https://www.wordy.com/writers-workshop/writing-an-academic-report/) having [p5.js](https://p5js.org/) sketches. - -## Hacking - -Install the [gohugo](https://gohugo.io/) [static site generator](https://jamstack.org/generators/) then: - -```sh -$git clone https://github.com/VisualComputing/showcase -$cd showcase -$git submodule update --init --recursive -$hugo server -D --disableFastRender -``` - -Deploy with `$git push` after redefined `baseURL` in `config.toml` which should point to your actual public remote. - -### Remarks - -{{< hint info >}} -If you renamed the repo, say to `newreponame`, don't forget to update all url references of the markdown and js file sources, to reflect that change, i.e., look in all the [content folder](https://github.com/VisualComputing/showcase/tree/main/content) files for `showcase` occurrences and replace them by `newreponame`. -{{< /hint >}} - -{{< hint info >}} -If you forked the repo don't forget to activate the [actions](https://github.com/VisualComputing/showcase/actions). -{{< /hint >}} - -{{< hint info >}} -Don't forget to select the `gh-pages` branch as the one to serve your site from at the [pages section of your repo configuration page](https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site), if it is no so by default. -{{< /hint >}} - -{{< hint info >}} -The **showcase** template uses the [hugo-book](https://github.com/alex-shpak/hugo-book) theme by default. Check the [hugo themes site](https://themes.gohugo.io/) if you wish to add other ones. -{{< /hint >}} \ No newline at end of file +# Grupo de estudio +- Angela Cardenas +- Diego Carvajal +- Brayan Portela +- David Muñoz \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Convoluciones.md b/content/docs/shortcodes/Taller 1/Convoluciones.md new file mode 100644 index 00000000..096086f9 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Convoluciones.md @@ -0,0 +1,313 @@ +# **1. Convoluciones** +--- +## Problem statement + +Una convolucion sobre una imagen es un calculo matematico sobre un conjunto de pixeles sobre la misma, esta operacion hace uso de los denominados **Kernel**; +Un kernel es una matriz con valores determinados los cuales permiten aplicar diferentes mascaras sobre las imagenes, los valores dentro de las matrices de los kernel se pueden alterar con base en el resultado que se desee obtener se pueden modificar. + +- Se desea una aplicacion web que pueda aplicar diferentes convoluciones a una imagen. + +## Background + +La **operacion de convolucion** se define como: + +{{< katex display >}} +g(x,y)=\omega *f(x,y)=\sum _{dx=-a}^{a}{\sum _{dy=-b}^{b}{\omega (dx,dy)f(x-dx,y-dy)}} +{{< /katex >}} + +Sin embargo, se puede definir mas facilmente si se utiliza el kernel como un vector 1-dimensional asi. Con este vector, se toman los 4 canales **__R,G,B,A__** y se separan en vectores que puedan operarse de manera escalar, recordemos que el producto escalar entre dos vectores se define como; + + +{{< katex display >}} +u \cdot v = u {\displaystyle =u_{1}\cdot v_{1}+u_{2}\cdot v_{2}+...+u_{n}\cdot v_{n}} {\displaystyle =u_{1}\cdot v_{1}+u_{2}\cdot v_{2}+...+u_{n}\cdot v_{n}}, +{{< /katex >}} + + +**Precaucion** +> Al operar la imagen se deben tener en cuenta la inexistencia de pixeles externos, si se aplicara la convolucion donde el centro del kernel se ubica sobre el primer pixel, habran posiciones que no esten definidas por lo cual hay dos posibles alternativas. +* Operar desde el pixel **(1,1)** +* Operar desde el pixel **(0,0)** pero reescribiendo toda la imagen añadiendo pixeles de valor 0 al rededor de la imagen; +--- + +{{< hint info >}} +**¿Como interactuar con la ilusión?** +Para cambiar los efectos sobre la imagen hay de usar el Slider para seleccionar uno +de los kernels, ya despues de seleccionado se debe presionar el boton **Recargar canvas**. +{{< /hint >}} + +**Kernels disponibles** + + +| Name | Matrix | +|-----------|--------| +|Identity| [0, 0, 0, 0, 1, 0, 0, 0, 0]| +|Sharpen| [0, -1, 0, -1, 5, -1, 0, -1, 0]| +|Box Blur| [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]| +|Edge Detection| [-1, -1, -1, -1, 8, -1, -1, -1, -1]| +|Gaussian Blur| [1, 2, 1, 2, 4, 2, 1, 2, 1]| +|Emboss| [-2, -1, 0, -1, 1, 1, 0, 1, 2]| +|Bottom Sobel| [-1,2,-1,0,0,0,1,2,1]| +|Outline| [-1,-1,-1,-1,8,-1,-1,-1,-1]| +|Top Sobel| [1,2,1,0,0,0,-1,-2,-1| + +## Code + +{{< p5-iframe sketch="/visual_computing/sketches/convolutions.js" width="625" height="625" >}} + +{{< details "**CODIGO:** Convoluciones" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript + var img,kernel; +let channelsMap,RedMat,BlueMat,GreenMat,newChannels,fMap; + +function preload() { + img = loadImage('/showcase/sketches/bubbleCatC.png'); +} + +function setup() { + createCanvas(600,600); + noLoop(); + + //Boton de Recarga + button = createButton('Recargar Canvas'); + button.position(10, 10); + button.mousePressed(reload); + + //Cambiar el kernel + slider = createSlider(1, 9, 1, 1); + slider.position(200, 10); + slider.style('width', '120px'); +} + +//Calcular el producto punto +function ppunto(Pix,Ker){ + let sum = 0; + for(let x = 0;x < Ker.length;x++){ + sum = sum + (Pix[x]*Ker[x]) + } + return sum; +} + +//Dividimos los canales en arreglos individuales +function ChannelDivider(ImgArr){ + let imgRed = [], imgGreen = [], imgBlue = [], imgAlpha = []; + for(let i = 0; i < ImgArr.length ; i+=4){ + imgRed.push(ImgArr[i]); + imgGreen.push(ImgArr[i+1]); + imgBlue.push(ImgArr[i+2]); + imgAlpha.push(ImgArr[i+3]); + } + return [imgRed,imgGreen,imgBlue,imgAlpha] +} + +//Recomponer la imagen +function ChannelComposer(R,G,B,A){ + let imageChannels = []; + for(let i = 0; i < A.length*4 ; i+=4){ + imageChannels[i] = R[i/4]; + imageChannels[i+1] = G[i/4]; + imageChannels[i+2] = B[i/4]; + imageChannels[i+3] = A[i/4]; + } + return imageChannels; +} + +//separar los arreglos para hacer una matriz +function ArraySplice(arr,dim){ + var matrix = [], i, k; + for (i = 0, k = -1; i < arr.length; i++) { + if (i % dim === 0) { + k++; + matrix[k] = []; + } + matrix[k].push(arr[i]); + } + return matrix; +} +//Reescribir el arreglo como matriz +function dimensioner(LTM){ + var extended = []; + for(let r = 0; r < LTM.length ; r++){ + for(let c = 0; c < LTM[r].length; c++){ + //Si estoy en el primer pixel + if(r==0 && c==0){ + extended.push( + [0,0,0, + 0,LTM[r][c],LTM[r][c+1], + 0,LTM[r+1][c],LTM[r+1][c+1]] + ); + }else + //si estoy en la primer fila + if(r==0 && (c>0 && c!=LTM[r].length - 1)){ + extended.push( + [0,0,0, + LTM[r][c-1],LTM[r][c],LTM[r][c+1], + LTM[r+1][c-1],LTM[r+1][c],LTM[r+1][c+1]] + ); + }else + //Si estoy en el el ultimo pixel de una fila + if(r==0 && c==LTM[r].length - 1){ + extended.push( + [0,0,0, + LTM[r][c-1],LTM[r][c],0, + LTM[r+1][c-1],LTM[r+1][c],0] + ); + }else + + //si estoy en el primer pixel de una columna + if((r>0 && r0 && r0 && c }} + +--- + +## Conclusions + +El ejercicio es bastante complejo debido a las limitantes que existen al momento del renderizado, Sin embargo la manipulacion matematica de la imagen permite un acercamiento practico a funciones utilizadas por editores graficos lo cual permite entender que procesos se realizan bajo las interfaces para poder obtener resultados. \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Histograma.md b/content/docs/shortcodes/Taller 1/Histograma.md new file mode 100644 index 00000000..99cfb346 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Histograma.md @@ -0,0 +1,89 @@ +# Histograma +--- +## Problem statement + +Un histograma de imagen es una representación gráfica de la distribución tonal en una imagen digital. Para esto traza el número de píxeles para cada valor tonal de manera que al mirar el histograma de una imagen específica, un espectador podrá juzgar la distribución tonal completa de un vistazo. + +Tiene muchos usos entre ellos sirve dar al fotógrafo una mejor comprensión de los valores de brillo en una imagen. + + + +## Background +Un histograma es una representación de la distribución de datos numericos, este fue creado por Karl Pearson. Este tiene 2 ejes x y y, el primero contiene eventos cuya frecuencia debe contar y el otro contiene la frecuencia. + +## Code + +{{< p5-iframe sketch="/visual_computing/sketches/histogram.js" width="720" height="420" >}} +{{< p5-iframe sketch="/visual_computing/sketches/histogram2.js" width="700" height="440" >}} +{{< p5-iframe sketch="/visual_computing/sketches/histogram3.js" width="400" height="400" >}} + +{{< details "**CODIGO:** Histograma" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +var img; +var maxRange = 256; +var histogram = new Array(maxRange); +function preload() { + img = loadImage("/visual_computing/sketches/einstein.jpg"); // Load the image +} + +function setup() { + createCanvas(img.width, img.height+10); + background(255); + img.resize(0,400); + colorMode(HSL, maxRange); + image(img, 0, 0); + + for (i = 0; i <= maxRange; i++) { + histogram[i] = 0 + } + + transform_rgb(); + + construir_histograma(); + +} + +function construir_histograma(){ + image(img, 0, 0); + stroke(300,100,80) + push() + translate(10,0) + for (x = 0; x <= maxRange; x++) { + index = histogram[x]; + + y1=int(map(index, 0, max(histogram), img.height, img.height-200)); + y2 = img.height + xPos = map(x,0,maxRange,0, img.width-20) + stroke('red'); + line(xPos, y1, xPos, y2); + + } + pop() +} + +function transform_rgb(){ + loadPixels(); + + for (var x = 0; x < img.width; x+=5) { + for (var y = 0; y < img.height; y+=5) { + var loc = (x + y * img.width) * 4; + var h = pixels[loc]; + var s = pixels[loc + 1]; + var l = pixels[loc + 2]; + var a = pixels[loc + 3]; + b = int(l); + histogram[b]++ + } + } +} + + //Bibliografia: https://editor.p5js.org/ebenjmuse/sketches/HyPfeGkCZ +``` +{{< /details >}} + +--- + +## Conclusions + +El ejercicio es bastante complejo debido a que debe adaptarse a cualquier imagen, pero es un analisis muy util de la imagen ya que con un solo vistazo se sabe cual es la tendencia de los colores. \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Ilusiones/BindingMovement.md b/content/docs/shortcodes/Taller 1/Ilusiones/BindingMovement.md new file mode 100644 index 00000000..5d6f8f2b --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Ilusiones/BindingMovement.md @@ -0,0 +1,149 @@ +# Movimiento Enlazado +--- +## Problem statement + +La presente ilusión muestra 4 líneas aparentemente moviéndose de forma _independiente_, sin embargo, al revisarlas de forma extensiva se puede notar que se mueven en pares ordenados paralelos. La figura que describe este movimiento corresponde a un rombo el cual posee sus vértices ocultos; + +Al hacer que los vértices sean visibles se puede notar como el tenerlos ocultos crea el movimiento ilusorio. + +{{< hint info >}} +**¿Como interactuar con la ilusión?** +Para visibilizar las figuras que desmontan la ilusión es necesario marcar +el checkbox **"Visible"** , el Slider que se encuentra permite cambiar la +visibilidad _"Alpha"_ de las figuras. +{{< /hint >}} + +## Code + +{{< p5-global-iframe id="sketchid" width="625" height="625" >}} + let bgColor = 200, checkbox; + function setup() { + createCanvas(600,600); + angleMode(DEGREES); + rectMode(CENTER); + + //transparency + slider = createSlider(20, 255, 100); + slider.position(10, 10); + slider.style('width', '80px'); + + //Squares Transparency + checkbox = createCheckbox('Visible', false); + checkbox.position(10,40); + + } + + function drawSquares(visible){ + let xAxis = 150; + let yAxis = 150; + let size = 120; + + rotate(45); + + if(!checkbox.checked()){ + fill(bgColor); + noStroke() + }else{ + let alpha = slider.value(); + fill(0,100,100,alpha); + noStroke(); + } + + rect(xAxis,-yAxis,size,size); + rect(-xAxis,yAxis,size,size); + rect(xAxis,yAxis,size,size); + rect(-xAxis,-yAxis,size,size); + } + + function mainSquare(){ + translate(p5.Vector.fromAngle(millis()/500,40)); + let bSize = 300; + rotate(45); + fill(bgColor) + stroke(0, 0, 255); + strokeWeight(6); + rect(0,0,bSize,bSize); + } + + function draw() { + background(bgColor); + translate(width/2,height/2); + + push(); + mainSquare(); + pop(); + + drawSquares(false); + } +{{< /p5-global-iframe >}} + +{{< details "**CODIGO:** Movimiento Enlazado" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript + let bgColor = 200, checkbox; + function setup() { + createCanvas(600,600); + angleMode(DEGREES); + rectMode(CENTER); + + //transparency + slider = createSlider(20, 255, 100); + slider.position(10, 10); + slider.style('width', '80px'); + + //Squares Transparency + checkbox = createCheckbox('Visible', false); + checkbox.position(10,40); + + } + + function drawSquares(visible){ + let xAxis = 150; + let yAxis = 150; + let size = 120; + + rotate(45); + + if(!checkbox.checked()){ + fill(bgColor); + noStroke() + }else{ + let alpha = slider.value(); + fill(0,100,100,alpha); + noStroke(); + } + + rect(xAxis,-yAxis,size,size); + rect(-xAxis,yAxis,size,size); + rect(xAxis,yAxis,size,size); + rect(-xAxis,-yAxis,size,size); + } + + function mainSquare(){ + translate(p5.Vector.fromAngle(millis()/500,40)); + let bSize = 300; + rotate(45); + fill(bgColor) + stroke(0, 0, 255); + strokeWeight(6); + rect(0,0,bSize,bSize); + } + + function draw() { + background(bgColor); + translate(width/2,height/2); + + push(); + mainSquare(); + pop(); + + drawSquares(false); + } +``` +{{< /details >}} + +--- + +## Conclusions + +Para el ojo inexperto el movimiento puede resultar complejo ya que la ilusion cumple con el objetivo y de primera mano da a enter que tras ella se requieren calculos y codigos complejos para obtener la sincronizacion. Sin embargo, el desarrollo del ejercicio permite entender como la manipulacion geometrica y de factores como perspectiva y velocidad permiten generar animaciones complejas. \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Ilusiones/SKE.md b/content/docs/shortcodes/Taller 1/Ilusiones/SKE.md new file mode 100644 index 00000000..d9ca04b8 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Ilusiones/SKE.md @@ -0,0 +1,58 @@ +# Efecto esteroquinético + +## Problem statement + +El efecto esteroquinético es una ilusión visual de la profundidad. Es un efecto ilusorio que depende del movimiento. Se basa en que la rotación de figuras adecuadas crea una ilusión tridimensional + +## Code + +Pasos dentro del código: + +1. Dibujar el primer circulo +2. Iterar por cada círculo definiendo su rotación y su posición. + +{{< details title="source code" open=false >}} +{{< highlight html >}} +let angle = 0; +let speed = 0.05; +let circleColor = true; + +function setup() { +createCanvas(400, 400); +} + +function draw() { +background(220); +angle += speed; +strokeWeight(1) +circle(200,200,400); +cirrcle(375) +} + +function cirrcle(size){ +fill(255,255,0) +if(circleColor){ +fill(0,0,255) + } +circleColor = !circleColor + +if(size>100){ +translate(p5.Vector.fromAngle(millis() / 1000, 12.5)); +strokeWeight(0) +circle(200,200, size); +cirrcle(size-25) +}else if(size>0){ +translate(p5.Vector.fromAngle(millis() / 1000, -12.5)); +circle(200,200, size); + cirrcle(size-25) +} +return +} +{{< /highlight >}} +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/illusion3d.js" width="450" height="450" >}} + +## Conclusions + +Es una manera muy interesante de crear la ilusión de la tercera dimensión, estos conceptos van encaminados hacia la creación de gráficas en 3D. diff --git a/content/docs/shortcodes/Taller 1/Ilusiones/SteppingFeet.md b/content/docs/shortcodes/Taller 1/Ilusiones/SteppingFeet.md new file mode 100644 index 00000000..e9769bdf --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Ilusiones/SteppingFeet.md @@ -0,0 +1,184 @@ +# Paso a paso +--- +## Problem statement + +Tambien llamada Stepping feet, es una ilusión visual de percepción de movimiento. Esta muestra dos pies, uno azul y otro amarillo, que se mueven horizontalmente a través de un paisaje que consta de rayas blancas y negras. Aunque ambos pies se mueven a una velocidad constante, su velocidad percibida es distinta. + + +{{< hint info >}} +**¿Como interactuar con la ilusión?** +Para cambiar la velocidad de las figuras se usa el primer slider, para cambiar la relación baras/pie se usa el segundo slider y para mover o detener los pies se debe clickear la casilla de move. +{{< /hint >}} + +## Code + +{{< p5-iframe sketch="/visual_computing/sketches/stepping_feet.js" width="625" height="625" >}} + +{{< details "**CODIGO:** Paso a paso" close >}} +**C**odigo generado usando el editor web de **P5.js**. +```javascript +var canvasWidth = 600; +var canvasHeight = 400; + +var quantity = 2; +var speed = 1; + +var positionXBar1 = 0; +var positionYBar1 = canvasHeight / 3; +var positionYBar2 = (2*canvasHeight) / 3; +var widthBar = 80; +var heightBar = 40; +var colorBar1 = 'yellow'; +var colorBar2 = 'blue'; +var moveBarRight = true; +var isMove = true; + +var sliderSpeed; + +function setup() { + createCanvas(canvasWidth, canvasHeight); + background('white'); + drawLayout(); +} + +function draw() { + drawBoard(); + updateSpeed(); + drawBar1(); + drawBar2(); +} + +function drawBoard(){ + let position; + + quantity = sliderQuantity.value(); + + let realLines = (canvasWidth / widthBar) * quantity; + let widthLine = widthBar / quantity; + let numberLines = realLines % 2 == 0 ? realLines + 1 : realLines; + + for (let i = 0; i < numberLines; i++) { + position = i * widthLine; + if (i % 2 == 0) { + fill('black'); + rect(position, 0, widthLine, canvasHeight); + } else { + strokeWeight(0) + fill('white'); + rect(position, 0, widthLine, canvasHeight); + } + } +} + +function drawBar1(){ + fill(colorBar1); + rect(positionXBar1, positionYBar1, widthBar, heightBar); + if (moveBarRight) { + positionXBar1 += speed; + if (positionXBar1 + widthBar > canvasWidth) { + moveBarRight = false; + } + } else { + positionXBar1 -= speed; + if (positionXBar1 <= 0) { + moveBarRight = true; + } + } +} + +function drawBar2() { + fill(colorBar2); + rect(positionXBar1, positionYBar2, widthBar, heightBar); + if (moveBarRight) { + positionXBar1 += speed; + if (positionXBar1 + widthBar > canvasWidth) { + moveBarRight = false; + } + } else { + positionXBar1 -= speed; + if (positionXBar1 <= 0) { + moveBarRight = true; + } + } + } + + function updateSpeed() { + if (isMove) { + speed = sliderSpeed.value(); + } + } + +function drawLayout() { + //Reset button + button = createButton('Reset'); + button.position(40, 440); + button.mousePressed(() => { + canvasWidth = 600; + canvasHeight = 400; + quantity = 2; + speed = 1; + positionXBar1 = 0; + positionYBar1 = canvasHeight / 3; + positionXBar2 = 0; + positionYBar2 = (2*canvasHeight) / 3; + widthBar = 80; + heightBar = 40; + moveBarRight = true; + }); + + //Move checkbox + checkbox = createCheckbox('Move', isMove); + checkbox.position(40, 470); + checkbox.mousePressed(() => { + if (speed === 0) { + isMove = true; + speed = sliderSpeed.value(); + } else { + isMove = false; + speed = 0; + } + }); + + //Slider speed + sliderSpeed = createSlider(1, 10, 1); + sliderSpeed.position(40, 500); + sliderSpeed.style('width', '80px'); + + //Slider quantity + sliderQuantity = createSlider(1, 10, 1); + sliderQuantity.position(40, 540); + sliderQuantity.style('width', '80px'); + + //Change color + sel = createSelect(); + sel.position(40, 580); + sel.option('blue-yellow'); + sel.option('red-green'); + sel.option('grey'); + sel.selected('kiwi'); + sel.changed((value) => { + switch(value.target.value) { + case 'blue-yellow': + colorBar1 = 'yellow' + colorBar2 = 'blue' + break; + case 'red-green': + colorBar1 = 'green' + colorBar2 = 'red' + break; + case 'grey': + colorBar1 = 'white' + colorBar2 = 'black' + break; + } + }); + +} +``` +{{< /details >}} + +--- + +## Conclusions + +La clave de esta ilusión es el contraste, ya que cuando hay un mayor contraste entre el pie y el fondo, el pie se hace visible más facilmente y da una sensación de movimiento rapido mientras que cuando el contraste es bajo, el pie es más dificil de diferenciar del fondo y parecer ir más lento. Esta ilusió demuestra que el fondo de un objeto puede tener un efecto significativo en su velocidad percibida. \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 1/Ilusiones/_index.md b/content/docs/shortcodes/Taller 1/Ilusiones/_index.md new file mode 100644 index 00000000..ab17ba59 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Ilusiones/_index.md @@ -0,0 +1,13 @@ +--- +bookCollapseSection: true +--- + +# Taller 1 + +## Objetivo + +En este taller fortaleceremos conceptos de manipulación de píxeles para la modificación de una imagen mediante Kernels, reproduciremos ilusiones ópticas para familiarizarnos con P5.js y construiremos un visualizador de histogramas. + +## Types + +{{
}} diff --git a/content/docs/shortcodes/Taller 1/Lightness.md b/content/docs/shortcodes/Taller 1/Lightness.md new file mode 100644 index 00000000..f64f9013 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Lightness.md @@ -0,0 +1,87 @@ +# Lightness + +## Problem statement + +Sería útil tener una herramienta que permita la manipulación de luminosidad de una imagen, y de esta manera poder aclarar imágenes oscuras para poder ver sus siluetas. + +## Background + +- Manipulación de pixeles usando `P5.js` +- Uso de [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV#Lightness) +- Conversión entre HSL y RGB + +## Code + +Pasos dentro del código: + +1. Cargar la imagen a manipular y el `botón de rango` +2. Dado un valor en el `botón de rango`, se aumenta la luminosidad de cada pixel en la imagen.S + +{{< details title="source code" open=false >}} +{{< highlight html >}} + +new p5((p) =>{ +let img; +let myPixels; +p.preload = function() { +img = p.loadImage("/showcase/sketches/medusa.jpeg"); +} + +p.setup = function () { +p.createCanvas(400, 400); +let inp = p.createInput("0","range"); + +inp.size(100); + +inp.input((e) => handleBtn(e)); + +inp.position(0,p.height-20) +p.image(img, 0, 0, p.width, p.height); +p.colorMode(p.RGB) +p.loadPixels(); +myPixels = [...p.pixels] +console.log("myPixels",myPixels[0]) +} + +p.draw = function (){ + +} + +handleBtn= function(inp){ +console.log("inp", inp.target.value) +let d = p.pixelDensity(); +let halfImage = 4 _ (p.width _ d) _ (p.height _ d); +for (let i = 0; i < halfImage; i += 4) { + +let colorRGB = p.color(myPixels[i],myPixels[i+1], myPixels[i+2]) +let hueValue = p.floor( p.hue(colorRGB) ); +let saturationValue = p.saturation(colorRGB); +let lightnessValue = p.lightness(colorRGB); + +let colorHSV = p.color(`hsl(${ hueValue }, ${ saturationValue }%, ${ (lightnessValue + parseFloat(inp.target.value))}%)`) + +p.pixels[i] = p.red(colorHSV); +p.pixels[i + 1] = p.green(colorHSV); +p.pixels[i + 2] = p.blue(colorHSV); +p.pixels[i + 3] = p.alpha(colorHSV); +} +p.updatePixels(); +console.log("myPixels",myPixels[0]) +} + +handleImg = function(event){ +console.log("event.target",event.target.value) +p.loadImage(event.target.value, img2 => { +p.image(img2, 0, 0, p.width, p.height); +}); + +} +}) +{{< /highlight >}} +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/lightness.js" width="450" height="450" >}} + +## Conclusions + +Esta forma de manipular los pixeles llega a buenos resultados en cuanto a la modificación de luminocidad, pero es costosa computacionalmente, sería interesante descubrir el trabajo que realizan programas como Photoshop para lograr una óptima manipulación sobre una imagen. diff --git a/content/docs/shortcodes/Taller 1/Multiplicacion RGB.md b/content/docs/shortcodes/Taller 1/Multiplicacion RGB.md new file mode 100644 index 00000000..9d547b76 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/Multiplicacion RGB.md @@ -0,0 +1,54 @@ +# Multiplicación RGB + +## Problem statement + +¿Qué sucede si multiplicamos dos colores RGB? + +## Code + +Pasos dentro del código: + +1. Obtener los 2 valores RGB de la paleta +2. Calcular su multiplicación y mostrarla en pantalla + +{{< details title="source code" open=false >}} +{{< highlight html >}} +let backgroundColor; +let color1, color2 +function setup() { + createCanvas(200, 200); + let c1 = createInput("0,0,0",'color') + let c2 = createInput("0,0,0",'color') + + + c1.input(()=> setColor1(c1,c2)) + c2.input(()=> setColor1(c1,c2)) +} + +function setColor1(c1,c2){ + let color1 = color(red(c1.value()), green(c1.value()), blue(c1.value())) + let black = color(0,0,0) + fill(color1) + rect(0,0, 130,130) + let color2 = color(red(c2.value()), green(c2.value()), blue(c2.value())) + fill(color2) + rect(70,70, 130,130) + + //let white = color(255,255,255) + + const cred = (red(c1.value()) * red(c2.value())) / 255; + const cblue = (blue(c1.value()) * blue(c2.value())) / 255; + const cgreen = (green(c1.value()) * green(c2.value())) /255; + fill(color(cred, cgreen,cblue)) + rect(70,70, 60,60) + //background(cred,cgreen,cblue) + +} +{{< /highlight >}} +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/RGBmultiply.js" width="450" height="450" >}} + +## Conclusions + +La multiplicación RGB, bajo algunos casos, hacer ver que cuadrados tienen una cierta transparencia, y que los colores se combinan. diff --git a/content/docs/shortcodes/Taller 1/_index.md b/content/docs/shortcodes/Taller 1/_index.md new file mode 100644 index 00000000..ab17ba59 --- /dev/null +++ b/content/docs/shortcodes/Taller 1/_index.md @@ -0,0 +1,13 @@ +--- +bookCollapseSection: true +--- + +# Taller 1 + +## Objetivo + +En este taller fortaleceremos conceptos de manipulación de píxeles para la modificación de una imagen mediante Kernels, reproduciremos ilusiones ópticas para familiarizarnos con P5.js y construiremos un visualizador de histogramas. + +## Types + +{{
}} diff --git a/content/docs/shortcodes/Taller 2/Aplicacion 3-D/Laberinto.md b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/Laberinto.md new file mode 100644 index 00000000..143db232 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/Laberinto.md @@ -0,0 +1,348 @@ +# Laberinto 3-D + +## Problema + +Implemente una aplicacion 3D con WebGL. Puede usar la libreria p5.treegl o cualquier otra libreria necesaria. + +## Introduccion + +Un **laberinto** es un lugar compuesto por un conjunto de calles y encrucijadas con una disposicion compleja. El Objetivo de los laberintos es confudir a quienes se adentren dentro del mismo. Historicamente, los laberintos han sido mencionados en la mitologia como retos para los heroes **["El laberinto de Creta"]** asi mismo como una representacion artistica para la inteligencia y destreza. + +## Desarrollo + +Para poder Cumplir el objetivo de la aplicacion, se presenta el siguiente curso de acción tomado para el desarrollo. + +- Crear los objetos con ayuda de **P5.js**. +- Migrar los objetos a **p5.treegl** . +- Inclinar un plano en **3D**. +- Creacion de **colisiones** entre objetos. +- Mover un objeto sujeto al plano y sobre el plano. +- Induccion de fuerzas y mecanicas [**Aceleracion,Gravedad**]. + +## Codigos + +--- + +1. **Colisiones y Movimiento sobre la inclinacion del plano:** Haciendo uso de las libreria p5.treegl y los metodos nativos de p5, se consigue rotar un plano con base en el movimiento que dicte el cursor. Sobre este plano se encuentra una esfera la cual esta colisionando contra este. La esfera se movera sieguien el vector de rotacion y orientacion del plano. + +{{< hint info >}} +**¿Como interactuar con el plano?** +Para cambiar la inclinacion debe deslizar el mouse presionando el boton de click derecho sobre el Canvas. Para mover la esfera use las teclas **"a"** y **"d"**. +{{< /hint >}} + +{{< details "**CODIGO:** Colisiones y Movimiento" close >}} + +```javascript +let planePosition, + planeSize, + planeColor, + planeRotateV, + planeMagnitudeR, + planeMaxMagR; +let spherePosition, sphereMoveVector, sphereRadius, maxVertex, minVertex; +let fbo1, + cam1, + length = 600, + boxes, + box_key; +let mouseInitialV, mouseCurrentV, fovy; + +const SPEED = 5; + +function createPlane() { + planeMaxMagR = 25; + planeColor = "black"; + planeMagnitudeR = 0; + + planeRotateV = createVector(1, 0, 0); + planeSize = createVector(100, 50, 0); //ancho y alto + planePosition = createVector(0, 0, 0); +} + +function createSphere() { + sphereMoveVector = createVector(0, 1, 0); + sphereRadius = 10; + spherePosition = createVector(0, 0, sphereRadius); + + minVertex = createVector(-planeSize.x / 2, -planeSize.y / 2, 0); + maxVertex = createVector(planeSize.x / 2, planeSize.y / 2, 0); +} + +function setup() { + createCanvas(length, length); + fbo1 = createGraphics(width, height, WEBGL); + + // FBO camera + cam1 = new Dw.EasyCam(fbo1._renderer, { distance: 200 }); + let state1 = cam1.getState(); + cam1.state_reset = state1; // state to use on reset (double-click/tap) + cam1.setViewport([0, 0, width / 2, height]); + document.oncontextmenu = function () { + return false; + }; + + //Interactive elements + createPlane(); + createSphere(); + + // scene interactions + fovy = createSlider(PI / 12, PI * (11 / 12), PI / 3, PI / 48); + fovy.position(10, 10); + fovy.style("width", "80px"); +} + +function draw() { + //Background elements + fbo1.background(120, 125, 115); + fbo1.reset(); + fbo1.perspective(fovy.value()); + fbo1.axes(); + fbo1.grid(); + fbo1.rotate((PI / 100) * planeMagnitudeR, planeRotateV); + + //Dibujar el plano + fbo1.push(); + fbo1.fill(planeColor); + fbo1.translate(planePosition); + fbo1.plane(planeSize.x, planeSize.y); + fbo1.pop(); + + //Dibujar la esfera + fbo1.push(); + fbo1.fill("white"); + fbo1.translate(spherePosition); + fbo1.sphere(sphereRadius); + fbo1.pop(); + + // movimiento de la esfera + if (keyIsPressed && key == "a") { + spherePosition = createVector( + sphereMoveVector.x * 2 + spherePosition.x, + sphereMoveVector.y * 2 + spherePosition.y, + sphereMoveVector.z * 2 + spherePosition.z + ); + //spherePosition.z += 1 + } else if (keyIsPressed && key == "d") { + spherePosition = createVector( + sphereMoveVector.x * -2 + spherePosition.x, + sphereMoveVector.y * -2 + spherePosition.y, + sphereMoveVector.z * -2 + spherePosition.z + ); + } + + //Colisión + if ( + spherePosition.x >= minVertex.x && + spherePosition.y >= minVertex.y && + spherePosition.z - 10 >= minVertex.z && + spherePosition.x <= maxVertex.x && + spherePosition.y <= maxVertex.y && + spherePosition.z - 10 <= maxVertex.z + ) { + planeColor = "white"; + } else { + planeColor = "black"; + } + beginHUD(); + image(fbo1, 0, 0); + endHUD(); +} + +function getVectorModule(vector) { + return Math.sqrt(vector.x ** 2 + vector.y ** 2 + vector.z ** 2); +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0); +} + +function mouseDragged() { + mouseCurrentV = createVector(mouseX, mouseY, 0); + + let vectorSubstra = createVector( + mouseInitialV.x - mouseCurrentV.x, + mouseInitialV.y - mouseCurrentV.y, + mouseInitialV.z - mouseCurrentV.z + ); + let mod = getVectorModule(vectorSubstra); + + let vectorDir = createVector( + vectorSubstra.x / mod, + vectorSubstra.y / mod, + vectorSubstra.z / mod + ); + sphereMoveVector = createVector(vectorDir.x, vectorDir.y, vectorDir.z); + + let aux = vectorDir.x; + vectorDir.x = vectorDir.y; + vectorDir.y = -aux; + + if (mod < planeMaxMagR) { + planeMagnitudeR = mod; + } + planeRotateV = vectorDir; +} +``` + +{{< /details >}} + +## {{< p5-iframe srcdoc="lib3" srcdoc="lib4" sketch="/visual_computing/sketches/Inclination.js" width="625" height="625" >}} + +2. **Aceleracion:** Con base en el ejercicio anterior, ahora la esfera se deplaza sujeta al plano pero con una aceleracion de caracter oscilatorio dado por la funcion **Seno**. + +{{< hint info >}} +**¿Como interactuar con el plano?** +Para cambiar la inclinacion debe deslizar el mouse presionando el boton de click derecho sobre el Canvas, la esfera puede salirse del plano y del area visible por lo cual puede usar el slider para ajustar el zoom o el boton central del mouse. +{{< /hint >}} + +{{< details "**CODIGO:** Aceleracion" close >}} + +```javascript +let fbo1, cam1, fovy; +let P, B; +let mouseInitialV, mouseCurrentV; + +function Plane() { + this.planeMaxMagR = 25; + this.planeColor = "black"; + this.planeMagnitudeR = 0; + + this.planeRotateV = createVector(1, 0, 0); + this.planeSize = createVector(100, 100, 0); //ancho y alto + this.planePosition = createVector(0, 0, 0); + + this.draw = function (fbo) { + fbo.push(); + fbo.fill(this.planeColor); + fbo.translate(this.planePosition); + fbo.plane(this.planeSize.x, this.planeSize.y); + fbo.pop(); + }; +} + +function Ball(P) { + this.sphereMoveVector = createVector(0, 0, 0); + this.acceleration = createVector(0, 0, 0); + this.sphereRadius = 10; + this.spherePosition = createVector(0, 0, this.sphereRadius); + + this.minVertex = createVector(-P.planeSize.x / 2, -P.planeSize.y / 2, 0); + this.maxVertex = createVector(P.planeSize.x / 2, P.planeSize.y / 2, 0); + + this.draw = function (fbo) { + fbo.push(); + fbo.fill("white"); + fbo.translate(this.spherePosition); + fbo.sphere(this.sphereRadius); + fbo.pop(); + }; +} + +function setup() { + createCanvas(600, 600); + fbo1 = createGraphics(width, height, WEBGL); + + // FBO camera + cam1 = new Dw.EasyCam(fbo1._renderer, { distance: 200 }); + let state1 = cam1.getState(); + cam1.state_reset = state1; // state to use on reset (double-click/tap) + cam1.setViewport([0, 0, width / 2, height]); + document.oncontextmenu = function () { + return false; + }; + + // scene interactions + fovy = createSlider(PI / 12, PI * (11 / 12), PI / 3, PI / 48); + fovy.position(10, 10); + fovy.style("width", "80px"); + + P = new Plane(); + B = new Ball(P); +} + +function draw() { + fbo1.background(120, 125, 115); + fbo1.reset(); + fbo1.perspective(fovy.value()); + fbo1.axes(); + fbo1.grid(); + fbo1.rotate((PI / 180) * P.planeMagnitudeR, P.planeRotateV); + fbo1.strokeWeight(0.5); + + P.draw(fbo1); + B.draw(fbo1); + + // movimiento de la esfera + if (P.planeRotateV.x != 0 || P.planeRotateV.y != 0) { + B.sphereMoveVector.x = B.acceleration.x * 0.15 + B.sphereMoveVector.x; + B.sphereMoveVector.y = B.acceleration.y * 0.15 + B.sphereMoveVector.y; + + B.spherePosition.x = B.sphereMoveVector.x * 0.15 + B.spherePosition.x; + B.spherePosition.y = B.sphereMoveVector.y * 0.15 + B.spherePosition.y; + } else if (P.planeRotateV.x == 0 && P.planeRotateV.y == 0) { + B.sphereMoveVector = createVector(0, 0, 0); + B.acceleration = createVector(0, 0, 0); + } + + //Colisión + if ( + B.spherePosition.x >= B.minVertex.x && + B.spherePosition.y >= B.minVertex.y && + B.spherePosition.z - 10 >= B.minVertex.z && + B.spherePosition.x <= B.maxVertex.x && + B.spherePosition.y <= B.maxVertex.y && + B.spherePosition.z - 10 <= B.maxVertex.z + ) { + P.planeColor = "white"; + } else { + P.planeColor = "black"; + } + + beginHUD(); + image(fbo1, 0, 0); + endHUD(); +} + +function getVectorModule(vector) { + return Math.sqrt(vector.x ** 2 + vector.y ** 2 + vector.z ** 2); +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0); +} + +function mouseDragged() { + mouseCurrentV = createVector(mouseX, mouseY, 0); + let vectorSubstra = createVector( + mouseInitialV.x - mouseCurrentV.x, + mouseInitialV.y - mouseCurrentV.y, + mouseInitialV.z - mouseCurrentV.z + ); + let mod = getVectorModule(vectorSubstra); + let vectorDir = createVector( + vectorSubstra.x / mod, + vectorSubstra.y / mod, + vectorSubstra.z / mod + ); + let sine = sqrt(1 - sq(vectorDir.z)); + + B.acceleration = createVector( + -sine * vectorDir.x, + -sine * vectorDir.y, + sine * vectorDir.z + ); + + let aux = vectorDir.x; + vectorDir.x = vectorDir.y; + vectorDir.y = -aux; + + if (mod < P.planeMaxMagR) { + P.planeMagnitudeR = mod; + } + P.planeRotateV = vectorDir; + P.planeRotateV.z = 0; +} +``` + +{{< /details >}} +{{< p5-iframe srcdoc="lib3" srcdoc="lib4" sketch="/visual_computing/sketches/Acceleration.js" width="625" height="625" >}} diff --git a/content/docs/shortcodes/Taller 2/Aplicacion 3-D/LaberintoP2.md b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/LaberintoP2.md new file mode 100644 index 00000000..1abf8074 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/LaberintoP2.md @@ -0,0 +1,2045 @@ +## Parte 2 + +--- + +3. **Colisiones y Creacion:** Tomando lo creado en los ejercicios anteriores se crea un laberinto sencillo por el cual la esfera pueda desplazarse, se trata de simular fisicas como fuerzas Newtonianas para dar realismo a la aplicacion. + +{{< hint info >}} +**¿Como interactuar con el plano?** +Para cambiar la inclinacion debe deslizar el mouse presionando el boton de click derecho sobre el Canvas, la esfera puede salirse del plano y del area visible por lo cual puede usar el slider para ajustar el zoom o el boton central del mouse. +{{< /hint >}} + +{{< details "**CODIGO:** Aceleracion" close >}} + +```javascript +function Ball(P){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0) + this.sphereRadius = 7; + this.spherePosition = createVector(92.5-38*4.5,38*-1,this.sphereRadius); + + this.minVertex = createVector(-P.planeSize.x/2,-P.planeSize.y/2,0); + this.maxVertex = createVector(P.planeSize.x/2,P.planeSize.y/2,0); + + this.draw = function(fbo){ + fbo.push(); + fbo.fill("rgb(0, 0, 0)"); + fbo1.noStroke(); + fbo.translate(this.spherePosition); + fbo.sphere(this.sphereRadius) + fbo.pop() + } + this.move = function(P, acceleration, factorAcc, isAcelerate){ + + if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + if(isAcelerate){ + this.sphereMoveVector.x = (acceleration.x*factorAcc)*isAcelerate; + this.sphereMoveVector.y = (acceleration.y*factorAcc)*isAcelerate; + + this.spherePosition.x = (this.sphereMoveVector.x*factorAcc) + this.spherePosition.x + this.spherePosition.y = (this.sphereMoveVector.y*factorAcc) + this.spherePosition.y; + } + else{ + this.sphereMoveVector.x = (acceleration.x*factorAcc) + this.sphereMoveVector.x; + this.sphereMoveVector.y = (acceleration.y*factorAcc) + this.sphereMoveVector.y; + this.spherePosition.x = (this.sphereMoveVector.x*factorAcc) + this.spherePosition.x + this.spherePosition.y = (this.sphereMoveVector.y*factorAcc) + this.spherePosition.y; + } + + }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0); + } + // if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + // B.sphereMoveVector.x = (B.acceleration.x*0.1) + B.sphereMoveVector.x; + // B.sphereMoveVector.y = (B.acceleration.y*0.1) + B.sphereMoveVector.y; + + // B.spherePosition.x = (B.sphereMoveVector.x*0.1) + B.spherePosition.x + // B.spherePosition.y = (B.sphereMoveVector.y*0.1) + B.spherePosition.y; + + // }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + // B.sphereMoveVector = createVector(0,0,0); + // B.acceleration = createVector(0,0,0); + // } + } +} + + +'use strict'; + +// See: +// https://github.com/processing/p5.js/blob/main/contributor_docs/creating_libraries.md +// https://github.com/processing/p5.js/blob/main/src/core/README.md +// https://github.com/processing/p5.js/blob/main/contributor_docs/webgl_mode_architecture.md + +/** @namespace */ +var Tree = (function (ext) { + const INFO = + { + LIBRARY: 'p5.treegl', + VERSION: '0.3.0', + HOMEPAGE: 'https://github.com/VisualComputing/p5.treegl' + }; + Object.freeze(INFO); + const NONE = 0; + // Axes consts + const X = 1 << 0; + const Y = 1 << 1; + const Z = 1 << 2; + const _X = 1 << 3; + const _Y = 1 << 4; + const _Z = 1 << 5; + const LABELS = 1 << 6; + // grid style + const SOLID = 0; + const DOTS = 1 + // bullseye and picking shape + const SQUARE = 0; + const CIRCLE = 1; + // only picking shape + const PROJECTION = 2; + // Frustum consts + const NEAR = 1 << 0; + const FAR = 1 << 1; + const LEFT = 1 << 2; + const RIGHT = 1 << 3; + const BOTTOM = 1 << 4; + const TOP = 1 << 5; + const BODY = 1 << 6; + // visibility + const INVISIBLE = 0; + const VISIBLE = 1; + const SEMIVISIBLE = 2; + // spaces + const WORLD = 'WORLD'; + const EYE = 'EYE'; + const NDC = 'NDC'; + const SCREEN = 'SCREEN'; + const MODEL = 'MODEL'; + // points + const ORIGIN = [0, 0, 0]; + // vectors + const i = [1, 0, 0]; + const j = [0, 1, 0]; + const k = [0, 0, 1]; + const _i = [-1, 0, 0]; + const _j = [0, -1, 0]; + const _k = [0, 0, -1]; + // shaders + // precision + const lowp = 0; + const mediump = 1; + const highp = 2; + // in + const pmvMatrix = 1 << 0; + const pMatrix = 1 << 1; + const mvMatrix = 1 << 2; + const nMatrix = 1 << 3; + // out + const color4 = 1 << 0; + const texcoords2 = 1 << 1; + const normal3 = 1 << 2; + const position2 = 1 << 3; + const position3 = 1 << 4; + ext ??= {}; + ext.INFO = INFO; + ext.NONE = NONE; + ext.X = X; + ext.Y = Y; + ext.Z = Z; + ext._X = _X; + ext._Y = _Y; + ext._Z = _Z; + ext.LABELS = LABELS; + ext.SOLID = SOLID; + ext.DOTS = DOTS; + ext.SQUARE = SQUARE; + ext.CIRCLE = CIRCLE; + ext.PROJECTION = PROJECTION; + ext.NEAR = NEAR; + ext.FAR = FAR; + ext.LEFT = LEFT; + ext.RIGHT = RIGHT; + ext.BOTTOM = BOTTOM; + ext.TOP = TOP; + ext.BODY = BODY; + ext.INVISIBLE = INVISIBLE; + ext.VISIBLE = VISIBLE; + ext.SEMIVISIBLE = SEMIVISIBLE; + ext.WORLD = WORLD; + ext.EYE = EYE; + ext.NDC = NDC; + ext.SCREEN = SCREEN; + ext.MODEL = MODEL; + ext.ORIGIN = ORIGIN; + ext.i = i; + ext.j = j; + ext.k = k; + ext._i = _i; + ext._j = _j; + ext._k = _k; + ext.lowp = lowp; + ext.mediump = mediump; + ext.highp = highp; + ext.pmvMatrix = pmvMatrix; + ext.pMatrix = pMatrix; + ext.mvMatrix = mvMatrix; + ext.nMatrix = nMatrix; + ext.color4 = color4; + ext.texcoords2 = texcoords2; + ext.normal3 = normal3; + ext.position2 = position2; + ext.position3 = position3; + return ext; +})(Tree); + + +(function () { + console.log(Tree.INFO); + + // 1. Matrix stuff + + p5.Matrix.prototype.mult3 = function (vector) { + if (this.mat3 === undefined) { + console.error('mult3 only works with mat3'); + return; + } + return new p5.Vector(this.mat3[0] * vector.x + this.mat3[3] * vector.y + this.mat3[6] * vector.z, + this.mat3[1] * vector.x + this.mat3[4] * vector.y + this.mat3[7] * vector.z, + this.mat3[2] * vector.x + this.mat3[5] * vector.y + this.mat3[8] * vector.z); + }; + + p5.Matrix.prototype.mult4 = function (vector) { + return new p5.Vector(...this._mult4([vector.x, vector.y, vector.z, 1])); + }; + + p5.Matrix.prototype._mult4 = function (vec4) { + if (this.mat4 === undefined) { + console.error('_mult4 only works with mat4'); + return; + } + return [this.mat4[0] * vec4[0] + this.mat4[4] * vec4[1] + this.mat4[8] * vec4[2] + this.mat4[12] * vec4[3], + this.mat4[1] * vec4[0] + this.mat4[5] * vec4[1] + this.mat4[9] * vec4[2] + this.mat4[13] * vec4[3], + this.mat4[2] * vec4[0] + this.mat4[6] * vec4[1] + this.mat4[10] * vec4[2] + this.mat4[14] * vec4[3], + this.mat4[3] * vec4[0] + this.mat4[7] * vec4[1] + this.mat4[11] * vec4[2] + this.mat4[15] * vec4[3]]; + }; + + p5.prototype.tMatrix = function (matrix) { + return matrix.copy().transpose(matrix); + } + + p5.prototype.invMatrix = function (matrix) { + return matrix.copy().invert(matrix); + } + + p5.prototype.axbMatrix = function (a, b) { + return a.copy().apply(b); + } + + p5.prototype.iMatrix = function () { + return new p5.Matrix(); + } + + p5.prototype.lMatrix = function () { + return this._renderer.lMatrix(...arguments); + } + + // defaults: from: iMatrix, to: eMatrix + p5.RendererGL.prototype.lMatrix = function ( + { + from = new p5.Matrix(), + to = this.eMatrix() + } = {}) { + return to.copy().invert(to).apply(from); + } + + p5.prototype.dMatrix = function () { + return this._renderer.dMatrix(...arguments); + } + + // defaults: from: iMatrix, to: eMatrix + p5.RendererGL.prototype.dMatrix = function ( + { + from = new p5.Matrix(), + to = this.eMatrix(), + matrix = from.copy().invert(from).apply(to) + } = {}) { + // Note that this transposes mat4 into mat3 + return new p5.Matrix('mat3', [matrix.mat4[0], matrix.mat4[4], matrix.mat4[8], + matrix.mat4[1], matrix.mat4[5], matrix.mat4[9], + matrix.mat4[2], matrix.mat4[6], matrix.mat4[10]]); + } + + p5.prototype.pMatrix = function () { + return this._renderer.pMatrix(...arguments); + } + + p5.RendererGL.prototype.pMatrix = function () { + return this.uPMatrix.copy(); + } + + p5.prototype.mvMatrix = function () { + return this._renderer.mvMatrix(...arguments); + } + + // defaults when mMatrix is defined: vMatrix: this.vMatrix, mMatrix: + // otherwise it returns a copy of the current mvMatrix + p5.RendererGL.prototype.mvMatrix = function ( + { + vMatrix, + mMatrix + } = {}) { + return mMatrix ? (vMatrix ?? this.vMatrix()).copy().apply(mMatrix) : this.uMVMatrix.copy(); + } + + p5.prototype.mMatrix = function () { + return this._renderer.mMatrix(...arguments); + } + + // defaults: eMatrix: this.eMatrix, mvMatrix: this.mvMatrix + p5.RendererGL.prototype.mMatrix = function ( + { + eMatrix = this.eMatrix(), + mvMatrix = this.mvMatrix() + } = {}) { + return eMatrix.copy().apply(mvMatrix); + } + + p5.prototype.nMatrix = function () { + return this._renderer.nMatrix(...arguments); + } + + p5.RendererGL.prototype.nMatrix = function ({ + vMatrix, + mMatrix, + mvMatrix = this.mvMatrix({ mMatrix: mMatrix, vMatrix: vMatrix }) + } = {}) { + return new p5.Matrix('mat3').inverseTranspose(mvMatrix); + } + + // TODO check where to replace vMatrix for: + // this._curCamera.cameraMatrix + + p5.prototype.vMatrix = function () { + return this._renderer.vMatrix(...arguments); + } + + p5.RendererGL.prototype.vMatrix = function () { + return this._curCamera.vMatrix(); + } + + p5.Camera.prototype.vMatrix = function () { + return this.cameraMatrix.copy(); + } + + p5.prototype.eMatrix = function () { + return this._renderer.eMatrix(...arguments); + } + + p5.RendererGL.prototype.eMatrix = function () { + return this._curCamera.eMatrix(); + } + + p5.Camera.prototype.eMatrix = function () { + return this.cameraMatrix.copy().invert(this.cameraMatrix); + } + + p5.prototype.pmvMatrix = function () { + return this._renderer.pmvMatrix(...arguments); + } + + p5.RendererGL.prototype.pmvMatrix = function ( + { + pMatrix = this.uPMatrix, + vMatrix, + mMatrix, + mvMatrix = this.mvMatrix({ mMatrix: mMatrix, vMatrix: vMatrix }) + } = {}) { + return pMatrix.copy().apply(mvMatrix); + } + + p5.prototype.pvMatrix = function () { + return this._renderer.pvMatrix(...arguments); + } + + // defaults: pMatrix: this.pMatrix, vMatrix: this.vMatrix + p5.RendererGL.prototype.pvMatrix = function ( + { + pMatrix = this.uPMatrix, + vMatrix = this._curCamera.cameraMatrix + } = {}) { + return pMatrix.copy().apply(vMatrix); + } + + p5.prototype.pvInvMatrix = function () { + return this._renderer.pvInvMatrix(...arguments); + } + + p5.RendererGL.prototype.pvInvMatrix = function ( + { + pMatrix, + vMatrix, + pvMatrix + } = {}) { + let matrix = pvMatrix ? pvMatrix.copy() : this.pvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix }); + return matrix.invert(matrix); + } + + p5.prototype._isOrtho = function () { + return this._renderer._isOrtho(...arguments); + } + + p5.RendererGL.prototype._isOrtho = function () { + return this.uPMatrix._isOrtho(); + } + + p5.Matrix.prototype._isOrtho = function () { + return this.mat4[15] != 0; + } + + p5.prototype.nPlane = function () { + return this._renderer.nPlane(...arguments); + } + + p5.RendererGL.prototype.nPlane = function () { + return this.uPMatrix.nPlane(); + } + + p5.Matrix.prototype.nPlane = function () { + return this.mat4[15] == 0 ? this.mat4[14] / (this.mat4[10] - 1) : + (1 + this.mat4[14]) / this.mat4[10]; + } + + p5.prototype.fPlane = function () { + return this._renderer.fPlane(...arguments); + } + + p5.RendererGL.prototype.fPlane = function () { + return this.uPMatrix.fPlane(); + } + + p5.Matrix.prototype.fPlane = function () { + return this.mat4[15] == 0 ? this.mat4[14] / (1 + this.mat4[10]) : + (this.mat4[14] - 1) / this.mat4[10]; + } + + p5.prototype.lPlane = function () { + return this._renderer.lPlane(...arguments); + } + + p5.RendererGL.prototype.lPlane = function () { + return this.uPMatrix.lPlane(); + } + + p5.Matrix.prototype.lPlane = function () { + return this.mat4[15] == 1 ? -(1 + this.mat4[12]) / this.mat4[0] : + this.nPlane() * (this.mat4[8] - 1) / this.mat4[0]; + } + + p5.prototype.rPlane = function () { + return this._renderer.rPlane(...arguments); + } + + p5.RendererGL.prototype.rPlane = function () { + return this.uPMatrix.rPlane(); + } + + p5.Matrix.prototype.rPlane = function () { + return this.mat4[15] == 1 ? (1 - this.mat4[12]) / this.mat4[0] : + this.nPlane() * (1 + this.mat4[8]) / this.mat4[0]; + } + + p5.prototype.tPlane = function () { + return this._renderer.tPlane(...arguments); + } + + p5.RendererGL.prototype.tPlane = function () { + return this.uPMatrix.tPlane(); + } + + p5.Matrix.prototype.tPlane = function () { + // note that inverted values are returned if the projection + // matrix was set with @function frustum. + return this.mat4[15] == 1 ? (this.mat4[13] - 1) / this.mat4[5] : + this.nPlane() * (this.mat4[9] - 1) / this.mat4[5]; + } + + p5.prototype.bPlane = function () { + return this._renderer.bPlane(...arguments); + } + + p5.RendererGL.prototype.bPlane = function () { + return this.uPMatrix.bPlane(); + } + + p5.Matrix.prototype.bPlane = function () { + // note that inverted values are returned if the projection + // matrix was set with @function frustum. + return this.mat4[15] == 1 ? (1 + this.mat4[13]) / this.mat4[5] : + this.nPlane() * (1 + this.mat4[9]) / this.mat4[5]; + } + + p5.prototype.fov = function () { + return this._renderer.fov(...arguments); + } + + p5.RendererGL.prototype.fov = function () { + return this.uPMatrix.fov(); + } + + p5.Matrix.prototype.fov = function () { + if (this.mat4[15] != 0) { + console.error('fov only works for a perspective projection'); + return; + } + return Math.abs(2 * Math.atan(1 / this.mat4[5])); + } + + p5.prototype.hfov = function () { + return this._renderer.hfov(...arguments); + } + + p5.RendererGL.prototype.hfov = function () { + return this.uPMatrix.hfov(); + } + + p5.Matrix.prototype.hfov = function () { + if (this.mat4[15] != 0) { + console.error('hfov only works for a perspective projection'); + return; + } + return Math.abs(2 * Math.atan(1 / this.mat4[0])); + } + + // 2. Space transformations + + p5.prototype.beginHUD = function () { + if (this._renderer instanceof p5.RendererGL) { + this._renderer.beginHUD(...arguments); + } + } + + p5.RendererGL.prototype.beginHUD = function () { + this.mv = this.mvMatrix(); + this.p = this.pMatrix(); + this._rendererState = this.push(); + let gl = this.drawingContext; + gl.flush(); + gl.disable(gl.DEPTH_TEST); + this.resetMatrix(); + let z = Number.MAX_VALUE; + this._curCamera.ortho(0, this.width, -this.height, 0, -z, z); + } + + p5.prototype.endHUD = function () { + if (this._renderer instanceof p5.RendererGL) { + this._renderer.endHUD(...arguments); + } + } + + p5.RendererGL.prototype.endHUD = function () { + let gl = this.drawingContext; + gl.flush(); + gl.enable(gl.DEPTH_TEST); + this.pop(this._rendererState); + this.uPMatrix.set(this.p); + this.uMVMatrix.set(this.mv); + } + + // 2.1 Points + + // NDC stuff needs testing + + p5.prototype._map = function () { + return this._renderer._map(...arguments); + } + + p5.RendererGL.prototype._map = function (n, start1, stop1, start2, stop2) { + return (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; + } + + p5.prototype.treeLocation = function () { + return this._renderer.treeLocation(...arguments); + } + + /** + * Converts locations (i.e., points) from one space into another. + * @param {p5.Vector} vector location to be converted. + * @param {p5.Matrix|String} from source space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix|String} to target space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix} pMatrix projection matrix. + * @param {p5.Matrix} vMatrix view matrix. + * @param {p5.Matrix} pvMatrix projection times view matrix. + * @param {p5.Matrix} pvInvMatrix (projection times view matrix)^-1. + */ + p5.RendererGL.prototype.treeLocation = function () { + return arguments.length === 1 & arguments[0] instanceof Object ? this._treeLocation(Tree.ORIGIN, arguments[0]) : + this._treeLocation(...arguments); + } + + p5.prototype._treeLocation = function () { + return this._renderer._treeLocation(...arguments); + } + + p5.RendererGL.prototype._treeLocation = function (vector = Tree.ORIGIN, + { + from = Tree.EYE, + to = Tree.WORLD, + pMatrix, + vMatrix, + eMatrix, + pvMatrix, + pvInvMatrix + } = {}) { + if (Array.isArray(vector)) { + vector = new p5.Vector(vector[0] ?? 0, vector[1] ?? 0, vector[2] ?? 0); + } + if (from == Tree.MODEL) { + from = this.mMatrix({ eMatrix: eMatrix }); + } + if (to == Tree.MODEL) { + to = this.mMatrix({ eMatrix: eMatrix }); + } + if ((from == Tree.WORLD) && (to == Tree.SCREEN)) { + return this._screenLocation({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + if ((from == Tree.SCREEN) && (to == Tree.WORLD)) { + return this._location({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix }); + } + if (from == Tree.SCREEN && to == Tree.NDC) { + return this._screenToNDCLocation(vector); + } + if (from == Tree.NDC && to == Tree.SCREEN) { + return this._ndcToScreenLocation(vector); + } + if (from == Tree.WORLD && to == Tree.NDC) { + return this._screenToNDCLocation(this._screenLocation({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix })); + } + if (from == Tree.NDC && to == Tree.WORLD) { + return this._location({ vector: this._ndcToScreenLocation(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix }); + } + if (from == Tree.NDC && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(this._location({ vector: this._ndcToScreenLocation(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix })); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.NDC) { + return this._screenToNDCLocation(this._screenLocation({ vector: (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix })); + } + if (from == Tree.WORLD && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(vector); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.WORLD) { + return (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector); + } + if (from instanceof p5.Matrix && to instanceof p5.Matrix) { + return this.lMatrix({ from: from, to: to }).mult4(vector); + } + if (from == Tree.SCREEN && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(this._location({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix })); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.SCREEN) { + return this._screenLocation({ vector: (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + console.error('couldn\'t parse your treeLocation query!'); + return vector; + } + + p5.RendererGL.prototype._ndcToScreenLocation = function (vector) { + return new p5.Vector(this._map(vector.x, -1, 1, 0, this.width), + this._map(vector.y, -1, 1, 0, this.height), + this._map(vector.z, -1, 1, 0, 1)); + } + + p5.RendererGL.prototype._screenToNDCLocation = function (vector) { + return new p5.Vector(this._map(vector.x, 0, this.width, -1, 1), + this._map(vector.y, 0, this.height, -1, 1), + this._map(vector.z, 0, 1, -1, 1)); + } + + p5.RendererGL.prototype._screenLocation = function ( + { + vector = new p5.Vector(0, 0, 0.5), + pMatrix, + vMatrix, + pvMatrix = this.pvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix }) + } = {}) { + let target = pvMatrix._mult4([vector.x, vector.y, vector.z, 1]); + if (target[3] == 0) { + console.error('screenLocation broken. Check your pvMatrix!'); + return; + } + let viewport = [0, this.height, this.width, -this.height]; + // ndc, but y is inverted + target[0] /= target[3]; + target[1] /= target[3]; + target[2] /= target[3]; + // Map x, y and z to range 0-1 + target[0] = target[0] * 0.5 + 0.5; + target[1] = target[1] * 0.5 + 0.5; + target[2] = target[2] * 0.5 + 0.5; + // Map x,y to viewport + target[0] = target[0] * viewport[2] + viewport[0]; + target[1] = target[1] * viewport[3] + viewport[1]; + return new p5.Vector(target[0], target[1], target[2]); + } + + p5.RendererGL.prototype._location = function ( + { + vector = new p5.Vector(this.width / 2, this.height / 2, 0.5), + pMatrix, + vMatrix, + pvMatrix, + pvInvMatrix = this.pvInvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }) + } = {}) { + let viewport = [0, this.height, this.width, -this.height]; + let source = [vector.x, vector.y, vector.z, 1]; + // Map x and y from window coordinates + source[0] = (source[0] - viewport[0]) / viewport[2]; + source[1] = (source[1] - viewport[1]) / viewport[3]; + // Map to range -1 to 1 + source[0] = source[0] * 2 - 1; + source[1] = source[1] * 2 - 1; + source[2] = source[2] * 2 - 1; + let target = pvInvMatrix._mult4(source); + if (target[3] == 0) { + console.error('location broken. Check your pvInvMatrix!'); + return; + } + target[0] /= target[3]; + target[1] /= target[3]; + target[2] /= target[3]; + return new p5.Vector(target[0], target[1], target[2]); + } + + // 2.2. Vectors + + // NDC stuff needs testing + + p5.prototype.treeDisplacement = function () { + return this._renderer.treeDisplacement(...arguments); + } + + /** + * Converts displacements (i.e., vectors) from one space into another. + * @param {p5.Vector} vector location to be converted. + * @param {p5.Matrix|String} from source space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix|String} to target space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix} pMatrix projection matrix. + * @param {p5.Matrix} vMatrix view matrix. + * @param {p5.Matrix} pvMatrix projection times view matrix. + * @param {p5.Matrix} pvInvMatrix (projection times view matrix)^-1. + */ + p5.RendererGL.prototype.treeDisplacement = function () { + return arguments.length === 1 & arguments[0] instanceof Object ? this._treeDisplacement(Tree._k, arguments[0]) : + this._treeDisplacement(...arguments); + } + + p5.prototype._treeDisplacement = function () { + return this._renderer._treeDisplacement(...arguments); + } + + p5.RendererGL.prototype._treeDisplacement = function (vector = Tree._k, + { + from = Tree.EYE, + to = Tree.WORLD, + vMatrix, + eMatrix, + pMatrix + } = {}) { + if (Array.isArray(vector)) { + vector = new p5.Vector(vector[0] ?? 0, vector[1] ?? 0, vector[2] ?? 0); + } + if (from == Tree.MODEL) { + from = this.mMatrix({ eMatrix: eMatrix }); + } + if (to == Tree.MODEL) { + to = this.mMatrix({ eMatrix: eMatrix }); + } + if ((from == Tree.WORLD) && (to == Tree.SCREEN)) { + return this._worldToScreenDisplacement(vector, pMatrix); + } + if ((from == Tree.SCREEN) && (to == Tree.WORLD)) { + return this._screenToWorldDisplacement(vector, pMatrix); + } + if (from == Tree.SCREEN && to == Tree.NDC) { + return this._screenToNDCDisplacement(vector); + } + if (from == Tree.NDC && to == Tree.SCREEN) { + return this._ndcToScreenDisplacement(vector); + } + if (from == Tree.WORLD && to == Tree.NDC) { + return this._screenToNDCDisplacement(this._worldToScreenDisplacement(vector, pMatrix)); + } + if (from == Tree.NDC && to == Tree.WORLD) { + return this._screenToWorldDisplacement(this._ndcToScreenDisplacement(vector), pMatrix); + } + if (from == Tree.NDC && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(this._screenToWorldDisplacement(this._ndcToScreenDisplacement(vector), pMatrix)); + } + if (from == Tree.EYE && to == Tree.NDC) { + return this._screenToNDCDisplacement(this._worldToScreenDisplacement(this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector), pMatrix)); + } + if (from == Tree.SCREEN && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: to }).mult3(this._screenToWorldDisplacement(vector, pMatrix)); + } + if (from instanceof p5.Matrix && to == Tree.SCREEN) { + return this._worldToScreenDisplacement(this.dMatrix({ matrix: from.copy().invert(from) }).mult3(vector), pMatrix); + } + if (from instanceof p5.Matrix && to instanceof p5.Matrix) { + return this.dMatrix({ from: from, to: to }).mult3(vector); + } + // all cases below kept for efficiency but they all may + // be simply expressed in terms of the previous case, by: + // Tree.EYE -> eMatrix() + // Tree.WORLD -> iMatrix() + if (from == Tree.EYE && to == Tree.WORLD) { + return this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector); + } + if (from == Tree.WORLD && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(vector); + } + if (from == Tree.EYE && to == Tree.SCREEN) { + return this._worldToScreenDisplacement(this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector), pMatrix); + } + if (from == Tree.SCREEN && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(this._screenToWorldDisplacement(vector, pMatrix)); + } + if (from == Tree.EYE && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: (vMatrix ?? this.vMatrix()).apply(to) }).mult3(vector); + } + if (from instanceof p5.Matrix && to == Tree.EYE) { + return this.dMatrix({ matrix: from.copy().invert(from).apply(eMatrix ?? this.eMatrix()) }).mult3(vector); + } + if (from == Tree.WORLD && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: to }).mult3(vector); + } + if (from instanceof p5.Matrix && to == Tree.WORLD) { + return this.dMatrix({ matrix: from.copy().invert(from) }).mult3(vector); + } + console.error('couldn\'t parse your treeDisplacement query!'); + return vector; + } + + p5.RendererGL.prototype._worldToScreenDisplacement = function (vector, pMatrix = this.uPMatrix) { + let eyeVector = this._treeDisplacement(vector, { from: Tree.WORLD, to: Tree.EYE }); + let dx = eyeVector.x; + let dy = eyeVector.y; + let perspective = pMatrix.mat4[15] == 0; + if (perspective) { + let position = new p5.Vector(); + let k = Math.abs(this._treeLocation(position, { from: Tree.WORLD, to: Tree.EYE }).z * Math.tan(this.fov(pMatrix) / 2)); + dx /= 2 * k / this.height; + dy /= 2 * k / this.height; + } + let dz = eyeVector.z; + // sign is inverted + dz /= (pMatrix.nPlane() - pMatrix.fPlane()) / (perspective ? Math.tan(this.fov(pMatrix) / 2) : Math.abs(pMatrix.rPlane() - pMatrix.lPlane()) / this.width); + return new p5.Vector(dx, dy, dz); + } + + p5.RendererGL.prototype._screenToWorldDisplacement = function (vector, pMatrix = this.uPMatrix) { + let dx = vector.x; + let dy = vector.y; + // Scale to fit the screen relative vector displacement + let perspective = pMatrix.mat4[15] == 0; + if (perspective) { + let position = new p5.Vector(); + let k = Math.abs(this._treeLocation(position, { from: Tree.WORLD, to: Tree.EYE }).z * Math.tan(this.fov(pMatrix) / 2)); + dx *= 2 * k / this.height; + dy *= 2 * k / this.height; + } + let dz = vector.z; + dz *= (pMatrix.nPlane() - pMatrix.fPlane()) / (perspective ? Math.tan(this.fov(pMatrix) / 2) : Math.abs(pMatrix.rPlane() - pMatrix.lPlane()) / this.width); + let eyeVector = new p5.Vector(dx, dy, dz); + return this._treeDisplacement(eyeVector, { from: Tree.EYE, to: Tree.WORLD }); + } + + p5.RendererGL.prototype._ndcToScreenDisplacement = function (vector) { + return new p5.Vector(this.width * vector.x / 2, this.height * vector.y / 2, vector.z / 2); + } + + p5.RendererGL.prototype._screenToNDCDisplacement = function (vector) { + return new p5.Vector(2 * vector.x / this.width, 2 * vector.y / this.height, 2 * vector.z); + } + + // 3. Shader utilities + + p5.prototype.readShader = function (fragFilename, { + precision, + matrices, + varyings + } = {}) { + let shader = new p5.Shader(); + this._coupledWith = fragFilename.substring(fragFilename.lastIndexOf('/') + 1); + shader._vertSrc = this.parseVertexShader({ precision: precision, matrices: matrices, varyings: varyings, _specs: false }); + this._coupledWith = undefined; + this.loadStrings( + fragFilename, + result => { + shader._fragSrc = result.join('\n') + } + ); + return shader; + } + + p5.prototype.makeShader = function (fragSrc, { + precision, + matrices, + varyings + } = {}) { + let shader = new p5.Shader(); + this._coupledWith = 'the fragment shader provided as param in makeShader()'; + shader._vertSrc = this.parseVertexShader({ precision: precision, matrices: matrices, varyings: varyings, _specs: false }); + this._coupledWith = undefined; + shader._fragSrc = fragSrc; + return shader; + } + + p5.prototype.parseVertexShader = function ({ + precision = Tree.mediump, + matrices = Tree.pmvMatrix, + varyings = Tree.color4 | Tree.texcoords2, + _specs = true + } = {}) { + let floatPrecision = `precision ${precision === Tree.highp ? 'highp' : `${precision === Tree.mediump ? 'mediump' : 'lowp'}`} float;` + let color4 = ~(varyings | ~Tree.color4) === 0; + let texcoords2 = ~(varyings | ~Tree.texcoords2) === 0; + let normal3 = ~(varyings | ~Tree.normal3) === 0; + let position2 = ~(varyings | ~Tree.position2) === 0; + let position3 = ~(varyings | ~Tree.position3) === 0; + let pmv = ~(matrices | ~Tree.pmvMatrix) === 0; + let p = ~(matrices | ~Tree.pMatrix) === 0; + let mv = ~(matrices | ~Tree.mvMatrix) === 0; + let n = (~(matrices | ~Tree.nMatrix) === 0) || normal3; + const target = `gl_Position =${pmv ? ' uModelViewProjectionMatrix * ' : `${p && mv ? ' uProjectionMatrix * uModelViewMatrix *' : ''} `}vec4(aPosition, 1.0)`; + let vertexShader = ` +${floatPrecision} +attribute vec3 aPosition; +${color4 ? 'attribute vec4 aVertexColor;' : ''} +${texcoords2 ? 'attribute vec2 aTexCoord;' : ''} +${normal3 ? 'attribute vec3 aNormal;' : ''} +${pmv ? 'uniform mat4 uModelViewProjectionMatrix;' : ''} +${p ? 'uniform mat4 uProjectionMatrix;' : ''} +${mv ? 'uniform mat4 uModelViewMatrix;' : ''} +${n ? 'uniform mat3 uNormalMatrix;' : ''} +${color4 ? 'varying vec4 color4;' : ''} +${texcoords2 ? 'varying vec2 texcoords2;' : ''} +${normal3 ? 'varying vec3 normal3;' : ''} +${position2 ? 'varying vec2 position2;' : ''} +${position3 ? 'varying vec3 position3;' : ''} +void main() { + ${color4 ? 'color4 = aVertexColor;' : ''} + ${texcoords2 ? 'texcoords2 = aTexCoord;' : ''} + ${normal3 ? 'normal3 = normalize(uNormalMatrix * aNormal);' : ''} + ${position2 ? 'position2 = vec4(aPosition, 1.0).xy;' : ''} + ${position3 ? 'position3 = vec4(aPosition, 1.0).xyz;' : ''} + ${target}; +} +`; + let advice = ` +/* +${this._coupledWith ? 'Vertex shader code to be coupled with ' + this._coupledWith : ''} +Generated with treegl version ${Tree.INFO.VERSION} +${_specs ? ` +Feel free to copy, paste, edit and save it. +Refer to createShader (https://p5js.org/reference/#/p5/createShader), +loadShader (https://p5js.org/reference/#/p5/loadShader), readShader +and makeShader (https://github.com/VisualComputing/p5.treegl#handling), +for details.` : ''} +*/ +`; + let result = advice + vertexShader; + result = result.split(/\r?\n/) + .filter(line => line.trim() !== '') + .join("\n"); + console.log(result); + return result; + } + + p5.prototype.emitMousePosition = function (shader, uniform = 'u_mouse') { + shader.setUniform(uniform, [this.mouseX * pixelDensity(), (this.height - this.mouseY) * pixelDensity()]); + } + + p5.prototype.emitPointerPosition = function () { + this._renderer.emitPointerPosition(...arguments); + } + + p5.RendererGL.prototype.emitPointerPosition = function (shader, pointerX, pointerY, uniform = 'u_pointer') { + shader.setUniform(uniform, [pointerX * pixelDensity(), (this.height - pointerY) * pixelDensity()]); + } + + p5.prototype.emitResolution = function () { + this._renderer.emitResolution(...arguments); + } + + p5.RendererGL.prototype.emitResolution = function (shader, uniform = 'u_resolution') { + shader.setUniform(uniform, [this.width * pixelDensity(), this.height * pixelDensity()]); + } + + p5.prototype.emitTexOffset = function (shader, image, uniform = 'u_texoffset') { + shader.setUniform(uniform, [1 / image.width, 1 / image.height]); + } + + // 4. Utility functions + + p5.prototype.pixelRatio = function () { + return this._renderer.pixelRatio(...arguments); + } + + /** + * Returns the world to pixel ratio units at given world location. + * A line of n * pixelRatio(location) world units will be projected + * with a length of n pixels on screen. + * @param {p5.Vector | Array} location world location reference + */ + p5.RendererGL.prototype.pixelRatio = function (location) { + return this._isOrtho() ? Math.abs(this.tPlane() - this.bPlane()) / this.height : + 2 * Math.abs((this._treeLocation(location, { from: Tree.WORLD, to: Tree.EYE, vMatrix: this._curCamera.cameraMatrix })).z) * Math.tan(this.fov() / 2) / this.height; + } + + p5.prototype.visibility = function () { + return this._renderer.visibility(...arguments); + } + + /** + * Returns object visibility (i.e, lies within the eye bounds) + * either Tree.VISIBLE, Tree.INVISIBLE, or Tree.SEMIVISIBLE. + * Object may be either a point, a sphere or an axis-aligned box. + * @param {p5.Vector | Array} corner1 box corner1, use it with corner2. + * @param {p5.Vector | Array} corner2 box corner2, use it with corner1. + * @param {p5.Vector | Array} center sphere (or point) center. + * @param {Number} radius sphere radius. + * @param {Array} bounds frustum equations 6x4 matrix. + */ + p5.RendererGL.prototype.visibility = function ({ + corner1, + corner2, + center, + radius, + bounds = this.bounds() + } = {}) { + return center ? radius ? this._ballVisibility(center, radius, bounds) : this._pointVisibility(center, bounds) + : corner1 && corner2 ? this._boxVisibility(corner1, corner2, bounds) : console.error('couldn\'t parse your visibility query!'); + } + + p5.RendererGL.prototype._pointVisibility = function (point, bounds = this.bounds()) { + for (const key in bounds) { + let d = this.distanceToBound(point, key, bounds); + if (d > 0) { + return Tree.INVISIBLE; + } + if (d === 0) { + return Tree.SEMIVISIBLE; + } + } + return Tree.VISIBLE; + } + + p5.RendererGL.prototype._ballVisibility = function (center, radius, bounds = this.bounds()) { + let allInForAllPlanes = true; + for (const key in bounds) { + let d = this.distanceToBound(center, key, bounds); + if (d > radius) { + return Tree.INVISIBLE; + } + if ((d > 0) || (-d < radius)) { + allInForAllPlanes = false; + } + } + if (allInForAllPlanes) { + return Tree.VISIBLE; + } + return Tree.SEMIVISIBLE; + } + + p5.RendererGL.prototype._boxVisibility = function (corner1, corner2, bounds = this.bounds()) { + if (Array.isArray(corner1)) { + corner1 = new p5.Vector(corner1[0] ?? 0, corner1[1] ?? 0, corner1[2] ?? 0); + } + if (Array.isArray(corner2)) { + corner2 = new p5.Vector(corner2[0] ?? 0, corner2[1] ?? 0, corner2[2] ?? 0); + } + let allInForAllPlanes = true; + for (const key in bounds) { + let allOut = true; + for (let c = 0; c < 8; ++c) { + let pos = new p5.Vector(((c & 4) != 0) ? corner1.x : corner2.x, ((c & 2) != 0) ? corner1.y : corner2.y, + ((c & 1) != 0) ? corner1.z : corner2.z); + if (this.distanceToBound(pos, key, bounds) > 0) { + allInForAllPlanes = false; + } + else { + allOut = false; + } + } + // The eight points are on the outside side of this plane + if (allOut) { + return Tree.INVISIBLE; + } + } + if (allInForAllPlanes) { + return Tree.VISIBLE; + } + // Too conservative, but tangent cases are too expensive to detect + return Tree.SEMIVISIBLE; + } + + p5.prototype.bounds = function () { + return this._renderer.bounds(...arguments); + } + + /** + * Returns the 6 plane equations of the eye frustum bounds defined + * in the world coordinate system encoded as an object literal + * having 'Tree.LEFT' (left plane), 'Tree.RIGHT' (right plane), + * 'Tree.NEAR' (near plane), 'Tree.FAR' (far plane) 'Tree.TOP' + * (top plane) and 'Tree.BOTTOM' (bottom plane) keys. + * Each key holds a plane equation of the form: + * a*x + b*y + c*z + d = 0, where a, b, c and d are the 4 + * keys of each object literal. + */ + p5.RendererGL.prototype.bounds = function () { + let normals = Array(6); + let distances = Array(6); + // Computed once and for all + // TODO experimental: no need to normalize + let pos = this._treeLocation([0, 0, 0], { from: Tree.EYE, to: Tree.WORLD }); + let viewDir = this._treeDisplacement([0, 0, -1], { from: Tree.EYE, to: Tree.WORLD }); + // same as: let viewDir = this.treeDisplacement(); + let up = this._treeDisplacement([0, 1, 0], { from: Tree.EYE, to: Tree.WORLD }); + let right = this._treeDisplacement([1, 0, 0], { from: Tree.EYE, to: Tree.WORLD }); + let posViewDir = p5.Vector.dot(pos, viewDir); + if (this._isOrtho()) { + normals[0] = p5.Vector.mult(right, -1); + normals[1] = right; + normals[4] = up; + normals[5] = p5.Vector.mult(up, -1); + let wh0 = Math.abs(this.rPlane() - this.lPlane()) / 2; + let wh1 = Math.abs(this.tPlane() - this.bPlane()) / 2; + distances[0] = p5.Vector.dot(p5.Vector.sub(pos, p5.Vector.mult(right, wh0)), normals[0]); + distances[1] = p5.Vector.dot(p5.Vector.add(pos, p5.Vector.mult(right, wh0)), normals[1]); + distances[4] = p5.Vector.dot(p5.Vector.add(pos, p5.Vector.mult(up, wh1)), normals[4]); + distances[5] = p5.Vector.dot(p5.Vector.sub(pos, p5.Vector.mult(up, wh1)), normals[5]); + } + else { + let hhfov = this.hfov() / 2; + let chhfov = Math.cos(hhfov); + let shhfov = Math.sin(hhfov); + normals[0] = p5.Vector.mult(viewDir, -shhfov); + normals[1] = p5.Vector.add(normals[0], p5.Vector.mult(right, chhfov)); + normals[0] = p5.Vector.add(normals[0], p5.Vector.mult(right, -chhfov)); + normals[2] = p5.Vector.mult(viewDir, -1); + normals[3] = viewDir; + let hfov = this.fov() / 2; + let chfov = Math.cos(hfov); + let shfov = Math.sin(hfov); + normals[4] = p5.Vector.mult(viewDir, -shfov); + normals[5] = p5.Vector.add(normals[4], p5.Vector.mult(up, -chfov)); + normals[4] = p5.Vector.add(normals[4], p5.Vector.mult(up, chfov)); + for (let i = 0; i < 2; ++i) { + distances[i] = p5.Vector.dot(pos, normals[i]); + } + for (let j = 4; j < 6; ++j) { + distances[j] = p5.Vector.dot(pos, normals[j]); + } + // Natural equations are: + // dist[0,1,4,5] = pos * normal[0,1,4,5]; + // dist[2] = (pos + zNear() * viewDir) * normal[2]; + // dist[3] = (pos + zFar() * viewDir) * normal[3]; + // 2 times less computations using expanded/merged equations. Dir vectors + // are normalized. + let posRightCosHH = chhfov * p5.Vector.dot(pos, right); + distances[0] = -shhfov * posViewDir; + distances[1] = distances[0] + posRightCosHH; + distances[0] = distances[0] - posRightCosHH; + let posUpCosH = chfov * p5.Vector.dot(pos, up); + distances[4] = -shfov * posViewDir; + distances[5] = distances[4] - posUpCosH; + distances[4] = distances[4] + posUpCosH; + } + // Front and far planes are identical for both camera types. + normals[2] = p5.Vector.mult(viewDir, -1); + normals[3] = viewDir; + distances[2] = -posViewDir - this.nPlane(); + distances[3] = posViewDir + this.fPlane(); + let bounds = {}; + bounds[Tree.LEFT] = { a: normals[0].x, b: normals[0].y, c: normals[0].z, d: distances[0] }; + bounds[Tree.RIGHT] = { a: normals[1].x, b: normals[1].y, c: normals[1].z, d: distances[1] }; + bounds[Tree.NEAR] = { a: normals[2].x, b: normals[2].y, c: normals[2].z, d: distances[2] }; + bounds[Tree.FAR] = { a: normals[3].x, b: normals[3].y, c: normals[3].z, d: distances[3] }; + bounds[Tree.TOP] = { a: normals[4].x, b: normals[4].y, c: normals[4].z, d: distances[4] }; + bounds[Tree.BOTTOM] = { a: normals[5].x, b: normals[5].y, c: normals[5].z, d: distances[5] }; + return bounds; + } + + p5.prototype.distanceToBound = function () { + return this._renderer.distanceToBound(...arguments); + } + + /** + * Returns the signed distance between location and the frustum plane defined + * by bounds and key which may be either Tree.LEFT, Tree.RIGHT, Tree.BOTTOM, + * Tree.TOP, Tree.NEAR or Tree.FAR. The distance is negative if the point lies + * in the planes's bounding halfspace, and positive otherwise. + */ + p5.RendererGL.prototype.distanceToBound = function (location, key, bounds = this.bounds()) { + if (Array.isArray(location)) { + location = new p5.Vector(location[0] ?? 0, location[1] ?? 0, location[2] ?? 0); + } + return p5.Vector.dot(location, new p5.Vector(bounds[key].a, bounds[key].b, bounds[key].c)) - bounds[key].d; + } + + p5.prototype.mousePicking = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + return this.pointerPicking(this.mouseX, this.mouseY, { mMatrix: mMatrix, x: x, y: y, size: size, shape: shape, eMatrix: eMatrix, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + + p5.prototype.pointerPicking = function () { + return this._renderer.pointerPicking(...arguments); + } + + /** + * Returns true if pointer is close enough to pointerX, pointerY screen location. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size bullseye diameter. Default is 50. + * @param {Number} shape either Tree.CIRCLE, Tree.SQUARE or Tree.PROJECTION. Default is Tree.CIRCLE. + */ + p5.RendererGL.prototype.pointerPicking = function (pointerX, pointerY, { + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + // TODO implement webgl picking here using a switch statement: Tree.CIRCLE, Tree.SQUARE, Tree.PROJECTION + let radius = size / 2; + return shape === Tree.CIRCLE ? + Math.sqrt(Math.pow((x - pointerX), 2.0) + Math.pow((y - pointerY), 2.0)) < radius : + ((Math.abs(pointerX - x) < radius) && (Math.abs(pointerY - y) < radius)); + } + + // 5. Drawing stuff + + p5.prototype.axes = function () { + this._renderer.axes(...arguments); + }; + + /** + * Draws axes. + * @param {Number} size size in world units. + * @param {Number} bits bitwise mask that may be composed of Tree.X, Tree._X, + * Tree.Y, Tree._Y, Tree.Z, Tree._Z and Tree.LABELS bits. + */ + p5.RendererGL.prototype.axes = function ({ size = 100, bits = Tree.LABELS | Tree.X | Tree.Y | Tree.Z } = {}) { + this._rendererState = this.push(); + if (~(bits | ~Tree.LABELS) === 0) { + const charWidth = size / 40.0; + const charHeight = size / 30.0; + const charShift = 1.04 * size; + // The X + this.stroke(200, 0, 0); + this.line(charShift, charWidth, -charHeight, charShift, -charWidth, charHeight); + this.line(charShift, -charWidth, -charHeight, charShift, charWidth, charHeight); + // The Y + this.stroke(0, 200, 0); + this.line(charWidth, charShift, charHeight, 0.0, charShift, 0.0); + this.line(0.0, charShift, 0.0, -charWidth, charShift, charHeight); + this.line(-charWidth, charShift, charHeight, 0.0, charShift, 0.0); + this.line(0.0, charShift, 0.0, 0.0, charShift, -charHeight); + // The Z + this.stroke(0, 100, 200); + this.line(-charWidth, -charHeight, charShift, charWidth, -charHeight, charShift); + this.line(charWidth, -charHeight, charShift, -charWidth, charHeight, charShift); + this.line(-charWidth, charHeight, charShift, charWidth, charHeight, charShift); + } + // X Axis + this.stroke(200, 0, 0); + if (~(bits | ~Tree.X) === 0) { + this.line(0, 0, 0, size, 0, 0); + } + if (~(bits | ~Tree._X) === 0) { + this.line(0, 0, 0, -size, 0, 0); + } + // Y Axis + this.stroke(0, 200, 0); + if (~(bits | ~Tree.Y) === 0) { + this.line(0, 0, 0, 0, size, 0); + } + if (~(bits | ~Tree._Y) === 0) { + this.line(0, 0, 0, 0, -size, 0); + } + // Z Axis + this.stroke(0, 100, 200); + if (~(bits | ~Tree.Z) === 0) { + this.line(0, 0, 0, 0, 0, size); + } + if (~(bits | ~Tree._Z) === 0) { + this.line(0, 0, 0, 0, 0, -size); + } + this.pop(this._rendererState); + }; + + p5.prototype.grid = function () { + this._renderer.grid(...arguments); + }; + + /** + * Draws grid + * @param {Number} size grid size in world units. Default is 100. + * @param {Number} subdivisions number of grid subdivisions. Default is 10. + * @param {Number} style either Tree.DOTS or Tree.SOLID. Default is Tree.DOTS. + */ + p5.RendererGL.prototype.grid = function ({ size = 100, subdivisions = 10, style = Tree.DOTS } = {}) { + this._rendererState = this.push(); + if (style === Tree.DOTS) { + let weight = this.curStrokeWeight; + // other useful as well: this.curStrokeColor this.curFillColor + let posi = 0; + let posj = 0; + this.strokeWeight(weight * 2); + this.beginShape(0x0000); + for (let i = 0; i <= subdivisions; ++i) { + posi = size * (2.0 * i / subdivisions - 1.0); + for (let j = 0; j <= subdivisions; ++j) { + posj = size * (2.0 * j / subdivisions - 1.0); + this.vertex(posi, posj, 0); + } + } + this.endShape(); + const internalSub = 5; + const subSubdivisions = subdivisions * internalSub; + this.strokeWeight(weight); + this.beginShape(0x0000); + for (let i = 0; i <= subSubdivisions; ++i) { + posi = size * (2.0 * i / subSubdivisions - 1.0); + for (let j = 0; j <= subSubdivisions; ++j) { + posj = size * (2.0 * j / subSubdivisions - 1.0); + if (((i % internalSub) != 0) || ((j % internalSub) != 0)) + this.vertex(posi, posj, 0); + } + } + this.endShape(); + } + else { + for (let i = 0; i <= subdivisions; ++i) { + const pos = size * (2.0 * i / subdivisions - 1.0); + this.line(pos, -size, 0, pos, +size, 0); + this.line(-size, pos, 0, size, pos, 0); + } + } + this.pop(this._rendererState); + }; + + p5.prototype.cross = function () { + this._renderer.cross(...arguments); + }; + + /** + * Draws a cross on the screen. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size cross size. Default is 50. + */ + p5.RendererGL.prototype.cross = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + const half_size = size / 2.0; + this._rendererState = this.push(); + this.beginHUD(); + this.line(x - half_size, y, x + half_size, y); + this.line(x, y - half_size, x, y + half_size); + this.endHUD(); + this.pop(this._rendererState); + }; + + p5.prototype.bullsEye = function () { + this._renderer.bullsEye(...arguments); + }; + + /** + * Draws a bulls-eye on the screen. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size bullseye diameter. Default is 50. + * @param {Number} shape either Tree.CIRCLE or Tree.SQUARE. Default is Tree.CIRCLE. + */ + p5.RendererGL.prototype.bullsEye = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + this._rendererState = this.push(); + if (shape === Tree.CIRCLE) { + this.beginHUD(); + this._circle({ x, y, radius: size / 2 }) + this.endHUD(); + } + else { + const half_length = size / 2.0; + this.beginHUD(); + this.line((x - half_length), (y - half_length) + (0.6 * half_length), (x - half_length), (y - half_length)); + this.line((x - half_length), (y - half_length), (x - half_length) + (0.6 * half_length), (y - half_length)); + this.line((x + half_length) - (0.6 * half_length), (y - half_length), (x + half_length), (y - half_length)); + this.line((x + half_length), (y - half_length), (x + half_length), ((y - half_length) + (0.6 * half_length))); + this.line((x + half_length), ((y + half_length) - (0.6 * half_length)), (x + half_length), (y + half_length)); + this.line((x + half_length), (y + half_length), ((x + half_length) - (0.6 * half_length)), (y + half_length)); + this.line((x - half_length) + (0.6 * half_length), (y + half_length), (x - half_length), (y + half_length)); + this.line((x - half_length), (y + half_length), (x - half_length), ((y + half_length) - (0.6 * half_length))); + this.endHUD(); + } + this.cross({ x: x, y: y, size: 0.6 * size }); + this.pop(this._rendererState); + }; + + p5.prototype._circle = function () { + this._renderer._circle(...arguments); + }; + + p5.RendererGL.prototype._circle = function ({ filled = false, x = this.width / 2, y = this.height / 2, radius = 100, detail = 50 } = {}) { + this._rendererState = this.push(); + if (filled) { + this.beginShape(0x0005); + for (let t = 0; t <= detail; t++) { + const x = Math.cos(t * (2 * Math.PI) / detail); + const y = Math.sin(t * (2 * Math.PI) / detail); + this.vertex(0, 0, 0, 0.5, 0.5) + this.vertex(radius * x, radius * y, 0, (x * 0.5) + 0.5, (y * 0.5) + 0.5); + } + this.endShape(); + } + else { + this.translate(x, y); + const angle = (2 * Math.PI) / detail; + let lastPosition = { x: radius, y: 0 }; + for (let i = 1; i <= detail; i++) { + let position = { x: Math.cos(i * angle) * radius, y: Math.sin(i * angle) * radius }; + this.line(lastPosition.x, lastPosition.y, position.x, position.y); + lastPosition = position; + } + } + this.pop(this._rendererState); + }; + + p5.prototype.viewFrustum = function () { + this._renderer.viewFrustum(...arguments); + }; + + /** + * Display fbo view frustum. + * @param {p5.RendererGL | p5.Graphics} fbo renderer which viewing frustum is to be displayed. + * @param {Number} bits bitwise view-frustum mask that may be composed of Tree.NEAR, Tree.FAR and Tree.BODY bits. + * @param {Function} viewer callback fbo visual representation. + */ + p5.RendererGL.prototype.viewFrustum = function ({ + fbo = _renderer, + bits = Tree.NEAR | Tree.FAR, + viewer = () => this.axes({ size: 50, bits: Tree.X | Tree._X | Tree.Y | Tree._Y | Tree.Z | Tree._Z }) + } = {}) { + if (this === fbo) { + console.error('displaying viewFrustum requires an fbo different than this'); + return; + } + this._rendererState = this.push(); + this.resetMatrix(); + this.applyMatrix(...this.vMatrix().mat4); + this.applyMatrix(...fbo.eMatrix().mat4); + fbo._isOrtho() ? this._viewOrtho(fbo, bits, viewer) : this._viewPerspective(fbo, bits, viewer); + this.pop(this._rendererState); + }; + + p5.RendererGL.prototype._viewOrtho = function (fbo, bits, viewer) { + if (viewer !== Tree.NONE) { + viewer(); + } + let l = fbo.lPlane(); + let r = fbo.rPlane(); + let b = fbo.bPlane(); + let t = fbo.tPlane(); + let n = fbo.nPlane(); + let f = fbo.fPlane(); + if (~(bits | ~Tree.FAR) === 0) { + this.beginShape(); + this.vertex(r, t, -f, 0, 0); + this.vertex(l, t, -f, 1, 0); + this.vertex(l, b, -f, 1, 1); + this.vertex(r, b, -f, 0, 1); + this.endShape(); + } + else { + this.line(r, t, -f, l, t, -f); + this.line(l, t, -f, l, b, -f); + this.line(l, b, -f, r, b, -f); + this.line(r, b, -f, r, t, -f); + } + if (~(bits | ~Tree.BODY) === 0) { + this.beginShape(); + this.vertex(l, t, -f); + this.vertex(l, t, -n); + this.vertex(r, t, -n); + this.vertex(r, t, -f); + this.endShape(); + this.beginShape(); + this.vertex(r, t, -f); + this.vertex(r, t, -n); + this.vertex(r, b, -n); + this.vertex(r, b, -f); + this.endShape(); + this.beginShape(); + this.vertex(r, b, -f); + this.vertex(r, b, -n); + this.vertex(l, b, -n); + this.vertex(l, b, -f); + this.endShape(); + this.beginShape(); + this.vertex(l, t, -n); + this.vertex(l, t, -f); + this.vertex(l, b, -f); + this.vertex(l, b, -n); + this.endShape(); + } + else { + this.line(r, t, -n, r, t, -f); + this.line(l, t, -n, l, t, -f); + this.line(l, b, -n, l, b, -f); + this.line(r, b, -n, r, b, -f); + } + // TODO implement near plane texture + if (~(bits | ~Tree.NEAR) === 0) { + this.beginShape(); + this.vertex(r, t, -n, 0, 0); + this.vertex(l, t, -n, 1, 0); + this.vertex(l, b, -n, 1, 1); + this.vertex(r, b, -n, 0, 1); + this.endShape(); + } + else { + this.line(r, t, -n, l, t, -n); + this.line(l, t, -n, l, b, -n); + this.line(l, b, -n, r, b, -n); + this.line(r, b, -n, r, t, -n); + } + }; + + p5.RendererGL.prototype._viewPerspective = function (fbo, bits, viewer) { + if (viewer !== Tree.NONE) { + viewer(); + } + let magnitude = Math.tan(fbo.fov() / 2); + let aspectRatio = fbo.width / fbo.height; + const points = [ + { x: 0, y: 0, z: 0 }, + { x: 0, y: 0, z: 0 }, + ]; + points[0].z = fbo.nPlane(); + points[1].z = fbo.fPlane(); + points[0].y = points[0].z * magnitude; + points[0].x = points[0].y * aspectRatio; + const ratio = points[1].z / points[0].z; + points[1].y = ratio * points[0].y; + points[1].x = ratio * points[0].x; + if (~(bits | ~Tree.FAR) === 0) { + this.beginShape(); + this.vertex(-points[1].x, points[1].y, -points[1].z, 0, 0); + this.vertex(points[1].x, points[1].y, -points[1].z, 1, 0); + this.vertex(points[1].x, -points[1].y, -points[1].z, 0, 1); + this.vertex(-points[1].x, -points[1].y, -points[1].z, 1, 1); + this.endShape(); + } + else { + this.line(-points[1].x, points[1].y, -points[1].z, points[1].x, points[1].y, -points[1].z); + this.line(points[1].x, points[1].y, -points[1].z, points[1].x, -points[1].y, -points[1].z); + this.line(points[1].x, -points[1].y, -points[1].z, -points[1].x, -points[1].y, -points[1].z); + this.line(-points[1].x, -points[1].y, -points[1].z, -points[1].x, points[1].y, -points[1].z); + } + if (~(bits | ~Tree.BODY) === 0) { + this.beginShape(); + this.vertex(-points[1].x, points[1].y, -points[1].z); + this.vertex(-points[0].x, points[0].y, -points[0].z); + this.vertex(points[0].x, points[0].y, -points[0].z); + this.vertex(points[1].x, points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(points[1].x, points[1].y, -points[1].z); + this.vertex(points[0].x, points[0].y, -points[0].z); + this.vertex(points[0].x, -points[0].y, -points[0].z); + this.vertex(points[1].x, -points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(points[1].x, -points[1].y, -points[1].z); + this.vertex(points[0].x, -points[0].y, -points[0].z); + this.vertex(-points[0].x, -points[0].y, -points[0].z); + this.vertex(-points[1].x, -points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(-points[0].x, points[0].y, -points[0].z); + this.vertex(-points[1].x, points[1].y, -points[1].z); + this.vertex(-points[1].x, -points[1].y, -points[1].z); + this.vertex(-points[0].x, -points[0].y, -points[0].z); + this.endShape(); + this.line(0, 0, 0, points[0].x, points[0].y, -points[0].z); + this.line(0, 0, 0, -points[0].x, points[0].y, -points[0].z); + this.line(0, 0, 0, -points[0].x, -points[0].y, -points[0].z); + this.line(0, 0, 0, points[0].x, -points[0].y, -points[0].z); + } + else { + this.line(0, 0, 0, points[1].x, points[1].y, -points[1].z); + this.line(0, 0, 0, -points[1].x, points[1].y, -points[1].z); + this.line(0, 0, 0, -points[1].x, -points[1].y, -points[1].z); + this.line(0, 0, 0, points[1].x, -points[1].y, -points[1].z); + } + // TODO implement near plane texture + // Something along the lines + // this.textureMode(NORMAL); + // this.tint(255, 126); // Apply transparency without changing color + // this.texture(fbo); + // doesn't work since this.texture is not found + if (~(bits | ~Tree.NEAR) === 0) { + this.beginShape(); + this.vertex(-points[0].x, points[0].y, -points[0].z, 0, 0); + this.vertex(points[0].x, points[0].y, -points[0].z, 1, 0); + this.vertex(points[0].x, -points[0].y, -points[0].z, 0, 1); + this.vertex(-points[0].x, -points[0].y, -points[0].z, 1, 1); + this.endShape(); + } + else { + this.line(-points[0].x, points[0].y, -points[0].z, points[0].x, points[0].y, -points[0].z); + this.line(points[0].x, points[0].y, -points[0].z, points[0].x, -points[0].y, -points[0].z); + this.line(points[0].x, -points[0].y, -points[0].z, -points[0].x, -points[0].y, -points[0].z); + this.line(-points[0].x, -points[0].y, -points[0].z, -points[0].x, points[0].y, -points[0].z); + } + }; +})(); + +function Plane(){ + this.planeMaxMagR = 25; + this.planeColor = "rgb(255, 247, 233)"; + this.planeMagnitudeR = 0; + + this.planeRotateV = createVector(1,0,0); + this.planeSize = createVector(200,200,0); //ancho y alto + this.planePosition = createVector(0,0,0); + + this.draw = function(fbo){ + + fbo.fill(this.planeColor); + fbo.translate(this.planePosition); + fbo.plane(this.planeSize.x,this.planeSize.y) + + }; +} + +class Wall { + + constructor(originX,originY,originZ,width,height,depth, fillColor){ + this.fillColor = fillColor + this.origin = createVector(originX,originY,originZ) + this.width = width + this.height = height + this.depth = depth + this.wallMax = createVector(originX+ width/2, originY+ height/2, originZ+ depth/2) + this.wallMin = createVector(originX-width/2, originY-height/2, originZ - depth/2) + } + + + draw(fbo){ + fbo.push() + //fbo.line(this.wallMin.x,this.wallMin.y,this.wallMin.z,this.wallMax.x,this.wallMax.y,this.wallMax.z) + fbo.fill(this.fillColor) + fbo.translate(this.origin.x,this.origin.y,this.origin.z) + fbo.box(this.width, this.height,this.depth) + fbo.pop() + }; + closestPointSphere(B) { + // get box closest point to sphere center by clamping + const x = Math.max(this.wallMin.x, Math.min(B.spherePosition.x, this.wallMax.x)); + const y = Math.max(this.wallMin.y, Math.min(B.spherePosition.y, this.wallMax.y)); + const z = Math.max(this.wallMin.z, Math.min(B.spherePosition.z, this.wallMax.z)); + + // this is the same as isPointInsidespherePosition + return createVector(x,y,z); +} +isPointInside(point) { + return ( + point.x >= this.wallMin.x && + point.x <= this.wallMax.x && + point.y >= this.wallMin.y && + point.y <= this.wallMax.y && + point.z >= this.wallMin.z && + point.z <= this.wallMax.z + ); +} + collisionWithSphere(B){ + let cPoint = this.closestPointSphere(B) + const distance = Math.sqrt( + (cPoint.x - B.spherePosition.x) * (cPoint.x - B.spherePosition.x) + + (cPoint.y - B.spherePosition.y) * (cPoint.y - B.spherePosition.y) + + (cPoint.z - B.spherePosition.z) * (cPoint.z - B.spherePosition.z) + ); + let sine = sqrt(1-sq(B.acceleration.z)); + let cPointBouncing = undefined + if(distance= B.minVertex.x && + B.spherePosition.y >= B.minVertex.y && + B.spherePosition.z-10 >= B.minVertex.z && + B.spherePosition.x <= B.maxVertex.x && + B.spherePosition.y <= B.maxVertex.y && + B.spherePosition.z-10 <= B.maxVertex.z){ + + P.planeColor = "white" + } + else{ + P.planeColor = "rgba(255, 247, 233,1)" + } + + + beginHUD(); + image(fbo1, 0, 0); + endHUD(); +} +} + + +function getVectorModule(vector){ + return Math.sqrt(vector.x**2 +vector.y**2 +vector.z**2); +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0); +} + + +function mouseDragged(){ + + mouseCurrentV = createVector(mouseX, mouseY, 0); + let vectorSubstra = createVector(mouseInitialV.x - mouseCurrentV.x, + mouseInitialV.y - mouseCurrentV.y, + mouseInitialV.z - mouseCurrentV.z); + let mod = getVectorModule(vectorSubstra); + let vectorDir = createVector(vectorSubstra.x/mod, + vectorSubstra.y/mod, + vectorSubstra.z/mod ); + let sine = sqrt(1-sq(vectorDir.z)); + + B.acceleration = createVector(-sine*vectorDir.x, -sine*vectorDir.y, sine*vectorDir.z); + + let aux = vectorDir.x; + vectorDir.x = vectorDir.y; + vectorDir.y = -aux; + + if (mod < P.planeMaxMagR){ + P.planeMagnitudeR = mod + } + P.planeRotateV = vectorDir; + P.planeRotateV.z = 0; + +} + +function closestPoint(spherePosition, boxMin, boxMax) { + // get box closest point to sphere center by clamping + const x = Math.max(boxMin.x, Math.min(spherePosition.x, boxMax.x)); + const y = Math.max(boxMin.y, Math.min(spherePosition.y, boxMax.y)); + const z = Math.max(boxMin.z, Math.min(spherePosition.z, boxMax.z)); + + // this is the same as isPointInsidespherePosition + return createVector(x,y,z); +} +function dataToWalls(wallsData){ + let walls = wallsData.map(({x,y,z,width,height,depth, fillColor}) =>{ + return new Wall(x,y,z,width,height,depth,fillColor) + }) + return walls +} +function drawListObjects(list, fbo){ + list.forEach(object =>{ + object.draw(fbo) + }) +} +function collisionWalls(walls, B) { + + for(let i=0;i}} +{{< p5-iframe srcdoc="lib3" srcdoc="lib4" sketch="/visual_computing/sketches/maze/sketch.js" width="450" height="450">}} + +--- + +# Conclusiones + +- **P5.treegl** Permitio que la realizacion del ejercicio fuera un poco mas simple de lo que se hubiese logrado a fuerza bruta, sin embargo p5.js presenta muchas desventajas al momento de simular fisicas en los objetos ya que para crearlos son pocos los parametros que existen por lo cual no se recomienda para personas no experimentadas. +- El Funcionamiento de tipo vectorial que existe en **P5** permite una aproximacion matematica para la manipulacion del espacio y los objetos creados en el. + +# Referencias + +{{< hint warning >}} + +- [1] _“Reference | p5.js,”_ **p5js.org.** https://p5js.org/es/reference/ (accessed Oct. 18, 2022). +- [2] _“p5.treegl,”_ **GitHub**, Sep. 12, 2022. https://github.com/VisualComputing/p5.treegl (accessed Oct. 18, 2022). +- [3] _“Laberinto,”_ **Wikipedia**, Aug. 24, 2022. https://es.wikipedia.org/wiki/Laberinto (accessed Oct. 18, 2022). + +{{< /hint >}} diff --git a/content/docs/shortcodes/Taller 2/Aplicacion 3-D/_index.md b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/_index.md new file mode 100644 index 00000000..af83640f --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Aplicacion 3-D/_index.md @@ -0,0 +1,11 @@ +--- +bookCollapseSection: true +--- + +# Aplicacion 3D + +## Objetivo + +X + +{{
}} diff --git a/content/docs/shortcodes/Taller 2/Rasterizacion/Midpoint Circle Algorithm.md b/content/docs/shortcodes/Taller 2/Rasterizacion/Midpoint Circle Algorithm.md new file mode 100644 index 00000000..b5e379b6 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Rasterizacion/Midpoint Circle Algorithm.md @@ -0,0 +1,55 @@ +# Midpoint Circle Algorithm + +El algoritmo de dibujo de círculo de punto medio es un algoritmo utilizado para determinar los puntos necesarios para rasterizar un círculo. + +Usamos el algoritmo del punto medio para calcular todos los puntos del perímetro del círculo en el primer octante y luego los imprimimos junto con sus puntos de espejo en los otros octantes. Esto funcionará porque un círculo es simétrico con respecto a su centro. + +![](https://media.geeksforgeeks.org/wp-content/uploads/circle-5.jpg) + +## Formulas + +Dado un circle centrado en (0,0) y un radio r. Teniendo un punto con coordenadas p(x,y) + +{{< katex display >}} +F(p) = x^2+y^2-r^2 +{{< /katex >}} + +| Name | Matrix | +| ------------------------------------------- | -------------------------------- | +| {{< katex display >}}F(p) < 0{{< /katex >}} | El punto esta dentro del circulo | +| {{< katex display >}}F(p) = 0{{< /katex >}} | El punto esta en el perimetro | +| {{< katex display >}}F(p) > 0{{< /katex >}} | El punto esta fuera del circulo | + +![](https://3.bp.blogspot.com/-X8qWA41L1Tc/W8wU2ONH55I/AAAAAAAAAKY/DFM7qT67HfgIpRwThlCH8izwzHG6JF7gACLcBGAs/s1600/midpointcircle%2B%25281%2529.png) + +{{< details title="Midpoint circle algorithm" open=false >}} + +```javascript +function calculateOctant(middle) { + x += 1; + // Mid-point is inside or on the perimeter + if (p <= 0) { + p = p + 2 * x + 1; + } else { + y -= 1; + p = p + 2 * x - 2 * y + 1; + } + const __x = x * space; + const __y = y * space; + savePointsCircle(__x, __y); + if (fillCircle) { + for (let i = 1; i < r; i++) { + savePointsCircle(__x, __y - space * i); + } + } + + if (x >= y - 1) { + return true; + } + return false; +} +``` +{{< /details >}} + + +{{< p5-iframe sketch="/visual_computing/sketches/rasterization.js" width="646" height="646" >}} diff --git a/content/docs/shortcodes/Taller 2/Rasterizacion/Triangle Rasterization.md b/content/docs/shortcodes/Taller 2/Rasterizacion/Triangle Rasterization.md new file mode 100644 index 00000000..6711c0ee --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Rasterizacion/Triangle Rasterization.md @@ -0,0 +1,220 @@ +# Triangle rasterization + +La rasterización es el proceso por el cual una imagen se transforma en un conjunto de pixeles, los cuales pueden ser mostrados a traves de una salida digital. Este procedimiento incluye el uso de diferentes algoritmos dependiendo de la figura que se vaya a rasterizar. + +Por ejemplo para razterizar un triangulo se necesita el desarrollo de dos pasos: +- Capturar su figura +- Recorrer su figura a traves de los pixeles + +Para el primer paso es necesario verificar si el triangulo encaja en alguna de las siguientes opciones: + +![](https://brakeza.com/wp-content/uploads/2018/12/concepto_rasterizacio%CC%81n.png) + +Si no encaja en la figura BottomFlat o TopFlat, el triangulo debera partirse en dos como muestra la siguiente imagen: + +![](https://docs.hektorprofe.net/cdn/graficos3d/image-49.png) + +De manera que los triangulos resultantes sean de tipo BottomFlat o TopFlat. + +Posteriormente se determinan los valores de x por donde pasa el triangulo, de forma que si el triangulo es de tipo BottomFlat, se recorra linea por linea de arriba abajo, y de izquierda a derecha y si es de tipo TopFlat de abajo hacia arriba y de izquierda a derecha. + + ## Formulas +La formula para determinar los valores de x antes mencionada es dependiente del tipo, asi con pa, pb y pc como puntos del triangulo, las formulas serian las siguientes: + +- BottomFlat + {{< katex display >}} + ext1 = (pb.x - pa.x) / (pb.y - pa.y); + ext2 = (pc.x - pa.x) / (pc.y - pa.y); + {{< /katex >}} +- TopFlat +{{< katex display >}} + ext1 = (pc.x - pa.x) / (pc.y - pa.y); + ext2 = (pc.x - pb.x) / (pc.y - pb.y); + {{< /katex >}} + + Donde ext1 representa el expremo izquierdo de la fila y ext1 representa el expremo derecho de la fila que contiene el triangulo. + + + +{{< details title="Raterization algorithm" open=false >}} + +```javascript +let n1 = 500; +let n2 = 420; +let n3 = 258; +let n4 = 420; +let n5 = 486; +let n6 = 275; +let space = 20; +var p1, p2, p3, p4; +let puntos; +let x,y; +let beads; +let beadSize = 20; +let cols, rows; +let num; + +function setup() { + createCanvas(621, 621) + cols = ceil(621 / beadSize); + rows = ceil(621 / beadSize); + beads = new Array(cols); + for (let x = 0; x < cols; x++){ + beads[x] = new Array(rows).fill(false); + } + organizeTriangle(); + clasifyTriangle(); +} + +function draw() { + background(0,0,40); + drawGrid(); + paint(num); + line(puntos[0].x, puntos[0].y, puntos[1].x, puntos[1].y); + line(puntos[0].x, puntos[0].y, puntos[2].x, puntos[2].y); + line(puntos[2].x, puntos[2].y, puntos[1].x, puntos[1].y); + stroke("red"); + +} + +function drawBeads(columnainicial, columnafinal,filas){ + let filasm = filas + 1; + let columnainicialm = columnainicial - 4; + push(); + noStroke(); + //fill(0); + fill(0, 179, 255); + for (let i = columnainicialm; i <= columnafinal; i++){ + for (let j = filas; j < filasm; j++){ + square(i * beadSize, j * beadSize, beadSize); + } + + } + pop(); +} + +function drawGrid(){ + push(); + stroke(200); + for (let x = 0; x < 621; x+= beadSize){ + line(x, 0, x, 621); + } + + for (let y = 0; y < 621; y+= beadSize){ + line(0, y, 621, y); + } + pop(); +} + + +function organizeTriangle(){ + p1= { + x: n1, + y: n2 + }; + p2 = { + x: n3, + y: n4 + }; + p3 = { + x: n5, + y: n6 + } + puntos = [p1, p2, p3]; + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < 2; j++){ + if(puntos[i].y > puntos[j+1].y ){ + let punto = puntos[i]; + puntos[i] = puntos[j + 1]; + puntos[j + 1 ] = punto; + } + } + } + + if(puntos[0].y == puntos[1].y){ + if(puntos[0].x > puntos[1].x){ + let punto = puntos[0]; + puntos[0] = puntos[1]; + puntos[1] = punto; + } + } + +} + +function clasifyTriangle(){ + if (puntos[1].y == puntos[2].y) { + num = 1; + } else if (puntos[0].y == puntos[1].y) { + num = 2; + } else { + num = 3; + x = (int) (puntos[0].x + ((puntos[1].y - puntos[0].y) / (puntos[2].y - puntos[0].y)) * (puntos[2].x - puntos[0].x)); + y = (int) (puntos[1].y); + + p4 = { + x: x, + y: y + } + + //scanBottomFlatTriangle(puntos[0], puntos[1], p4); + //scanTopFlatTriangle(p4, puntos[1], puntos[2]); + + } +} + +function scanTopFlatTriangle(pa, pb, pc){ + + let invslope1 = (pc.x - pa.x) / (pc.y - pa.y); + let invslope2 = (pc.x - pb.x) / (pc.y - pb.y); + + let curx1 = pc.x; + let curx2 = pc.x; + + for (var scanlineY = pc.y; scanlineY < pa.y;scanlineY--) { + scanLine(curx1, curx2, scanlineY); + curx1 -= invslope1; + curx2 -= invslope2; + } +} + +function scanBottomFlatTriangle(pa, pb, pc){ + let invslope1 = parseInt((pb.x - pa.x) / (pb.y - pa.y)); + let invslope2 = parseInt((pc.x - pa.x) / (pc.y - pa.y)); + + let curx1 = pa.x; + let curx2 = pa.x; + + for (var scanlineY = pa.y; scanlineY <= pb.y;scanlineY++) { + scanLine(curx1, curx2, scanlineY); + curx1 += invslope1; + curx2 += invslope2; + } +} +function scanLine(curx1, curx2, scanlineY){ + curx1 = parseInt(curx1/ beadSize); + curx2 = parseInt(curx2 / beadSize); + scanlineY = parseInt(scanlineY / beadSize); + console.log(curx1); + console.log(curx2); + console.log(scanlineY); + drawBeads(curx1, curx2,scanlineY); +} + +function paint(num){ + if(num == 1){ + scanBottomFlatTriangle(puntos[0], puntos[1], puntos[2]); + }else{ + if(num == 2){ + scanTopFlatTriangle(puntos[0], puntos[1], puntos[2]); + } + } +} +``` +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/rasterization_2.js" width="646" height="646" >}} + + ## Referencias + + https://brakeza.com/rasterizacion-del-triangulo#:~:text=El%20t%C3%A9rmino%20bajo%20el%20que,el%20interior%20de%20un%20tri%C3%A1ngulo. diff --git a/content/docs/shortcodes/Taller 2/Rasterizacion/_index.md b/content/docs/shortcodes/Taller 2/Rasterizacion/_index.md new file mode 100644 index 00000000..f11d6ff1 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/Rasterizacion/_index.md @@ -0,0 +1,11 @@ +--- +bookCollapseSection: true +--- + +# Rasterizacion + +## Objetivo + +X + +{{
}} diff --git a/content/docs/shortcodes/Taller 2/_index.md b/content/docs/shortcodes/Taller 2/_index.md new file mode 100644 index 00000000..3cf1d754 --- /dev/null +++ b/content/docs/shortcodes/Taller 2/_index.md @@ -0,0 +1,11 @@ +--- +bookCollapseSection: true +--- + +# Taller 2 + +## Objetivo + +X + +{{
}} diff --git a/content/docs/shortcodes/Taller 3/Coloring/_index.md b/content/docs/shortcodes/Taller 3/Coloring/_index.md new file mode 100644 index 00000000..124ce974 --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Coloring/_index.md @@ -0,0 +1,10 @@ +# Color blending + +Blending two colors is implemented by doing a component-wise multiplication between them +{{< p5-iframe sketch="/visual_computing/sketches/shaders/blend.js" width="470" height="275" >}} + +# Color blending with lightness +{{< p5-iframe sketch="/visual_computing/sketches/shaders/light.js" width="470" height="275" >}} + +# Different blending modes +{{< p5-iframe sketch="/visual_computing/sketches/shaders/blendMode.js" width="470" height="475" >}} diff --git a/content/docs/shortcodes/Taller 3/Image Processing/_index.md b/content/docs/shortcodes/Taller 3/Image Processing/_index.md new file mode 100644 index 00000000..ca09eb6d --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Image Processing/_index.md @@ -0,0 +1,420 @@ +## Image Processing + +El **procesamiento de imagenes** es la manipulación de imagenes mediante procesos computacionales manejados por **GPU** y el uso de algoritmos que modifican las imagenes. En muchos de los casos se utilizan **operaciones matematicas de nivel matricial** para transformar los colores de las imagenes, o distorsionarlas como se lograria con **efectos de amplificación**. + +### 1. **Procesamiento** + +{{< hint info >}} +**Ejercicio 1:** +Implemente una aplicacion para el procesamiento de imagenes / videos que soporte el uso de diferentes mascaras, incluyendo kernels de tamaño diferente a 3x3 y: +* Una Herramienta de region de interes para aplicar selectivamente una mascara: +* Una Herramienta de magnidicacion. +* Una herramienta que integre **Luma** y otras herramientas. +{{< /hint >}} + +{{< hint info >}} +**Ejercicio 2.1:** +Incluir el canal **azul** en la visualizacion UV, ya sea **Azul + Verde** ó **Azul + Rojo**. +{{< /hint >}} + +{{< hint warning >}} +**Solucion Ejercicio 2.1:** +Modificar el shader para que evalue 2 variables y reajuste el color dependiendo de una de las opciones seleccionadas, modificando uno de los canales dependiendo de la opcion. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/app.js" width="725" height="725" >}} + +{{< details "**CODIGO:** app.js" close >}} +```javascript + +let maskShader; +let img; +let video_src; +let video_on; +let cam_src; +let cam_on; +let ColorT; + +let mask_mode; +let coloring; +let lenses; +//let maskmode; + +function preload() { + video_src = createVideo(['/visual_computing/vid/drift.mp4']); + video_src.hide(); + + cam_src = createCapture(VIDEO); + cam_src.size(width, height); + cam_src.hide(); + + maskShader = readShader('/visual_computing/sketches/shaders/mask.frag', { varyings: Tree.texcoords2 }); + img = loadImage('/visual_computing/imgs/car.jpg'); +} + +function setup() { + createCanvas(700, 700, WEBGL); + noStroke(); + textureMode(NORMAL); + + //Camera selector + cam_on = createCheckbox('Live', false); + cam_on.style('color','black'); + cam_on.position(10,50); + + //Camera Controls + cam_on.changed(() => { + if(cam_on.checked()){ + maskShader.setUniform('texture',cam_src); + }else{ + maskShader.setUniform('texture', img); + } + }); + + + //Video Controls + video_on = createCheckbox('Video', false); + video_on.style('color', 'black'); + video_on.position(10, 30); + + //Video & image Switcher + video_on.changed(() => { + if (video_on.checked()) { + maskShader.setUniform('texture', video_src); + video_src.loop(); + } else { + maskShader.setUniform('texture', img); + video_src.pause(); + } + }); + + //Mask controls + mask_mode = createCheckbox('Masks', false); + mask_mode.position(10, 10); + mask_mode.style('color', 'black'); + + //Coloring checkbox + coloring = createCheckbox('Coloring',false); + coloring.position(165, 10); + coloring.style('color','black'); + + //Lenses checkbox + lenses = createCheckbox('Lense',false); + lenses.position(360, 10); + lenses.style('color','black'); + + //Shader apply + shader(maskShader); + maskShader.setUniform('texture', img); + emitTexOffset(maskShader, img, 'texOffset'); + + //Kernel selector + sel = createSelect(); + sel.position(80, 10); + sel.option('None'); + sel.option('Edges'); + sel.option('Sharpen'); + sel.option('Box Blur'); + sel.option('Emboss'); + + + sel.selected('None'); + + //Coloring selector + selC = createSelect(); + selC.position(245, 10); + selC.option('None'); + selC.option('Luma'); + selC.option('Average'); + selC.option('HSV Value V'); + selC.option('HSL Value L'); + selC.option('Tint'); + + selC.selected('None'); + + //Color Picker + colorT = createColorPicker(color(255,255,255)); + colorT.position(175, 30); + + //lenses parameters + Rslider = createSlider(50.0, 150.0, 50.0); + Rslider.position(360, 30); + Rslider.style('width', '80px'); + let div1 = createDiv('Lens Radio'); + div1.style('font-size', '18px'); + div1.style('color', '#000000'); + div1.position(450, 30); + + Sslider = createSlider(0.0, 1.0, 0.0, 0.01); + Sslider.position(360, 50); + Sslider.style('width', '80px'); + let div2 = createDiv('Lens Amplitude'); + div2.style('font-size', '18px'); + div2.style('color', '#000000'); + div2.position(450, 50); + +} + +function draw() { + background(0); + + //Mask Mode + if (mask_mode.checked()){ + + //Enable Masks Mode + maskShader.setUniform('maskmode',true); + maskShader.setUniform('coloringmode',false); + + //kernels + if (sel.value()=='Edges') { + maskShader.setUniform('mask', [-1, -1, -1, -1, 8, -1, -1, -1, -1]); + }else if(sel.value()=='Sharpen'){ + maskShader.setUniform('mask', [0, -1, 0, -1, 5, -1, 0, -1, 0]); + }else if(sel.value()=='Box Blur'){ + maskShader.setUniform('mask', [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]); + }else if(sel.value()=='Emboss'){ + maskShader.setUniform('mask', [-2, -1, 0, -1, 1, 1, 0, 1, 2]); + }else{ + maskShader.setUniform('mask', [0, 0, 0, 0, 1, 0, 0, 0, 0]); + } + + }else if(coloring.checked()){ + + + //Enable Coloring Mode + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',true); + + if(selC.value()=="None"){ + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('average',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value()=="Luma"){ + maskShader.setUniform('grey_scale',true); + maskShader.setUniform('average',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value()=="Average"){ + maskShader.setUniform('average',true); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="HSV Value V"){ + maskShader.setUniform('HSVV',true); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="HSL Value L"){ + maskShader.setUniform('HSLL',true); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="Tint"){ + maskShader.setUniform('Tint',true); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + + let RC = colorT.color(); + maskShader.setUniform('colorT',[red(RC),green(RC),blue(RC),1.0]); + } + + }else if(lenses.checked()){ + maskShader.setUniform('lensemode',true); + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',false); + + maskShader.setUniform('mouseData',[mouseX,mouseY]); + maskShader.setUniform('resolution',[width,height]); + maskShader.setUniform('radio', Rslider.value()); + maskShader.setUniform('scale', Sslider.value()); + }else{ + maskShader.setUniform('lensemode',false); + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',false); + } + + + quad(-width / 2, -height / 2, width / 2, -height / 2, width / 2, height / 2, -width / 2, height / 2); +} + +``` +{{< /details >}} + +{{< details "**CODIGO:** mask.frag" close >}} +```glsl +precision mediump float; + +uniform bool maskmode; +uniform bool coloringmode; +uniform bool lensemode; + +uniform bool grey_scale; +uniform bool average; +uniform bool HSVV; +uniform bool HSLL; +uniform bool Tint; + +uniform vec4 colorT; + +uniform sampler2D texture; + +uniform vec2 texOffset; +uniform float mask[9]; + +varying vec2 texcoords2; + +uniform vec2 mouseData; +uniform vec2 resolution; + +uniform vec4 passerGL; + +uniform float radio; +uniform float scale; + +//-------------------------------------------------------------------------- + +float rim = 2.0; +vec2 handview = vec2(10.0,50.0); + +vec2 curveGen(vec2 toPow, float dist){ + float x = dist/radio; + return toPow * (1.0 - x) * exp (-2.0 * x * x); +} + +void Amplify (){ + + vec2 UV = gl_FragCoord.xy / resolution.xy; + gl_FragColor = texture2D(texture, UV); + + vec2 center = mouseData.xy; + float dist = distance(gl_FragCoord.xy,center); + + vec2 distV = gl_FragCoord.xy - center; + + if (dist > radio && dist < radio + rim){ + gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); + } + + if(abs(distV.x) < (handview.x / 2.0 ) && abs(distV.y + radio) < (handview.y) && dist >= radio + rim){ + gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); + } + + if(dist < radio){ + vec2 trueUV = (gl_FragCoord.xy - (curveGen(distV,dist) * scale)) / resolution.xy ; + gl_FragColor = texture2D(texture, trueUV); + } +} + +//-------------------------------------------------------------------------- + +void Convolution(){ + + vec2 tc0 = texcoords2 + vec2(-texOffset.s, -texOffset.t); + vec2 tc1 = texcoords2 + vec2( 0.0, -texOffset.t); + vec2 tc2 = texcoords2 + vec2(+texOffset.s, -texOffset.t); + vec2 tc3 = texcoords2 + vec2(-texOffset.s, 0.0); + + vec2 tc4 = texcoords2 + vec2( 0.0, 0.0); + vec2 tc5 = texcoords2 + vec2(+texOffset.s, 0.0); + vec2 tc6 = texcoords2 + vec2(-texOffset.s, +texOffset.t); + vec2 tc7 = texcoords2 + vec2( 0.0, +texOffset.t); + vec2 tc8 = texcoords2 + vec2(+texOffset.s, +texOffset.t); + + + vec4 rgba[9]; + rgba[0] = texture2D(texture, tc0); + rgba[1] = texture2D(texture, tc1); + rgba[2] = texture2D(texture, tc2); + rgba[3] = texture2D(texture, tc3); + rgba[4] = texture2D(texture, tc4); + rgba[5] = texture2D(texture, tc5); + rgba[6] = texture2D(texture, tc6); + rgba[7] = texture2D(texture, tc7); + rgba[8] = texture2D(texture, tc8); + + + vec4 convolution; + for (int i = 0; i < 9; i++) { + convolution += rgba[i]*mask[i]; + } + + + gl_FragColor = vec4(convolution.rgb, 1.0); +} + +//-------------------------------------------------------------------------- + +float luma(vec3 texel){ + return 0.299 * texel.r + 0.587 * texel.g + 0.114 * texel.b; + } + +float favg(vec3 texel){ + return (texel.r + texel.g + texel.b ) / 3.0; + } + +float HSV (vec3 texel){ + return max(max(texel.r,texel.g),texel.b); ; + } + +float HSL (vec3 texel){ + float CMax = max(max(texel.r,texel.g),texel.b); + float CMin = min(min(texel.r,texel.g),texel.b); + return (CMax + CMin) / 2.0 ; + } + +float Ftint(float channel, float color){ + float N = channel * (color / 255.0); + return N; + } + +void Coloring(){ + + vec4 texel = texture2D(texture, texcoords2); + + if(grey_scale == true){ + gl_FragColor = vec4((vec3(luma(texel.rgb))), 1.0); + }else if(average == true){ + gl_FragColor = vec4((vec3(favg(texel.rgb))), 1.0); + }else if(HSVV== true){ + gl_FragColor = vec4((vec3(HSV(texel.rgb))), 1.0); + }else if(HSLL== true){ + gl_FragColor = vec4((vec3(HSL(texel.rgb))), 1.0); + }else if(Tint == true){ + gl_FragColor = vec4(Ftint(texel.r,colorT.x),Ftint(texel.g,colorT.y),Ftint(texel.b,colorT.z),1.0); + }else{ + gl_FragColor = texel; + } +} + +//-------------------------------------------------------------------------- + +void main() { + + if(maskmode == true){ + Convolution(); + Coloring(); + }else if(coloringmode == true){ + Coloring(); + }else if(lensemode == true){ + Amplify(); + }else{ + gl_FragColor = texture2D(texture, texcoords2); + } + +} + +``` +{{< /details >}} \ No newline at end of file diff --git a/content/docs/shortcodes/Taller 3/Photomosaic/_index.md b/content/docs/shortcodes/Taller 3/Photomosaic/_index.md new file mode 100644 index 00000000..db9d96da --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Photomosaic/_index.md @@ -0,0 +1,20 @@ +## Fotomosaico + +El fotomosaico es una imagen, retrato o fotografía que se divide por figuras geométricas, generalmente +por cuadrados o rectángulos del mismo tamaño, esto con el fin de remplazar las mismas +por otros retratos, fotografías o imágenes que concuerden con los colores promedio que encierran las +figuras geométricas de la imagen original, logrando que al visualizar la +imagen de un punto lejano se logre ver como la original , pero que al ver de un punto cercano o al +hacer zoom se pueda percibir que se compone de otras imágenes. + +# Fotomosaico + +## Fotomosaico por hardware + +La implementación del fotomosaico se puede realizar a través de hardware, es decir, la construcción de un algoritmo que se encargue de convertir la imagen original en un mosaico de otras. + +En la funcion `preload` definimos el fragmento a usar demoninado `photomosaic.frag`, a partir de ahi al mosaico final vamos a definir ciertos parametros que van a ser obtenidos al momento de recorrer la imagen, aqui se comparan los texeles del color promedio que posee cada pixel de la imagen o video original. + +Los colores promedio de la imagen original son comparados con la imagen devuelta por el quadrille, haciendo uso de una tolerancia que va aumentando hasta encontrar el color mas cercano al del original y de esta forma ese color encontrado es el que se usa para llenar en la imagen que se muestra como resultado. + +{{< p5-iframe sketch="/visual_computing/sketches/photomosaic.js" lib1="/visual_computing/sketches/libraries/p5.shaderbox.js" lib2="/visual_computing/sketches/libraries/p5.quadrille.js" width="675" height="675" >}} diff --git a/content/docs/shortcodes/Taller 3/Texturing/_index.md b/content/docs/shortcodes/Taller 3/Texturing/_index.md new file mode 100644 index 00000000..3b11298d --- /dev/null +++ b/content/docs/shortcodes/Taller 3/Texturing/_index.md @@ -0,0 +1,476 @@ +## Texturing + +La **texturizacion** es el proceso por el cual una imagen o mapa de bits es **mapeado** sobre un objeto 3D o una superficie, esto se logra trabajando con los sistemas coorddenados de las figuras y de la textura, la cual mediante el **shader** y la **GPU** son procesados haciendo uso de **GLSL** y algunos paradigmas de programacion, como programacion en paralelo. + +### 1. **Visualizacion UV** + +La visualizacion UV nos permite mostrar una textura sobre un espacio particular. + +{{< hint info >}} +**Ejercicio 1:** +Redefinir las coordenas de la figura texturizada para invertir la orientacion vertical de la imagen. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/uvoriginal.js" width="325" height="325" >}} + +{{< hint warning >}} +**Solucion Ejercicio 1:** +Redefinir las coordenadas [u] y [v] de los vertex definidos en uv.js para que cada punto del clip space mapeara a su inverso en el texture space. +{{< /hint >}} + +{{< details "**CODIGO:** uv_inverse.js" close >}} +```javascript +let uvShader; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/uv.frag', { matrices: Tree.NONE, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(300, 300, WEBGL); + noStroke(); + shader(uvShader); + textureMode(NORMAL); +} + +function draw() { + background(0); + beginShape(); + vertex(-1, -1, 0, 0, 1); + vertex( 1, -1, 0, 1, 1); + vertex( 1, 1, 0, 1, 0); + vertex(-1, 1, 0, 0, 0); + endShape(); +} +``` +{{< /details >}} + +{{< details "**CODIGO:** uv.frag" close >}} +```glsl +precision mediump float; +varying vec2 texcoords2; + +void main() { + gl_FragColor = vec4(texcoords2.xy, 0.0, 1.0); +} +``` +{{< /details >}} + +{{< p5-iframe sketch="/visual_computing/sketches/uv_inverse.js" width="325" height="325" >}} + +--- + +### 2. **3D** + +La visualizacion 3D de espaciosUV nos permite mostrar una textura sobre un objeto particular en un espacio que permite la interaccion **3D**, sin embargo esto no altera en demasia . + + +{{< hint info >}} +**Ejercicio 2.1:** +Incluir el canal **azul** en la visualizacion UV, ya sea **Azul + Verde** ó **Azul + Rojo**. +{{< /hint >}} + +{{< hint warning >}} +**Solucion Ejercicio 2.1:** +Modificar el shader para que evalue 2 variables y reajuste el color dependiendo de una de las opciones seleccionadas, modificando uno de los canales dependiendo de la opcion. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/uvplus.js" width="325" height="340" >}} + + +{{< details "**CODIGO:** uvplus.js" close >}} +```javascript +let easycam; +let uvShader; +let c1, c2; + +let rtb = false, gtb = false; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/uvplus.frag',{ matrices: Tree.pmvMatrix, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(300, 300, WEBGL); + textureMode(NORMAL); + c1 = createCheckbox('Red To Blue', false); + c2 = createCheckbox('Green To Blue', false); + c1.position(10, 310); + c2.position(150, 310); + shader(uvShader); +} + +function draw() { + background(200); + orbitControl(); + axes(); + push(); + noStroke(); + quad(-width / 2, -height / 2, width / 2, -height / 2, + width / 2, height / 2, -width / 2, height / 2); + pop(); + + if(c1.checked()){ + uvShader.setUniform('rtb',true) + uvShader.setUniform('gtb',false) + }else if(c2.checked()){ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',true) + }else{ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',false) + } +} + +function mouseWheel(event) { + return false; +} +``` +{{< /details >}} + +{{< details "**CODIGO:** uvplus.frag" close >}} +```glsl +precision mediump float; + +uniform bool rtb; +uniform bool gtb; +varying vec2 texcoords2; + +void main() { + if(rtb==true){ + gl_FragColor = vec4(0.0 ,texcoords2.y,texcoords2.x, 1.0); + }else if(gtb==true){ + gl_FragColor = vec4(texcoords2.x , 0.0, texcoords2.y, 1.0); + }else{ + gl_FragColor = vec4(texcoords2.xy, 0.0, 1.0); + } +} +``` +{{< /details >}} + +--- + +{{< hint info >}} +**Ejercicio 2.2:** +Utilizar figuras diferentes a **Quad** como filtros de pantalla. +{{< /hint >}} + +{{< hint warning >}} +**Solucion Ejercicio 2.2:** +Modificar las figuras mediante la definicion de metodos y figuras de P5, añadir el control de opacidad y el cambio de canales **[RGB]**. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/screen.js" width="475" height="475" >}} + + +{{< details "**CODIGO:** screen.js" close >}} +```javascript +let easycam; +let uvShader; +let opacity; + +let c1, c2; + +let rtb = false, gtb = false; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/screen.frag',{ matrices: Tree.pmvMatrix, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(450, 450, WEBGL); + + // easycam stuff + let state = { + distance: 250, + center: [0, 0, 0], + rotation: [0, 0, 0, 1], + }; + easycam = createEasyCam(); + easycam.state_reset = state; + easycam.setState(state, 2000); + textureMode(NORMAL); + opacity = createSlider(0, 1, 0.5, 0.01); + opacity.position(10, 25); + opacity.style('width', '280px'); + + c1 = createCheckbox('R To B', false); + c2 = createCheckbox('G To B', false); + c1.position(100, 10); + c2.position(200, 10); + + sel = createSelect(); + sel.position(10, 10); + sel.option('Quad'); + sel.option('Triangle'); + sel.option('Circle'); + sel.selected('Quad'); + +} + +function draw() { + background(200); + + resetShader(); + + axes(); + grid(); + translate(0, -70); + rotateY(0.5); + fill(color(255, 0, 255, 125)); + box(30, 50); + translate(70, 70); + fill(color(0, 255, 255, 125)); + sphere(30, 50); + + shader(uvShader); + + uvShader.setUniform('opacity', opacity.value()); + + beginHUD(); + + noStroke(); + + if(sel.value() == "Quad"){ + quad(0, 0, width, 0, width, height, 0, height); + }else if(sel.value() == "Triangle"){ + triangle(0,0,width,0,width/2,height) + }else if (sel.value() == "Circle"){ + circle(width/2,height/2,width) + } + + if(c1.checked()){ + uvShader.setUniform('rtb',true) + uvShader.setUniform('gtb',false) + }else if(c2.checked()){ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',true) + }else{ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',false) + } + + endHUD(); +} + +function mouseWheel(event) { + //comment to enable page scrolling + return false; +} +``` +{{< /details >}} + +{{< details "**CODIGO:** screen.frag" close >}} +```glsl +precision mediump float; + +uniform bool rtb; +uniform bool gtb; +uniform float opacity; +varying vec2 texcoords2; + +void main() { + if(rtb==true){ + gl_FragColor = vec4(0.0 ,texcoords2.y,texcoords2.x, opacity); + }else if(gtb==true){ + gl_FragColor = vec4(texcoords2.x , 0.0, texcoords2.y, opacity); + }else{ + gl_FragColor = vec4(texcoords2.xy, 0.0, opacity); + } +} +``` +{{< /details >}} + +--- +### 3. **Muestreo de Texturas** + +Los efectos que puedan aplicarse a una imagen requieren utilizar coordenaddas dadas, las coordenadas **texcoords2** y los **texels** permiten realizar operaciones pixel a pixel haciendo uso de la GPU . + +{{< hint info >}} +**Ejercicio 3.1 y 3.2:** +* Implementar heraamientas de iluminacion i color tales como *HSV valor V, HSL luminancia L, Promedio de componentes*. +* Implementar el tintado de texturas mezclando el colo y los datos interpolados de los texeles. +{{< /hint >}} + +{{< hint warning >}} +**Solucion Ejercicio 3.1 y 3.2:** +Para modificar la imagen se opera matematicamente los valores que se obtienen en los texels **[Canales RGBA]** , o se modifican de plano para que el shader los procese nuevamente. +{{< /hint >}} + +{{< p5-iframe sketch="/visual_computing/sketches/tools.js" width="725" height="525" >}} + +{{< details "**CODIGO:** tools.js" close >}} +```javascript +let lumaShader; +let img; +let grey_scale; +let average; +let HSVV; +let Tint; +let ColorT; + +function preload() { + lumaShader = readShader('/visual_computing/sketches/shaders/colors.frag',{ varyings: Tree.texcoords2}); + img = loadImage('/visual_computing/imgs/car.jpg'); +} + +function drawControls(enabled){ + if(enabled){ + colorT = createColorPicker(color(255,255,255)); + colorT.position(125, 10); + } +} + +function setup() { + createCanvas(700, 500, WEBGL); + noStroke(); + textureMode(NORMAL); + + sel = createSelect(); + sel.position(10, 10); + sel.option('None'); + sel.option('Luma'); + sel.option('Average'); + sel.option('HSV Value V'); + sel.option('HSL Value L'); + sel.option('Tint'); + + sel.selected('None'); + + drawControls(true); + + + +} + +function draw() { + background(0); + + if(sel.value()=="None"){ + shader(lumaShader); + lumaShader.setUniform('texture', img); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('average',false); + + }else if(sel.value()=="Luma"){ + shader(lumaShader); + lumaShader.setUniform('grey_scale',true); + lumaShader.setUniform('average',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value()=="Average"){ + shader(lumaShader); + lumaShader.setUniform('average',true); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="HSV Value V"){ + shader(lumaShader); + lumaShader.setUniform('HSVV',true); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="HSL Value L"){ + shader(lumaShader); + lumaShader.setUniform('HSLL',true); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="Tint"){ + shader(lumaShader); + lumaShader.setUniform('Tint',true); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + let RC = colorT.color(); + lumaShader.setUniform('colorT',[red(RC),green(RC),blue(RC),1.0]); + + } + + quad(-width / 2, -height / 2, width / 2, -height / 2, width / 2, height / 2, -width / 2, height / 2); +} +``` +{{< /details >}} + +{{< details "**CODIGO:** colors.frag" close >}} +```glsl +precision mediump float; + +uniform bool grey_scale; +uniform bool average; +uniform bool HSVV; +uniform bool HSLL; +uniform bool Tint; + +uniform vec4 colorT; + +uniform sampler2D texture; + +varying vec2 texcoords2; + +float luma(vec3 texel) { + return 0.299 * texel.r + 0.587 * texel.g + 0.114 * texel.b; +} + +float favg(vec3 texel){ + return (texel.r + texel.g + texel.b ) / 3.0; +} + +float HSV (vec3 texel){ + return max(max(texel.r,texel.g),texel.b); ; +} + +float HSL (vec3 texel){ + float CMax = max(max(texel.r,texel.g),texel.b); + float CMin = min(min(texel.r,texel.g),texel.b); + return (CMax + CMin) / 2.0 ; +} + +float Ftint(float channel, float color){ + float N = channel * (color / 255.0); + return N; +} + + +void main() { + + vec4 texel = texture2D(texture, texcoords2); + + if(grey_scale == true){ + gl_FragColor = vec4((vec3(luma(texel.rgb))), 1.0); + }else if(average == true){ + gl_FragColor = vec4((vec3(favg(texel.rgb))), 1.0); + }else if(HSVV== true){ + gl_FragColor = vec4((vec3(HSV(texel.rgb))), 1.0); + }else if(HSLL== true){ + gl_FragColor = vec4((vec3(HSL(texel.rgb))), 1.0); + }else if(Tint == true){ + gl_FragColor = vec4(Ftint(texel.r,colorT.x),Ftint(texel.g,colorT.y),Ftint(texel.b,colorT.z),1.0); + }else{ + gl_FragColor = texel; + } + +} +``` +{{< /details >}} + +{{< hint danger >}} +**Referencias:** +* **[Speeding Up tint() in p5]:** https://www.davepagurek.com/blog/p5-tint/ +* **[HSL & HSV]:** https://en.wikipedia.org/wiki/HSL_and_HSV#Disadvantages +* **[Blend Modes]:** https://en.wikipedia.org/wiki/Blend_modes#Overlay +* **[P5.js]:** https://p5js.org/es/reference/ +{{< /hint >}} diff --git a/content/docs/shortcodes/Taller 3/_index.md b/content/docs/shortcodes/Taller 3/_index.md new file mode 100644 index 00000000..65cdaac8 --- /dev/null +++ b/content/docs/shortcodes/Taller 3/_index.md @@ -0,0 +1,11 @@ +--- +bookCollapseSection: true +--- + +# Shaders + +## Objetivo + +X + +{{
}} diff --git a/content/docs/shortcodes/buttons.md b/content/docs/shortcodes/buttons.md deleted file mode 100644 index c2ef1e75..00000000 --- a/content/docs/shortcodes/buttons.md +++ /dev/null @@ -1,13 +0,0 @@ -# Buttons - -Buttons are styled links that can lead to local page or external link. - -## Example - -```tpl -{{}}Get Home{{}} -{{}}Contribute{{}} -``` - -{{< button relref="/" >}}Get Home{{< /button >}} -{{< button href="https://github.com/alex-shpak/hugo-book" >}}Contribute{{< /button >}} diff --git a/content/docs/shortcodes/columns.md b/content/docs/shortcodes/columns.md deleted file mode 100644 index 0b8fde83..00000000 --- a/content/docs/shortcodes/columns.md +++ /dev/null @@ -1,45 +0,0 @@ -# Columns - -Columns help organize shorter pieces of content horizontally for readability. - - -```html -{{}} -# Left Content -Lorem markdownum insigne... - -<---> - -# Mid Content -Lorem markdownum insigne... - -<---> - -# Right Content -Lorem markdownum insigne... -{{}} -``` - -## Example - -{{< columns >}} -## Left Content -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. - -<---> - -## Mid Content -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! - -<---> - -## Right Content -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. -{{< /columns >}} diff --git a/content/docs/shortcodes/details.md b/content/docs/shortcodes/details.md deleted file mode 100644 index 3d5aedc4..00000000 --- a/content/docs/shortcodes/details.md +++ /dev/null @@ -1,22 +0,0 @@ -# Details - -Details shortcode is a helper for `details` html5 element. It is going to replace `expand` shortcode. - -## Example - -```tpl -{{}} -## Markdown content -Lorem markdownum insigne... -{{}} -``` - -{{< details "Title" open >}} -## Markdown content -Lorem markdownum insigne... -{{< /details >}} - -{{< details "Title" >}} -## Markdown content -Lorem markdownum insigne... -{{< /details >}} diff --git a/content/docs/shortcodes/hints.md b/content/docs/shortcodes/hints.md deleted file mode 100644 index 3477113d..00000000 --- a/content/docs/shortcodes/hints.md +++ /dev/null @@ -1,32 +0,0 @@ -# Hints - -Hint shortcode can be used as hint/alerts/notification block. -There are 3 colors to choose: `info`, `warning` and `danger`. - -```tpl -{{}} -**Markdown content** -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -{{}} -``` - -## Example - -{{< hint info >}} -**Markdown content** -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -{{< /hint >}} - -{{< hint warning >}} -**Markdown content** -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -{{< /hint >}} - -{{< hint danger >}} -**Markdown content** -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -{{< /hint >}} diff --git a/content/docs/shortcodes/katex.md b/content/docs/shortcodes/katex.md deleted file mode 100644 index dd0a8591..00000000 --- a/content/docs/shortcodes/katex.md +++ /dev/null @@ -1,25 +0,0 @@ -# KaTeX - -KaTeX shortcode let you render math typesetting in markdown document. See [KaTeX](https://katex.org/) - -## Example - -{{< columns >}} -{{< highlight latex >}} -{{}} -f(x) = \int_{-\infty}^\infty\hat f(\xi)\,e^{2 \pi i \xi x}\,d\xi -{{}} -{{< /highlight >}} -<---> -{{< katex display >}} -f(x) = \int_{-\infty}^\infty\hat f(\xi)\,e^{2 \pi i \xi x}\,d\xi -{{< /katex >}} -{{< /columns >}} - -## Display Mode Example - -Here is some inline example: {{< katex >}}\pi(x){{< /katex >}}, rendered in the same line. And below is `display` example, having `display: block` -{{< katex display >}} -f(x) = \int_{-\infty}^\infty\hat f(\xi)\,e^{2 \pi i \xi x}\,d\xi -{{< /katex >}} -Text continues here. diff --git a/content/docs/shortcodes/mermaid.md b/content/docs/shortcodes/mermaid.md deleted file mode 100644 index a8819d9f..00000000 --- a/content/docs/shortcodes/mermaid.md +++ /dev/null @@ -1,41 +0,0 @@ -# Mermaid Chart - -[MermaidJS](https://mermaid-js.github.io/) is library for generating svg charts and diagrams from text. - -{{< hint info >}} -**Override Mermaid Initialization Config** - -To override the [initialization config](https://mermaid-js.github.io/mermaid/#/Setup) for Mermaid, -create a `mermaid.json` file in your `assets` folder! -{{< /hint >}} - -## Example - -{{< columns >}} -{{< highlight tpl1 >}} -{{}} -stateDiagram-v2 - State1: The state with a note - note right of State1 - Important information! You can write - notes. - end note - State1 --> State2 - note left of State2 : This is the note to the left. -{{}} -{{< /highlight >}} - -<---> - -{{< mermaid >}} -stateDiagram-v2 - State1: The state with a note - note right of State1 - Important information! You can write - notes. - end note - State1 --> State2 - note left of State2 : This is the note to the left. -{{< /mermaid >}} - -{{< /columns >}} diff --git a/content/docs/shortcodes/p5/_index.md b/content/docs/shortcodes/p5/_index.md deleted file mode 100644 index 0cf152de..00000000 --- a/content/docs/shortcodes/p5/_index.md +++ /dev/null @@ -1,11 +0,0 @@ ---- -bookCollapseSection: true ---- - -# p5 - -`p5` helps add [p5 sketches](https://p5js.org/) into your book. There are two types of `p5` [shortcodes](https://gohugo.io/content-management/shortcodes/) according to the html element used to embed them. - -## Types - -{{
}} diff --git a/content/docs/shortcodes/p5/div.md b/content/docs/shortcodes/p5/div.md deleted file mode 100644 index 2277ea5f..00000000 --- a/content/docs/shortcodes/p5/div.md +++ /dev/null @@ -1,206 +0,0 @@ -p5 `div` [shortcodes](https://gohugo.io/content-management/shortcodes/) embed [p5.js](https://p5js.org/) code within a [div element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div). There are two p5 `div` shortcodes: [p5-div](#p5-div) and [p5-instance-div](#p5-instance-div). - -# p5-div - -```html -{{}} -``` - -All parameters are optional but `sketch`. Default values are shown in the above snippet but for `libs*`. Up to `lib5` libs may be specified. - -## Scintillating grid - -Look at [this](https://mathworld.wolfram.com/ScintillatingGridIllusion.html) and also [this](https://www.illusionsindex.org/i/scintillating-grid) among many more references there are. - -{{< details title="p5-div markdown" open=false >}} -{{< highlight html >}} -{{}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-div sketch="/showcase/sketches/scintillating.js" >}} - -# p5-instance-div - -```html -{{}} - // inline sketch code -{{< /p5-instance-div */>}} -``` - -{{< hint warning >}} -Note that the inline `sketch` should be coded in [p5 instance mode](https://github.com/processing/p5.js/wiki/Global-and-instance-mode) syntax. -{{< /hint >}} - -All parameters are optional but `id`. Default values are shown in the above snippet but for `libs*`. Up to `lib5` libs may be specified. - -## Lilac chaser - -Look at [this](https://en.wikipedia.org/wiki/Lilac_chaser) introductory reference. - -{{< details title="p5-instance-div markdown" open=false >}} -{{< highlight md >}} -{{}} - // Adapted from [this](https://github.com/VisualComputing/Cognitive/blob/gh-pages/sketches/lilacChaser.js) - let jump = 0; - let count = 0; - - p5.setup = function() { - p5.createCanvas(400, 400); - p5.frameRate(7); - }; - - function drawBlurCircles(x, y, r) { - p5.push(); - p5.noStroke(); - var opc = 0.4; - var step = 3.0/r; - - for (var i = r; i > 0; i-=1.5) { - if (opc < 5) { - opc += step; - p5.fill(255, 20, 180, opc); - } - p5.ellipse(x, y, i, i); - } - p5.pop(); - }; - - p5.draw = function() { - p5.background(200); - var numCircles = 12; - var stepAngle = 360.0/numCircles; - p5.push(); - p5.translate(p5.width/2.0, p5.height/2.0); - for (var i = 0; i < 360; i = i + stepAngle) { - if (i != jump) { - p5.push(); - p5.rotate(p5.radians(i)); - drawBlurCircles(120, 0, 60); - p5.pop(); - } - } - if( !p5.mouseIsPressed ) { - jump = (jump + stepAngle)%360; - } - p5.push(); - p5.strokeWeight(1.5); - p5.line(-7, 0, 7, 0); - p5.line(0, -7, 0, 7); - p5.pop(); - p5.pop(); - } -{{< /p5-instance-div */>}} -{{< /highlight >}} -{{< hint warning >}} -Note that `p5` should be the name to be used for the sketch object variable. -{{< /hint >}} -{{< /details >}} - -{{< p5-instance-div id="pacman" >}} - let jump = 0; - let count = 0; - - p5.setup = function() { - p5.createCanvas(380, 380); - p5.frameRate(7); - }; - - function drawBlurCircles(x, y, r) { - p5.push(); - p5.noStroke(); - var opc = 0.4; - var step = 3.0/r; - - for (var i = r; i > 0; i-=1.5) { - if (opc < 5) { - opc += step; - p5.fill(255, 20, 180, opc); - } - p5.ellipse(x, y, i, i); - } - p5.pop(); - }; - - p5.draw = function() { - p5.background(200); - var numCircles = 12; - var stepAngle = 360.0/numCircles; - p5.push(); - p5.translate(p5.width/2.0, p5.height/2.0); - for (var i = 0; i < 360; i = i + stepAngle) { - if (i != jump) { - p5.push(); - p5.rotate(p5.radians(i)); - drawBlurCircles(120, 0, 60); - p5.pop(); - } - } - if( !p5.mouseIsPressed ) { - jump = (jump + stepAngle)%360; - } - p5.push(); - p5.strokeWeight(1.5); - p5.line(-7, 0, 7, 0); - p5.line(0, -7, 0, 7); - p5.pop(); - p5.pop(); - } -{{< /p5-instance-div >}} - -## Video on canvas - -Adapted from [here](https://p5js.org/examples/dom-video-canvas.html). Don't forget to checkout also the [video on dom](https://p5js.org/examples/dom-video.html) example. - -{{< details title="p5-instance-div markdown" open=false >}} -{{< highlight md >}} -{{}} - let fingers; - - p5.setup = function() { - p5.createCanvas(710, 400); - // specify multiple formats for different browsers - fingers = p5.createVideo(['/showcase/sketches/fingers.mov', '/showcase/sketches/fingers.webm']); - fingers.hide(); // by default video shows up in separate dom - // element. hide it and draw it to the canvas instead - }; - - p5.draw = function() { - p5.background(150); - p5.image(fingers, 10, 10); // draw the video frame to canvas - p5.filter(p5.GRAY); - p5.image(fingers, 150, 150); // draw a second copy to canvas - }; - - p5.mousePressed = function() { - fingers.loop(); // set the video to loop and start playing - } -{{< /p5-instance-div */>}} -{{< /highlight >}} -{{< hint warning >}} -Note that `p5` should be the name to be used for the sketch object variable. -{{< /hint >}} -{{< /details >}} - -{{< p5-instance-div id="video" >}} - let fingers; - - p5.setup = function() { - p5.createCanvas(710, 400); - // specify multiple formats for different browsers - fingers = p5.createVideo(['/showcase/sketches/fingers.mov', '/showcase/sketches/fingers.webm']); - fingers.hide(); // by default video shows up in separate dom - // element. hide it and draw it to the canvas instead - }; - - p5.draw = function() { - p5.background(150); - p5.image(fingers, 10, 10); // draw the video frame to canvas - p5.filter(p5.GRAY); - p5.image(fingers, 150, 150); // draw a second copy to canvas - }; - - p5.mousePressed = function() { - fingers.loop(); // set the video to loop and start playing - } -{{< /p5-instance-div >}} \ No newline at end of file diff --git a/content/docs/shortcodes/p5/iframe.md b/content/docs/shortcodes/p5/iframe.md deleted file mode 100644 index 93dbe5a7..00000000 --- a/content/docs/shortcodes/p5/iframe.md +++ /dev/null @@ -1,176 +0,0 @@ -p5 `iframe` [shortcodes](https://gohugo.io/content-management/shortcodes/) embed [p5.js](https://p5js.org/) code within an [iframe element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe). There are two p5 `iframe` shortcodes: [p5-iframe](#p5-iframe) and [p5-global-iframe](#p5-global-iframe). - -# p5-iframe - -```html -{{}} -``` - -All parameters are optional but `sketch`. Default values are shown in the above snippet but for `libs*`. Up to `lib5` libs may be specified. - -## Color relativity - -Look at this [brief explanation](https://p5js.org/examples/color-relativity.html) about what color relativity is. - -{{< details title="p5-iframe markdown" open=false >}} -{{< highlight html >}} -{{}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-iframe sketch="/showcase/sketches/colors.js" width="725" height="425" >}} - -## Third party libraries - -Example adapted from [p5.EasyCam](https://github.com/freshfork/p5.EasyCam/blob/master/examples/QuickStart/QuickStart.js). - -{{< details title="p5-iframe markdown" open=false >}} -{{< highlight html >}} -{{}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-iframe sketch="/showcase/sketches/quick_easycam.js" lib1="https://cdn.jsdelivr.net/gh/freshfork/p5.EasyCam@1.2.1/p5.easycam.min.js" width="525" height="525" >}} - -## Sound - -Example took from the [p5 examples](https://p5js.org/examples/sound-sound-effect.html). - -{{< details title="p5-iframe markdown" open=false >}} -{{< highlight html >}} -{{}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-iframe sketch="/showcase/sketches/sound.js" width="225" height="225" >}} - -# p5-global-iframe - -```html -{{}} - // inline sketch code -{{< /p5-global-iframe */>}} -``` - -{{< hint warning >}} -Note that the inline `sketch` should be coded in [p5 global mode](https://github.com/processing/p5.js/wiki/Global-and-instance-mode) syntax. -{{< /hint >}} - -All parameters are optional but `id`. Default values are shown in the above snippet but for `libs*`. Up to `lib5` libs may be specified. - -## Breathing square - -Look at [this reference](https://michaelbach.de/ot/mot-breathingSquare/) for an explanation and further parameterization of the illusion. - -{{< details title="p5-global-iframe markdown" open=false >}} -{{< highlight html >}} -{{}} - // Coded as `global mode` of [this](https://github.com/VisualComputing/Cognitive/blob/gh-pages/sketches/rotateSquare.js) - let angle = 0; - let speed = 0.06; - - function setup() { - createCanvas(600, 600); - } - - function draw() { - background(255, 255, 255); - rotateSquare(); - if (!mouseIsPressed) { - strokeWeight(0); - stroke(0); - fill(255, 140, 0); - rect(0, 0, 281, 281); - rect(318, 0, 281, 281); - rect(0, 318, 281, 281); - rect(318, 318, 281, 281); - } - } - - function rotateSquare() { - push(); - angle += speed; - strokeWeight(0); - stroke(0); - fill(0, 0, 255); - translate(width / 2, height / 2); - rotate(angle); - rect(-187.5, -187.5, 375, 375); - pop(); - } -{{< /p5-global-iframe */>}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-global-iframe id="breath" width="625" height="625" >}} - let angle = 0; - let speed = 0.06; - - function setup() { - createCanvas(600, 600); - } - - function draw() { - background(255, 255, 255); - rotateSquare(); - if (!mouseIsPressed) { - strokeWeight(0); - stroke(0); - fill(255, 140, 0); - rect(0, 0, 281, 281); - rect(318, 0, 281, 281); - rect(0, 318, 281, 281); - rect(318, 318, 281, 281); - } - } - - function rotateSquare() { - push(); - angle += speed; - strokeWeight(0); - stroke(0); - fill(0, 0, 255); - translate(width / 2, height / 2); - rotate(angle); - rect(-187.5, -187.5, 375, 375); - pop(); - } -{{< /p5-global-iframe >}} - -# p5-widget - -The `p5-widget` [shortcode](https://gohugo.io/content-management/shortcodes/) embed [p5.js](https://p5js.org/) code within an [p5-widget](https://toolness.github.io/p5.js-widget/). - -```html -{{}} - // inline sketch code -{{< /p5-widget */>}} -``` - -All parameters are optional. Default `ver` is `1.4.2`. For example: - -## Widget example - -{{< details title="p5-widget markdown" open=false >}} -{{< highlight html >}} -{{}} -function setup() { - createCanvas(300, 300); -} - -function draw() { - background(255, 0, 255); -} -{{< /p5-widget */>}} -{{< /highlight >}} -{{< /details >}} - -{{< p5-widget autoplay=true height="400" width="400" ver="1.4.2" >}} -function setup() { - createCanvas(300, 300); -} - -function draw() { - background(255, 0, 255); -} -{{< /p5-widget >}} \ No newline at end of file diff --git a/content/docs/shortcodes/tabs.md b/content/docs/shortcodes/tabs.md deleted file mode 100644 index 096892c6..00000000 --- a/content/docs/shortcodes/tabs.md +++ /dev/null @@ -1,50 +0,0 @@ -# Tabs - -Tabs let you organize content by context, for example installation instructions for each supported platform. - -```tpl -{{}} -{{}} # MacOS Content {{}} -{{}} # Linux Content {{}} -{{}} # Windows Content {{}} -{{}} -``` - -## Example - -{{< tabs "uniqueid" >}} -{{< tab "MacOS" >}} -# MacOS - -This is tab **MacOS** content. - -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. -{{< /tab >}} - -{{< tab "Linux" >}} - -# Linux - -This is tab **Linux** content. - -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. -{{< /tab >}} - -{{< tab "Windows" >}} - -# Windows - -This is tab **Windows** content. - -Lorem markdownum insigne. Olympo signis Delphis! Retexi Nereius nova develat -stringit, frustra Saturnius uteroque inter! Oculis non ritibus Telethusa -protulit, sed sed aere valvis inhaesuro Pallas animam: qui _quid_, ignes. -Miseratus fonte Ditis conubia. -{{< /tab >}} -{{< /tabs >}} diff --git a/content/imgs/car.jpg b/content/imgs/car.jpg new file mode 100644 index 00000000..012b7455 Binary files /dev/null and b/content/imgs/car.jpg differ diff --git a/content/imgs/cars/000001.jpg b/content/imgs/cars/000001.jpg new file mode 100644 index 00000000..81c3beca Binary files /dev/null and b/content/imgs/cars/000001.jpg differ diff --git a/content/imgs/cars/000002.jpg b/content/imgs/cars/000002.jpg new file mode 100644 index 00000000..bdc74701 Binary files /dev/null and b/content/imgs/cars/000002.jpg differ diff --git a/content/imgs/cars/000003.jpg b/content/imgs/cars/000003.jpg new file mode 100644 index 00000000..a1f188c6 Binary files /dev/null and b/content/imgs/cars/000003.jpg differ diff --git a/content/imgs/cars/000004.jpg b/content/imgs/cars/000004.jpg new file mode 100644 index 00000000..7c877529 Binary files /dev/null and b/content/imgs/cars/000004.jpg differ diff --git a/content/imgs/cars/000005.jpg b/content/imgs/cars/000005.jpg new file mode 100644 index 00000000..8cecd983 Binary files /dev/null and b/content/imgs/cars/000005.jpg differ diff --git a/content/imgs/cars/000006.jpg b/content/imgs/cars/000006.jpg new file mode 100644 index 00000000..884f1e75 Binary files /dev/null and b/content/imgs/cars/000006.jpg differ diff --git a/content/imgs/cars/000007.jpg b/content/imgs/cars/000007.jpg new file mode 100644 index 00000000..8df38996 Binary files /dev/null and b/content/imgs/cars/000007.jpg differ diff --git a/content/imgs/cars/000008.jpg b/content/imgs/cars/000008.jpg new file mode 100644 index 00000000..ae9b67ce Binary files /dev/null and b/content/imgs/cars/000008.jpg differ diff --git a/content/imgs/cars/000009.jpg b/content/imgs/cars/000009.jpg new file mode 100644 index 00000000..00763ab2 Binary files /dev/null and b/content/imgs/cars/000009.jpg differ diff --git a/content/imgs/cars/000010.jpg b/content/imgs/cars/000010.jpg new file mode 100644 index 00000000..a942fa09 Binary files /dev/null and b/content/imgs/cars/000010.jpg differ diff --git a/content/imgs/cars/000011.jpg b/content/imgs/cars/000011.jpg new file mode 100644 index 00000000..710a1877 Binary files /dev/null and b/content/imgs/cars/000011.jpg differ diff --git a/content/imgs/cars/000012.jpg b/content/imgs/cars/000012.jpg new file mode 100644 index 00000000..713d1f79 Binary files /dev/null and b/content/imgs/cars/000012.jpg differ diff --git a/content/imgs/cars/000013.jpg b/content/imgs/cars/000013.jpg new file mode 100644 index 00000000..d13871d9 Binary files /dev/null and b/content/imgs/cars/000013.jpg differ diff --git a/content/imgs/cars/000014.jpg b/content/imgs/cars/000014.jpg new file mode 100644 index 00000000..7acf986f Binary files /dev/null and b/content/imgs/cars/000014.jpg differ diff --git a/content/imgs/cars/000015.jpg b/content/imgs/cars/000015.jpg new file mode 100644 index 00000000..c534a2aa Binary files /dev/null and b/content/imgs/cars/000015.jpg differ diff --git a/content/imgs/cars/000016.jpg b/content/imgs/cars/000016.jpg new file mode 100644 index 00000000..fba47777 Binary files /dev/null and b/content/imgs/cars/000016.jpg differ diff --git a/content/imgs/cars/000017.jpg b/content/imgs/cars/000017.jpg new file mode 100644 index 00000000..e67e02a6 Binary files /dev/null and b/content/imgs/cars/000017.jpg differ diff --git a/content/imgs/cars/000018.jpg b/content/imgs/cars/000018.jpg new file mode 100644 index 00000000..c8f5a25c Binary files /dev/null and b/content/imgs/cars/000018.jpg differ diff --git a/content/imgs/cars/000019.jpg b/content/imgs/cars/000019.jpg new file mode 100644 index 00000000..d000d1fb Binary files /dev/null and b/content/imgs/cars/000019.jpg differ diff --git a/content/imgs/cars/000020.jpg b/content/imgs/cars/000020.jpg new file mode 100644 index 00000000..d5e93587 Binary files /dev/null and b/content/imgs/cars/000020.jpg differ diff --git a/content/imgs/cars/000021.jpg b/content/imgs/cars/000021.jpg new file mode 100644 index 00000000..7b4db854 Binary files /dev/null and b/content/imgs/cars/000021.jpg differ diff --git a/content/imgs/cars/000022.jpg b/content/imgs/cars/000022.jpg new file mode 100644 index 00000000..b2fd72a9 Binary files /dev/null and b/content/imgs/cars/000022.jpg differ diff --git a/content/imgs/cars/000023.jpg b/content/imgs/cars/000023.jpg new file mode 100644 index 00000000..1e6fbb30 Binary files /dev/null and b/content/imgs/cars/000023.jpg differ diff --git a/content/imgs/cars/000024.jpg b/content/imgs/cars/000024.jpg new file mode 100644 index 00000000..15fbcd3e Binary files /dev/null and b/content/imgs/cars/000024.jpg differ diff --git a/content/imgs/cars/000025.jpg b/content/imgs/cars/000025.jpg new file mode 100644 index 00000000..9207f9b1 Binary files /dev/null and b/content/imgs/cars/000025.jpg differ diff --git a/content/imgs/cars/000026.jpg b/content/imgs/cars/000026.jpg new file mode 100644 index 00000000..3977672b Binary files /dev/null and b/content/imgs/cars/000026.jpg differ diff --git a/content/imgs/cars/000027.jpg b/content/imgs/cars/000027.jpg new file mode 100644 index 00000000..62af1107 Binary files /dev/null and b/content/imgs/cars/000027.jpg differ diff --git a/content/imgs/cars/000028.jpg b/content/imgs/cars/000028.jpg new file mode 100644 index 00000000..e5e14600 Binary files /dev/null and b/content/imgs/cars/000028.jpg differ diff --git a/content/imgs/cars/000029.jpg b/content/imgs/cars/000029.jpg new file mode 100644 index 00000000..466f8d7d Binary files /dev/null and b/content/imgs/cars/000029.jpg differ diff --git a/content/imgs/cars/000030.jpg b/content/imgs/cars/000030.jpg new file mode 100644 index 00000000..c026f8d3 Binary files /dev/null and b/content/imgs/cars/000030.jpg differ diff --git a/content/imgs/cars/000031.jpg b/content/imgs/cars/000031.jpg new file mode 100644 index 00000000..bafef81a Binary files /dev/null and b/content/imgs/cars/000031.jpg differ diff --git a/content/imgs/cars/000032.jpg b/content/imgs/cars/000032.jpg new file mode 100644 index 00000000..f7bb8881 Binary files /dev/null and b/content/imgs/cars/000032.jpg differ diff --git a/content/imgs/cars/000033.jpg b/content/imgs/cars/000033.jpg new file mode 100644 index 00000000..c77c0d83 Binary files /dev/null and b/content/imgs/cars/000033.jpg differ diff --git a/content/imgs/cars/000034.jpg b/content/imgs/cars/000034.jpg new file mode 100644 index 00000000..6de33739 Binary files /dev/null and b/content/imgs/cars/000034.jpg differ diff --git a/content/imgs/cars/000035.jpg b/content/imgs/cars/000035.jpg new file mode 100644 index 00000000..f1005cb0 Binary files /dev/null and b/content/imgs/cars/000035.jpg differ diff --git a/content/imgs/cars/000036.jpg b/content/imgs/cars/000036.jpg new file mode 100644 index 00000000..4d9d6163 Binary files /dev/null and b/content/imgs/cars/000036.jpg differ diff --git a/content/imgs/cars/000037.jpg b/content/imgs/cars/000037.jpg new file mode 100644 index 00000000..25fd38cb Binary files /dev/null and b/content/imgs/cars/000037.jpg differ diff --git a/content/imgs/cars/000038.jpg b/content/imgs/cars/000038.jpg new file mode 100644 index 00000000..bbe4426e Binary files /dev/null and b/content/imgs/cars/000038.jpg differ diff --git a/content/imgs/cars/000039.jpg b/content/imgs/cars/000039.jpg new file mode 100644 index 00000000..95b05329 Binary files /dev/null and b/content/imgs/cars/000039.jpg differ diff --git a/content/imgs/cars/000040.jpg b/content/imgs/cars/000040.jpg new file mode 100644 index 00000000..7ca4e4c5 Binary files /dev/null and b/content/imgs/cars/000040.jpg differ diff --git a/content/imgs/madusa.jpeg b/content/imgs/madusa.jpeg new file mode 100644 index 00000000..ade5de93 Binary files /dev/null and b/content/imgs/madusa.jpeg differ diff --git a/content/menu/index.md b/content/menu/index.md index dc3c1e8d..0977e140 100644 --- a/content/menu/index.md +++ b/content/menu/index.md @@ -11,4 +11,4 @@ headless: true - [Katex]({{< relref "/docs/shortcodes/katex" >}}) - [Mermaid]({{< relref "/docs/shortcodes/mermaid" >}}) - [Tabs]({{< relref "/docs/shortcodes/tabs" >}}) -
+
diff --git a/content/sketches/Acceleration.js b/content/sketches/Acceleration.js new file mode 100644 index 00000000..4a3f6e57 --- /dev/null +++ b/content/sketches/Acceleration.js @@ -0,0 +1,145 @@ +let fbo1, cam1, fovy +let P,B +let mouseInitialV,mouseCurrentV + +function Plane(){ + this.planeMaxMagR = 25; + this.planeColor = "black"; + this.planeMagnitudeR = 0; + + this.planeRotateV = createVector(1,0,0); + this.planeSize = createVector(100,100,0); //ancho y alto + this.planePosition = createVector(0,0,0); + + this.draw = function(fbo){ + fbo.push(); + fbo.fill(this.planeColor); + fbo.translate(this.planePosition); + fbo.plane(this.planeSize.x,this.planeSize.y) + fbo.pop() + }; +} + +function Ball(P){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0) + this.sphereRadius = 10; + this.spherePosition = createVector(0,0,this.sphereRadius); + + this.minVertex = createVector(-P.planeSize.x/2,-P.planeSize.y/2,0); + this.maxVertex = createVector(P.planeSize.x/2,P.planeSize.y/2,0); + + this.draw = function(fbo){ + fbo.push(); + fbo.fill("white"); + fbo.translate(this.spherePosition); + fbo.sphere(this.sphereRadius) + fbo.pop() + } +} + +function setup() { + + createCanvas(600, 600); + fbo1 = createGraphics(width, height, WEBGL); + + // FBO camera + cam1 = new Dw.EasyCam(fbo1._renderer, { distance: 200 }); + let state1 = cam1.getState(); + cam1.state_reset = state1; // state to use on reset (double-click/tap) + cam1.setViewport([0, 0, width / 2, height]); + document.oncontextmenu = function () { return false; } + + // scene interactions + fovy = createSlider(PI / 12, PI * (11 / 12), PI / 3, PI / 48); + fovy.position(10, 10); + fovy.style('width', '80px'); + + P = new Plane(); + B = new Ball(P); + +} + +function draw() { + + fbo1.background(120, 125, 115); + fbo1.reset(); + fbo1.perspective(fovy.value()); + fbo1.axes(); + fbo1.grid(); + fbo1.rotate((PI/180)*P.planeMagnitudeR, P.planeRotateV); + fbo1.strokeWeight(0.5) + + + P.draw(fbo1); + B.draw(fbo1); + + // movimiento de la esfera + if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + B.sphereMoveVector.x = (B.acceleration.x*0.15) + B.sphereMoveVector.x; + B.sphereMoveVector.y = (B.acceleration.y*0.15) + B.sphereMoveVector.y; + + B.spherePosition.x = (B.sphereMoveVector.x*0.15) + B.spherePosition.x + B.spherePosition.y = (B.sphereMoveVector.y*0.15) + B.spherePosition.y; + + }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + B.sphereMoveVector = createVector(0,0,0); + B.acceleration = createVector(0,0,0); + } + + //Colisión + if(B.spherePosition.x >= B.minVertex.x && + B.spherePosition.y >= B.minVertex.y && + B.spherePosition.z-10 >= B.minVertex.z && + B.spherePosition.x <= B.maxVertex.x && + B.spherePosition.y <= B.maxVertex.y && + B.spherePosition.z-10 <= B.maxVertex.z){ + + P.planeColor = "white" + } + else{ + P.planeColor = "black" + } + + + beginHUD(); + image(fbo1, 0, 0); + endHUD(); + +} + + +function getVectorModule(vector){ + return Math.sqrt(vector.x**2 +vector.y**2 +vector.z**2); +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0); +} + + +function mouseDragged(){ + + mouseCurrentV = createVector(mouseX, mouseY, 0); + let vectorSubstra = createVector(mouseInitialV.x - mouseCurrentV.x, + mouseInitialV.y - mouseCurrentV.y, + mouseInitialV.z - mouseCurrentV.z); + let mod = getVectorModule(vectorSubstra); + let vectorDir = createVector(vectorSubstra.x/mod, + vectorSubstra.y/mod, + vectorSubstra.z/mod ); + let sine = sqrt(1-sq(vectorDir.z)); + + B.acceleration = createVector(-sine*vectorDir.x, -sine*vectorDir.y, sine*vectorDir.z); + + let aux = vectorDir.x; + vectorDir.x = vectorDir.y; + vectorDir.y = -aux; + + if (mod < P.planeMaxMagR){ + P.planeMagnitudeR = mod + } + P.planeRotateV = vectorDir; + P.planeRotateV.z = 0; + +} \ No newline at end of file diff --git a/content/sketches/Inclination.js b/content/sketches/Inclination.js new file mode 100644 index 00000000..385d191a --- /dev/null +++ b/content/sketches/Inclination.js @@ -0,0 +1,129 @@ + + +let planePosition,planeSize,planeColor,planeRotateV,planeMagnitudeR,planeMaxMagR; +let spherePosition,sphereMoveVector,sphereRadius,maxVertex,minVertex; +let fbo1,cam1,length = 600,boxes,box_key; +let mouseInitialV,mouseCurrentV,fovy; + +const SPEED = 5; + +function createPlane(){ + planeMaxMagR = 25; + planeColor = "black"; + planeMagnitudeR = 0; + + planeRotateV = createVector(1,0,0) + planeSize = createVector(100,50,0) //ancho y alto + planePosition = createVector(0,0,0) +} + +function createSphere(){ + + sphereMoveVector = createVector(0,1,0); + sphereRadius = 10; + spherePosition = createVector(0,0,sphereRadius); + + minVertex = createVector(-planeSize.x/2,-planeSize.y/2,0); + maxVertex = createVector(planeSize.x/2,planeSize.y/2,0); +} + +function setup() { + + createCanvas(length, length); + fbo1 = createGraphics(width, height, WEBGL); + + // FBO camera + cam1 = new Dw.EasyCam(fbo1._renderer, { distance: 200 }); + let state1 = cam1.getState(); + cam1.state_reset = state1; // state to use on reset (double-click/tap) + cam1.setViewport([0, 0, width / 2, height]); + document.oncontextmenu = function () { return false; } + + //Interactive elements + createPlane(); + createSphere(); + + + // scene interactions + fovy = createSlider(PI / 12, PI * (11 / 12), PI / 3, PI / 48); + fovy.position(10, 10); + fovy.style('width', '80px'); +} + +function draw() { + //Background elements + fbo1.background(120, 125, 115); + fbo1.reset(); + fbo1.perspective(fovy.value()); + fbo1.axes(); + fbo1.grid(); + fbo1.rotate((PI/100)*planeMagnitudeR, planeRotateV) + + //Dibujar el plano + fbo1.push(); + fbo1.fill(planeColor); + fbo1.translate(planePosition); + fbo1.plane(planeSize.x,planeSize.y) + fbo1.pop() + + //Dibujar la esfera + fbo1.push(); + fbo1.fill("white"); + fbo1.translate(spherePosition); + fbo1.sphere(sphereRadius) + fbo1.pop() + + // movimiento de la esfera + if(keyIsPressed && key == "a"){ + spherePosition = createVector(sphereMoveVector.x*2+spherePosition.x, + sphereMoveVector.y*2+spherePosition.y, + sphereMoveVector.z*2+spherePosition.z) + //spherePosition.z += 1 + } + else if(keyIsPressed && key == "d"){ + spherePosition = createVector(sphereMoveVector.x*-2+spherePosition.x, + sphereMoveVector.y*-2+spherePosition.y, + sphereMoveVector.z*-2+spherePosition.z) + } + + //Colisión + if(spherePosition.x >= minVertex.x && spherePosition.y >= minVertex.y && spherePosition.z-10 >= minVertex.z && + spherePosition.x <= maxVertex.x && spherePosition.y <= maxVertex.y && spherePosition.z-10 <= maxVertex.z){ + planeColor = "white" + } + else{ + planeColor = "black" + } + beginHUD(); + image(fbo1, 0, 0); + endHUD(); + +} + +function getVectorModule(vector){ + return Math.sqrt(vector.x**2 +vector.y**2 +vector.z**2) +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0) +} + + +function mouseDragged(){ + mouseCurrentV = createVector(mouseX, mouseY, 0) + + let vectorSubstra = createVector(mouseInitialV.x - mouseCurrentV.x,mouseInitialV.y - mouseCurrentV.y,mouseInitialV.z - mouseCurrentV.z) + let mod = getVectorModule(vectorSubstra) + + let vectorDir = createVector(vectorSubstra.x/mod,vectorSubstra.y/mod,vectorSubstra.z/mod ) + sphereMoveVector = createVector(vectorDir.x, vectorDir.y, vectorDir.z) + + let aux = vectorDir.x + vectorDir.x = vectorDir.y + vectorDir.y = -aux + + if (mod < planeMaxMagR){ + planeMagnitudeR = mod + } + planeRotateV = vectorDir +} \ No newline at end of file diff --git a/content/sketches/Labyrinth.js b/content/sketches/Labyrinth.js new file mode 100644 index 00000000..e69de29b diff --git a/content/sketches/Que-es-paisaje.jpg b/content/sketches/Que-es-paisaje.jpg new file mode 100644 index 00000000..c6c421f5 Binary files /dev/null and b/content/sketches/Que-es-paisaje.jpg differ diff --git a/content/sketches/RGBmultiply.js b/content/sketches/RGBmultiply.js new file mode 100644 index 00000000..c8829239 --- /dev/null +++ b/content/sketches/RGBmultiply.js @@ -0,0 +1,31 @@ +let backgroundColor; +let color1, color2 +function setup() { + createCanvas(200, 200); + let c1 = createInput("0,0,0",'color') + let c2 = createInput("0,0,0",'color') + + + c1.input(()=> setColor1(c1,c2)) + c2.input(()=> setColor1(c1,c2)) +} + +function setColor1(c1,c2){ + let color1 = color(red(c1.value()), green(c1.value()), blue(c1.value())) + let black = color(0,0,0) + fill(color1) + rect(0,0, 130,130) + let color2 = color(red(c2.value()), green(c2.value()), blue(c2.value())) + fill(color2) + rect(70,70, 130,130) + + //let white = color(255,255,255) + + const cred = (red(c1.value()) * red(c2.value())) / 255; + const cblue = (blue(c1.value()) * blue(c2.value())) / 255; + const cgreen = (green(c1.value()) * green(c2.value())) /255; + fill(color(cred, cgreen,cblue)) + rect(70,70, 60,60) + //background(cred,cgreen,cblue) + +} \ No newline at end of file diff --git a/content/sketches/app.js b/content/sketches/app.js new file mode 100644 index 00000000..e97ed787 --- /dev/null +++ b/content/sketches/app.js @@ -0,0 +1,222 @@ +let maskShader; +let img; +let video_src; +let video_on; +let cam_src; +let cam_on; +let ColorT; + +let mask_mode; +let coloring; +let lenses; +//let maskmode; + +function preload() { + video_src = createVideo(['/visual_computing/vid/drift.mp4']); + video_src.hide(); + + cam_src = createCapture(VIDEO); + cam_src.size(width, height); + cam_src.hide(); + + maskShader = readShader('/visual_computing/sketches/shaders/mask.frag', { varyings: Tree.texcoords2 }); + img = loadImage('/visual_computing/imgs/car.jpg'); +} + +function setup() { + createCanvas(700, 700, WEBGL); + noStroke(); + textureMode(NORMAL); + + //Camera selector + cam_on = createCheckbox('Live', false); + cam_on.style('color','red'); + cam_on.position(10,50); + + //Camera Controls + cam_on.changed(() => { + if(cam_on.checked()){ + maskShader.setUniform('texture',cam_src); + }else{ + maskShader.setUniform('texture', img); + } + }); + + + //Video Controls + video_on = createCheckbox('Video', false); + video_on.style('color', 'red'); + video_on.position(10, 30); + + //Video & image Switcher + video_on.changed(() => { + if (video_on.checked()) { + maskShader.setUniform('texture', video_src); + video_src.loop(); + } else { + maskShader.setUniform('texture', img); + video_src.pause(); + } + }); + + //Mask controls + mask_mode = createCheckbox('Masks', false); + mask_mode.position(10, 10); + mask_mode.style('color', 'red'); + + //Coloring checkbox + coloring = createCheckbox('Coloring',false); + coloring.position(165, 10); + coloring.style('color','red'); + + //Lenses checkbox + lenses = createCheckbox('Lense',false); + lenses.position(360, 10); + lenses.style('color','red'); + + //Shader apply + shader(maskShader); + maskShader.setUniform('texture', img); + emitTexOffset(maskShader, img, 'texOffset'); + + //Kernel selector + sel = createSelect(); + sel.position(80, 10); + sel.option('None'); + sel.option('Edges'); + sel.option('Sharpen'); + sel.option('Box Blur'); + sel.option('Emboss'); + + + sel.selected('None'); + + //Coloring selector + selC = createSelect(); + selC.position(245, 10); + selC.option('None'); + selC.option('Luma'); + selC.option('Average'); + selC.option('HSV Value V'); + selC.option('HSL Value L'); + selC.option('Tint'); + + selC.selected('None'); + + //Color Picker + colorT = createColorPicker(color(255,255,255)); + colorT.position(175, 30); + + //lenses parameters + Rslider = createSlider(50.0, 150.0, 50.0); + Rslider.position(360, 30); + Rslider.style('width', '80px'); + let div1 = createDiv('Lens Radio'); + div1.style('font-size', '18px'); + div1.style('color', 'blue'); + div1.position(450, 30); + + Sslider = createSlider(0.0, 1.0, 0.0, 0.01); + Sslider.position(360, 50); + Sslider.style('width', '80px'); + let div2 = createDiv('Lens Amplitude'); + div2.style('font-size', '18px'); + div2.style('color', 'yellow'); + div2.position(450, 50); + +} + +function draw() { + background(0); + + //Mask Mode + if (mask_mode.checked()){ + + //Enable Masks Mode + maskShader.setUniform('maskmode',true); + maskShader.setUniform('coloringmode',false); + + //kernels + if (sel.value()=='Edges') { + maskShader.setUniform('mask', [-1, -1, -1, -1, 8, -1, -1, -1, -1]); + }else if(sel.value()=='Sharpen'){ + maskShader.setUniform('mask', [0, -1, 0, -1, 5, -1, 0, -1, 0]); + }else if(sel.value()=='Box Blur'){ + maskShader.setUniform('mask', [1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9]); + }else if(sel.value()=='Emboss'){ + maskShader.setUniform('mask', [-2, -1, 0, -1, 1, 1, 0, 1, 2]); + }else{ + maskShader.setUniform('mask', [0, 0, 0, 0, 1, 0, 0, 0, 0]); + } + + }else if(coloring.checked()){ + + + //Enable Coloring Mode + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',true); + + if(selC.value()=="None"){ + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('average',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value()=="Luma"){ + maskShader.setUniform('grey_scale',true); + maskShader.setUniform('average',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value()=="Average"){ + maskShader.setUniform('average',true); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="HSV Value V"){ + maskShader.setUniform('HSVV',true); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="HSL Value L"){ + maskShader.setUniform('HSLL',true); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + maskShader.setUniform('Tint',false); + + }else if(selC.value() =="Tint"){ + maskShader.setUniform('Tint',true); + maskShader.setUniform('HSLL',false); + maskShader.setUniform('HSVV',false); + maskShader.setUniform('average',false); + maskShader.setUniform('grey_scale',false); + + let RC = colorT.color(); + maskShader.setUniform('colorT',[red(RC),green(RC),blue(RC),1.0]); + } + + }else if(lenses.checked()){ + maskShader.setUniform('lensemode',true); + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',false); + + maskShader.setUniform('mouseData',[mouseX,mouseY]); + maskShader.setUniform('resolution',[width,height]); + maskShader.setUniform('radio', Rslider.value()); + maskShader.setUniform('scale', Sslider.value()); + }else{ + maskShader.setUniform('lensemode',false); + maskShader.setUniform('maskmode',false); + maskShader.setUniform('coloringmode',false); + } + + + quad(-width / 2, -height / 2, width / 2, -height / 2, width / 2, height / 2, -width / 2, height / 2); +} \ No newline at end of file diff --git a/content/sketches/bubbleCatC.png b/content/sketches/bubbleCatC.png new file mode 100644 index 00000000..f36b0a93 Binary files /dev/null and b/content/sketches/bubbleCatC.png differ diff --git a/content/sketches/colores.jpg b/content/sketches/colores.jpg new file mode 100644 index 00000000..3338c5b8 Binary files /dev/null and b/content/sketches/colores.jpg differ diff --git a/content/sketches/convolutions.js b/content/sketches/convolutions.js new file mode 100644 index 00000000..a8c92a61 --- /dev/null +++ b/content/sketches/convolutions.js @@ -0,0 +1,246 @@ +var img,kernel; +let channelsMap,RedMat,BlueMat,GreenMat,newChannels,fMap; + +function preload() { + img = loadImage('/visual_computing/sketches/bubbleCatC.png'); +} + +function setup() { + createCanvas(600,600); + noLoop(); + + //Boton de Recarga + button = createButton('Aplicar Kernel'); + button.position(135, 10); + button.mousePressed(reload); + + //Cambiar el kernel + slider = createSlider(1, 8, 1, 1); + slider.position(10, 10); + slider.style('width', '120px'); +} + +//Calcular el producto punto +function ppunto(Pix,Ker){ + let sum = 0; + for(let x = 0;x < Ker.length;x++){ + sum = sum + (Pix[x]*Ker[x]) + } + return sum; +} + +//Dividimos los canales en arreglos individuales +function ChannelDivider(ImgArr){ + let imgRed = [], imgGreen = [], imgBlue = [], imgAlpha = []; + for(let i = 0; i < ImgArr.length ; i+=4){ + imgRed.push(ImgArr[i]); + imgGreen.push(ImgArr[i+1]); + imgBlue.push(ImgArr[i+2]); + imgAlpha.push(ImgArr[i+3]); + } + return [imgRed,imgGreen,imgBlue,imgAlpha] +} + +//Recomponer la imagen +function ChannelComposer(R,G,B,A){ + let imageChannels = []; + for(let i = 0; i < A.length*4 ; i+=4){ + imageChannels[i] = R[i/4]; + imageChannels[i+1] = G[i/4]; + imageChannels[i+2] = B[i/4]; + imageChannels[i+3] = A[i/4]; + } + return imageChannels; +} + +//separar los arreglos para hacer una matriz +function ArraySplice(arr,dim){ + var matrix = [], i, k; + for (i = 0, k = -1; i < arr.length; i++) { + if (i % dim === 0) { + k++; + matrix[k] = []; + } + matrix[k].push(arr[i]); + } + return matrix; +} +//Reescribir el arreglo como matriz +function dimensioner(LTM){ + var extended = []; + for(let r = 0; r < LTM.length ; r++){ + for(let c = 0; c < LTM[r].length; c++){ + //Si estoy en el primer pixel + if(r==0 && c==0){ + extended.push( + [0,0,0, + 0,LTM[r][c],LTM[r][c+1], + 0,LTM[r+1][c],LTM[r+1][c+1]] + ); + }else + //si estoy en la primer fila + if(r==0 && (c>0 && c!=LTM[r].length - 1)){ + extended.push( + [0,0,0, + LTM[r][c-1],LTM[r][c],LTM[r][c+1], + LTM[r+1][c-1],LTM[r+1][c],LTM[r+1][c+1]] + ); + }else + //Si estoy en el el ultimo pixel de una fila + if(r==0 && c==LTM[r].length - 1){ + extended.push( + [0,0,0, + LTM[r][c-1],LTM[r][c],0, + LTM[r+1][c-1],LTM[r+1][c],0] + ); + }else + + //si estoy en el primer pixel de una columna + if((r>0 && r0 && r0 && c 100){ + translate(p5.Vector.fromAngle(millis() / 1000, 12.5)); + strokeWeight(0) + circle(200,200, size); + cirrcle(size-25) + }else if(size>0){ + translate(p5.Vector.fromAngle(millis() / 1000, -12.5)); + circle(200,200, size); + cirrcle(size-25) + } + return +} \ No newline at end of file diff --git a/content/sketches/libraries/p5.quadrille.js b/content/sketches/libraries/p5.quadrille.js new file mode 100644 index 00000000..eb3d11b0 --- /dev/null +++ b/content/sketches/libraries/p5.quadrille.js @@ -0,0 +1,1309 @@ +/*************************************************************************************** + * p5.quadrille.js + * Copyright (c) 2021 Universidad Nacional de Colombia + * @author Jean Pierre Charalambos, https://github.com/objetos/p5.quadrille.js/ + * Released under the terms of the GPLv3, refer to: http://www.gnu.org/licenses/gpl.html + * + * In geometry, the square-tiling, square-tessellation or square-grid is a + * regular tiling of the Euclidean plane. + * + * John Horton Conway called it a quadrille. + * + * The internal angle of the square is 90 degrees so four squares at a point + * make a full 360 degrees. It is one of three regular tilings of the plane. + * The other two are the triangular-tiling and the hexagonal-tiling. + * + * Refer to the [wikipedia square tiling](https://en.wikipedia.org/wiki/Square_tiling) + * article for details. + ***************************************************************************************/ + +class Quadrille { + /** + * Current library version. + */ + static version = "0.9.2"; + + /** + * Default background used in sort. + */ + static BACKGROUND = "white"; + + /** + * Default drawing char color. + */ + static CHAR_COLOR = "cyan"; + + /** + * Default drawing number color. + */ + static NUMBER_COLOR = "orange"; + + /** + * Default drawing outline. + */ + static OUTLINE = "magenta"; + + /** + * Default drawing outline weight. + */ + static OUTLINE_WEIGHT = 2; + + /** + * Default drawing cell length. + */ + static CELL_LENGTH = 100; + + /** + * @param {Quadrille} quadrille1 + * @param {Quadrille} quadrille2 + * @param {number} row respect to quadrille1 origin + * @param {number} col respect to quadrille1 origin + * @returns {Quadrille} the smallest Quadrille obtained after applying a logic AND operation on the two given quadrilles. + */ + static AND(quadrille1, quadrille2, row = 0, col = 0) { + return this.OP( + quadrille1, + quadrille2, + (q1, q2) => { + if (q1 && q2) { + return q1; + } + }, + row, + col + ); + } + + /** + * @param {Quadrille} quadrille1 + * @param {Quadrille} quadrille2 + * @param {number} row respect to quadrille1 origin + * @param {number} col respect to quadrille1 origin + * @returns {Quadrille} the smallest Quadrille obtained after applying a logic OR operation on the two given quadrilles. + */ + static OR(quadrille1, quadrille2, row = 0, col = 0) { + return this.OP( + quadrille1, + quadrille2, + (q1, q2) => { + if (q1) { + return q1; + } + if (q2) { + return q2; + } + }, + row, + col + ); + } + + /** + * @param {Quadrille} quadrille1 + * @param {Quadrille} quadrille2 + * @param {number} row respect to quadrille1 origin + * @param {number} col respect to quadrille1 origin + * @returns {Quadrille} the smallest Quadrille obtained after applying a logic XOR operation on the two given quadrilles. + */ + static XOR(quadrille1, quadrille2, row = 0, col = 0) { + return this.OP( + quadrille1, + quadrille2, + (q1, q2) => { + if (q1 && !q2) { + return q1; + } + if (!q1 && q2) { + return q2; + } + }, + row, + col + ); + } + + /** + * @param {Quadrille} quadrille1 + * @param {Quadrille} quadrille2 + * @param {number} row respect to quadrille1 origin + * @param {number} col respect to quadrille1 origin + * @returns {Quadrille} the smallest Quadrille obtained after applying a logic DIFF operation on the two given quadrilles. + */ + static DIFF(quadrille1, quadrille2, row = 0, col = 0) { + return this.OP( + quadrille1, + quadrille2, + (q1, q2) => { + if (q1 && !q2) { + return q1; + } + }, + row, + col + ); + } + + /** + * @param {Quadrille} quadrille + * @param {p5.Image | p5.Color Array | string | number} pattern used to fill the returned quadrille. + * @returns {Quadrille} the Quadrille obtained after applying a logic NEG operation on the given quadrille. + */ + static NEG(quadrille, pattern) { + let result = new Quadrille(quadrille.width, quadrille.height); + for (let i = 0; i < quadrille.height; i++) { + for (let j = 0; j < quadrille.width; j++) { + if (!quadrille._memory2D[i][j]) { + result._memory2D[i][j] = pattern; + } + } + } + return result; + } + + /** + * @param {Quadrille} quadrille1 + * @param {Quadrille} quadrille2 + * @param {Function} operator function implementing the logic operator. + * @param {number} row respect to quadrille1 origin + * @param {number} col respect to quadrille1 origin + * @returns {Quadrille} the smallest Quadrille obtained after applying the logic operator on the two given quadrilles. + */ + static OP(quadrille1, quadrille2, operator, row = 0, col = 0) { + // i. create resulted quadrille + let quadrille = new Quadrille( + col < 0 + ? Math.max(quadrille2.width, quadrille1.width - col) + : Math.max(quadrille1.width, quadrille2.width + col), + row < 0 + ? Math.max(quadrille2.height, quadrille1.height - row) + : Math.max(quadrille1.height, quadrille2.height + row) + ); + // ii. fill result with passed quadrilles + for (let i = 0; i < quadrille._memory2D.length; i++) { + for (let j = 0; j < quadrille._memory2D[i].length; j++) { + let result = operator( + quadrille1.read(row < 0 ? i + row : i, col < 0 ? j + col : j), + quadrille2.read(row > 0 ? i - row : i, col > 0 ? j - col : j) + ); + if (result) { + quadrille._memory2D[i][j] = result; + } + } + } + // iii. return resulted quadrille + return quadrille; + } + + /** + * Constructs either an empty or a filled quadrille: + * 1. Pass string. + * 2. Pass array or matrix of patterns (p5 colors, 4-length color arrays, chars, emojis and numbers). + * 3. Pass width and string. + * 4. Pass width and an array of patterns (p5 colors, 4-length color arrays, chars, emojis and numbers). + * 5. Pass width and heigth to construct and empty quadrille (filled with 0's). + * 6. Pass width and image, to construct a quadrille filled image. + * 7. Pass width, bitboard and pattern, to construct a quadrille filled with pattern from the given bitboard. + * 8. Pass width, height, order and pattern, to construct a quadrille filled with pattern of the given order. + * @see from + * @see rand + * @see order + */ + constructor() { + if (arguments.length === 1) { + if (typeof arguments[0] === "string") { + this._init1D([...arguments[0]]); + return; + } + if (Array.isArray(arguments[0])) { + if (!Array.isArray(arguments[0][0])) { + this._init1D(arguments[0]); + return; + } + let memory2D = arguments[0].map((array) => { + return array.slice(); + }); + let width; + for (const entry of memory2D) { + if (!Array.isArray(entry)) { + throw new Error("Not 2D Array"); + } + if (!width) { + width = entry.length; + } else if (width < entry.length) { + width = entry.length; + } + } + for (let i = 0; i < memory2D.length; i++) { + memory2D[i] = this._format(memory2D[i], width); + } + this._memory2D = memory2D; + return; + } + } + if (arguments.length === 2 && typeof arguments[0] === "number") { + if (typeof arguments[1] === "string") { + this._init1D([...arguments[1]], arguments[0]); + return; + } + if (Array.isArray(arguments[1])) { + this._init1D(arguments[1], arguments[0]); + return; + } + } + if ( + arguments.length === 2 && + typeof arguments[0] === "number" && + typeof arguments[1] === "number" + ) { + this._memory2D = Array(arguments[1]) + .fill() + .map(() => Array(arguments[0]).fill(0)); + return; + } + if ( + arguments.length === 2 && + typeof arguments[0] === "number" && + typeof arguments[1] !== "number" + ) { + this._memory2D = Array( + Math.round((arguments[0] * arguments[1].height) / arguments[1].width) + ) + .fill() + .map(() => Array(arguments[0]).fill(0)); + this.from(arguments[1]); + return; + } + if ( + arguments.length === 3 && + typeof arguments[0] === "number" && + typeof arguments[1] === "number" + ) { + this._memory2D = Array( + Math.ceil(arguments[1].toString(2).length / arguments[0]) + ) + .fill() + .map(() => Array(arguments[0]).fill(0)); + this.from(arguments[1], arguments[2]); + return; + } + if ( + arguments.length === 4 && + typeof arguments[0] === "number" && + typeof arguments[1] === "number" && + typeof arguments[2] === "number" + ) { + this._memory2D = Array(arguments[1]) + .fill() + .map(() => Array(arguments[0]).fill(0)); + this.rand(arguments[2], arguments[3]); + return; + } + } + + _init1D(memory1D, width = memory1D.length) { + let height = Math.ceil(memory1D.length / width); + this._memory2D = new Array(height); + for (let i = 0; i < height; i++) { + let start = width * i; + let end = start + width; + this._memory2D[i] = this._format(memory1D.slice(start, end), width); + } + } + + _format(memory1D, size) { + for (let i = 0; i < memory1D.length; i++) { + if ( + typeof memory1D[i] !== "number" && + typeof memory1D[i] !== "string" && + !Array.isArray(memory1D[i]) && + !(memory1D[i] instanceof p5.Color) && + !(memory1D[i] instanceof p5.Image) + ) { + memory1D[i] = 0; + } + } + if (memory1D.length < size) { + return memory1D.concat(new Array(size - memory1D.length).fill(0)); + } + return memory1D; + } + + /** + * Converts image (p5.Image) or bitboard (integer) to quadrille. Forms: + * 1. from(image); or, + * 2. from(bitboard, pattern) where pattern may be either a p5.Image, p5.Color, + * a 4-length color array, a string (emoji) or a number. + */ + from() { + if (arguments.length === 1 && arguments[0] instanceof p5.Image) { + // a. image + /* + // 1st method uses image.resize + let image = new p5.Image(arguments[0].width, arguments[0].height); + image.copy(arguments[0], 0, 0, arguments[0].width, arguments[0].height, + 0, 0, arguments[0].width, arguments[0].height); + image.resize(this.width, this.height); + image.loadPixels(); + for (let i = 0; i < image.pixels.length / 4; i++) { + let r = image.pixels[4 * i]; + let g = image.pixels[4 * i + 1]; + let b = image.pixels[4 * i + 2]; + let a = image.pixels[4 * i + 3]; + let _ = this._fromIndex(i); + this._memory2D[_.row][_.col] = [r, g, b, a]; + } + image.updatePixels(); + // */ + // /* + // 2nd method seems to give better visual results + let image = arguments[0]; + image.loadPixels(); + let r = Array(this.height) + .fill() + .map(() => Array(this.width).fill(0)); + let g = Array(this.height) + .fill() + .map(() => Array(this.width).fill(0)); + let b = Array(this.height) + .fill() + .map(() => Array(this.width).fill(0)); + let a = Array(this.height) + .fill() + .map(() => Array(this.width).fill(0)); + let t = Array(this.height) + .fill() + .map(() => Array(this.width).fill(0)); + for (let i = 0; i < image.pixels.length / 4; i++) { + let _ = this._fromIndex(i, image.width); + let _i = Math.floor((_.row * this.height) / image.height); + let _j = Math.floor((_.col * this.width) / image.width); + r[_i][_j] += image.pixels[4 * i]; + g[_i][_j] += image.pixels[4 * i + 1]; + b[_i][_j] += image.pixels[4 * i + 2]; + a[_i][_j] += image.pixels[4 * i + 3]; + t[_i][_j] += 1; + } + image.updatePixels(); + for (let i = 0; i < this.height; i++) { + for (let j = 0; j < this.width; j++) { + this._memory2D[i][j] = [ + r[i][j] / t[i][j], + g[i][j] / t[i][j], + b[i][j] / t[i][j], + a[i][j] / t[i][j], + ]; + } + } + // */ + } + // b. bitboard, pattern + if (arguments.length === 2 && typeof arguments[0] === "number") { + let length = this.width * this.height; + let bitboard = Math.abs(Math.round(arguments[0])); + if (bitboard.toString(2).length > length) { + throw new Error("Value is to high to fill quadrille"); + } + for (let i = 0; i <= length - 1; i++) { + if (bitboard & (1 << (length - 1 - i))) { + this._memory2D[this._fromIndex(i).row][this._fromIndex(i).col] = + arguments[1]; + } + } + } + } + + _fromIndex(index, width = this.width) { + return { row: (index / width) | 0, col: index % width }; + } + + _toIndex(row, col, width = this.width) { + return row * width + col; + } + + /** + * @returns {number} integer representation using big-endian and row-major ordering + * of the quadrille entries. + */ + toInt() { + let result = 0; + for (let i = 0; i < this.height; i++) { + for (let j = 0; j < this.width; j++) { + if (this._memory2D[i][j]) { + result += Math.pow(2, this.width * (this.height - i) - (j + 1)); + } + } + } + return result; + } + + /** + * @returns {Array} Quadrille representation. + */ + toArray() { + let memory2D = this.clone()._memory2D; + let result = new Array(); + for (let i = 0; i < memory2D.length; i++) { + result = result.concat(memory2D[i]); + } + return result; + } + + /** + * @returns {Array} Quadrille matrix (Array2D) representation. + */ + toMatrix() { + return this.clone()._memory2D; + } + + // TODO toAscii() + + /** + * @returns {number} quadrille width, i.e., number of columns. + */ + get width() { + return this._memory2D[0].length; + } + + /** + * @returns {number} quadrille height, i.e., number of rows. + */ + get height() { + return this._memory2D.length; + } + + /** + * @returns {number} width * height. + */ + get size() { + return this.width * this.height; + } + + /** + * @returns {number} Number of non-empty quadrille cells. + */ + get order() { + let result = 0; + for (let i = 0; i < this.height; i++) { + for (let j = 0; j < this.width; j++) { + if (this._memory2D[i][j]) { + result++; + } + } + } + return result; + } + + /** + * @param {number} row. + * @returns {number} Number of non-empty quadrille cells at row. + */ + magnitude(row) { + let result = 0; + for (let j = 0; j < this.width; j++) { + if (this._memory2D[row][j]) { + result++; + } + } + return result; + } + + // TODO isPolyomino + + /** + * Search pattern1 and replaces with pattern2, pattern1 and pattern2 may be + * either a p5.Image, p5.Color, a 4-length color array, a string (emoji) or a number. + */ + replace(pattern1, pattern2) { + for (let i = 0; i < this.height; i++) { + for (let j = 0; j < this.width; j++) { + if (this._memory2D[i][j] === pattern1) { + this._memory2D[i][j] = pattern2; + } + } + } + } + + /** + * Fills quadrille cells with given pattern. Either: + * 1. fill(pattern), fills current filled cells; + * 2. fill(row, pattern), fills row; or, + * 3. fill(row, col, pattern), fills cell. + * pattern may be either a p5.Image, a p5.Color, a 4-length color array, a string (emoji) or a number. + */ + fill() { + if (arguments.length === 1) { + for (let i = 0; i < this.height; i++) { + for (let j = 0; j < this.width; j++) { + if (this._memory2D[i][j]) { + this._memory2D[i][j] = arguments[0]; + } + } + } + } + if (arguments.length === 2 && typeof arguments[0] === "number") { + if (arguments[0] >= 0 && arguments[0] < this.height) { + this._memory2D[arguments[0]].fill(arguments[1]); + } + } + if ( + arguments.length === 3 && + typeof arguments[0] === "number" && + typeof arguments[1] === "number" + ) { + if ( + arguments[0] >= 0 && + arguments[0] < this.height && + arguments[1] >= 0 && + arguments[1] < this.width + ) { + this._memory2D[arguments[0]][arguments[1]] = arguments[2]; + } + } + } + + /** + * @param {number} row + * @param {number} col + * @returns {p5.Image | p5.Color | Array | string | number} quadrille entry + */ + read(row, col) { + if (row >= 0 && row < this.height && col >= 0 && col < this.width) { + return this._memory2D[row][col]; + } + } + + /** + * Convolutes this quadrille against the quadrille kernel mask. kernel weights + * may be encoded within the quadrille mask, both numerically or using colors. + * Luma is used in the latter case to convert colors to weights. Forms: + * 1. filter(mask) convolutes the whole quadrille or, + * 2. filter(mask, i, j) convolutes the whole quadrille at i, j. Both i and j + * should be greater or equal than the mask half_size which is computed as: + * (mask.width - 1) / 2). + * @params {Quadrille} nxn (n is odd) quadrille convolution kernel mask. + * @param {number} row if 0 convolutes the whole quadrille + * @param {number} col if 0 convolutes the whole quadrille + */ + filter(mask, row = 0, col = 0) { + if ( + mask.size % 2 === 1 && + mask.width === mask.height && + this.size >= mask.size + ) { + let half_size = (mask.width - 1) / 2; + if (row == 0 || col == 0) { + for (let i = half_size; i < this.height - half_size; i++) { + for (let j = half_size; j < this.width - half_size; j++) { + this._conv(mask, i, j, half_size); + } + } + } else { + this._conv(mask, row, col, half_size); + } + } + } + + _conv(mask, row, col, cache_half_size = (mask.width - 1) / 2) { + if ( + row >= cache_half_size && + col >= cache_half_size && + row < this.height - cache_half_size && + col < this.width - cache_half_size + ) { + let r = 0; + let g = 0; + let b = 0; + for (let imask = 0; imask < mask.height; imask++) { + for (let jmask = 0; jmask < mask.width; jmask++) { + let i = row + imask - cache_half_size; + let j = col + jmask - cache_half_size; + let neighbour = this._memory2D[i][j]; + let mask_value = mask._memory2D[imask][jmask]; + if ( + (neighbour instanceof p5.Color || Array.isArray(neighbour)) && + typeof mask_value !== "string" && + !(mask_value instanceof p5.Image) + ) { + // luma coefficients are: 0.299, 0.587, 0.114, 0 + let weight = + typeof mask_value === "number" + ? mask_value + : 0.299 * red(mask_value) + + 0.587 * green(mask_value) + + 0.114 * blue(mask_value); + r += red(neighbour) * weight; + g += green(neighbour) * weight; + b += blue(neighbour) * weight; + } + } + } + r = constrain(r, 0, 255); + g = constrain(g, 0, 255); + b = constrain(b, 0, 255); + //this._memory2D[row][col] = [r, g, b]; + this._memory2D[row][col] = color(r, g, b); + } + } + + /** + * Rasterize the (row0, col0), (row1, col1), (row2, col2) triangle, + * using pattern0, pattern1 and pattern2 vertex patterns, respectively. + */ + rasterize( + row0, + col0, + row1, + col1, + row2, + col2, + pattern0, + pattern1 = pattern0, + pattern2 = pattern0 + ) { + if ( + (pattern0 instanceof p5.Color || Array.isArray(pattern0)) && + (pattern1 instanceof p5.Color || Array.isArray(pattern1)) && + (pattern2 instanceof p5.Color || Array.isArray(pattern2)) + ) { + for (let i = 0; i < this.height; i++) { + for (let j = 0; j < this.width; j++) { + let coords = this._barycentric_coords( + j, + i, + row0, + col0, + row1, + col1, + row2, + col2 + ); + if (coords.w0 >= 0 && coords.w1 >= 0 && coords.w2 >= 0) { + let r = + red(pattern0) * coords.w0 + + red(pattern1) * coords.w1 + + red(pattern2) * coords.w2; + let g = + green(pattern0) * coords.w0 + + green(pattern1) * coords.w1 + + green(pattern2) * coords.w2; + let b = + blue(pattern0) * coords.w0 + + blue(pattern1) * coords.w1 + + blue(pattern2) * coords.w2; + let a = + alpha(pattern0) * coords.w0 + + alpha(pattern1) * coords.w1 + + alpha(pattern2) * coords.w2; + //this._memory2D[i][j] = [r, g, b, a]; + this._memory2D[i][j] = color(r, g, b, a); + } + } + } + } + } + + /** + * Returns the (row0, col0), (row1, col1), (row2, col2) triangle + * barycentric coordinates at (row, col) as the {w0, w1, w2} object literal. + */ + _barycentric_coords(row, col, row0, col0, row1, col1, row2, col2) { + let edges = this._edge_functions( + row, + col, + row0, + col0, + row1, + col1, + row2, + col2 + ); + let area = this._parallelogram_area(row0, col0, row1, col1, row2, col2); + return { w0: edges.e12 / area, w1: edges.e20 / area, w2: edges.e01 / area }; + } + + /** + * Returns the parallelogram signed area spawn by the + * (row0, col0), (row1, col1), (row2, col2) triangle. + */ + _parallelogram_area(row0, col0, row1, col1, row2, col2) { + return (col1 - col0) * (row2 - row0) - (col2 - col0) * (row1 - row0); + } + + /** + * Returns the (row0, col0), (row1, col1), (row2, col2) triangle edge_functions + * at (row, col) as the {e01, e12, e20} object literal. + */ + _edge_functions(row, col, row0, col0, row1, col1, row2, col2) { + let e01 = + (row0 - row1) * col + (col1 - col0) * row + (col0 * row1 - row0 * col1); + let e12 = + (row1 - row2) * col + (col2 - col1) * row + (col1 * row2 - row1 * col2); + let e20 = + (row2 - row0) * col + (col0 - col2) * row + (col2 * row0 - row2 * col0); + return { e01, e12, e20 }; + } + + // TODO perlin noise + + /** + * Randomly fills quadrille with pattern up to order. + * @param {number} order + * @param {p5.Image | p5.Color | Array | string | number} pattern + * @see order + */ + rand(order, pattern) { + order = Math.abs(order); + if (order > this.size) { + order = this.size; + } + let disorder = this.order; + let counter = 0; + while (counter < Math.abs(order - disorder)) { + let _ = this._fromIndex(Math.floor(Math.random() * this.size)); + if ( + order > disorder + ? !this._memory2D[_.row][_.col] + : this._memory2D[_.row][_.col] + ) { + this._memory2D[_.row][_.col] = order > disorder ? pattern : 0; + counter++; + } + } + } + + /** + * Randomly re-arranges cell entries. + */ + randomize() { + let clone = this.clone(); + this.clear(); + for (let i = 0; i < clone.height; i++) { + for (let j = 0; j < clone.width; j++) { + if (clone._memory2D[i][j]) { + let _i, _j; + do { + _i = int(random(this.height)); + _j = int(random(this.width)); + } while (this._memory2D[_i][_j]); + this._memory2D[_i][_j] = clone._memory2D[i][j]; + } + } + } + } + + /** + * Inserts an empty row. + * @param {number} row + */ + insert(row) { + this._memory2D.splice(row, 0, Array(this.width).fill(0)); + } + + /** + * Deletes the given row. + * @param {number} row + */ + delete(row) { + if (this.height > 1 && row >= 0 && row < this.height) { + this._memory2D.splice(row, 1); + } + } + + /** + * Fill this quadrille memory entries with 0's. Pass number to clear + * only the given row. Pass no params to clear all the quadrille. + */ + clear() { + if (arguments.length === 0) { + this._memory2D = this._memory2D.map((x) => x.map((y) => (y = 0))); + } + if (arguments.length === 1 && typeof arguments[0] === "number") { + this._memory2D[arguments[0]].fill(0); + } + } + + /** + * Horizontal reflection. + */ + reflect() { + this._memory2D.reverse(); + } + + /** + * Transpose the quadrille. + */ + transpose() { + // credit goes to Fawad Ghafoor + // who wrote about it here: https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript + this._memory2D = this._memory2D[0].map((_, i) => + this._memory2D.map((row) => row[i]) + ); + } + + /** + * π/2 clockwise rotation. + */ + rotate() { + // credit goes to Nitin Jadhav: https://github.com/nitinja + // who wrote about it here: https://stackoverflow.com/questions/15170942/how-to-rotate-a-matrix-in-an-array-in-javascript/58668351#58668351 + this._memory2D = this._memory2D[0].map((_, i) => + this._memory2D.map((row) => row[i]).reverse() + ); + } + + /** + * Returns a shallow copy of this quadrille. May be used in conjunction with + * {@link reflect} and {@link rotate} to create different quadrille instances. + */ + clone() { + return new Quadrille( + this._memory2D.map((array) => { + return array.slice(); + }) + ); + } + + /** + * Sort cells according to their coloring. Modes are: 'LUMA', 'AVG' and 'DISTANCE' (to a given target). + */ + sort({ + mode = "LUMA", + target = "magenta", + ascending = true, + charColor = "black", + background = this.BACKGROUND, + cellLength = this.width, + numberColor = this.numberColor, + min = 0, + max = 0, + } = {}) { + let memory1D = this.toArray(); + switch (mode) { + case "DISTANCE": + memory1D.sort((cellA, cellB) => { + let sa = Quadrille.sample({ + cell: cellA, + background: background, + cellLength: cellLength, + charColor: charColor, + numberColor: numberColor, + min: min, + max: max, + }); + let sb = Quadrille.sample({ + cell: cellB, + background: background, + cellLength: cellLength, + charColor: charColor, + numberColor: numberColor, + min: min, + max: max, + }); + let wa = Math.sqrt( + Math.pow(sa.r / sa.total - red(target), 2) + + Math.pow(sa.g / sa.total - green(target), 2) + + Math.pow(sa.b / sa.total - blue(target), 2) + + Math.pow(sa.a / sa.total - alpha(target), 2) + ); + let wb = Math.sqrt( + Math.pow(sb.r / sb.total - red(target), 2) + + Math.pow(sb.g / sb.total - green(target), 2) + + Math.pow(sb.b / sb.total - blue(target), 2) + + Math.pow(sb.a / sb.total - alpha(target), 2) + ); + return wa - wb; + }); + break; + case "AVG": + memory1D.sort((cellA, cellB) => { + let sa = Quadrille.sample({ + cell: cellA, + background: background, + cellLength: cellLength, + charColor: charColor, + numberColor: numberColor, + min: min, + max: max, + }); + let sb = Quadrille.sample({ + cell: cellB, + background: background, + cellLength: cellLength, + charColor: charColor, + numberColor: numberColor, + min: min, + max: max, + }); + let wa = 0.333 * sa.r + 0.333 * sa.g + 0.333 * sa.b; + let wb = 0.333 * sb.r + 0.333 * sb.g + 0.333 * sb.b; + return wa - wb; + }); + break; + case "LUMA": + default: + memory1D.sort((cellA, cellB) => { + let sa = Quadrille.sample({ + cell: cellA, + background: background, + cellLength: cellLength, + charColor: charColor, + numberColor: numberColor, + min: min, + max: max, + }); + let sb = Quadrille.sample({ + cell: cellB, + background: background, + cellLength: cellLength, + charColor: charColor, + numberColor: numberColor, + min: min, + max: max, + }); + let wa = 0.299 * sa.r + 0.587 * sa.g + 0.114 * sa.b; + let wb = 0.299 * sb.r + 0.587 * sb.g + 0.114 * sb.b; + return wa - wb; + }); + break; + } + this._init1D( + (memory1D = ascending ? memory1D : memory1D.reverse()), + this.width + ); + } + + saveLuma({ + charColor = "black", + background = this.BACKGROUND, + cellLength = this.width, + numberColor = this.numberColor, + min = 0, + max = 0, + } = {}) { + let luma = []; + let memory1D = this.toArray(); + memory1D.forEach((cellA) => { + let sa = Quadrille.sample({ + cell: cellA, + background: background, + cellLength: cellLength, + charColor: charColor, + numberColor: numberColor, + min: min, + max: max, + }); + let wa = 0.299 * sa.r + 0.587 * sa.g + 0.114 * sa.b; + luma.push(wa); + }); + return luma; + } + + saveRGB({ + charColor = "black", + background = this.BACKGROUND, + cellLength = this.width, + numberColor = this.numberColor, + min = 0, + max = 0, + } = {}) { + let r = []; + let g = []; + let b = []; + let memory1D = this.toArray(); + memory1D.forEach((cellA) => { + let sa = Quadrille.sample({ + cell: cellA, + background: background, + cellLength: cellLength, + charColor: charColor, + numberColor: numberColor, + min: min, + max: max, + }); + r.push(sa.r); + g.push(sa.g); + b.push(sa.b); + }); + return { r, g, b }; + } + + /** + * Sample cell using background as the {r, g, b, a, total} object literal. + */ + static sample({ + cell, + charColor = "black", + background = this.BACKGROUND, + cellLength = this.CELL_LENGTH, + numberColor = this.numberColor, + min = 0, + max = 0, + } = {}) { + let r, g, b, a; + let pg = createGraphics(cellLength, cellLength); + pg.background(background); + if (cell instanceof p5.Color || Array.isArray(cell)) { + Quadrille.COLOR({ + graphics: pg, + outlineWeight: 0, + cell: cell, + cellLength: cellLength, + }); + } else if (cell instanceof p5.Image) { + Quadrille.IMAGE({ + graphics: pg, + outlineWeight: 0, + cell: cell, + cellLength: cellLength, + }); + } else if (typeof cell === "string") { + Quadrille.CHAR({ + graphics: pg, + charColor: charColor, + outlineWeight: 0, + cell: cell, + cellLength: cellLength, + }); + } else if (typeof cell === "number") { + Quadrille.NUMBER({ + graphics: pg, + outlineWeight: 0, + cell: cell, + cellLength: cellLength, + numberColor: numberColor, + min: min, + max: max, + }); + } + pg.loadPixels(); + r = g = b = a = 0; + let total = pg.pixels.length / 4; + for (let i = 0; i < total; i++) { + r += pg.pixels[4 * i]; + g += pg.pixels[4 * i + 1]; + b += pg.pixels[4 * i + 2]; + a += pg.pixels[4 * i + 3]; + } + r /= total; + g /= total; + b /= total; + pg.updatePixels(); + return { r, g, b, a, total }; + } + + /** + * Color cell drawing. + */ + static COLOR({ + graphics, + cell = color("red"), + cellLength = this.CELL_LENGTH, + outline = this.OUTLINE, + outlineWeight = this.OUTLINE_WEIGHT, + } = {}) { + graphics.push(); + graphics.stroke(outline); + graphics.strokeWeight(outlineWeight); + graphics.fill(cell); + graphics.rect(0, 0, cellLength, cellLength); + graphics.pop(); + } + + /** + * Image cell drawing. + */ + static IMAGE({ + graphics, + cell = null, + outline = this.OUTLINE, + outlineWeight = this.OUTLINE_WEIGHT, + cellLength = this.CELL_LENGTH, + } = {}) { + if (cell) { + graphics.push(); + graphics.image(cell, 0, 0, cellLength, cellLength); + graphics.pop(); + if (outlineWeight !== 0) { + graphics.push(); + graphics.noFill(); + graphics.stroke(outline); + graphics.strokeWeight(outlineWeight); + graphics.rect(0, 0, cellLength, cellLength); + graphics.pop(); + } + } + } + + /** + * Char cell drawing. + */ + static CHAR({ + graphics, + cell = "?", + charColor = this.CHAR_COLOR, + outline = this.OUTLINE, + outlineWeight = this.OUTLINE_WEIGHT, + cellLength = this.CELL_LENGTH, + } = {}) { + graphics.push(); + graphics.noStroke(); + graphics.fill(charColor); + graphics.textSize(cellLength); + graphics.text(cell, 0, 0, cellLength, cellLength); + graphics.pop(); + if (outlineWeight !== 0) { + graphics.push(); + graphics.noFill(); + graphics.stroke(outline); + graphics.strokeWeight(outlineWeight); + graphics.rect(0, 0, cellLength, cellLength); + graphics.pop(); + } + } + + /** + * Number cell drawing. + */ + static NUMBER({ + graphics, + cell = 0, + outline = this.OUTLINE, + outlineWeight = this.OUTLINE_WEIGHT, + min = 0, + max = 0, + numberColor = this.NUMBER_COLOR, + cellLength = this.CELL_LENGTH, + } = {}) { + if (min < max) { + graphics.push(); + graphics.colorMode(graphics.RGB, 255); + graphics.fill( + graphics.color( + red(numberColor), + green(numberColor), + blue(numberColor), + graphics.map(cell, min, max, 0, 255) + ) + ); + graphics.rect(0, 0, cellLength, cellLength); + graphics.pop(); + } + if (outlineWeight !== 0) { + graphics.push(); + graphics.noFill(); + graphics.stroke(outline); + graphics.strokeWeight(outlineWeight); + graphics.rect(0, 0, cellLength, cellLength); + graphics.pop(); + } + } + + /** + * Frame cell drawing. Used by the drawQuadrille board property. + */ + static FRAME({ + graphics, + outline = this.OUTLINE, + outlineWeight = this.OUTLINE_WEIGHT, + cellLength = this.CELL_LENGTH, + } = {}) { + if (outlineWeight !== 0) { + graphics.push(); + graphics.noFill(); + graphics.stroke(outline); + graphics.strokeWeight(outlineWeight); + graphics.rect(0, 0, cellLength, cellLength); + graphics.pop(); + } + } +} + +// Details here: +// https://github.com/processing/p5.js/blob/main/contributor_docs/creating_libraries.md +(function () { + p5.prototype.createQuadrille = function () { + return new Quadrille(...arguments); + }; + + p5.prototype.drawQuadrille = function ( + quadrille, + { + graphics = this, + pixelX = 0, + pixelY = 0, + row = 0, + col = 0, + cellLength = Quadrille.CELL_LENGTH, + outlineWeight = Quadrille.OUTLINE_WEIGHT, + outline = Quadrille.OUTLINE, + charColor = Quadrille.CHAR_COLOR, + board = false, + numberColor = Quadrille.NUMBER_COLOR, + min = 0, + max = 0, + } = {} + ) { + graphics.push(); + graphics.translate( + pixelX > 0 ? pixelX : col * cellLength, + pixelY > 0 ? pixelY : row * cellLength + ); + for (let i = 0; i < quadrille._memory2D.length; i++) { + for (let j = 0; j < quadrille._memory2D[i].length; j++) { + graphics.push(); + graphics.translate(j * cellLength, i * cellLength); + let cell = quadrille._memory2D[i][j]; + if (cell) { + // Note that the Array.isArray(cell) condition should be rethought + // once 3D Quadrilles appear. + if (cell instanceof p5.Color || Array.isArray(cell)) { + Quadrille.COLOR({ + graphics: graphics, + cell: cell, + outline: outline, + outlineWeight: outlineWeight, + cellLength: cellLength, + }); + } else if (cell instanceof p5.Image) { + Quadrille.IMAGE({ + graphics: graphics, + cell: cell, + outline: outline, + outlineWeight: outlineWeight, + cellLength: cellLength, + }); + } else if (typeof cell === "string") { + Quadrille.CHAR({ + graphics: graphics, + cell: cell, + charColor: charColor, + outline: outline, + outlineWeight: outlineWeight, + cellLength: cellLength, + }); + } else if (typeof cell === "number") { + Quadrille.NUMBER({ + graphics: graphics, + cell: cell, + outline: outline, + outlineWeight: outlineWeight, + numberColor: numberColor, + min: min, + max: max, + cellLength: cellLength, + }); + } + } else if (board) { + Quadrille.FRAME({ + graphics: graphics, + outline: outline, + outlineWeight: outlineWeight, + cellLength: cellLength, + }); + } + graphics.pop(); + } + } + graphics.pop(); + }; +})(); diff --git a/content/sketches/libraries/p5.shaderbox.js b/content/sketches/libraries/p5.shaderbox.js new file mode 100644 index 00000000..cec67e7e --- /dev/null +++ b/content/sketches/libraries/p5.shaderbox.js @@ -0,0 +1,132 @@ +/*************************************************************************************** +* p5.shaderbox.js +* @author Jean Pierre Charalambos, https://github.com/VisualComputing/p5.shaderbox/ +* Released under the terms of the GPLv3, refer to: http://www.gnu.org/licenses/gpl.html +***************************************************************************************/ + +// See: +// https://github.com/processing/p5.js/blob/main/contributor_docs/creating_libraries.md +// https://github.com/processing/p5.js/blob/main/src/core/README.md +// https://github.com/processing/p5.js/blob/main/contributor_docs/webgl_mode_architecture.md +(function () { + p5.prototype.readShader = function (fragFilename, + { color = 'vVertexColor', + texcoord = 'vTexCoord' + } = {}) { + let shader = new p5.Shader(); + shader._vertSrc = _vertexShader(color, texcoord); + this.loadStrings( + fragFilename, + result => { + shader._fragSrc = result.join('\n') + } + ); + return shader; + } + + p5.prototype.makeShader = function (fragSrc, + { color = 'vVertexColor', + texcoord = 'vTexCoord' + } = {}) { + let shader = new p5.Shader(); + shader._vertSrc = _vertexShader(color, texcoord); + shader._fragSrc = fragSrc; + return shader; + } + + p5.prototype.cover = function ({ + graphics = this, + texture = false, + x = -graphics.width / 2, + y = -graphics.height / 2, + w = graphics.width, + h = graphics.height, + pattern0 = null, + pattern1 = pattern0, + pattern2 = pattern0, + pattern3 = pattern0 } = {}) { + if (!(graphics._renderer instanceof p5.RendererGL)) { + throw new Error(`WEBGL is required to use shaderbox.cover`); + } + this.beginHUD(graphics); + graphics.beginShape(); + let color = this.color(255); + if (texture) { + graphics.textureMode = this.NORMAL; + } + graphics.fill(pattern0 ?? color); + graphics.vertex(x, y, 0, 0, 0); + graphics.fill(pattern1 ?? color); + graphics.vertex(x + w, y, 0, texture ? 1 : 0, 0); + graphics.fill(pattern2 ?? color); + graphics.vertex(x + w, y + h, 0, texture ? 1 : 0, texture ? 1 : 0); + graphics.fill(pattern3 ?? color); + graphics.vertex(x, y + h, 0, 0, texture ? 1 : 0); + graphics.endShape(this.CLOSE); + this.endHUD(graphics); + } + + // gl handling took from p5.Easycam (https://github.com/freshfork/p5.EasyCam) + p5.prototype.beginHUD = function (graphics = this) { + let renderer = graphics._renderer; + if (!(renderer instanceof p5.RendererGL)) { + throw new Error(`WEBGL is required to use shaderbox.beginHUD`); + } + this._cacheModelView = renderer.uMVMatrix.copy(); + this._cacheProjection = renderer.uPMatrix.copy(); + this._rendererState = renderer.push(); + let gl = renderer.drawingContext; + gl.flush(); + gl.disable(gl.DEPTH_TEST); + let z = Number.MAX_VALUE; + renderer.resetMatrix(); + renderer._curCamera.ortho(-renderer.width / 2, renderer.width / 2, -renderer.height / 2, renderer.height / 2, -z, z); + } + + p5.prototype.endHUD = function (graphics = this) { + let renderer = graphics._renderer; + if (!(renderer instanceof p5.RendererGL)) { + throw new Error(`WEBGL is required to use shaderbox.endHUD`); + } + let gl = renderer.drawingContext; + gl.flush(); + gl.enable(gl.DEPTH_TEST); + renderer.pop(this._rendererState); + renderer.uPMatrix.set(this._cacheProjection); + renderer.uMVMatrix.set(this._cacheModelView); + } + + p5.prototype.emitMousePosition = function (shader, { + graphics = this, + mouseX = this.mouseX, + mouseY = this.mouseY, + uniform = 'u_mouse' } = {}) { + shader.setUniform(uniform, [mouseX * this.pixelDensity(), (graphics.height - mouseY) * this.pixelDensity()]); + } + + p5.prototype.emitResolution = function (shader, { + graphics = this, + uniform = 'u_resolution' } = {}) { + shader.setUniform(uniform, [graphics.width * this.pixelDensity(), graphics.height * this.pixelDensity()]); + } + + p5.prototype.emitTexOffset = function (shader, image, uniform = 'u_texoffset') { + shader.setUniform(uniform, [1 / image.width, 1 / image.height]); + } + + function _vertexShader(color, texcoord) { + return `precision highp float; + attribute vec3 aPosition; + attribute vec2 aTexCoord; + attribute vec4 aVertexColor; + uniform mat4 uProjectionMatrix; + uniform mat4 uModelViewMatrix; + varying vec4 ${color}; + varying vec2 ${texcoord}; + void main() { + ${color} = aVertexColor; + ${texcoord} = aTexCoord; + gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0); + }`; + } +})(); \ No newline at end of file diff --git a/content/sketches/lightness.js b/content/sketches/lightness.js new file mode 100644 index 00000000..71617b7e --- /dev/null +++ b/content/sketches/lightness.js @@ -0,0 +1,60 @@ + +new p5((p) =>{ + let img; + let myPixels; + p.preload = function() { + img = p.loadImage("/visual_computing/sketches/medusa.jpeg"); + } + + +p.setup = function () { + p.createCanvas(400, 400); + let inp = p.createInput("0","range"); + + inp.size(100); + + inp.input((e) => handleBtn(e)); + + inp.position(0,p.height-20) + p.image(img, 0, 0, p.width, p.height); + p.colorMode(p.RGB) + p.loadPixels(); + myPixels = [...p.pixels] + console.log("myPixels",myPixels[0]) +} + +p.draw = function (){ + +} + +handleBtn= function(inp){ + console.log("inp", inp.target.value) +let d = p.pixelDensity(); +let halfImage = 4 * (p.width * d) * (p.height * d); +for (let i = 0; i < halfImage; i += 4) { + + let colorRGB = p.color(myPixels[i],myPixels[i+1], myPixels[i+2]) + let hueValue = p.floor( p.hue(colorRGB) ); + let saturationValue = p.saturation(colorRGB); + let lightnessValue = p.lightness(colorRGB); + + let colorHSV = p.color(`hsl(${ hueValue }, ${ saturationValue }%, ${ (lightnessValue + parseFloat(inp.target.value))}%)`) + + + p.pixels[i] = p.red(colorHSV); + p.pixels[i + 1] = p.green(colorHSV); + p.pixels[i + 2] = p.blue(colorHSV); + p.pixels[i + 3] = p.alpha(colorHSV); +} +p.updatePixels(); + console.log("myPixels",myPixels[0]) +} + +handleImg = function(event){ + console.log("event.target",event.target.value) + p.loadImage(event.target.value, img2 => { + p.image(img2, 0, 0, p.width, p.height); + }); + +} +}) \ No newline at end of file diff --git a/content/sketches/mahakala.jpg b/content/sketches/mahakala.jpg deleted file mode 100644 index 1b094951..00000000 Binary files a/content/sketches/mahakala.jpg and /dev/null differ diff --git a/content/sketches/mandrill.png b/content/sketches/mandrill.png deleted file mode 100644 index fc10cd54..00000000 Binary files a/content/sketches/mandrill.png and /dev/null differ diff --git a/content/sketches/mandrill.webm b/content/sketches/mandrill.webm deleted file mode 100644 index b0a5d813..00000000 Binary files a/content/sketches/mandrill.webm and /dev/null differ diff --git a/content/sketches/maze/ball.js b/content/sketches/maze/ball.js new file mode 100644 index 00000000..c4012341 --- /dev/null +++ b/content/sketches/maze/ball.js @@ -0,0 +1,51 @@ +function Ball(P){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0) + this.sphereRadius = 7; + this.spherePosition = createVector(92.5-38*4.5,38*-1,this.sphereRadius); + + this.minVertex = createVector(-P.planeSize.x/2,-P.planeSize.y/2,0); + this.maxVertex = createVector(P.planeSize.x/2,P.planeSize.y/2,0); + + this.draw = function(fbo){ + fbo.push(); + fbo.fill("rgb(0, 0, 0)"); + fbo1.noStroke(); + fbo.translate(this.spherePosition); + fbo.sphere(this.sphereRadius) + fbo.pop() + } + this.move = function(P, acceleration, factorAcc, isAcelerate){ + + if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + if(isAcelerate){ + this.sphereMoveVector.x = (acceleration.x*factorAcc)*isAcelerate; + this.sphereMoveVector.y = (acceleration.y*factorAcc)*isAcelerate; + + this.spherePosition.x = (this.sphereMoveVector.x*factorAcc) + this.spherePosition.x + this.spherePosition.y = (this.sphereMoveVector.y*factorAcc) + this.spherePosition.y; + } + else{ + this.sphereMoveVector.x = (acceleration.x*factorAcc) + this.sphereMoveVector.x; + this.sphereMoveVector.y = (acceleration.y*factorAcc) + this.sphereMoveVector.y; + this.spherePosition.x = (this.sphereMoveVector.x*factorAcc) + this.spherePosition.x + this.spherePosition.y = (this.sphereMoveVector.y*factorAcc) + this.spherePosition.y; + } + + }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0); + } + // if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + // B.sphereMoveVector.x = (B.acceleration.x*0.1) + B.sphereMoveVector.x; + // B.sphereMoveVector.y = (B.acceleration.y*0.1) + B.sphereMoveVector.y; + + // B.spherePosition.x = (B.sphereMoveVector.x*0.1) + B.spherePosition.x + // B.spherePosition.y = (B.sphereMoveVector.y*0.1) + B.spherePosition.y; + + // }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + // B.sphereMoveVector = createVector(0,0,0); + // B.acceleration = createVector(0,0,0); + // } + } + } \ No newline at end of file diff --git a/content/sketches/maze/p5.treegl.js b/content/sketches/maze/p5.treegl.js new file mode 100644 index 00000000..8166e282 --- /dev/null +++ b/content/sketches/maze/p5.treegl.js @@ -0,0 +1,1599 @@ +'use strict'; + +// See: +// https://github.com/processing/p5.js/blob/main/contributor_docs/creating_libraries.md +// https://github.com/processing/p5.js/blob/main/src/core/README.md +// https://github.com/processing/p5.js/blob/main/contributor_docs/webgl_mode_architecture.md + +/** @namespace */ +var Tree = (function (ext) { + const INFO = + { + LIBRARY: 'p5.treegl', + VERSION: '0.3.0', + HOMEPAGE: 'https://github.com/VisualComputing/p5.treegl' + }; + Object.freeze(INFO); + const NONE = 0; + // Axes consts + const X = 1 << 0; + const Y = 1 << 1; + const Z = 1 << 2; + const _X = 1 << 3; + const _Y = 1 << 4; + const _Z = 1 << 5; + const LABELS = 1 << 6; + // grid style + const SOLID = 0; + const DOTS = 1 + // bullseye and picking shape + const SQUARE = 0; + const CIRCLE = 1; + // only picking shape + const PROJECTION = 2; + // Frustum consts + const NEAR = 1 << 0; + const FAR = 1 << 1; + const LEFT = 1 << 2; + const RIGHT = 1 << 3; + const BOTTOM = 1 << 4; + const TOP = 1 << 5; + const BODY = 1 << 6; + // visibility + const INVISIBLE = 0; + const VISIBLE = 1; + const SEMIVISIBLE = 2; + // spaces + const WORLD = 'WORLD'; + const EYE = 'EYE'; + const NDC = 'NDC'; + const SCREEN = 'SCREEN'; + const MODEL = 'MODEL'; + // points + const ORIGIN = [0, 0, 0]; + // vectors + const i = [1, 0, 0]; + const j = [0, 1, 0]; + const k = [0, 0, 1]; + const _i = [-1, 0, 0]; + const _j = [0, -1, 0]; + const _k = [0, 0, -1]; + // shaders + // precision + const lowp = 0; + const mediump = 1; + const highp = 2; + // in + const pmvMatrix = 1 << 0; + const pMatrix = 1 << 1; + const mvMatrix = 1 << 2; + const nMatrix = 1 << 3; + // out + const color4 = 1 << 0; + const texcoords2 = 1 << 1; + const normal3 = 1 << 2; + const position2 = 1 << 3; + const position3 = 1 << 4; + ext ??= {}; + ext.INFO = INFO; + ext.NONE = NONE; + ext.X = X; + ext.Y = Y; + ext.Z = Z; + ext._X = _X; + ext._Y = _Y; + ext._Z = _Z; + ext.LABELS = LABELS; + ext.SOLID = SOLID; + ext.DOTS = DOTS; + ext.SQUARE = SQUARE; + ext.CIRCLE = CIRCLE; + ext.PROJECTION = PROJECTION; + ext.NEAR = NEAR; + ext.FAR = FAR; + ext.LEFT = LEFT; + ext.RIGHT = RIGHT; + ext.BOTTOM = BOTTOM; + ext.TOP = TOP; + ext.BODY = BODY; + ext.INVISIBLE = INVISIBLE; + ext.VISIBLE = VISIBLE; + ext.SEMIVISIBLE = SEMIVISIBLE; + ext.WORLD = WORLD; + ext.EYE = EYE; + ext.NDC = NDC; + ext.SCREEN = SCREEN; + ext.MODEL = MODEL; + ext.ORIGIN = ORIGIN; + ext.i = i; + ext.j = j; + ext.k = k; + ext._i = _i; + ext._j = _j; + ext._k = _k; + ext.lowp = lowp; + ext.mediump = mediump; + ext.highp = highp; + ext.pmvMatrix = pmvMatrix; + ext.pMatrix = pMatrix; + ext.mvMatrix = mvMatrix; + ext.nMatrix = nMatrix; + ext.color4 = color4; + ext.texcoords2 = texcoords2; + ext.normal3 = normal3; + ext.position2 = position2; + ext.position3 = position3; + return ext; +})(Tree); + + +(function () { + console.log(Tree.INFO); + + // 1. Matrix stuff + + p5.Matrix.prototype.mult3 = function (vector) { + if (this.mat3 === undefined) { + console.error('mult3 only works with mat3'); + return; + } + return new p5.Vector(this.mat3[0] * vector.x + this.mat3[3] * vector.y + this.mat3[6] * vector.z, + this.mat3[1] * vector.x + this.mat3[4] * vector.y + this.mat3[7] * vector.z, + this.mat3[2] * vector.x + this.mat3[5] * vector.y + this.mat3[8] * vector.z); + }; + + p5.Matrix.prototype.mult4 = function (vector) { + return new p5.Vector(...this._mult4([vector.x, vector.y, vector.z, 1])); + }; + + p5.Matrix.prototype._mult4 = function (vec4) { + if (this.mat4 === undefined) { + console.error('_mult4 only works with mat4'); + return; + } + return [this.mat4[0] * vec4[0] + this.mat4[4] * vec4[1] + this.mat4[8] * vec4[2] + this.mat4[12] * vec4[3], + this.mat4[1] * vec4[0] + this.mat4[5] * vec4[1] + this.mat4[9] * vec4[2] + this.mat4[13] * vec4[3], + this.mat4[2] * vec4[0] + this.mat4[6] * vec4[1] + this.mat4[10] * vec4[2] + this.mat4[14] * vec4[3], + this.mat4[3] * vec4[0] + this.mat4[7] * vec4[1] + this.mat4[11] * vec4[2] + this.mat4[15] * vec4[3]]; + }; + + p5.prototype.tMatrix = function (matrix) { + return matrix.copy().transpose(matrix); + } + + p5.prototype.invMatrix = function (matrix) { + return matrix.copy().invert(matrix); + } + + p5.prototype.axbMatrix = function (a, b) { + return a.copy().apply(b); + } + + p5.prototype.iMatrix = function () { + return new p5.Matrix(); + } + + p5.prototype.lMatrix = function () { + return this._renderer.lMatrix(...arguments); + } + + // defaults: from: iMatrix, to: eMatrix + p5.RendererGL.prototype.lMatrix = function ( + { + from = new p5.Matrix(), + to = this.eMatrix() + } = {}) { + return to.copy().invert(to).apply(from); + } + + p5.prototype.dMatrix = function () { + return this._renderer.dMatrix(...arguments); + } + + // defaults: from: iMatrix, to: eMatrix + p5.RendererGL.prototype.dMatrix = function ( + { + from = new p5.Matrix(), + to = this.eMatrix(), + matrix = from.copy().invert(from).apply(to) + } = {}) { + // Note that this transposes mat4 into mat3 + return new p5.Matrix('mat3', [matrix.mat4[0], matrix.mat4[4], matrix.mat4[8], + matrix.mat4[1], matrix.mat4[5], matrix.mat4[9], + matrix.mat4[2], matrix.mat4[6], matrix.mat4[10]]); + } + + p5.prototype.pMatrix = function () { + return this._renderer.pMatrix(...arguments); + } + + p5.RendererGL.prototype.pMatrix = function () { + return this.uPMatrix.copy(); + } + + p5.prototype.mvMatrix = function () { + return this._renderer.mvMatrix(...arguments); + } + + // defaults when mMatrix is defined: vMatrix: this.vMatrix, mMatrix: + // otherwise it returns a copy of the current mvMatrix + p5.RendererGL.prototype.mvMatrix = function ( + { + vMatrix, + mMatrix + } = {}) { + return mMatrix ? (vMatrix ?? this.vMatrix()).copy().apply(mMatrix) : this.uMVMatrix.copy(); + } + + p5.prototype.mMatrix = function () { + return this._renderer.mMatrix(...arguments); + } + + // defaults: eMatrix: this.eMatrix, mvMatrix: this.mvMatrix + p5.RendererGL.prototype.mMatrix = function ( + { + eMatrix = this.eMatrix(), + mvMatrix = this.mvMatrix() + } = {}) { + return eMatrix.copy().apply(mvMatrix); + } + + p5.prototype.nMatrix = function () { + return this._renderer.nMatrix(...arguments); + } + + p5.RendererGL.prototype.nMatrix = function ({ + vMatrix, + mMatrix, + mvMatrix = this.mvMatrix({ mMatrix: mMatrix, vMatrix: vMatrix }) + } = {}) { + return new p5.Matrix('mat3').inverseTranspose(mvMatrix); + } + + // TODO check where to replace vMatrix for: + // this._curCamera.cameraMatrix + + p5.prototype.vMatrix = function () { + return this._renderer.vMatrix(...arguments); + } + + p5.RendererGL.prototype.vMatrix = function () { + return this._curCamera.vMatrix(); + } + + p5.Camera.prototype.vMatrix = function () { + return this.cameraMatrix.copy(); + } + + p5.prototype.eMatrix = function () { + return this._renderer.eMatrix(...arguments); + } + + p5.RendererGL.prototype.eMatrix = function () { + return this._curCamera.eMatrix(); + } + + p5.Camera.prototype.eMatrix = function () { + return this.cameraMatrix.copy().invert(this.cameraMatrix); + } + + p5.prototype.pmvMatrix = function () { + return this._renderer.pmvMatrix(...arguments); + } + + p5.RendererGL.prototype.pmvMatrix = function ( + { + pMatrix = this.uPMatrix, + vMatrix, + mMatrix, + mvMatrix = this.mvMatrix({ mMatrix: mMatrix, vMatrix: vMatrix }) + } = {}) { + return pMatrix.copy().apply(mvMatrix); + } + + p5.prototype.pvMatrix = function () { + return this._renderer.pvMatrix(...arguments); + } + + // defaults: pMatrix: this.pMatrix, vMatrix: this.vMatrix + p5.RendererGL.prototype.pvMatrix = function ( + { + pMatrix = this.uPMatrix, + vMatrix = this._curCamera.cameraMatrix + } = {}) { + return pMatrix.copy().apply(vMatrix); + } + + p5.prototype.pvInvMatrix = function () { + return this._renderer.pvInvMatrix(...arguments); + } + + p5.RendererGL.prototype.pvInvMatrix = function ( + { + pMatrix, + vMatrix, + pvMatrix + } = {}) { + let matrix = pvMatrix ? pvMatrix.copy() : this.pvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix }); + return matrix.invert(matrix); + } + + p5.prototype._isOrtho = function () { + return this._renderer._isOrtho(...arguments); + } + + p5.RendererGL.prototype._isOrtho = function () { + return this.uPMatrix._isOrtho(); + } + + p5.Matrix.prototype._isOrtho = function () { + return this.mat4[15] != 0; + } + + p5.prototype.nPlane = function () { + return this._renderer.nPlane(...arguments); + } + + p5.RendererGL.prototype.nPlane = function () { + return this.uPMatrix.nPlane(); + } + + p5.Matrix.prototype.nPlane = function () { + return this.mat4[15] == 0 ? this.mat4[14] / (this.mat4[10] - 1) : + (1 + this.mat4[14]) / this.mat4[10]; + } + + p5.prototype.fPlane = function () { + return this._renderer.fPlane(...arguments); + } + + p5.RendererGL.prototype.fPlane = function () { + return this.uPMatrix.fPlane(); + } + + p5.Matrix.prototype.fPlane = function () { + return this.mat4[15] == 0 ? this.mat4[14] / (1 + this.mat4[10]) : + (this.mat4[14] - 1) / this.mat4[10]; + } + + p5.prototype.lPlane = function () { + return this._renderer.lPlane(...arguments); + } + + p5.RendererGL.prototype.lPlane = function () { + return this.uPMatrix.lPlane(); + } + + p5.Matrix.prototype.lPlane = function () { + return this.mat4[15] == 1 ? -(1 + this.mat4[12]) / this.mat4[0] : + this.nPlane() * (this.mat4[8] - 1) / this.mat4[0]; + } + + p5.prototype.rPlane = function () { + return this._renderer.rPlane(...arguments); + } + + p5.RendererGL.prototype.rPlane = function () { + return this.uPMatrix.rPlane(); + } + + p5.Matrix.prototype.rPlane = function () { + return this.mat4[15] == 1 ? (1 - this.mat4[12]) / this.mat4[0] : + this.nPlane() * (1 + this.mat4[8]) / this.mat4[0]; + } + + p5.prototype.tPlane = function () { + return this._renderer.tPlane(...arguments); + } + + p5.RendererGL.prototype.tPlane = function () { + return this.uPMatrix.tPlane(); + } + + p5.Matrix.prototype.tPlane = function () { + // note that inverted values are returned if the projection + // matrix was set with @function frustum. + return this.mat4[15] == 1 ? (this.mat4[13] - 1) / this.mat4[5] : + this.nPlane() * (this.mat4[9] - 1) / this.mat4[5]; + } + + p5.prototype.bPlane = function () { + return this._renderer.bPlane(...arguments); + } + + p5.RendererGL.prototype.bPlane = function () { + return this.uPMatrix.bPlane(); + } + + p5.Matrix.prototype.bPlane = function () { + // note that inverted values are returned if the projection + // matrix was set with @function frustum. + return this.mat4[15] == 1 ? (1 + this.mat4[13]) / this.mat4[5] : + this.nPlane() * (1 + this.mat4[9]) / this.mat4[5]; + } + + p5.prototype.fov = function () { + return this._renderer.fov(...arguments); + } + + p5.RendererGL.prototype.fov = function () { + return this.uPMatrix.fov(); + } + + p5.Matrix.prototype.fov = function () { + if (this.mat4[15] != 0) { + console.error('fov only works for a perspective projection'); + return; + } + return Math.abs(2 * Math.atan(1 / this.mat4[5])); + } + + p5.prototype.hfov = function () { + return this._renderer.hfov(...arguments); + } + + p5.RendererGL.prototype.hfov = function () { + return this.uPMatrix.hfov(); + } + + p5.Matrix.prototype.hfov = function () { + if (this.mat4[15] != 0) { + console.error('hfov only works for a perspective projection'); + return; + } + return Math.abs(2 * Math.atan(1 / this.mat4[0])); + } + + // 2. Space transformations + + p5.prototype.beginHUD = function () { + if (this._renderer instanceof p5.RendererGL) { + this._renderer.beginHUD(...arguments); + } + } + + p5.RendererGL.prototype.beginHUD = function () { + this.mv = this.mvMatrix(); + this.p = this.pMatrix(); + this._rendererState = this.push(); + let gl = this.drawingContext; + gl.flush(); + gl.disable(gl.DEPTH_TEST); + this.resetMatrix(); + let z = Number.MAX_VALUE; + this._curCamera.ortho(0, this.width, -this.height, 0, -z, z); + } + + p5.prototype.endHUD = function () { + if (this._renderer instanceof p5.RendererGL) { + this._renderer.endHUD(...arguments); + } + } + + p5.RendererGL.prototype.endHUD = function () { + let gl = this.drawingContext; + gl.flush(); + gl.enable(gl.DEPTH_TEST); + this.pop(this._rendererState); + this.uPMatrix.set(this.p); + this.uMVMatrix.set(this.mv); + } + + // 2.1 Points + + // NDC stuff needs testing + + p5.prototype._map = function () { + return this._renderer._map(...arguments); + } + + p5.RendererGL.prototype._map = function (n, start1, stop1, start2, stop2) { + return (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; + } + + p5.prototype.treeLocation = function () { + return this._renderer.treeLocation(...arguments); + } + + /** + * Converts locations (i.e., points) from one space into another. + * @param {p5.Vector} vector location to be converted. + * @param {p5.Matrix|String} from source space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix|String} to target space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix} pMatrix projection matrix. + * @param {p5.Matrix} vMatrix view matrix. + * @param {p5.Matrix} pvMatrix projection times view matrix. + * @param {p5.Matrix} pvInvMatrix (projection times view matrix)^-1. + */ + p5.RendererGL.prototype.treeLocation = function () { + return arguments.length === 1 & arguments[0] instanceof Object ? this._treeLocation(Tree.ORIGIN, arguments[0]) : + this._treeLocation(...arguments); + } + + p5.prototype._treeLocation = function () { + return this._renderer._treeLocation(...arguments); + } + + p5.RendererGL.prototype._treeLocation = function (vector = Tree.ORIGIN, + { + from = Tree.EYE, + to = Tree.WORLD, + pMatrix, + vMatrix, + eMatrix, + pvMatrix, + pvInvMatrix + } = {}) { + if (Array.isArray(vector)) { + vector = new p5.Vector(vector[0] ?? 0, vector[1] ?? 0, vector[2] ?? 0); + } + if (from == Tree.MODEL) { + from = this.mMatrix({ eMatrix: eMatrix }); + } + if (to == Tree.MODEL) { + to = this.mMatrix({ eMatrix: eMatrix }); + } + if ((from == Tree.WORLD) && (to == Tree.SCREEN)) { + return this._screenLocation({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + if ((from == Tree.SCREEN) && (to == Tree.WORLD)) { + return this._location({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix }); + } + if (from == Tree.SCREEN && to == Tree.NDC) { + return this._screenToNDCLocation(vector); + } + if (from == Tree.NDC && to == Tree.SCREEN) { + return this._ndcToScreenLocation(vector); + } + if (from == Tree.WORLD && to == Tree.NDC) { + return this._screenToNDCLocation(this._screenLocation({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix })); + } + if (from == Tree.NDC && to == Tree.WORLD) { + return this._location({ vector: this._ndcToScreenLocation(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix }); + } + if (from == Tree.NDC && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(this._location({ vector: this._ndcToScreenLocation(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix })); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.NDC) { + return this._screenToNDCLocation(this._screenLocation({ vector: (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix })); + } + if (from == Tree.WORLD && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(vector); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.WORLD) { + return (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector); + } + if (from instanceof p5.Matrix && to instanceof p5.Matrix) { + return this.lMatrix({ from: from, to: to }).mult4(vector); + } + if (from == Tree.SCREEN && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(this._location({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix })); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.SCREEN) { + return this._screenLocation({ vector: (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + console.error('couldn\'t parse your treeLocation query!'); + return vector; + } + + p5.RendererGL.prototype._ndcToScreenLocation = function (vector) { + return new p5.Vector(this._map(vector.x, -1, 1, 0, this.width), + this._map(vector.y, -1, 1, 0, this.height), + this._map(vector.z, -1, 1, 0, 1)); + } + + p5.RendererGL.prototype._screenToNDCLocation = function (vector) { + return new p5.Vector(this._map(vector.x, 0, this.width, -1, 1), + this._map(vector.y, 0, this.height, -1, 1), + this._map(vector.z, 0, 1, -1, 1)); + } + + p5.RendererGL.prototype._screenLocation = function ( + { + vector = new p5.Vector(0, 0, 0.5), + pMatrix, + vMatrix, + pvMatrix = this.pvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix }) + } = {}) { + let target = pvMatrix._mult4([vector.x, vector.y, vector.z, 1]); + if (target[3] == 0) { + console.error('screenLocation broken. Check your pvMatrix!'); + return; + } + let viewport = [0, this.height, this.width, -this.height]; + // ndc, but y is inverted + target[0] /= target[3]; + target[1] /= target[3]; + target[2] /= target[3]; + // Map x, y and z to range 0-1 + target[0] = target[0] * 0.5 + 0.5; + target[1] = target[1] * 0.5 + 0.5; + target[2] = target[2] * 0.5 + 0.5; + // Map x,y to viewport + target[0] = target[0] * viewport[2] + viewport[0]; + target[1] = target[1] * viewport[3] + viewport[1]; + return new p5.Vector(target[0], target[1], target[2]); + } + + p5.RendererGL.prototype._location = function ( + { + vector = new p5.Vector(this.width / 2, this.height / 2, 0.5), + pMatrix, + vMatrix, + pvMatrix, + pvInvMatrix = this.pvInvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }) + } = {}) { + let viewport = [0, this.height, this.width, -this.height]; + let source = [vector.x, vector.y, vector.z, 1]; + // Map x and y from window coordinates + source[0] = (source[0] - viewport[0]) / viewport[2]; + source[1] = (source[1] - viewport[1]) / viewport[3]; + // Map to range -1 to 1 + source[0] = source[0] * 2 - 1; + source[1] = source[1] * 2 - 1; + source[2] = source[2] * 2 - 1; + let target = pvInvMatrix._mult4(source); + if (target[3] == 0) { + console.error('location broken. Check your pvInvMatrix!'); + return; + } + target[0] /= target[3]; + target[1] /= target[3]; + target[2] /= target[3]; + return new p5.Vector(target[0], target[1], target[2]); + } + + // 2.2. Vectors + + // NDC stuff needs testing + + p5.prototype.treeDisplacement = function () { + return this._renderer.treeDisplacement(...arguments); + } + + /** + * Converts displacements (i.e., vectors) from one space into another. + * @param {p5.Vector} vector location to be converted. + * @param {p5.Matrix|String} from source space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix|String} to target space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix} pMatrix projection matrix. + * @param {p5.Matrix} vMatrix view matrix. + * @param {p5.Matrix} pvMatrix projection times view matrix. + * @param {p5.Matrix} pvInvMatrix (projection times view matrix)^-1. + */ + p5.RendererGL.prototype.treeDisplacement = function () { + return arguments.length === 1 & arguments[0] instanceof Object ? this._treeDisplacement(Tree._k, arguments[0]) : + this._treeDisplacement(...arguments); + } + + p5.prototype._treeDisplacement = function () { + return this._renderer._treeDisplacement(...arguments); + } + + p5.RendererGL.prototype._treeDisplacement = function (vector = Tree._k, + { + from = Tree.EYE, + to = Tree.WORLD, + vMatrix, + eMatrix, + pMatrix + } = {}) { + if (Array.isArray(vector)) { + vector = new p5.Vector(vector[0] ?? 0, vector[1] ?? 0, vector[2] ?? 0); + } + if (from == Tree.MODEL) { + from = this.mMatrix({ eMatrix: eMatrix }); + } + if (to == Tree.MODEL) { + to = this.mMatrix({ eMatrix: eMatrix }); + } + if ((from == Tree.WORLD) && (to == Tree.SCREEN)) { + return this._worldToScreenDisplacement(vector, pMatrix); + } + if ((from == Tree.SCREEN) && (to == Tree.WORLD)) { + return this._screenToWorldDisplacement(vector, pMatrix); + } + if (from == Tree.SCREEN && to == Tree.NDC) { + return this._screenToNDCDisplacement(vector); + } + if (from == Tree.NDC && to == Tree.SCREEN) { + return this._ndcToScreenDisplacement(vector); + } + if (from == Tree.WORLD && to == Tree.NDC) { + return this._screenToNDCDisplacement(this._worldToScreenDisplacement(vector, pMatrix)); + } + if (from == Tree.NDC && to == Tree.WORLD) { + return this._screenToWorldDisplacement(this._ndcToScreenDisplacement(vector), pMatrix); + } + if (from == Tree.NDC && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(this._screenToWorldDisplacement(this._ndcToScreenDisplacement(vector), pMatrix)); + } + if (from == Tree.EYE && to == Tree.NDC) { + return this._screenToNDCDisplacement(this._worldToScreenDisplacement(this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector), pMatrix)); + } + if (from == Tree.SCREEN && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: to }).mult3(this._screenToWorldDisplacement(vector, pMatrix)); + } + if (from instanceof p5.Matrix && to == Tree.SCREEN) { + return this._worldToScreenDisplacement(this.dMatrix({ matrix: from.copy().invert(from) }).mult3(vector), pMatrix); + } + if (from instanceof p5.Matrix && to instanceof p5.Matrix) { + return this.dMatrix({ from: from, to: to }).mult3(vector); + } + // all cases below kept for efficiency but they all may + // be simply expressed in terms of the previous case, by: + // Tree.EYE -> eMatrix() + // Tree.WORLD -> iMatrix() + if (from == Tree.EYE && to == Tree.WORLD) { + return this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector); + } + if (from == Tree.WORLD && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(vector); + } + if (from == Tree.EYE && to == Tree.SCREEN) { + return this._worldToScreenDisplacement(this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector), pMatrix); + } + if (from == Tree.SCREEN && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(this._screenToWorldDisplacement(vector, pMatrix)); + } + if (from == Tree.EYE && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: (vMatrix ?? this.vMatrix()).apply(to) }).mult3(vector); + } + if (from instanceof p5.Matrix && to == Tree.EYE) { + return this.dMatrix({ matrix: from.copy().invert(from).apply(eMatrix ?? this.eMatrix()) }).mult3(vector); + } + if (from == Tree.WORLD && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: to }).mult3(vector); + } + if (from instanceof p5.Matrix && to == Tree.WORLD) { + return this.dMatrix({ matrix: from.copy().invert(from) }).mult3(vector); + } + console.error('couldn\'t parse your treeDisplacement query!'); + return vector; + } + + p5.RendererGL.prototype._worldToScreenDisplacement = function (vector, pMatrix = this.uPMatrix) { + let eyeVector = this._treeDisplacement(vector, { from: Tree.WORLD, to: Tree.EYE }); + let dx = eyeVector.x; + let dy = eyeVector.y; + let perspective = pMatrix.mat4[15] == 0; + if (perspective) { + let position = new p5.Vector(); + let k = Math.abs(this._treeLocation(position, { from: Tree.WORLD, to: Tree.EYE }).z * Math.tan(this.fov(pMatrix) / 2)); + dx /= 2 * k / this.height; + dy /= 2 * k / this.height; + } + let dz = eyeVector.z; + // sign is inverted + dz /= (pMatrix.nPlane() - pMatrix.fPlane()) / (perspective ? Math.tan(this.fov(pMatrix) / 2) : Math.abs(pMatrix.rPlane() - pMatrix.lPlane()) / this.width); + return new p5.Vector(dx, dy, dz); + } + + p5.RendererGL.prototype._screenToWorldDisplacement = function (vector, pMatrix = this.uPMatrix) { + let dx = vector.x; + let dy = vector.y; + // Scale to fit the screen relative vector displacement + let perspective = pMatrix.mat4[15] == 0; + if (perspective) { + let position = new p5.Vector(); + let k = Math.abs(this._treeLocation(position, { from: Tree.WORLD, to: Tree.EYE }).z * Math.tan(this.fov(pMatrix) / 2)); + dx *= 2 * k / this.height; + dy *= 2 * k / this.height; + } + let dz = vector.z; + dz *= (pMatrix.nPlane() - pMatrix.fPlane()) / (perspective ? Math.tan(this.fov(pMatrix) / 2) : Math.abs(pMatrix.rPlane() - pMatrix.lPlane()) / this.width); + let eyeVector = new p5.Vector(dx, dy, dz); + return this._treeDisplacement(eyeVector, { from: Tree.EYE, to: Tree.WORLD }); + } + + p5.RendererGL.prototype._ndcToScreenDisplacement = function (vector) { + return new p5.Vector(this.width * vector.x / 2, this.height * vector.y / 2, vector.z / 2); + } + + p5.RendererGL.prototype._screenToNDCDisplacement = function (vector) { + return new p5.Vector(2 * vector.x / this.width, 2 * vector.y / this.height, 2 * vector.z); + } + + // 3. Shader utilities + + p5.prototype.readShader = function (fragFilename, { + precision, + matrices, + varyings + } = {}) { + let shader = new p5.Shader(); + this._coupledWith = fragFilename.substring(fragFilename.lastIndexOf('/') + 1); + shader._vertSrc = this.parseVertexShader({ precision: precision, matrices: matrices, varyings: varyings, _specs: false }); + this._coupledWith = undefined; + this.loadStrings( + fragFilename, + result => { + shader._fragSrc = result.join('\n') + } + ); + return shader; + } + + p5.prototype.makeShader = function (fragSrc, { + precision, + matrices, + varyings + } = {}) { + let shader = new p5.Shader(); + this._coupledWith = 'the fragment shader provided as param in makeShader()'; + shader._vertSrc = this.parseVertexShader({ precision: precision, matrices: matrices, varyings: varyings, _specs: false }); + this._coupledWith = undefined; + shader._fragSrc = fragSrc; + return shader; + } + + p5.prototype.parseVertexShader = function ({ + precision = Tree.mediump, + matrices = Tree.pmvMatrix, + varyings = Tree.color4 | Tree.texcoords2, + _specs = true + } = {}) { + let floatPrecision = `precision ${precision === Tree.highp ? 'highp' : `${precision === Tree.mediump ? 'mediump' : 'lowp'}`} float;` + let color4 = ~(varyings | ~Tree.color4) === 0; + let texcoords2 = ~(varyings | ~Tree.texcoords2) === 0; + let normal3 = ~(varyings | ~Tree.normal3) === 0; + let position2 = ~(varyings | ~Tree.position2) === 0; + let position3 = ~(varyings | ~Tree.position3) === 0; + let pmv = ~(matrices | ~Tree.pmvMatrix) === 0; + let p = ~(matrices | ~Tree.pMatrix) === 0; + let mv = ~(matrices | ~Tree.mvMatrix) === 0; + let n = (~(matrices | ~Tree.nMatrix) === 0) || normal3; + const target = `gl_Position =${pmv ? ' uModelViewProjectionMatrix * ' : `${p && mv ? ' uProjectionMatrix * uModelViewMatrix *' : ''} `}vec4(aPosition, 1.0)`; + let vertexShader = ` +${floatPrecision} +attribute vec3 aPosition; +${color4 ? 'attribute vec4 aVertexColor;' : ''} +${texcoords2 ? 'attribute vec2 aTexCoord;' : ''} +${normal3 ? 'attribute vec3 aNormal;' : ''} +${pmv ? 'uniform mat4 uModelViewProjectionMatrix;' : ''} +${p ? 'uniform mat4 uProjectionMatrix;' : ''} +${mv ? 'uniform mat4 uModelViewMatrix;' : ''} +${n ? 'uniform mat3 uNormalMatrix;' : ''} +${color4 ? 'varying vec4 color4;' : ''} +${texcoords2 ? 'varying vec2 texcoords2;' : ''} +${normal3 ? 'varying vec3 normal3;' : ''} +${position2 ? 'varying vec2 position2;' : ''} +${position3 ? 'varying vec3 position3;' : ''} +void main() { + ${color4 ? 'color4 = aVertexColor;' : ''} + ${texcoords2 ? 'texcoords2 = aTexCoord;' : ''} + ${normal3 ? 'normal3 = normalize(uNormalMatrix * aNormal);' : ''} + ${position2 ? 'position2 = vec4(aPosition, 1.0).xy;' : ''} + ${position3 ? 'position3 = vec4(aPosition, 1.0).xyz;' : ''} + ${target}; +} +`; + let advice = ` +/* +${this._coupledWith ? 'Vertex shader code to be coupled with ' + this._coupledWith : ''} +Generated with treegl version ${Tree.INFO.VERSION} +${_specs ? ` +Feel free to copy, paste, edit and save it. +Refer to createShader (https://p5js.org/reference/#/p5/createShader), +loadShader (https://p5js.org/reference/#/p5/loadShader), readShader +and makeShader (https://github.com/VisualComputing/p5.treegl#handling), +for details.` : ''} +*/ +`; + let result = advice + vertexShader; + result = result.split(/\r?\n/) + .filter(line => line.trim() !== '') + .join("\n"); + console.log(result); + return result; + } + + p5.prototype.emitMousePosition = function (shader, uniform = 'u_mouse') { + shader.setUniform(uniform, [this.mouseX * pixelDensity(), (this.height - this.mouseY) * pixelDensity()]); + } + + p5.prototype.emitPointerPosition = function () { + this._renderer.emitPointerPosition(...arguments); + } + + p5.RendererGL.prototype.emitPointerPosition = function (shader, pointerX, pointerY, uniform = 'u_pointer') { + shader.setUniform(uniform, [pointerX * pixelDensity(), (this.height - pointerY) * pixelDensity()]); + } + + p5.prototype.emitResolution = function () { + this._renderer.emitResolution(...arguments); + } + + p5.RendererGL.prototype.emitResolution = function (shader, uniform = 'u_resolution') { + shader.setUniform(uniform, [this.width * pixelDensity(), this.height * pixelDensity()]); + } + + p5.prototype.emitTexOffset = function (shader, image, uniform = 'u_texoffset') { + shader.setUniform(uniform, [1 / image.width, 1 / image.height]); + } + + // 4. Utility functions + + p5.prototype.pixelRatio = function () { + return this._renderer.pixelRatio(...arguments); + } + + /** + * Returns the world to pixel ratio units at given world location. + * A line of n * pixelRatio(location) world units will be projected + * with a length of n pixels on screen. + * @param {p5.Vector | Array} location world location reference + */ + p5.RendererGL.prototype.pixelRatio = function (location) { + return this._isOrtho() ? Math.abs(this.tPlane() - this.bPlane()) / this.height : + 2 * Math.abs((this._treeLocation(location, { from: Tree.WORLD, to: Tree.EYE, vMatrix: this._curCamera.cameraMatrix })).z) * Math.tan(this.fov() / 2) / this.height; + } + + p5.prototype.visibility = function () { + return this._renderer.visibility(...arguments); + } + + /** + * Returns object visibility (i.e, lies within the eye bounds) + * either Tree.VISIBLE, Tree.INVISIBLE, or Tree.SEMIVISIBLE. + * Object may be either a point, a sphere or an axis-aligned box. + * @param {p5.Vector | Array} corner1 box corner1, use it with corner2. + * @param {p5.Vector | Array} corner2 box corner2, use it with corner1. + * @param {p5.Vector | Array} center sphere (or point) center. + * @param {Number} radius sphere radius. + * @param {Array} bounds frustum equations 6x4 matrix. + */ + p5.RendererGL.prototype.visibility = function ({ + corner1, + corner2, + center, + radius, + bounds = this.bounds() + } = {}) { + return center ? radius ? this._ballVisibility(center, radius, bounds) : this._pointVisibility(center, bounds) + : corner1 && corner2 ? this._boxVisibility(corner1, corner2, bounds) : console.error('couldn\'t parse your visibility query!'); + } + + p5.RendererGL.prototype._pointVisibility = function (point, bounds = this.bounds()) { + for (const key in bounds) { + let d = this.distanceToBound(point, key, bounds); + if (d > 0) { + return Tree.INVISIBLE; + } + if (d === 0) { + return Tree.SEMIVISIBLE; + } + } + return Tree.VISIBLE; + } + + p5.RendererGL.prototype._ballVisibility = function (center, radius, bounds = this.bounds()) { + let allInForAllPlanes = true; + for (const key in bounds) { + let d = this.distanceToBound(center, key, bounds); + if (d > radius) { + return Tree.INVISIBLE; + } + if ((d > 0) || (-d < radius)) { + allInForAllPlanes = false; + } + } + if (allInForAllPlanes) { + return Tree.VISIBLE; + } + return Tree.SEMIVISIBLE; + } + + p5.RendererGL.prototype._boxVisibility = function (corner1, corner2, bounds = this.bounds()) { + if (Array.isArray(corner1)) { + corner1 = new p5.Vector(corner1[0] ?? 0, corner1[1] ?? 0, corner1[2] ?? 0); + } + if (Array.isArray(corner2)) { + corner2 = new p5.Vector(corner2[0] ?? 0, corner2[1] ?? 0, corner2[2] ?? 0); + } + let allInForAllPlanes = true; + for (const key in bounds) { + let allOut = true; + for (let c = 0; c < 8; ++c) { + let pos = new p5.Vector(((c & 4) != 0) ? corner1.x : corner2.x, ((c & 2) != 0) ? corner1.y : corner2.y, + ((c & 1) != 0) ? corner1.z : corner2.z); + if (this.distanceToBound(pos, key, bounds) > 0) { + allInForAllPlanes = false; + } + else { + allOut = false; + } + } + // The eight points are on the outside side of this plane + if (allOut) { + return Tree.INVISIBLE; + } + } + if (allInForAllPlanes) { + return Tree.VISIBLE; + } + // Too conservative, but tangent cases are too expensive to detect + return Tree.SEMIVISIBLE; + } + + p5.prototype.bounds = function () { + return this._renderer.bounds(...arguments); + } + + /** + * Returns the 6 plane equations of the eye frustum bounds defined + * in the world coordinate system encoded as an object literal + * having 'Tree.LEFT' (left plane), 'Tree.RIGHT' (right plane), + * 'Tree.NEAR' (near plane), 'Tree.FAR' (far plane) 'Tree.TOP' + * (top plane) and 'Tree.BOTTOM' (bottom plane) keys. + * Each key holds a plane equation of the form: + * a*x + b*y + c*z + d = 0, where a, b, c and d are the 4 + * keys of each object literal. + */ + p5.RendererGL.prototype.bounds = function () { + let normals = Array(6); + let distances = Array(6); + // Computed once and for all + // TODO experimental: no need to normalize + let pos = this._treeLocation([0, 0, 0], { from: Tree.EYE, to: Tree.WORLD }); + let viewDir = this._treeDisplacement([0, 0, -1], { from: Tree.EYE, to: Tree.WORLD }); + // same as: let viewDir = this.treeDisplacement(); + let up = this._treeDisplacement([0, 1, 0], { from: Tree.EYE, to: Tree.WORLD }); + let right = this._treeDisplacement([1, 0, 0], { from: Tree.EYE, to: Tree.WORLD }); + let posViewDir = p5.Vector.dot(pos, viewDir); + if (this._isOrtho()) { + normals[0] = p5.Vector.mult(right, -1); + normals[1] = right; + normals[4] = up; + normals[5] = p5.Vector.mult(up, -1); + let wh0 = Math.abs(this.rPlane() - this.lPlane()) / 2; + let wh1 = Math.abs(this.tPlane() - this.bPlane()) / 2; + distances[0] = p5.Vector.dot(p5.Vector.sub(pos, p5.Vector.mult(right, wh0)), normals[0]); + distances[1] = p5.Vector.dot(p5.Vector.add(pos, p5.Vector.mult(right, wh0)), normals[1]); + distances[4] = p5.Vector.dot(p5.Vector.add(pos, p5.Vector.mult(up, wh1)), normals[4]); + distances[5] = p5.Vector.dot(p5.Vector.sub(pos, p5.Vector.mult(up, wh1)), normals[5]); + } + else { + let hhfov = this.hfov() / 2; + let chhfov = Math.cos(hhfov); + let shhfov = Math.sin(hhfov); + normals[0] = p5.Vector.mult(viewDir, -shhfov); + normals[1] = p5.Vector.add(normals[0], p5.Vector.mult(right, chhfov)); + normals[0] = p5.Vector.add(normals[0], p5.Vector.mult(right, -chhfov)); + normals[2] = p5.Vector.mult(viewDir, -1); + normals[3] = viewDir; + let hfov = this.fov() / 2; + let chfov = Math.cos(hfov); + let shfov = Math.sin(hfov); + normals[4] = p5.Vector.mult(viewDir, -shfov); + normals[5] = p5.Vector.add(normals[4], p5.Vector.mult(up, -chfov)); + normals[4] = p5.Vector.add(normals[4], p5.Vector.mult(up, chfov)); + for (let i = 0; i < 2; ++i) { + distances[i] = p5.Vector.dot(pos, normals[i]); + } + for (let j = 4; j < 6; ++j) { + distances[j] = p5.Vector.dot(pos, normals[j]); + } + // Natural equations are: + // dist[0,1,4,5] = pos * normal[0,1,4,5]; + // dist[2] = (pos + zNear() * viewDir) * normal[2]; + // dist[3] = (pos + zFar() * viewDir) * normal[3]; + // 2 times less computations using expanded/merged equations. Dir vectors + // are normalized. + let posRightCosHH = chhfov * p5.Vector.dot(pos, right); + distances[0] = -shhfov * posViewDir; + distances[1] = distances[0] + posRightCosHH; + distances[0] = distances[0] - posRightCosHH; + let posUpCosH = chfov * p5.Vector.dot(pos, up); + distances[4] = -shfov * posViewDir; + distances[5] = distances[4] - posUpCosH; + distances[4] = distances[4] + posUpCosH; + } + // Front and far planes are identical for both camera types. + normals[2] = p5.Vector.mult(viewDir, -1); + normals[3] = viewDir; + distances[2] = -posViewDir - this.nPlane(); + distances[3] = posViewDir + this.fPlane(); + let bounds = {}; + bounds[Tree.LEFT] = { a: normals[0].x, b: normals[0].y, c: normals[0].z, d: distances[0] }; + bounds[Tree.RIGHT] = { a: normals[1].x, b: normals[1].y, c: normals[1].z, d: distances[1] }; + bounds[Tree.NEAR] = { a: normals[2].x, b: normals[2].y, c: normals[2].z, d: distances[2] }; + bounds[Tree.FAR] = { a: normals[3].x, b: normals[3].y, c: normals[3].z, d: distances[3] }; + bounds[Tree.TOP] = { a: normals[4].x, b: normals[4].y, c: normals[4].z, d: distances[4] }; + bounds[Tree.BOTTOM] = { a: normals[5].x, b: normals[5].y, c: normals[5].z, d: distances[5] }; + return bounds; + } + + p5.prototype.distanceToBound = function () { + return this._renderer.distanceToBound(...arguments); + } + + /** + * Returns the signed distance between location and the frustum plane defined + * by bounds and key which may be either Tree.LEFT, Tree.RIGHT, Tree.BOTTOM, + * Tree.TOP, Tree.NEAR or Tree.FAR. The distance is negative if the point lies + * in the planes's bounding halfspace, and positive otherwise. + */ + p5.RendererGL.prototype.distanceToBound = function (location, key, bounds = this.bounds()) { + if (Array.isArray(location)) { + location = new p5.Vector(location[0] ?? 0, location[1] ?? 0, location[2] ?? 0); + } + return p5.Vector.dot(location, new p5.Vector(bounds[key].a, bounds[key].b, bounds[key].c)) - bounds[key].d; + } + + p5.prototype.mousePicking = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + return this.pointerPicking(this.mouseX, this.mouseY, { mMatrix: mMatrix, x: x, y: y, size: size, shape: shape, eMatrix: eMatrix, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + + p5.prototype.pointerPicking = function () { + return this._renderer.pointerPicking(...arguments); + } + + /** + * Returns true if pointer is close enough to pointerX, pointerY screen location. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size bullseye diameter. Default is 50. + * @param {Number} shape either Tree.CIRCLE, Tree.SQUARE or Tree.PROJECTION. Default is Tree.CIRCLE. + */ + p5.RendererGL.prototype.pointerPicking = function (pointerX, pointerY, { + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + // TODO implement webgl picking here using a switch statement: Tree.CIRCLE, Tree.SQUARE, Tree.PROJECTION + let radius = size / 2; + return shape === Tree.CIRCLE ? + Math.sqrt(Math.pow((x - pointerX), 2.0) + Math.pow((y - pointerY), 2.0)) < radius : + ((Math.abs(pointerX - x) < radius) && (Math.abs(pointerY - y) < radius)); + } + + // 5. Drawing stuff + + p5.prototype.axes = function () { + this._renderer.axes(...arguments); + }; + + /** + * Draws axes. + * @param {Number} size size in world units. + * @param {Number} bits bitwise mask that may be composed of Tree.X, Tree._X, + * Tree.Y, Tree._Y, Tree.Z, Tree._Z and Tree.LABELS bits. + */ + p5.RendererGL.prototype.axes = function ({ size = 100, bits = Tree.LABELS | Tree.X | Tree.Y | Tree.Z } = {}) { + this._rendererState = this.push(); + if (~(bits | ~Tree.LABELS) === 0) { + const charWidth = size / 40.0; + const charHeight = size / 30.0; + const charShift = 1.04 * size; + // The X + this.stroke(200, 0, 0); + this.line(charShift, charWidth, -charHeight, charShift, -charWidth, charHeight); + this.line(charShift, -charWidth, -charHeight, charShift, charWidth, charHeight); + // The Y + this.stroke(0, 200, 0); + this.line(charWidth, charShift, charHeight, 0.0, charShift, 0.0); + this.line(0.0, charShift, 0.0, -charWidth, charShift, charHeight); + this.line(-charWidth, charShift, charHeight, 0.0, charShift, 0.0); + this.line(0.0, charShift, 0.0, 0.0, charShift, -charHeight); + // The Z + this.stroke(0, 100, 200); + this.line(-charWidth, -charHeight, charShift, charWidth, -charHeight, charShift); + this.line(charWidth, -charHeight, charShift, -charWidth, charHeight, charShift); + this.line(-charWidth, charHeight, charShift, charWidth, charHeight, charShift); + } + // X Axis + this.stroke(200, 0, 0); + if (~(bits | ~Tree.X) === 0) { + this.line(0, 0, 0, size, 0, 0); + } + if (~(bits | ~Tree._X) === 0) { + this.line(0, 0, 0, -size, 0, 0); + } + // Y Axis + this.stroke(0, 200, 0); + if (~(bits | ~Tree.Y) === 0) { + this.line(0, 0, 0, 0, size, 0); + } + if (~(bits | ~Tree._Y) === 0) { + this.line(0, 0, 0, 0, -size, 0); + } + // Z Axis + this.stroke(0, 100, 200); + if (~(bits | ~Tree.Z) === 0) { + this.line(0, 0, 0, 0, 0, size); + } + if (~(bits | ~Tree._Z) === 0) { + this.line(0, 0, 0, 0, 0, -size); + } + this.pop(this._rendererState); + }; + + p5.prototype.grid = function () { + this._renderer.grid(...arguments); + }; + + /** + * Draws grid + * @param {Number} size grid size in world units. Default is 100. + * @param {Number} subdivisions number of grid subdivisions. Default is 10. + * @param {Number} style either Tree.DOTS or Tree.SOLID. Default is Tree.DOTS. + */ + p5.RendererGL.prototype.grid = function ({ size = 100, subdivisions = 10, style = Tree.DOTS } = {}) { + this._rendererState = this.push(); + if (style === Tree.DOTS) { + let weight = this.curStrokeWeight; + // other useful as well: this.curStrokeColor this.curFillColor + let posi = 0; + let posj = 0; + this.strokeWeight(weight * 2); + this.beginShape(0x0000); + for (let i = 0; i <= subdivisions; ++i) { + posi = size * (2.0 * i / subdivisions - 1.0); + for (let j = 0; j <= subdivisions; ++j) { + posj = size * (2.0 * j / subdivisions - 1.0); + this.vertex(posi, posj, 0); + } + } + this.endShape(); + const internalSub = 5; + const subSubdivisions = subdivisions * internalSub; + this.strokeWeight(weight); + this.beginShape(0x0000); + for (let i = 0; i <= subSubdivisions; ++i) { + posi = size * (2.0 * i / subSubdivisions - 1.0); + for (let j = 0; j <= subSubdivisions; ++j) { + posj = size * (2.0 * j / subSubdivisions - 1.0); + if (((i % internalSub) != 0) || ((j % internalSub) != 0)) + this.vertex(posi, posj, 0); + } + } + this.endShape(); + } + else { + for (let i = 0; i <= subdivisions; ++i) { + const pos = size * (2.0 * i / subdivisions - 1.0); + this.line(pos, -size, 0, pos, +size, 0); + this.line(-size, pos, 0, size, pos, 0); + } + } + this.pop(this._rendererState); + }; + + p5.prototype.cross = function () { + this._renderer.cross(...arguments); + }; + + /** + * Draws a cross on the screen. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size cross size. Default is 50. + */ + p5.RendererGL.prototype.cross = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + const half_size = size / 2.0; + this._rendererState = this.push(); + this.beginHUD(); + this.line(x - half_size, y, x + half_size, y); + this.line(x, y - half_size, x, y + half_size); + this.endHUD(); + this.pop(this._rendererState); + }; + + p5.prototype.bullsEye = function () { + this._renderer.bullsEye(...arguments); + }; + + /** + * Draws a bulls-eye on the screen. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size bullseye diameter. Default is 50. + * @param {Number} shape either Tree.CIRCLE or Tree.SQUARE. Default is Tree.CIRCLE. + */ + p5.RendererGL.prototype.bullsEye = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + this._rendererState = this.push(); + if (shape === Tree.CIRCLE) { + this.beginHUD(); + this._circle({ x, y, radius: size / 2 }) + this.endHUD(); + } + else { + const half_length = size / 2.0; + this.beginHUD(); + this.line((x - half_length), (y - half_length) + (0.6 * half_length), (x - half_length), (y - half_length)); + this.line((x - half_length), (y - half_length), (x - half_length) + (0.6 * half_length), (y - half_length)); + this.line((x + half_length) - (0.6 * half_length), (y - half_length), (x + half_length), (y - half_length)); + this.line((x + half_length), (y - half_length), (x + half_length), ((y - half_length) + (0.6 * half_length))); + this.line((x + half_length), ((y + half_length) - (0.6 * half_length)), (x + half_length), (y + half_length)); + this.line((x + half_length), (y + half_length), ((x + half_length) - (0.6 * half_length)), (y + half_length)); + this.line((x - half_length) + (0.6 * half_length), (y + half_length), (x - half_length), (y + half_length)); + this.line((x - half_length), (y + half_length), (x - half_length), ((y + half_length) - (0.6 * half_length))); + this.endHUD(); + } + this.cross({ x: x, y: y, size: 0.6 * size }); + this.pop(this._rendererState); + }; + + p5.prototype._circle = function () { + this._renderer._circle(...arguments); + }; + + p5.RendererGL.prototype._circle = function ({ filled = false, x = this.width / 2, y = this.height / 2, radius = 100, detail = 50 } = {}) { + this._rendererState = this.push(); + if (filled) { + this.beginShape(0x0005); + for (let t = 0; t <= detail; t++) { + const x = Math.cos(t * (2 * Math.PI) / detail); + const y = Math.sin(t * (2 * Math.PI) / detail); + this.vertex(0, 0, 0, 0.5, 0.5) + this.vertex(radius * x, radius * y, 0, (x * 0.5) + 0.5, (y * 0.5) + 0.5); + } + this.endShape(); + } + else { + this.translate(x, y); + const angle = (2 * Math.PI) / detail; + let lastPosition = { x: radius, y: 0 }; + for (let i = 1; i <= detail; i++) { + let position = { x: Math.cos(i * angle) * radius, y: Math.sin(i * angle) * radius }; + this.line(lastPosition.x, lastPosition.y, position.x, position.y); + lastPosition = position; + } + } + this.pop(this._rendererState); + }; + + p5.prototype.viewFrustum = function () { + this._renderer.viewFrustum(...arguments); + }; + + /** + * Display fbo view frustum. + * @param {p5.RendererGL | p5.Graphics} fbo renderer which viewing frustum is to be displayed. + * @param {Number} bits bitwise view-frustum mask that may be composed of Tree.NEAR, Tree.FAR and Tree.BODY bits. + * @param {Function} viewer callback fbo visual representation. + */ + p5.RendererGL.prototype.viewFrustum = function ({ + fbo = _renderer, + bits = Tree.NEAR | Tree.FAR, + viewer = () => this.axes({ size: 50, bits: Tree.X | Tree._X | Tree.Y | Tree._Y | Tree.Z | Tree._Z }) + } = {}) { + if (this === fbo) { + console.error('displaying viewFrustum requires an fbo different than this'); + return; + } + this._rendererState = this.push(); + this.resetMatrix(); + this.applyMatrix(...this.vMatrix().mat4); + this.applyMatrix(...fbo.eMatrix().mat4); + fbo._isOrtho() ? this._viewOrtho(fbo, bits, viewer) : this._viewPerspective(fbo, bits, viewer); + this.pop(this._rendererState); + }; + + p5.RendererGL.prototype._viewOrtho = function (fbo, bits, viewer) { + if (viewer !== Tree.NONE) { + viewer(); + } + let l = fbo.lPlane(); + let r = fbo.rPlane(); + let b = fbo.bPlane(); + let t = fbo.tPlane(); + let n = fbo.nPlane(); + let f = fbo.fPlane(); + if (~(bits | ~Tree.FAR) === 0) { + this.beginShape(); + this.vertex(r, t, -f, 0, 0); + this.vertex(l, t, -f, 1, 0); + this.vertex(l, b, -f, 1, 1); + this.vertex(r, b, -f, 0, 1); + this.endShape(); + } + else { + this.line(r, t, -f, l, t, -f); + this.line(l, t, -f, l, b, -f); + this.line(l, b, -f, r, b, -f); + this.line(r, b, -f, r, t, -f); + } + if (~(bits | ~Tree.BODY) === 0) { + this.beginShape(); + this.vertex(l, t, -f); + this.vertex(l, t, -n); + this.vertex(r, t, -n); + this.vertex(r, t, -f); + this.endShape(); + this.beginShape(); + this.vertex(r, t, -f); + this.vertex(r, t, -n); + this.vertex(r, b, -n); + this.vertex(r, b, -f); + this.endShape(); + this.beginShape(); + this.vertex(r, b, -f); + this.vertex(r, b, -n); + this.vertex(l, b, -n); + this.vertex(l, b, -f); + this.endShape(); + this.beginShape(); + this.vertex(l, t, -n); + this.vertex(l, t, -f); + this.vertex(l, b, -f); + this.vertex(l, b, -n); + this.endShape(); + } + else { + this.line(r, t, -n, r, t, -f); + this.line(l, t, -n, l, t, -f); + this.line(l, b, -n, l, b, -f); + this.line(r, b, -n, r, b, -f); + } + // TODO implement near plane texture + if (~(bits | ~Tree.NEAR) === 0) { + this.beginShape(); + this.vertex(r, t, -n, 0, 0); + this.vertex(l, t, -n, 1, 0); + this.vertex(l, b, -n, 1, 1); + this.vertex(r, b, -n, 0, 1); + this.endShape(); + } + else { + this.line(r, t, -n, l, t, -n); + this.line(l, t, -n, l, b, -n); + this.line(l, b, -n, r, b, -n); + this.line(r, b, -n, r, t, -n); + } + }; + + p5.RendererGL.prototype._viewPerspective = function (fbo, bits, viewer) { + if (viewer !== Tree.NONE) { + viewer(); + } + let magnitude = Math.tan(fbo.fov() / 2); + let aspectRatio = fbo.width / fbo.height; + const points = [ + { x: 0, y: 0, z: 0 }, + { x: 0, y: 0, z: 0 }, + ]; + points[0].z = fbo.nPlane(); + points[1].z = fbo.fPlane(); + points[0].y = points[0].z * magnitude; + points[0].x = points[0].y * aspectRatio; + const ratio = points[1].z / points[0].z; + points[1].y = ratio * points[0].y; + points[1].x = ratio * points[0].x; + if (~(bits | ~Tree.FAR) === 0) { + this.beginShape(); + this.vertex(-points[1].x, points[1].y, -points[1].z, 0, 0); + this.vertex(points[1].x, points[1].y, -points[1].z, 1, 0); + this.vertex(points[1].x, -points[1].y, -points[1].z, 0, 1); + this.vertex(-points[1].x, -points[1].y, -points[1].z, 1, 1); + this.endShape(); + } + else { + this.line(-points[1].x, points[1].y, -points[1].z, points[1].x, points[1].y, -points[1].z); + this.line(points[1].x, points[1].y, -points[1].z, points[1].x, -points[1].y, -points[1].z); + this.line(points[1].x, -points[1].y, -points[1].z, -points[1].x, -points[1].y, -points[1].z); + this.line(-points[1].x, -points[1].y, -points[1].z, -points[1].x, points[1].y, -points[1].z); + } + if (~(bits | ~Tree.BODY) === 0) { + this.beginShape(); + this.vertex(-points[1].x, points[1].y, -points[1].z); + this.vertex(-points[0].x, points[0].y, -points[0].z); + this.vertex(points[0].x, points[0].y, -points[0].z); + this.vertex(points[1].x, points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(points[1].x, points[1].y, -points[1].z); + this.vertex(points[0].x, points[0].y, -points[0].z); + this.vertex(points[0].x, -points[0].y, -points[0].z); + this.vertex(points[1].x, -points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(points[1].x, -points[1].y, -points[1].z); + this.vertex(points[0].x, -points[0].y, -points[0].z); + this.vertex(-points[0].x, -points[0].y, -points[0].z); + this.vertex(-points[1].x, -points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(-points[0].x, points[0].y, -points[0].z); + this.vertex(-points[1].x, points[1].y, -points[1].z); + this.vertex(-points[1].x, -points[1].y, -points[1].z); + this.vertex(-points[0].x, -points[0].y, -points[0].z); + this.endShape(); + this.line(0, 0, 0, points[0].x, points[0].y, -points[0].z); + this.line(0, 0, 0, -points[0].x, points[0].y, -points[0].z); + this.line(0, 0, 0, -points[0].x, -points[0].y, -points[0].z); + this.line(0, 0, 0, points[0].x, -points[0].y, -points[0].z); + } + else { + this.line(0, 0, 0, points[1].x, points[1].y, -points[1].z); + this.line(0, 0, 0, -points[1].x, points[1].y, -points[1].z); + this.line(0, 0, 0, -points[1].x, -points[1].y, -points[1].z); + this.line(0, 0, 0, points[1].x, -points[1].y, -points[1].z); + } + // TODO implement near plane texture + // Something along the lines + // this.textureMode(NORMAL); + // this.tint(255, 126); // Apply transparency without changing color + // this.texture(fbo); + // doesn't work since this.texture is not found + if (~(bits | ~Tree.NEAR) === 0) { + this.beginShape(); + this.vertex(-points[0].x, points[0].y, -points[0].z, 0, 0); + this.vertex(points[0].x, points[0].y, -points[0].z, 1, 0); + this.vertex(points[0].x, -points[0].y, -points[0].z, 0, 1); + this.vertex(-points[0].x, -points[0].y, -points[0].z, 1, 1); + this.endShape(); + } + else { + this.line(-points[0].x, points[0].y, -points[0].z, points[0].x, points[0].y, -points[0].z); + this.line(points[0].x, points[0].y, -points[0].z, points[0].x, -points[0].y, -points[0].z); + this.line(points[0].x, -points[0].y, -points[0].z, -points[0].x, -points[0].y, -points[0].z); + this.line(-points[0].x, -points[0].y, -points[0].z, -points[0].x, points[0].y, -points[0].z); + } + }; +})(); \ No newline at end of file diff --git a/content/sketches/maze/plane.js b/content/sketches/maze/plane.js new file mode 100644 index 00000000..4b596772 --- /dev/null +++ b/content/sketches/maze/plane.js @@ -0,0 +1,17 @@ +function Plane(){ + this.planeMaxMagR = 25; + this.planeColor = "rgb(255, 247, 233)"; + this.planeMagnitudeR = 0; + + this.planeRotateV = createVector(1,0,0); + this.planeSize = createVector(200,200,0); //ancho y alto + this.planePosition = createVector(0,0,0); + + this.draw = function(fbo){ + + fbo.fill(this.planeColor); + fbo.translate(this.planePosition); + fbo.plane(this.planeSize.x,this.planeSize.y) + + }; + } \ No newline at end of file diff --git a/content/sketches/maze/sketch.js b/content/sketches/maze/sketch.js new file mode 100644 index 00000000..981b73be --- /dev/null +++ b/content/sketches/maze/sketch.js @@ -0,0 +1,2010 @@ +function Ball(P){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0) + this.sphereRadius = 7; + this.spherePosition = createVector(92.5-38*4.5,38*-1,this.sphereRadius); + + this.minVertex = createVector(-P.planeSize.x/2,-P.planeSize.y/2,0); + this.maxVertex = createVector(P.planeSize.x/2,P.planeSize.y/2,0); + + this.draw = function(fbo){ + fbo.push(); + fbo.fill("rgb(0, 0, 0)"); + fbo1.noStroke(); + fbo.translate(this.spherePosition); + fbo.sphere(this.sphereRadius) + fbo.pop() + } + this.move = function(P, acceleration, factorAcc, isAcelerate){ + + if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + if(isAcelerate){ + this.sphereMoveVector.x = (acceleration.x*factorAcc)*isAcelerate; + this.sphereMoveVector.y = (acceleration.y*factorAcc)*isAcelerate; + + this.spherePosition.x = (this.sphereMoveVector.x*factorAcc) + this.spherePosition.x + this.spherePosition.y = (this.sphereMoveVector.y*factorAcc) + this.spherePosition.y; + } + else{ + this.sphereMoveVector.x = (acceleration.x*factorAcc) + this.sphereMoveVector.x; + this.sphereMoveVector.y = (acceleration.y*factorAcc) + this.sphereMoveVector.y; + this.spherePosition.x = (this.sphereMoveVector.x*factorAcc) + this.spherePosition.x + this.spherePosition.y = (this.sphereMoveVector.y*factorAcc) + this.spherePosition.y; + } + + }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + this.sphereMoveVector = createVector(0,0,0); + this.acceleration = createVector(0,0,0); + } + // if(P.planeRotateV.x != 0 || P.planeRotateV.y != 0){ + // B.sphereMoveVector.x = (B.acceleration.x*0.1) + B.sphereMoveVector.x; + // B.sphereMoveVector.y = (B.acceleration.y*0.1) + B.sphereMoveVector.y; + + // B.spherePosition.x = (B.sphereMoveVector.x*0.1) + B.spherePosition.x + // B.spherePosition.y = (B.sphereMoveVector.y*0.1) + B.spherePosition.y; + + // }else if(P.planeRotateV.x == 0 && P.planeRotateV.y == 0){ + // B.sphereMoveVector = createVector(0,0,0); + // B.acceleration = createVector(0,0,0); + // } + } +} + + +'use strict'; + +// See: +// https://github.com/processing/p5.js/blob/main/contributor_docs/creating_libraries.md +// https://github.com/processing/p5.js/blob/main/src/core/README.md +// https://github.com/processing/p5.js/blob/main/contributor_docs/webgl_mode_architecture.md + +/** @namespace */ +var Tree = (function (ext) { + const INFO = + { + LIBRARY: 'p5.treegl', + VERSION: '0.3.0', + HOMEPAGE: 'https://github.com/VisualComputing/p5.treegl' + }; + Object.freeze(INFO); + const NONE = 0; + // Axes consts + const X = 1 << 0; + const Y = 1 << 1; + const Z = 1 << 2; + const _X = 1 << 3; + const _Y = 1 << 4; + const _Z = 1 << 5; + const LABELS = 1 << 6; + // grid style + const SOLID = 0; + const DOTS = 1 + // bullseye and picking shape + const SQUARE = 0; + const CIRCLE = 1; + // only picking shape + const PROJECTION = 2; + // Frustum consts + const NEAR = 1 << 0; + const FAR = 1 << 1; + const LEFT = 1 << 2; + const RIGHT = 1 << 3; + const BOTTOM = 1 << 4; + const TOP = 1 << 5; + const BODY = 1 << 6; + // visibility + const INVISIBLE = 0; + const VISIBLE = 1; + const SEMIVISIBLE = 2; + // spaces + const WORLD = 'WORLD'; + const EYE = 'EYE'; + const NDC = 'NDC'; + const SCREEN = 'SCREEN'; + const MODEL = 'MODEL'; + // points + const ORIGIN = [0, 0, 0]; + // vectors + const i = [1, 0, 0]; + const j = [0, 1, 0]; + const k = [0, 0, 1]; + const _i = [-1, 0, 0]; + const _j = [0, -1, 0]; + const _k = [0, 0, -1]; + // shaders + // precision + const lowp = 0; + const mediump = 1; + const highp = 2; + // in + const pmvMatrix = 1 << 0; + const pMatrix = 1 << 1; + const mvMatrix = 1 << 2; + const nMatrix = 1 << 3; + // out + const color4 = 1 << 0; + const texcoords2 = 1 << 1; + const normal3 = 1 << 2; + const position2 = 1 << 3; + const position3 = 1 << 4; + ext ??= {}; + ext.INFO = INFO; + ext.NONE = NONE; + ext.X = X; + ext.Y = Y; + ext.Z = Z; + ext._X = _X; + ext._Y = _Y; + ext._Z = _Z; + ext.LABELS = LABELS; + ext.SOLID = SOLID; + ext.DOTS = DOTS; + ext.SQUARE = SQUARE; + ext.CIRCLE = CIRCLE; + ext.PROJECTION = PROJECTION; + ext.NEAR = NEAR; + ext.FAR = FAR; + ext.LEFT = LEFT; + ext.RIGHT = RIGHT; + ext.BOTTOM = BOTTOM; + ext.TOP = TOP; + ext.BODY = BODY; + ext.INVISIBLE = INVISIBLE; + ext.VISIBLE = VISIBLE; + ext.SEMIVISIBLE = SEMIVISIBLE; + ext.WORLD = WORLD; + ext.EYE = EYE; + ext.NDC = NDC; + ext.SCREEN = SCREEN; + ext.MODEL = MODEL; + ext.ORIGIN = ORIGIN; + ext.i = i; + ext.j = j; + ext.k = k; + ext._i = _i; + ext._j = _j; + ext._k = _k; + ext.lowp = lowp; + ext.mediump = mediump; + ext.highp = highp; + ext.pmvMatrix = pmvMatrix; + ext.pMatrix = pMatrix; + ext.mvMatrix = mvMatrix; + ext.nMatrix = nMatrix; + ext.color4 = color4; + ext.texcoords2 = texcoords2; + ext.normal3 = normal3; + ext.position2 = position2; + ext.position3 = position3; + return ext; +})(Tree); + + +(function () { + console.log(Tree.INFO); + + // 1. Matrix stuff + + p5.Matrix.prototype.mult3 = function (vector) { + if (this.mat3 === undefined) { + console.error('mult3 only works with mat3'); + return; + } + return new p5.Vector(this.mat3[0] * vector.x + this.mat3[3] * vector.y + this.mat3[6] * vector.z, + this.mat3[1] * vector.x + this.mat3[4] * vector.y + this.mat3[7] * vector.z, + this.mat3[2] * vector.x + this.mat3[5] * vector.y + this.mat3[8] * vector.z); + }; + + p5.Matrix.prototype.mult4 = function (vector) { + return new p5.Vector(...this._mult4([vector.x, vector.y, vector.z, 1])); + }; + + p5.Matrix.prototype._mult4 = function (vec4) { + if (this.mat4 === undefined) { + console.error('_mult4 only works with mat4'); + return; + } + return [this.mat4[0] * vec4[0] + this.mat4[4] * vec4[1] + this.mat4[8] * vec4[2] + this.mat4[12] * vec4[3], + this.mat4[1] * vec4[0] + this.mat4[5] * vec4[1] + this.mat4[9] * vec4[2] + this.mat4[13] * vec4[3], + this.mat4[2] * vec4[0] + this.mat4[6] * vec4[1] + this.mat4[10] * vec4[2] + this.mat4[14] * vec4[3], + this.mat4[3] * vec4[0] + this.mat4[7] * vec4[1] + this.mat4[11] * vec4[2] + this.mat4[15] * vec4[3]]; + }; + + p5.prototype.tMatrix = function (matrix) { + return matrix.copy().transpose(matrix); + } + + p5.prototype.invMatrix = function (matrix) { + return matrix.copy().invert(matrix); + } + + p5.prototype.axbMatrix = function (a, b) { + return a.copy().apply(b); + } + + p5.prototype.iMatrix = function () { + return new p5.Matrix(); + } + + p5.prototype.lMatrix = function () { + return this._renderer.lMatrix(...arguments); + } + + // defaults: from: iMatrix, to: eMatrix + p5.RendererGL.prototype.lMatrix = function ( + { + from = new p5.Matrix(), + to = this.eMatrix() + } = {}) { + return to.copy().invert(to).apply(from); + } + + p5.prototype.dMatrix = function () { + return this._renderer.dMatrix(...arguments); + } + + // defaults: from: iMatrix, to: eMatrix + p5.RendererGL.prototype.dMatrix = function ( + { + from = new p5.Matrix(), + to = this.eMatrix(), + matrix = from.copy().invert(from).apply(to) + } = {}) { + // Note that this transposes mat4 into mat3 + return new p5.Matrix('mat3', [matrix.mat4[0], matrix.mat4[4], matrix.mat4[8], + matrix.mat4[1], matrix.mat4[5], matrix.mat4[9], + matrix.mat4[2], matrix.mat4[6], matrix.mat4[10]]); + } + + p5.prototype.pMatrix = function () { + return this._renderer.pMatrix(...arguments); + } + + p5.RendererGL.prototype.pMatrix = function () { + return this.uPMatrix.copy(); + } + + p5.prototype.mvMatrix = function () { + return this._renderer.mvMatrix(...arguments); + } + + // defaults when mMatrix is defined: vMatrix: this.vMatrix, mMatrix: + // otherwise it returns a copy of the current mvMatrix + p5.RendererGL.prototype.mvMatrix = function ( + { + vMatrix, + mMatrix + } = {}) { + return mMatrix ? (vMatrix ?? this.vMatrix()).copy().apply(mMatrix) : this.uMVMatrix.copy(); + } + + p5.prototype.mMatrix = function () { + return this._renderer.mMatrix(...arguments); + } + + // defaults: eMatrix: this.eMatrix, mvMatrix: this.mvMatrix + p5.RendererGL.prototype.mMatrix = function ( + { + eMatrix = this.eMatrix(), + mvMatrix = this.mvMatrix() + } = {}) { + return eMatrix.copy().apply(mvMatrix); + } + + p5.prototype.nMatrix = function () { + return this._renderer.nMatrix(...arguments); + } + + p5.RendererGL.prototype.nMatrix = function ({ + vMatrix, + mMatrix, + mvMatrix = this.mvMatrix({ mMatrix: mMatrix, vMatrix: vMatrix }) + } = {}) { + return new p5.Matrix('mat3').inverseTranspose(mvMatrix); + } + + // TODO check where to replace vMatrix for: + // this._curCamera.cameraMatrix + + p5.prototype.vMatrix = function () { + return this._renderer.vMatrix(...arguments); + } + + p5.RendererGL.prototype.vMatrix = function () { + return this._curCamera.vMatrix(); + } + + p5.Camera.prototype.vMatrix = function () { + return this.cameraMatrix.copy(); + } + + p5.prototype.eMatrix = function () { + return this._renderer.eMatrix(...arguments); + } + + p5.RendererGL.prototype.eMatrix = function () { + return this._curCamera.eMatrix(); + } + + p5.Camera.prototype.eMatrix = function () { + return this.cameraMatrix.copy().invert(this.cameraMatrix); + } + + p5.prototype.pmvMatrix = function () { + return this._renderer.pmvMatrix(...arguments); + } + + p5.RendererGL.prototype.pmvMatrix = function ( + { + pMatrix = this.uPMatrix, + vMatrix, + mMatrix, + mvMatrix = this.mvMatrix({ mMatrix: mMatrix, vMatrix: vMatrix }) + } = {}) { + return pMatrix.copy().apply(mvMatrix); + } + + p5.prototype.pvMatrix = function () { + return this._renderer.pvMatrix(...arguments); + } + + // defaults: pMatrix: this.pMatrix, vMatrix: this.vMatrix + p5.RendererGL.prototype.pvMatrix = function ( + { + pMatrix = this.uPMatrix, + vMatrix = this._curCamera.cameraMatrix + } = {}) { + return pMatrix.copy().apply(vMatrix); + } + + p5.prototype.pvInvMatrix = function () { + return this._renderer.pvInvMatrix(...arguments); + } + + p5.RendererGL.prototype.pvInvMatrix = function ( + { + pMatrix, + vMatrix, + pvMatrix + } = {}) { + let matrix = pvMatrix ? pvMatrix.copy() : this.pvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix }); + return matrix.invert(matrix); + } + + p5.prototype._isOrtho = function () { + return this._renderer._isOrtho(...arguments); + } + + p5.RendererGL.prototype._isOrtho = function () { + return this.uPMatrix._isOrtho(); + } + + p5.Matrix.prototype._isOrtho = function () { + return this.mat4[15] != 0; + } + + p5.prototype.nPlane = function () { + return this._renderer.nPlane(...arguments); + } + + p5.RendererGL.prototype.nPlane = function () { + return this.uPMatrix.nPlane(); + } + + p5.Matrix.prototype.nPlane = function () { + return this.mat4[15] == 0 ? this.mat4[14] / (this.mat4[10] - 1) : + (1 + this.mat4[14]) / this.mat4[10]; + } + + p5.prototype.fPlane = function () { + return this._renderer.fPlane(...arguments); + } + + p5.RendererGL.prototype.fPlane = function () { + return this.uPMatrix.fPlane(); + } + + p5.Matrix.prototype.fPlane = function () { + return this.mat4[15] == 0 ? this.mat4[14] / (1 + this.mat4[10]) : + (this.mat4[14] - 1) / this.mat4[10]; + } + + p5.prototype.lPlane = function () { + return this._renderer.lPlane(...arguments); + } + + p5.RendererGL.prototype.lPlane = function () { + return this.uPMatrix.lPlane(); + } + + p5.Matrix.prototype.lPlane = function () { + return this.mat4[15] == 1 ? -(1 + this.mat4[12]) / this.mat4[0] : + this.nPlane() * (this.mat4[8] - 1) / this.mat4[0]; + } + + p5.prototype.rPlane = function () { + return this._renderer.rPlane(...arguments); + } + + p5.RendererGL.prototype.rPlane = function () { + return this.uPMatrix.rPlane(); + } + + p5.Matrix.prototype.rPlane = function () { + return this.mat4[15] == 1 ? (1 - this.mat4[12]) / this.mat4[0] : + this.nPlane() * (1 + this.mat4[8]) / this.mat4[0]; + } + + p5.prototype.tPlane = function () { + return this._renderer.tPlane(...arguments); + } + + p5.RendererGL.prototype.tPlane = function () { + return this.uPMatrix.tPlane(); + } + + p5.Matrix.prototype.tPlane = function () { + // note that inverted values are returned if the projection + // matrix was set with @function frustum. + return this.mat4[15] == 1 ? (this.mat4[13] - 1) / this.mat4[5] : + this.nPlane() * (this.mat4[9] - 1) / this.mat4[5]; + } + + p5.prototype.bPlane = function () { + return this._renderer.bPlane(...arguments); + } + + p5.RendererGL.prototype.bPlane = function () { + return this.uPMatrix.bPlane(); + } + + p5.Matrix.prototype.bPlane = function () { + // note that inverted values are returned if the projection + // matrix was set with @function frustum. + return this.mat4[15] == 1 ? (1 + this.mat4[13]) / this.mat4[5] : + this.nPlane() * (1 + this.mat4[9]) / this.mat4[5]; + } + + p5.prototype.fov = function () { + return this._renderer.fov(...arguments); + } + + p5.RendererGL.prototype.fov = function () { + return this.uPMatrix.fov(); + } + + p5.Matrix.prototype.fov = function () { + if (this.mat4[15] != 0) { + console.error('fov only works for a perspective projection'); + return; + } + return Math.abs(2 * Math.atan(1 / this.mat4[5])); + } + + p5.prototype.hfov = function () { + return this._renderer.hfov(...arguments); + } + + p5.RendererGL.prototype.hfov = function () { + return this.uPMatrix.hfov(); + } + + p5.Matrix.prototype.hfov = function () { + if (this.mat4[15] != 0) { + console.error('hfov only works for a perspective projection'); + return; + } + return Math.abs(2 * Math.atan(1 / this.mat4[0])); + } + + // 2. Space transformations + + p5.prototype.beginHUD = function () { + if (this._renderer instanceof p5.RendererGL) { + this._renderer.beginHUD(...arguments); + } + } + + p5.RendererGL.prototype.beginHUD = function () { + this.mv = this.mvMatrix(); + this.p = this.pMatrix(); + this._rendererState = this.push(); + let gl = this.drawingContext; + gl.flush(); + gl.disable(gl.DEPTH_TEST); + this.resetMatrix(); + let z = Number.MAX_VALUE; + this._curCamera.ortho(0, this.width, -this.height, 0, -z, z); + } + + p5.prototype.endHUD = function () { + if (this._renderer instanceof p5.RendererGL) { + this._renderer.endHUD(...arguments); + } + } + + p5.RendererGL.prototype.endHUD = function () { + let gl = this.drawingContext; + gl.flush(); + gl.enable(gl.DEPTH_TEST); + this.pop(this._rendererState); + this.uPMatrix.set(this.p); + this.uMVMatrix.set(this.mv); + } + + // 2.1 Points + + // NDC stuff needs testing + + p5.prototype._map = function () { + return this._renderer._map(...arguments); + } + + p5.RendererGL.prototype._map = function (n, start1, stop1, start2, stop2) { + return (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; + } + + p5.prototype.treeLocation = function () { + return this._renderer.treeLocation(...arguments); + } + + /** + * Converts locations (i.e., points) from one space into another. + * @param {p5.Vector} vector location to be converted. + * @param {p5.Matrix|String} from source space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix|String} to target space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix} pMatrix projection matrix. + * @param {p5.Matrix} vMatrix view matrix. + * @param {p5.Matrix} pvMatrix projection times view matrix. + * @param {p5.Matrix} pvInvMatrix (projection times view matrix)^-1. + */ + p5.RendererGL.prototype.treeLocation = function () { + return arguments.length === 1 & arguments[0] instanceof Object ? this._treeLocation(Tree.ORIGIN, arguments[0]) : + this._treeLocation(...arguments); + } + + p5.prototype._treeLocation = function () { + return this._renderer._treeLocation(...arguments); + } + + p5.RendererGL.prototype._treeLocation = function (vector = Tree.ORIGIN, + { + from = Tree.EYE, + to = Tree.WORLD, + pMatrix, + vMatrix, + eMatrix, + pvMatrix, + pvInvMatrix + } = {}) { + if (Array.isArray(vector)) { + vector = new p5.Vector(vector[0] ?? 0, vector[1] ?? 0, vector[2] ?? 0); + } + if (from == Tree.MODEL) { + from = this.mMatrix({ eMatrix: eMatrix }); + } + if (to == Tree.MODEL) { + to = this.mMatrix({ eMatrix: eMatrix }); + } + if ((from == Tree.WORLD) && (to == Tree.SCREEN)) { + return this._screenLocation({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + if ((from == Tree.SCREEN) && (to == Tree.WORLD)) { + return this._location({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix }); + } + if (from == Tree.SCREEN && to == Tree.NDC) { + return this._screenToNDCLocation(vector); + } + if (from == Tree.NDC && to == Tree.SCREEN) { + return this._ndcToScreenLocation(vector); + } + if (from == Tree.WORLD && to == Tree.NDC) { + return this._screenToNDCLocation(this._screenLocation({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix })); + } + if (from == Tree.NDC && to == Tree.WORLD) { + return this._location({ vector: this._ndcToScreenLocation(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix }); + } + if (from == Tree.NDC && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(this._location({ vector: this._ndcToScreenLocation(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix })); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.NDC) { + return this._screenToNDCLocation(this._screenLocation({ vector: (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix })); + } + if (from == Tree.WORLD && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(vector); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.WORLD) { + return (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector); + } + if (from instanceof p5.Matrix && to instanceof p5.Matrix) { + return this.lMatrix({ from: from, to: to }).mult4(vector); + } + if (from == Tree.SCREEN && (to instanceof p5.Matrix || to == Tree.EYE)) { + return (to == Tree.EYE ? (vMatrix ?? this.vMatrix()) : to.copy().invert(to)).mult4(this._location({ vector: vector, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix, pvInvMatrix: pvInvMatrix })); + } + if ((from instanceof p5.Matrix || from == Tree.EYE) && to == Tree.SCREEN) { + return this._screenLocation({ vector: (from == Tree.EYE ? (eMatrix ?? this.eMatrix()) : from).mult4(vector), pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + console.error('couldn\'t parse your treeLocation query!'); + return vector; + } + + p5.RendererGL.prototype._ndcToScreenLocation = function (vector) { + return new p5.Vector(this._map(vector.x, -1, 1, 0, this.width), + this._map(vector.y, -1, 1, 0, this.height), + this._map(vector.z, -1, 1, 0, 1)); + } + + p5.RendererGL.prototype._screenToNDCLocation = function (vector) { + return new p5.Vector(this._map(vector.x, 0, this.width, -1, 1), + this._map(vector.y, 0, this.height, -1, 1), + this._map(vector.z, 0, 1, -1, 1)); + } + + p5.RendererGL.prototype._screenLocation = function ( + { + vector = new p5.Vector(0, 0, 0.5), + pMatrix, + vMatrix, + pvMatrix = this.pvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix }) + } = {}) { + let target = pvMatrix._mult4([vector.x, vector.y, vector.z, 1]); + if (target[3] == 0) { + console.error('screenLocation broken. Check your pvMatrix!'); + return; + } + let viewport = [0, this.height, this.width, -this.height]; + // ndc, but y is inverted + target[0] /= target[3]; + target[1] /= target[3]; + target[2] /= target[3]; + // Map x, y and z to range 0-1 + target[0] = target[0] * 0.5 + 0.5; + target[1] = target[1] * 0.5 + 0.5; + target[2] = target[2] * 0.5 + 0.5; + // Map x,y to viewport + target[0] = target[0] * viewport[2] + viewport[0]; + target[1] = target[1] * viewport[3] + viewport[1]; + return new p5.Vector(target[0], target[1], target[2]); + } + + p5.RendererGL.prototype._location = function ( + { + vector = new p5.Vector(this.width / 2, this.height / 2, 0.5), + pMatrix, + vMatrix, + pvMatrix, + pvInvMatrix = this.pvInvMatrix({ pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }) + } = {}) { + let viewport = [0, this.height, this.width, -this.height]; + let source = [vector.x, vector.y, vector.z, 1]; + // Map x and y from window coordinates + source[0] = (source[0] - viewport[0]) / viewport[2]; + source[1] = (source[1] - viewport[1]) / viewport[3]; + // Map to range -1 to 1 + source[0] = source[0] * 2 - 1; + source[1] = source[1] * 2 - 1; + source[2] = source[2] * 2 - 1; + let target = pvInvMatrix._mult4(source); + if (target[3] == 0) { + console.error('location broken. Check your pvInvMatrix!'); + return; + } + target[0] /= target[3]; + target[1] /= target[3]; + target[2] /= target[3]; + return new p5.Vector(target[0], target[1], target[2]); + } + + // 2.2. Vectors + + // NDC stuff needs testing + + p5.prototype.treeDisplacement = function () { + return this._renderer.treeDisplacement(...arguments); + } + + /** + * Converts displacements (i.e., vectors) from one space into another. + * @param {p5.Vector} vector location to be converted. + * @param {p5.Matrix|String} from source space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix|String} to target space: either a global + * transform matrix or Tree.WORLD, Tree.EYE, + * Tree.SCREEN, Tree.NDC or Tree.MODEL. + * @param {p5.Matrix} pMatrix projection matrix. + * @param {p5.Matrix} vMatrix view matrix. + * @param {p5.Matrix} pvMatrix projection times view matrix. + * @param {p5.Matrix} pvInvMatrix (projection times view matrix)^-1. + */ + p5.RendererGL.prototype.treeDisplacement = function () { + return arguments.length === 1 & arguments[0] instanceof Object ? this._treeDisplacement(Tree._k, arguments[0]) : + this._treeDisplacement(...arguments); + } + + p5.prototype._treeDisplacement = function () { + return this._renderer._treeDisplacement(...arguments); + } + + p5.RendererGL.prototype._treeDisplacement = function (vector = Tree._k, + { + from = Tree.EYE, + to = Tree.WORLD, + vMatrix, + eMatrix, + pMatrix + } = {}) { + if (Array.isArray(vector)) { + vector = new p5.Vector(vector[0] ?? 0, vector[1] ?? 0, vector[2] ?? 0); + } + if (from == Tree.MODEL) { + from = this.mMatrix({ eMatrix: eMatrix }); + } + if (to == Tree.MODEL) { + to = this.mMatrix({ eMatrix: eMatrix }); + } + if ((from == Tree.WORLD) && (to == Tree.SCREEN)) { + return this._worldToScreenDisplacement(vector, pMatrix); + } + if ((from == Tree.SCREEN) && (to == Tree.WORLD)) { + return this._screenToWorldDisplacement(vector, pMatrix); + } + if (from == Tree.SCREEN && to == Tree.NDC) { + return this._screenToNDCDisplacement(vector); + } + if (from == Tree.NDC && to == Tree.SCREEN) { + return this._ndcToScreenDisplacement(vector); + } + if (from == Tree.WORLD && to == Tree.NDC) { + return this._screenToNDCDisplacement(this._worldToScreenDisplacement(vector, pMatrix)); + } + if (from == Tree.NDC && to == Tree.WORLD) { + return this._screenToWorldDisplacement(this._ndcToScreenDisplacement(vector), pMatrix); + } + if (from == Tree.NDC && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(this._screenToWorldDisplacement(this._ndcToScreenDisplacement(vector), pMatrix)); + } + if (from == Tree.EYE && to == Tree.NDC) { + return this._screenToNDCDisplacement(this._worldToScreenDisplacement(this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector), pMatrix)); + } + if (from == Tree.SCREEN && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: to }).mult3(this._screenToWorldDisplacement(vector, pMatrix)); + } + if (from instanceof p5.Matrix && to == Tree.SCREEN) { + return this._worldToScreenDisplacement(this.dMatrix({ matrix: from.copy().invert(from) }).mult3(vector), pMatrix); + } + if (from instanceof p5.Matrix && to instanceof p5.Matrix) { + return this.dMatrix({ from: from, to: to }).mult3(vector); + } + // all cases below kept for efficiency but they all may + // be simply expressed in terms of the previous case, by: + // Tree.EYE -> eMatrix() + // Tree.WORLD -> iMatrix() + if (from == Tree.EYE && to == Tree.WORLD) { + return this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector); + } + if (from == Tree.WORLD && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(vector); + } + if (from == Tree.EYE && to == Tree.SCREEN) { + return this._worldToScreenDisplacement(this.dMatrix({ matrix: vMatrix ?? this.vMatrix() }).mult3(vector), pMatrix); + } + if (from == Tree.SCREEN && to == Tree.EYE) { + return this.dMatrix({ matrix: eMatrix ?? this.eMatrix() }).mult3(this._screenToWorldDisplacement(vector, pMatrix)); + } + if (from == Tree.EYE && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: (vMatrix ?? this.vMatrix()).apply(to) }).mult3(vector); + } + if (from instanceof p5.Matrix && to == Tree.EYE) { + return this.dMatrix({ matrix: from.copy().invert(from).apply(eMatrix ?? this.eMatrix()) }).mult3(vector); + } + if (from == Tree.WORLD && to instanceof p5.Matrix) { + return this.dMatrix({ matrix: to }).mult3(vector); + } + if (from instanceof p5.Matrix && to == Tree.WORLD) { + return this.dMatrix({ matrix: from.copy().invert(from) }).mult3(vector); + } + console.error('couldn\'t parse your treeDisplacement query!'); + return vector; + } + + p5.RendererGL.prototype._worldToScreenDisplacement = function (vector, pMatrix = this.uPMatrix) { + let eyeVector = this._treeDisplacement(vector, { from: Tree.WORLD, to: Tree.EYE }); + let dx = eyeVector.x; + let dy = eyeVector.y; + let perspective = pMatrix.mat4[15] == 0; + if (perspective) { + let position = new p5.Vector(); + let k = Math.abs(this._treeLocation(position, { from: Tree.WORLD, to: Tree.EYE }).z * Math.tan(this.fov(pMatrix) / 2)); + dx /= 2 * k / this.height; + dy /= 2 * k / this.height; + } + let dz = eyeVector.z; + // sign is inverted + dz /= (pMatrix.nPlane() - pMatrix.fPlane()) / (perspective ? Math.tan(this.fov(pMatrix) / 2) : Math.abs(pMatrix.rPlane() - pMatrix.lPlane()) / this.width); + return new p5.Vector(dx, dy, dz); + } + + p5.RendererGL.prototype._screenToWorldDisplacement = function (vector, pMatrix = this.uPMatrix) { + let dx = vector.x; + let dy = vector.y; + // Scale to fit the screen relative vector displacement + let perspective = pMatrix.mat4[15] == 0; + if (perspective) { + let position = new p5.Vector(); + let k = Math.abs(this._treeLocation(position, { from: Tree.WORLD, to: Tree.EYE }).z * Math.tan(this.fov(pMatrix) / 2)); + dx *= 2 * k / this.height; + dy *= 2 * k / this.height; + } + let dz = vector.z; + dz *= (pMatrix.nPlane() - pMatrix.fPlane()) / (perspective ? Math.tan(this.fov(pMatrix) / 2) : Math.abs(pMatrix.rPlane() - pMatrix.lPlane()) / this.width); + let eyeVector = new p5.Vector(dx, dy, dz); + return this._treeDisplacement(eyeVector, { from: Tree.EYE, to: Tree.WORLD }); + } + + p5.RendererGL.prototype._ndcToScreenDisplacement = function (vector) { + return new p5.Vector(this.width * vector.x / 2, this.height * vector.y / 2, vector.z / 2); + } + + p5.RendererGL.prototype._screenToNDCDisplacement = function (vector) { + return new p5.Vector(2 * vector.x / this.width, 2 * vector.y / this.height, 2 * vector.z); + } + + // 3. Shader utilities + + p5.prototype.readShader = function (fragFilename, { + precision, + matrices, + varyings + } = {}) { + let shader = new p5.Shader(); + this._coupledWith = fragFilename.substring(fragFilename.lastIndexOf('/') + 1); + shader._vertSrc = this.parseVertexShader({ precision: precision, matrices: matrices, varyings: varyings, _specs: false }); + this._coupledWith = undefined; + this.loadStrings( + fragFilename, + result => { + shader._fragSrc = result.join('\n') + } + ); + return shader; + } + + p5.prototype.makeShader = function (fragSrc, { + precision, + matrices, + varyings + } = {}) { + let shader = new p5.Shader(); + this._coupledWith = 'the fragment shader provided as param in makeShader()'; + shader._vertSrc = this.parseVertexShader({ precision: precision, matrices: matrices, varyings: varyings, _specs: false }); + this._coupledWith = undefined; + shader._fragSrc = fragSrc; + return shader; + } + + p5.prototype.parseVertexShader = function ({ + precision = Tree.mediump, + matrices = Tree.pmvMatrix, + varyings = Tree.color4 | Tree.texcoords2, + _specs = true + } = {}) { + let floatPrecision = `precision ${precision === Tree.highp ? 'highp' : `${precision === Tree.mediump ? 'mediump' : 'lowp'}`} float;` + let color4 = ~(varyings | ~Tree.color4) === 0; + let texcoords2 = ~(varyings | ~Tree.texcoords2) === 0; + let normal3 = ~(varyings | ~Tree.normal3) === 0; + let position2 = ~(varyings | ~Tree.position2) === 0; + let position3 = ~(varyings | ~Tree.position3) === 0; + let pmv = ~(matrices | ~Tree.pmvMatrix) === 0; + let p = ~(matrices | ~Tree.pMatrix) === 0; + let mv = ~(matrices | ~Tree.mvMatrix) === 0; + let n = (~(matrices | ~Tree.nMatrix) === 0) || normal3; + const target = `gl_Position =${pmv ? ' uModelViewProjectionMatrix * ' : `${p && mv ? ' uProjectionMatrix * uModelViewMatrix *' : ''} `}vec4(aPosition, 1.0)`; + let vertexShader = ` +${floatPrecision} +attribute vec3 aPosition; +${color4 ? 'attribute vec4 aVertexColor;' : ''} +${texcoords2 ? 'attribute vec2 aTexCoord;' : ''} +${normal3 ? 'attribute vec3 aNormal;' : ''} +${pmv ? 'uniform mat4 uModelViewProjectionMatrix;' : ''} +${p ? 'uniform mat4 uProjectionMatrix;' : ''} +${mv ? 'uniform mat4 uModelViewMatrix;' : ''} +${n ? 'uniform mat3 uNormalMatrix;' : ''} +${color4 ? 'varying vec4 color4;' : ''} +${texcoords2 ? 'varying vec2 texcoords2;' : ''} +${normal3 ? 'varying vec3 normal3;' : ''} +${position2 ? 'varying vec2 position2;' : ''} +${position3 ? 'varying vec3 position3;' : ''} +void main() { + ${color4 ? 'color4 = aVertexColor;' : ''} + ${texcoords2 ? 'texcoords2 = aTexCoord;' : ''} + ${normal3 ? 'normal3 = normalize(uNormalMatrix * aNormal);' : ''} + ${position2 ? 'position2 = vec4(aPosition, 1.0).xy;' : ''} + ${position3 ? 'position3 = vec4(aPosition, 1.0).xyz;' : ''} + ${target}; +} +`; + let advice = ` +/* +${this._coupledWith ? 'Vertex shader code to be coupled with ' + this._coupledWith : ''} +Generated with treegl version ${Tree.INFO.VERSION} +${_specs ? ` +Feel free to copy, paste, edit and save it. +Refer to createShader (https://p5js.org/reference/#/p5/createShader), +loadShader (https://p5js.org/reference/#/p5/loadShader), readShader +and makeShader (https://github.com/VisualComputing/p5.treegl#handling), +for details.` : ''} +*/ +`; + let result = advice + vertexShader; + result = result.split(/\r?\n/) + .filter(line => line.trim() !== '') + .join("\n"); + console.log(result); + return result; + } + + p5.prototype.emitMousePosition = function (shader, uniform = 'u_mouse') { + shader.setUniform(uniform, [this.mouseX * pixelDensity(), (this.height - this.mouseY) * pixelDensity()]); + } + + p5.prototype.emitPointerPosition = function () { + this._renderer.emitPointerPosition(...arguments); + } + + p5.RendererGL.prototype.emitPointerPosition = function (shader, pointerX, pointerY, uniform = 'u_pointer') { + shader.setUniform(uniform, [pointerX * pixelDensity(), (this.height - pointerY) * pixelDensity()]); + } + + p5.prototype.emitResolution = function () { + this._renderer.emitResolution(...arguments); + } + + p5.RendererGL.prototype.emitResolution = function (shader, uniform = 'u_resolution') { + shader.setUniform(uniform, [this.width * pixelDensity(), this.height * pixelDensity()]); + } + + p5.prototype.emitTexOffset = function (shader, image, uniform = 'u_texoffset') { + shader.setUniform(uniform, [1 / image.width, 1 / image.height]); + } + + // 4. Utility functions + + p5.prototype.pixelRatio = function () { + return this._renderer.pixelRatio(...arguments); + } + + /** + * Returns the world to pixel ratio units at given world location. + * A line of n * pixelRatio(location) world units will be projected + * with a length of n pixels on screen. + * @param {p5.Vector | Array} location world location reference + */ + p5.RendererGL.prototype.pixelRatio = function (location) { + return this._isOrtho() ? Math.abs(this.tPlane() - this.bPlane()) / this.height : + 2 * Math.abs((this._treeLocation(location, { from: Tree.WORLD, to: Tree.EYE, vMatrix: this._curCamera.cameraMatrix })).z) * Math.tan(this.fov() / 2) / this.height; + } + + p5.prototype.visibility = function () { + return this._renderer.visibility(...arguments); + } + + /** + * Returns object visibility (i.e, lies within the eye bounds) + * either Tree.VISIBLE, Tree.INVISIBLE, or Tree.SEMIVISIBLE. + * Object may be either a point, a sphere or an axis-aligned box. + * @param {p5.Vector | Array} corner1 box corner1, use it with corner2. + * @param {p5.Vector | Array} corner2 box corner2, use it with corner1. + * @param {p5.Vector | Array} center sphere (or point) center. + * @param {Number} radius sphere radius. + * @param {Array} bounds frustum equations 6x4 matrix. + */ + p5.RendererGL.prototype.visibility = function ({ + corner1, + corner2, + center, + radius, + bounds = this.bounds() + } = {}) { + return center ? radius ? this._ballVisibility(center, radius, bounds) : this._pointVisibility(center, bounds) + : corner1 && corner2 ? this._boxVisibility(corner1, corner2, bounds) : console.error('couldn\'t parse your visibility query!'); + } + + p5.RendererGL.prototype._pointVisibility = function (point, bounds = this.bounds()) { + for (const key in bounds) { + let d = this.distanceToBound(point, key, bounds); + if (d > 0) { + return Tree.INVISIBLE; + } + if (d === 0) { + return Tree.SEMIVISIBLE; + } + } + return Tree.VISIBLE; + } + + p5.RendererGL.prototype._ballVisibility = function (center, radius, bounds = this.bounds()) { + let allInForAllPlanes = true; + for (const key in bounds) { + let d = this.distanceToBound(center, key, bounds); + if (d > radius) { + return Tree.INVISIBLE; + } + if ((d > 0) || (-d < radius)) { + allInForAllPlanes = false; + } + } + if (allInForAllPlanes) { + return Tree.VISIBLE; + } + return Tree.SEMIVISIBLE; + } + + p5.RendererGL.prototype._boxVisibility = function (corner1, corner2, bounds = this.bounds()) { + if (Array.isArray(corner1)) { + corner1 = new p5.Vector(corner1[0] ?? 0, corner1[1] ?? 0, corner1[2] ?? 0); + } + if (Array.isArray(corner2)) { + corner2 = new p5.Vector(corner2[0] ?? 0, corner2[1] ?? 0, corner2[2] ?? 0); + } + let allInForAllPlanes = true; + for (const key in bounds) { + let allOut = true; + for (let c = 0; c < 8; ++c) { + let pos = new p5.Vector(((c & 4) != 0) ? corner1.x : corner2.x, ((c & 2) != 0) ? corner1.y : corner2.y, + ((c & 1) != 0) ? corner1.z : corner2.z); + if (this.distanceToBound(pos, key, bounds) > 0) { + allInForAllPlanes = false; + } + else { + allOut = false; + } + } + // The eight points are on the outside side of this plane + if (allOut) { + return Tree.INVISIBLE; + } + } + if (allInForAllPlanes) { + return Tree.VISIBLE; + } + // Too conservative, but tangent cases are too expensive to detect + return Tree.SEMIVISIBLE; + } + + p5.prototype.bounds = function () { + return this._renderer.bounds(...arguments); + } + + /** + * Returns the 6 plane equations of the eye frustum bounds defined + * in the world coordinate system encoded as an object literal + * having 'Tree.LEFT' (left plane), 'Tree.RIGHT' (right plane), + * 'Tree.NEAR' (near plane), 'Tree.FAR' (far plane) 'Tree.TOP' + * (top plane) and 'Tree.BOTTOM' (bottom plane) keys. + * Each key holds a plane equation of the form: + * a*x + b*y + c*z + d = 0, where a, b, c and d are the 4 + * keys of each object literal. + */ + p5.RendererGL.prototype.bounds = function () { + let normals = Array(6); + let distances = Array(6); + // Computed once and for all + // TODO experimental: no need to normalize + let pos = this._treeLocation([0, 0, 0], { from: Tree.EYE, to: Tree.WORLD }); + let viewDir = this._treeDisplacement([0, 0, -1], { from: Tree.EYE, to: Tree.WORLD }); + // same as: let viewDir = this.treeDisplacement(); + let up = this._treeDisplacement([0, 1, 0], { from: Tree.EYE, to: Tree.WORLD }); + let right = this._treeDisplacement([1, 0, 0], { from: Tree.EYE, to: Tree.WORLD }); + let posViewDir = p5.Vector.dot(pos, viewDir); + if (this._isOrtho()) { + normals[0] = p5.Vector.mult(right, -1); + normals[1] = right; + normals[4] = up; + normals[5] = p5.Vector.mult(up, -1); + let wh0 = Math.abs(this.rPlane() - this.lPlane()) / 2; + let wh1 = Math.abs(this.tPlane() - this.bPlane()) / 2; + distances[0] = p5.Vector.dot(p5.Vector.sub(pos, p5.Vector.mult(right, wh0)), normals[0]); + distances[1] = p5.Vector.dot(p5.Vector.add(pos, p5.Vector.mult(right, wh0)), normals[1]); + distances[4] = p5.Vector.dot(p5.Vector.add(pos, p5.Vector.mult(up, wh1)), normals[4]); + distances[5] = p5.Vector.dot(p5.Vector.sub(pos, p5.Vector.mult(up, wh1)), normals[5]); + } + else { + let hhfov = this.hfov() / 2; + let chhfov = Math.cos(hhfov); + let shhfov = Math.sin(hhfov); + normals[0] = p5.Vector.mult(viewDir, -shhfov); + normals[1] = p5.Vector.add(normals[0], p5.Vector.mult(right, chhfov)); + normals[0] = p5.Vector.add(normals[0], p5.Vector.mult(right, -chhfov)); + normals[2] = p5.Vector.mult(viewDir, -1); + normals[3] = viewDir; + let hfov = this.fov() / 2; + let chfov = Math.cos(hfov); + let shfov = Math.sin(hfov); + normals[4] = p5.Vector.mult(viewDir, -shfov); + normals[5] = p5.Vector.add(normals[4], p5.Vector.mult(up, -chfov)); + normals[4] = p5.Vector.add(normals[4], p5.Vector.mult(up, chfov)); + for (let i = 0; i < 2; ++i) { + distances[i] = p5.Vector.dot(pos, normals[i]); + } + for (let j = 4; j < 6; ++j) { + distances[j] = p5.Vector.dot(pos, normals[j]); + } + // Natural equations are: + // dist[0,1,4,5] = pos * normal[0,1,4,5]; + // dist[2] = (pos + zNear() * viewDir) * normal[2]; + // dist[3] = (pos + zFar() * viewDir) * normal[3]; + // 2 times less computations using expanded/merged equations. Dir vectors + // are normalized. + let posRightCosHH = chhfov * p5.Vector.dot(pos, right); + distances[0] = -shhfov * posViewDir; + distances[1] = distances[0] + posRightCosHH; + distances[0] = distances[0] - posRightCosHH; + let posUpCosH = chfov * p5.Vector.dot(pos, up); + distances[4] = -shfov * posViewDir; + distances[5] = distances[4] - posUpCosH; + distances[4] = distances[4] + posUpCosH; + } + // Front and far planes are identical for both camera types. + normals[2] = p5.Vector.mult(viewDir, -1); + normals[3] = viewDir; + distances[2] = -posViewDir - this.nPlane(); + distances[3] = posViewDir + this.fPlane(); + let bounds = {}; + bounds[Tree.LEFT] = { a: normals[0].x, b: normals[0].y, c: normals[0].z, d: distances[0] }; + bounds[Tree.RIGHT] = { a: normals[1].x, b: normals[1].y, c: normals[1].z, d: distances[1] }; + bounds[Tree.NEAR] = { a: normals[2].x, b: normals[2].y, c: normals[2].z, d: distances[2] }; + bounds[Tree.FAR] = { a: normals[3].x, b: normals[3].y, c: normals[3].z, d: distances[3] }; + bounds[Tree.TOP] = { a: normals[4].x, b: normals[4].y, c: normals[4].z, d: distances[4] }; + bounds[Tree.BOTTOM] = { a: normals[5].x, b: normals[5].y, c: normals[5].z, d: distances[5] }; + return bounds; + } + + p5.prototype.distanceToBound = function () { + return this._renderer.distanceToBound(...arguments); + } + + /** + * Returns the signed distance between location and the frustum plane defined + * by bounds and key which may be either Tree.LEFT, Tree.RIGHT, Tree.BOTTOM, + * Tree.TOP, Tree.NEAR or Tree.FAR. The distance is negative if the point lies + * in the planes's bounding halfspace, and positive otherwise. + */ + p5.RendererGL.prototype.distanceToBound = function (location, key, bounds = this.bounds()) { + if (Array.isArray(location)) { + location = new p5.Vector(location[0] ?? 0, location[1] ?? 0, location[2] ?? 0); + } + return p5.Vector.dot(location, new p5.Vector(bounds[key].a, bounds[key].b, bounds[key].c)) - bounds[key].d; + } + + p5.prototype.mousePicking = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + return this.pointerPicking(this.mouseX, this.mouseY, { mMatrix: mMatrix, x: x, y: y, size: size, shape: shape, eMatrix: eMatrix, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + } + + p5.prototype.pointerPicking = function () { + return this._renderer.pointerPicking(...arguments); + } + + /** + * Returns true if pointer is close enough to pointerX, pointerY screen location. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size bullseye diameter. Default is 50. + * @param {Number} shape either Tree.CIRCLE, Tree.SQUARE or Tree.PROJECTION. Default is Tree.CIRCLE. + */ + p5.RendererGL.prototype.pointerPicking = function (pointerX, pointerY, { + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + // TODO implement webgl picking here using a switch statement: Tree.CIRCLE, Tree.SQUARE, Tree.PROJECTION + let radius = size / 2; + return shape === Tree.CIRCLE ? + Math.sqrt(Math.pow((x - pointerX), 2.0) + Math.pow((y - pointerY), 2.0)) < radius : + ((Math.abs(pointerX - x) < radius) && (Math.abs(pointerY - y) < radius)); + } + + // 5. Drawing stuff + + p5.prototype.axes = function () { + this._renderer.axes(...arguments); + }; + + /** + * Draws axes. + * @param {Number} size size in world units. + * @param {Number} bits bitwise mask that may be composed of Tree.X, Tree._X, + * Tree.Y, Tree._Y, Tree.Z, Tree._Z and Tree.LABELS bits. + */ + p5.RendererGL.prototype.axes = function ({ size = 100, bits = Tree.LABELS | Tree.X | Tree.Y | Tree.Z } = {}) { + this._rendererState = this.push(); + if (~(bits | ~Tree.LABELS) === 0) { + const charWidth = size / 40.0; + const charHeight = size / 30.0; + const charShift = 1.04 * size; + // The X + this.stroke(200, 0, 0); + this.line(charShift, charWidth, -charHeight, charShift, -charWidth, charHeight); + this.line(charShift, -charWidth, -charHeight, charShift, charWidth, charHeight); + // The Y + this.stroke(0, 200, 0); + this.line(charWidth, charShift, charHeight, 0.0, charShift, 0.0); + this.line(0.0, charShift, 0.0, -charWidth, charShift, charHeight); + this.line(-charWidth, charShift, charHeight, 0.0, charShift, 0.0); + this.line(0.0, charShift, 0.0, 0.0, charShift, -charHeight); + // The Z + this.stroke(0, 100, 200); + this.line(-charWidth, -charHeight, charShift, charWidth, -charHeight, charShift); + this.line(charWidth, -charHeight, charShift, -charWidth, charHeight, charShift); + this.line(-charWidth, charHeight, charShift, charWidth, charHeight, charShift); + } + // X Axis + this.stroke(200, 0, 0); + if (~(bits | ~Tree.X) === 0) { + this.line(0, 0, 0, size, 0, 0); + } + if (~(bits | ~Tree._X) === 0) { + this.line(0, 0, 0, -size, 0, 0); + } + // Y Axis + this.stroke(0, 200, 0); + if (~(bits | ~Tree.Y) === 0) { + this.line(0, 0, 0, 0, size, 0); + } + if (~(bits | ~Tree._Y) === 0) { + this.line(0, 0, 0, 0, -size, 0); + } + // Z Axis + this.stroke(0, 100, 200); + if (~(bits | ~Tree.Z) === 0) { + this.line(0, 0, 0, 0, 0, size); + } + if (~(bits | ~Tree._Z) === 0) { + this.line(0, 0, 0, 0, 0, -size); + } + this.pop(this._rendererState); + }; + + p5.prototype.grid = function () { + this._renderer.grid(...arguments); + }; + + /** + * Draws grid + * @param {Number} size grid size in world units. Default is 100. + * @param {Number} subdivisions number of grid subdivisions. Default is 10. + * @param {Number} style either Tree.DOTS or Tree.SOLID. Default is Tree.DOTS. + */ + p5.RendererGL.prototype.grid = function ({ size = 100, subdivisions = 10, style = Tree.DOTS } = {}) { + this._rendererState = this.push(); + if (style === Tree.DOTS) { + let weight = this.curStrokeWeight; + // other useful as well: this.curStrokeColor this.curFillColor + let posi = 0; + let posj = 0; + this.strokeWeight(weight * 2); + this.beginShape(0x0000); + for (let i = 0; i <= subdivisions; ++i) { + posi = size * (2.0 * i / subdivisions - 1.0); + for (let j = 0; j <= subdivisions; ++j) { + posj = size * (2.0 * j / subdivisions - 1.0); + this.vertex(posi, posj, 0); + } + } + this.endShape(); + const internalSub = 5; + const subSubdivisions = subdivisions * internalSub; + this.strokeWeight(weight); + this.beginShape(0x0000); + for (let i = 0; i <= subSubdivisions; ++i) { + posi = size * (2.0 * i / subSubdivisions - 1.0); + for (let j = 0; j <= subSubdivisions; ++j) { + posj = size * (2.0 * j / subSubdivisions - 1.0); + if (((i % internalSub) != 0) || ((j % internalSub) != 0)) + this.vertex(posi, posj, 0); + } + } + this.endShape(); + } + else { + for (let i = 0; i <= subdivisions; ++i) { + const pos = size * (2.0 * i / subdivisions - 1.0); + this.line(pos, -size, 0, pos, +size, 0); + this.line(-size, pos, 0, size, pos, 0); + } + } + this.pop(this._rendererState); + }; + + p5.prototype.cross = function () { + this._renderer.cross(...arguments); + }; + + /** + * Draws a cross on the screen. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size cross size. Default is 50. + */ + p5.RendererGL.prototype.cross = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + const half_size = size / 2.0; + this._rendererState = this.push(); + this.beginHUD(); + this.line(x - half_size, y, x + half_size, y); + this.line(x, y - half_size, x, y + half_size); + this.endHUD(); + this.pop(this._rendererState); + }; + + p5.prototype.bullsEye = function () { + this._renderer.bullsEye(...arguments); + }; + + /** + * Draws a bulls-eye on the screen. + * @param {p5.Matrix} mMatrix model space matrix origin to compute (x, y) from. + * @param {Number} x screen x coordinate. Default is width / 2. + * @param {Number} y screen y coordinate. Default is height / 2. + * @param {Number} size bullseye diameter. Default is 50. + * @param {Number} shape either Tree.CIRCLE or Tree.SQUARE. Default is Tree.CIRCLE. + */ + p5.RendererGL.prototype.bullsEye = function ({ + mMatrix = this.mMatrix(), + x, + y, + size = 50, + shape = Tree.CIRCLE, + eMatrix, + pMatrix, + vMatrix, + pvMatrix + } = {}) { + if (!(x && y)) { + let screenLocation = this.treeLocation({ from: mMatrix, to: Tree.SCREEN, pMatrix: pMatrix, vMatrix: vMatrix, pvMatrix: pvMatrix }); + x = screenLocation.x; + y = screenLocation.y; + size = size / this.pixelRatio(this.treeLocation({ from: mMatrix, to: Tree.WORLD, eMatrix: eMatrix })); + } + this._rendererState = this.push(); + if (shape === Tree.CIRCLE) { + this.beginHUD(); + this._circle({ x, y, radius: size / 2 }) + this.endHUD(); + } + else { + const half_length = size / 2.0; + this.beginHUD(); + this.line((x - half_length), (y - half_length) + (0.6 * half_length), (x - half_length), (y - half_length)); + this.line((x - half_length), (y - half_length), (x - half_length) + (0.6 * half_length), (y - half_length)); + this.line((x + half_length) - (0.6 * half_length), (y - half_length), (x + half_length), (y - half_length)); + this.line((x + half_length), (y - half_length), (x + half_length), ((y - half_length) + (0.6 * half_length))); + this.line((x + half_length), ((y + half_length) - (0.6 * half_length)), (x + half_length), (y + half_length)); + this.line((x + half_length), (y + half_length), ((x + half_length) - (0.6 * half_length)), (y + half_length)); + this.line((x - half_length) + (0.6 * half_length), (y + half_length), (x - half_length), (y + half_length)); + this.line((x - half_length), (y + half_length), (x - half_length), ((y + half_length) - (0.6 * half_length))); + this.endHUD(); + } + this.cross({ x: x, y: y, size: 0.6 * size }); + this.pop(this._rendererState); + }; + + p5.prototype._circle = function () { + this._renderer._circle(...arguments); + }; + + p5.RendererGL.prototype._circle = function ({ filled = false, x = this.width / 2, y = this.height / 2, radius = 100, detail = 50 } = {}) { + this._rendererState = this.push(); + if (filled) { + this.beginShape(0x0005); + for (let t = 0; t <= detail; t++) { + const x = Math.cos(t * (2 * Math.PI) / detail); + const y = Math.sin(t * (2 * Math.PI) / detail); + this.vertex(0, 0, 0, 0.5, 0.5) + this.vertex(radius * x, radius * y, 0, (x * 0.5) + 0.5, (y * 0.5) + 0.5); + } + this.endShape(); + } + else { + this.translate(x, y); + const angle = (2 * Math.PI) / detail; + let lastPosition = { x: radius, y: 0 }; + for (let i = 1; i <= detail; i++) { + let position = { x: Math.cos(i * angle) * radius, y: Math.sin(i * angle) * radius }; + this.line(lastPosition.x, lastPosition.y, position.x, position.y); + lastPosition = position; + } + } + this.pop(this._rendererState); + }; + + p5.prototype.viewFrustum = function () { + this._renderer.viewFrustum(...arguments); + }; + + /** + * Display fbo view frustum. + * @param {p5.RendererGL | p5.Graphics} fbo renderer which viewing frustum is to be displayed. + * @param {Number} bits bitwise view-frustum mask that may be composed of Tree.NEAR, Tree.FAR and Tree.BODY bits. + * @param {Function} viewer callback fbo visual representation. + */ + p5.RendererGL.prototype.viewFrustum = function ({ + fbo = _renderer, + bits = Tree.NEAR | Tree.FAR, + viewer = () => this.axes({ size: 50, bits: Tree.X | Tree._X | Tree.Y | Tree._Y | Tree.Z | Tree._Z }) + } = {}) { + if (this === fbo) { + console.error('displaying viewFrustum requires an fbo different than this'); + return; + } + this._rendererState = this.push(); + this.resetMatrix(); + this.applyMatrix(...this.vMatrix().mat4); + this.applyMatrix(...fbo.eMatrix().mat4); + fbo._isOrtho() ? this._viewOrtho(fbo, bits, viewer) : this._viewPerspective(fbo, bits, viewer); + this.pop(this._rendererState); + }; + + p5.RendererGL.prototype._viewOrtho = function (fbo, bits, viewer) { + if (viewer !== Tree.NONE) { + viewer(); + } + let l = fbo.lPlane(); + let r = fbo.rPlane(); + let b = fbo.bPlane(); + let t = fbo.tPlane(); + let n = fbo.nPlane(); + let f = fbo.fPlane(); + if (~(bits | ~Tree.FAR) === 0) { + this.beginShape(); + this.vertex(r, t, -f, 0, 0); + this.vertex(l, t, -f, 1, 0); + this.vertex(l, b, -f, 1, 1); + this.vertex(r, b, -f, 0, 1); + this.endShape(); + } + else { + this.line(r, t, -f, l, t, -f); + this.line(l, t, -f, l, b, -f); + this.line(l, b, -f, r, b, -f); + this.line(r, b, -f, r, t, -f); + } + if (~(bits | ~Tree.BODY) === 0) { + this.beginShape(); + this.vertex(l, t, -f); + this.vertex(l, t, -n); + this.vertex(r, t, -n); + this.vertex(r, t, -f); + this.endShape(); + this.beginShape(); + this.vertex(r, t, -f); + this.vertex(r, t, -n); + this.vertex(r, b, -n); + this.vertex(r, b, -f); + this.endShape(); + this.beginShape(); + this.vertex(r, b, -f); + this.vertex(r, b, -n); + this.vertex(l, b, -n); + this.vertex(l, b, -f); + this.endShape(); + this.beginShape(); + this.vertex(l, t, -n); + this.vertex(l, t, -f); + this.vertex(l, b, -f); + this.vertex(l, b, -n); + this.endShape(); + } + else { + this.line(r, t, -n, r, t, -f); + this.line(l, t, -n, l, t, -f); + this.line(l, b, -n, l, b, -f); + this.line(r, b, -n, r, b, -f); + } + // TODO implement near plane texture + if (~(bits | ~Tree.NEAR) === 0) { + this.beginShape(); + this.vertex(r, t, -n, 0, 0); + this.vertex(l, t, -n, 1, 0); + this.vertex(l, b, -n, 1, 1); + this.vertex(r, b, -n, 0, 1); + this.endShape(); + } + else { + this.line(r, t, -n, l, t, -n); + this.line(l, t, -n, l, b, -n); + this.line(l, b, -n, r, b, -n); + this.line(r, b, -n, r, t, -n); + } + }; + + p5.RendererGL.prototype._viewPerspective = function (fbo, bits, viewer) { + if (viewer !== Tree.NONE) { + viewer(); + } + let magnitude = Math.tan(fbo.fov() / 2); + let aspectRatio = fbo.width / fbo.height; + const points = [ + { x: 0, y: 0, z: 0 }, + { x: 0, y: 0, z: 0 }, + ]; + points[0].z = fbo.nPlane(); + points[1].z = fbo.fPlane(); + points[0].y = points[0].z * magnitude; + points[0].x = points[0].y * aspectRatio; + const ratio = points[1].z / points[0].z; + points[1].y = ratio * points[0].y; + points[1].x = ratio * points[0].x; + if (~(bits | ~Tree.FAR) === 0) { + this.beginShape(); + this.vertex(-points[1].x, points[1].y, -points[1].z, 0, 0); + this.vertex(points[1].x, points[1].y, -points[1].z, 1, 0); + this.vertex(points[1].x, -points[1].y, -points[1].z, 0, 1); + this.vertex(-points[1].x, -points[1].y, -points[1].z, 1, 1); + this.endShape(); + } + else { + this.line(-points[1].x, points[1].y, -points[1].z, points[1].x, points[1].y, -points[1].z); + this.line(points[1].x, points[1].y, -points[1].z, points[1].x, -points[1].y, -points[1].z); + this.line(points[1].x, -points[1].y, -points[1].z, -points[1].x, -points[1].y, -points[1].z); + this.line(-points[1].x, -points[1].y, -points[1].z, -points[1].x, points[1].y, -points[1].z); + } + if (~(bits | ~Tree.BODY) === 0) { + this.beginShape(); + this.vertex(-points[1].x, points[1].y, -points[1].z); + this.vertex(-points[0].x, points[0].y, -points[0].z); + this.vertex(points[0].x, points[0].y, -points[0].z); + this.vertex(points[1].x, points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(points[1].x, points[1].y, -points[1].z); + this.vertex(points[0].x, points[0].y, -points[0].z); + this.vertex(points[0].x, -points[0].y, -points[0].z); + this.vertex(points[1].x, -points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(points[1].x, -points[1].y, -points[1].z); + this.vertex(points[0].x, -points[0].y, -points[0].z); + this.vertex(-points[0].x, -points[0].y, -points[0].z); + this.vertex(-points[1].x, -points[1].y, -points[1].z); + this.endShape(); + this.beginShape(); + this.vertex(-points[0].x, points[0].y, -points[0].z); + this.vertex(-points[1].x, points[1].y, -points[1].z); + this.vertex(-points[1].x, -points[1].y, -points[1].z); + this.vertex(-points[0].x, -points[0].y, -points[0].z); + this.endShape(); + this.line(0, 0, 0, points[0].x, points[0].y, -points[0].z); + this.line(0, 0, 0, -points[0].x, points[0].y, -points[0].z); + this.line(0, 0, 0, -points[0].x, -points[0].y, -points[0].z); + this.line(0, 0, 0, points[0].x, -points[0].y, -points[0].z); + } + else { + this.line(0, 0, 0, points[1].x, points[1].y, -points[1].z); + this.line(0, 0, 0, -points[1].x, points[1].y, -points[1].z); + this.line(0, 0, 0, -points[1].x, -points[1].y, -points[1].z); + this.line(0, 0, 0, points[1].x, -points[1].y, -points[1].z); + } + // TODO implement near plane texture + // Something along the lines + // this.textureMode(NORMAL); + // this.tint(255, 126); // Apply transparency without changing color + // this.texture(fbo); + // doesn't work since this.texture is not found + if (~(bits | ~Tree.NEAR) === 0) { + this.beginShape(); + this.vertex(-points[0].x, points[0].y, -points[0].z, 0, 0); + this.vertex(points[0].x, points[0].y, -points[0].z, 1, 0); + this.vertex(points[0].x, -points[0].y, -points[0].z, 0, 1); + this.vertex(-points[0].x, -points[0].y, -points[0].z, 1, 1); + this.endShape(); + } + else { + this.line(-points[0].x, points[0].y, -points[0].z, points[0].x, points[0].y, -points[0].z); + this.line(points[0].x, points[0].y, -points[0].z, points[0].x, -points[0].y, -points[0].z); + this.line(points[0].x, -points[0].y, -points[0].z, -points[0].x, -points[0].y, -points[0].z); + this.line(-points[0].x, -points[0].y, -points[0].z, -points[0].x, points[0].y, -points[0].z); + } + }; +})(); + +function Plane(){ + this.planeMaxMagR = 25; + this.planeColor = "rgb(255, 247, 233)"; + this.planeMagnitudeR = 0; + + this.planeRotateV = createVector(1,0,0); + this.planeSize = createVector(200,200,0); //ancho y alto + this.planePosition = createVector(0,0,0); + + this.draw = function(fbo){ + + fbo.fill(this.planeColor); + fbo.translate(this.planePosition); + fbo.plane(this.planeSize.x,this.planeSize.y) + + }; +} + +class Wall { + + constructor(originX,originY,originZ,width,height,depth, fillColor){ + this.fillColor = fillColor + this.origin = createVector(originX,originY,originZ) + this.width = width + this.height = height + this.depth = depth + this.wallMax = createVector(originX+ width/2, originY+ height/2, originZ+ depth/2) + this.wallMin = createVector(originX-width/2, originY-height/2, originZ - depth/2) + } + + + draw(fbo){ + fbo.push() + //fbo.line(this.wallMin.x,this.wallMin.y,this.wallMin.z,this.wallMax.x,this.wallMax.y,this.wallMax.z) + fbo.fill(this.fillColor) + fbo.translate(this.origin.x,this.origin.y,this.origin.z) + fbo.box(this.width, this.height,this.depth) + fbo.pop() + }; + closestPointSphere(B) { + // get box closest point to sphere center by clamping + const x = Math.max(this.wallMin.x, Math.min(B.spherePosition.x, this.wallMax.x)); + const y = Math.max(this.wallMin.y, Math.min(B.spherePosition.y, this.wallMax.y)); + const z = Math.max(this.wallMin.z, Math.min(B.spherePosition.z, this.wallMax.z)); + + // this is the same as isPointInsidespherePosition + return createVector(x,y,z); +} +isPointInside(point) { + return ( + point.x >= this.wallMin.x && + point.x <= this.wallMax.x && + point.y >= this.wallMin.y && + point.y <= this.wallMax.y && + point.z >= this.wallMin.z && + point.z <= this.wallMax.z + ); +} + collisionWithSphere(B){ + let cPoint = this.closestPointSphere(B) + const distance = Math.sqrt( + (cPoint.x - B.spherePosition.x) * (cPoint.x - B.spherePosition.x) + + (cPoint.y - B.spherePosition.y) * (cPoint.y - B.spherePosition.y) + + (cPoint.z - B.spherePosition.z) * (cPoint.z - B.spherePosition.z) + ); + let sine = sqrt(1-sq(B.acceleration.z)); + let cPointBouncing = undefined + if(distance= B.minVertex.x && + B.spherePosition.y >= B.minVertex.y && + B.spherePosition.z-10 >= B.minVertex.z && + B.spherePosition.x <= B.maxVertex.x && + B.spherePosition.y <= B.maxVertex.y && + B.spherePosition.z-10 <= B.maxVertex.z){ + + P.planeColor = "white" + } + else{ + P.planeColor = "rgba(255, 247, 233,1)" + } + + + beginHUD(); + image(fbo1, 0, 0); + endHUD(); +} +} + + +function getVectorModule(vector){ + return Math.sqrt(vector.x**2 +vector.y**2 +vector.z**2); +} + +function mousePressed() { + mouseInitialV = createVector(mouseX, mouseY, 0); +} + + +function mouseDragged(){ + + mouseCurrentV = createVector(mouseX, mouseY, 0); + let vectorSubstra = createVector(mouseInitialV.x - mouseCurrentV.x, + mouseInitialV.y - mouseCurrentV.y, + mouseInitialV.z - mouseCurrentV.z); + let mod = getVectorModule(vectorSubstra); + let vectorDir = createVector(vectorSubstra.x/mod, + vectorSubstra.y/mod, + vectorSubstra.z/mod ); + let sine = sqrt(1-sq(vectorDir.z)); + + B.acceleration = createVector(-sine*vectorDir.x, -sine*vectorDir.y, sine*vectorDir.z); + + let aux = vectorDir.x; + vectorDir.x = vectorDir.y; + vectorDir.y = -aux; + + if (mod < P.planeMaxMagR){ + P.planeMagnitudeR = mod + } + P.planeRotateV = vectorDir; + P.planeRotateV.z = 0; + +} + +function closestPoint(spherePosition, boxMin, boxMax) { + // get box closest point to sphere center by clamping + const x = Math.max(boxMin.x, Math.min(spherePosition.x, boxMax.x)); + const y = Math.max(boxMin.y, Math.min(spherePosition.y, boxMax.y)); + const z = Math.max(boxMin.z, Math.min(spherePosition.z, boxMax.z)); + + // this is the same as isPointInsidespherePosition + return createVector(x,y,z); +} +function dataToWalls(wallsData){ + let walls = wallsData.map(({x,y,z,width,height,depth, fillColor}) =>{ + return new Wall(x,y,z,width,height,depth,fillColor) + }) + return walls +} +function drawListObjects(list, fbo){ + list.forEach(object =>{ + object.draw(fbo) + }) +} +function collisionWalls(walls, B) { + + for(let i=0;i= this.wallMin.x && + point.x <= this.wallMax.x && + point.y >= this.wallMin.y && + point.y <= this.wallMax.y && + point.z >= this.wallMin.z && + point.z <= this.wallMax.z + ); + } + collisionWithSphere(B){ + let cPoint = this.closestPointSphere(B) + const distance = Math.sqrt( + (cPoint.x - B.spherePosition.x) * (cPoint.x - B.spherePosition.x) + + (cPoint.y - B.spherePosition.y) * (cPoint.y - B.spherePosition.y) + + (cPoint.z - B.spherePosition.z) * (cPoint.z - B.spherePosition.z) + ); + let sine = sqrt(1-sq(B.acceleration.z)); + let cPointBouncing = undefined + if(distance { + mosaic.setUniform("debug", sel.value() === "keys"); + mosaic.setUniform("color_on", false); + }); + + video_on = createSelect(); + video_on.position(10, 30); + video_on.option("image"); + video_on.option("video"); + video_on.option("camera"); + video_on.selected("image"); + video_on.changed(() => { + mosaic.setUniform( + "source", + video_on.value() === "image" + ? image_src + : video_on.value() === "video" + ? video_src + : cam + ); + if (video_on.value() === "video") { + video_src.loop(); + } else { + video_src.pause(); + } + }); + + video_on.position(10, 30); + mosaic.setUniform("source", image_src); + resolution = createSlider(10, 300, SAMPLE_RES, 5); + resolution.position(10, 50); + resolution.style("width", "80px"); + resolution.input(() => { + mosaic.setUniform("resolution", resolution.value()); + }); + mosaic.setUniform("resolution", resolution.value()); + pg = createGraphics(SAMPLE_RES * imageCells.width, SAMPLE_RES); + mosaic.setUniform("cols", imageCells.width); + sample(); +} + +function sample() { + if (pg.width !== SAMPLE_RES * imageCells.width) { + pg = createGraphics(SAMPLE_RES * imageCells.width, SAMPLE_RES); + mosaic.setUniform("cols", imageCells.width); + } + imageCells.sort({ + ascending: true, + cellLength: SAMPLE_RES, + mode: "LUMA", + }); + + luma = imageCells.saveLuma({ + cellLength: SAMPLE_RES, + }); + rgb = imageCells.saveRGB({ + cellLength: SAMPLE_RES, + }); + drawQuadrille(imageCells, { + graphics: pg, + cellLength: SAMPLE_RES, + outlineWeight: 0, + }); + mosaic.setUniform("palette", pg); + mosaic.setUniform("lumas", luma); + mosaic.setUniform("red_palette", rgb.r); + mosaic.setUniform("green_palette", rgb.g); + mosaic.setUniform("blue_palette", rgb.b); +} + +function draw() { + cover({ + texture: true, + }); + // let div = createDiv(floor(frameRate())); + // div.style("font-size", "16px"); + // div.style("background-color", "white"); + // div.style("font-family", "Arial"); + // div.style("font-size", "30px"); + // div.style("font-weight", "bold"); + // div.position(20, 20); +} + +function windowResized() { + resizeCanvas(windowWidth, windowHeight); +} diff --git a/content/sketches/rasterization.js b/content/sketches/rasterization.js new file mode 100644 index 00000000..b1ba76e4 --- /dev/null +++ b/content/sketches/rasterization.js @@ -0,0 +1,217 @@ +var p, + x, + y, + r, + space, + decrease, + move = 0, + showCircle = true, + fillCircle = false, + randomizeColors = true; +let circleX = []; +let circleY = []; +let existingCombinations = []; +function setup() { + createCanvas(621, 621); + frameRate(5); + move = 0; + r = 15; + space = 20; + decrease = true; + resetSketch(); + + var checkbox = createCheckbox('Completar el circulo', true); + checkbox.position(510, 20); + checkbox.changed((e) => { + showCircle = e.target.checked; + resetSketch(); + }); + + var checkbox2 = createCheckbox('Rellenar el circulo', false); + checkbox2.position(510, 580); + checkbox2.changed((e) => { + fillCircle = e.target.checked; + resetSketch(); + }); + + var checkbox3 = createCheckbox('Color random', true); + checkbox3.position(20, 580); + checkbox3.changed((e) => { + randomizeColors = e.target.checked; + resetSketch(); + }); +} + +function drawControls() { + var button = createButton('+'); + button.position(92, 35); + button.mousePressed(() => { + r++; + resetSketch(true); + }); + + var button2 = createButton('-'); + button2.position(70, 35); + button2.mousePressed(() => { + r--; + resetSketch(true); + }); + + var button3 = createButton('+'); + button3.position(92, 80); + button3.mousePressed(() => { + space += 2; + resetSketch(true); + }); + + var button4 = createButton('-'); + button4.position(70, 80); + button4.mousePressed(() => { + space--; + resetSketch(true); + }); + + fill(255, 255, 255); + rect(500, 10, 115, 40); + rect(500, 570, 115, 40); + rect(10, 570, 115, 40); + rect(10, 10, 100, 40); + rect(10, 55, 100, 40); + stroke(0, 0, 0); + textSize(15); + fill(0, 0, 0); + text('Radius', 12, 25); + text('Size', 12, 70); + fill(0, 102, 153); +} + +function resetSketch() { + circleX = []; + circleY = []; + existingCombinations = []; + move = 0; + p = 1 - r; + x = -1; + y = r; + clear(); + loop(); +} + +function drawGrid() { + for (let i = 0; i < width - 1 / space; i++) { + stroke(0, 200, 0); + strokeWeight(1); + line(i * space, 0, i * space, height - 1); + line(0, i * space, width - 1, i * space); + } +} + +function draw() { + background(0, 0, 40); + + let middle = floor((width - 1) / space / 2) * space; + drawGrid(); + + push(); + translate(middle, 0); + fill(150, 90); + rect(move, 0, space, height); + move += space; + pop(); + + fill(255, 0, 0); + square(middle, middle, space); + + res = calculateOctant(middle); + + push(); + translate(middle, middle); + for (let i = 0; i < circleX.length; i++) { + if (!randomizeColors && !fillCircle) { + if (i % 8 == 0) { + fill(255, 0, 0); + } else if (i % 8 == 1) { + fill(255, 255, 255); + } else if (i % 8 == 2) { + fill(0, 0, 255); + } else if (i % 8 == 3) { + fill(255, 255, 0); + } else if (i % 8 == 4) { + fill(0, 255, 255); + } else if (i % 8 == 5) { + fill(255, 0, 255); + } else if (i % 8 == 6) { + fill(0, 255, 0); + } else if (i % 8 == 7) { + fill(200, 200, 200); + } + } else if (!randomizeColors && fillCircle) { + const color = + fill(255,0,0) + } else { + const r = Math.floor(Math.random() * 255); + const g = Math.floor(Math.random() * 255); + const b = Math.floor(Math.random() * 255); + fill(r, g, b); + } + square(circleX[i], circleY[i], space); + } + pop(); + + drawControls(); + + if (res == true) { + noLoop(); + } +} + +function calculateOctant(middle) { + x += 1; + // Mid-point is inside or on the perimeter + if (p <= 0) { + p = p + 2 * x + 1; + } else { + y -= 1; + p = p + 2 * x - 2 * y + 1; + } + const __x = x * space; + const __y = y * space; + savePointsCircle(__x, __y); + if (fillCircle) { + for (let i = 1; i < r; i++) { + savePointsCircle(__x, __y - space * i); + } + } + + if (x >= y - 1) { + return true; + } + return false; +} + +function savePointsCircle(x, y) { + circleX.push(x); + circleY.push(-y); + if (showCircle) { + circleX.push(x); + circleY.push(y); + + circleX.push(-x); + circleY.push(y); + + circleX.push(-x); + circleY.push(-y); + + circleX.push(y); + circleY.push(x); + + circleX.push(y); + circleY.push(-x); + + circleX.push(-y); + circleY.push(x); + + circleX.push(-y); + circleY.push(-x); + } +} diff --git a/content/sketches/rasterization_2.js b/content/sketches/rasterization_2.js new file mode 100644 index 00000000..6fe45974 --- /dev/null +++ b/content/sketches/rasterization_2.js @@ -0,0 +1,171 @@ +let n1 = 500; +let n2 = 420; +let n3 = 258; +let n4 = 420; +let n5 = 486; +let n6 = 275; +let space = 20; +var p1, p2, p3, p4; +let puntos; +let x,y; +let beads; +let beadSize = 20; +let cols, rows; +let num; + +function setup() { + createCanvas(621, 621) + cols = ceil(621 / beadSize); + rows = ceil(621 / beadSize); + beads = new Array(cols); + for (let x = 0; x < cols; x++){ + beads[x] = new Array(rows).fill(false); + } + organizeTriangle(); + clasifyTriangle(); +} + +function draw() { + background(0,0,40); + drawGrid(); + paint(num); + line(puntos[0].x, puntos[0].y, puntos[1].x, puntos[1].y); + line(puntos[0].x, puntos[0].y, puntos[2].x, puntos[2].y); + line(puntos[2].x, puntos[2].y, puntos[1].x, puntos[1].y); + stroke("red"); + +} + +function drawBeads(columnainicial, columnafinal,filas){ + let filasm = filas + 1; + let columnainicialm = columnainicial - 4; + push(); + noStroke(); + //fill(0); + fill(0, 179, 255); + for (let i = columnainicialm; i <= columnafinal; i++){ + for (let j = filas; j < filasm; j++){ + square(i * beadSize, j * beadSize, beadSize); + } + + } + pop(); +} + +function drawGrid(){ + push(); + stroke(200); + for (let x = 0; x < 621; x+= beadSize){ + line(x, 0, x, 621); + } + + for (let y = 0; y < 621; y+= beadSize){ + line(0, y, 621, y); + } + pop(); +} + + +function organizeTriangle(){ + p1= { + x: n1, + y: n2 + }; + p2 = { + x: n3, + y: n4 + }; + p3 = { + x: n5, + y: n6 + } + puntos = [p1, p2, p3]; + + for (var i = 0; i < 3; i++) { + for (var j = 0; j < 2; j++){ + if(puntos[i].y > puntos[j+1].y ){ + let punto = puntos[i]; + puntos[i] = puntos[j + 1]; + puntos[j + 1 ] = punto; + } + } + } + + if(puntos[0].y == puntos[1].y){ + if(puntos[0].x > puntos[1].x){ + let punto = puntos[0]; + puntos[0] = puntos[1]; + puntos[1] = punto; + } + } + +} + +function clasifyTriangle(){ + if (puntos[1].y == puntos[2].y) { + num = 1; + } else if (puntos[0].y == puntos[1].y) { + num = 2; + } else { + num = 3; + x = (int) (puntos[0].x + ((puntos[1].y - puntos[0].y) / (puntos[2].y - puntos[0].y)) * (puntos[2].x - puntos[0].x)); + y = (int) (puntos[1].y); + + p4 = { + x: x, + y: y + } + + //scanBottomFlatTriangle(puntos[0], puntos[1], p4); + //scanTopFlatTriangle(p4, puntos[1], puntos[2]); + + } +} + +function scanTopFlatTriangle(pa, pb, pc){ + + let invslope1 = (pc.x - pa.x) / (pc.y - pa.y); + let invslope2 = (pc.x - pb.x) / (pc.y - pb.y); + + let curx1 = pc.x; + let curx2 = pc.x; + + for (var scanlineY = pc.y; scanlineY < pa.y;scanlineY--) { + scanLine(curx1, curx2, scanlineY); + curx1 -= invslope1; + curx2 -= invslope2; + } +} + +function scanBottomFlatTriangle(pa, pb, pc){ + let invslope1 = parseInt((pb.x - pa.x) / (pb.y - pa.y)); + let invslope2 = parseInt((pc.x - pa.x) / (pc.y - pa.y)); + + let curx1 = pa.x; + let curx2 = pa.x; + + for (var scanlineY = pa.y; scanlineY <= pb.y;scanlineY++) { + scanLine(curx1, curx2, scanlineY); + curx1 += invslope1; + curx2 += invslope2; + } +} +function scanLine(curx1, curx2, scanlineY){ + curx1 = parseInt(curx1/ beadSize); + curx2 = parseInt(curx2 / beadSize); + scanlineY = parseInt(scanlineY / beadSize); + console.log(curx1); + console.log(curx2); + console.log(scanlineY); + drawBeads(curx1, curx2,scanlineY); +} + +function paint(num){ + if(num == 1){ + scanBottomFlatTriangle(puntos[0], puntos[1], puntos[2]); + }else{ + if(num == 2){ + scanTopFlatTriangle(puntos[0], puntos[1], puntos[2]); + } + } +} \ No newline at end of file diff --git a/content/sketches/screen.js b/content/sketches/screen.js new file mode 100644 index 00000000..8d47b682 --- /dev/null +++ b/content/sketches/screen.js @@ -0,0 +1,92 @@ +let easycam; +let uvShader; +let opacity; + +let c1, c2; + +let rtb = false, gtb = false; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/screen.frag',{ matrices: Tree.pmvMatrix, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(450, 450, WEBGL); + + // easycam stuff + let state = { + distance: 250, + center: [0, 0, 0], + rotation: [0, 0, 0, 1], + }; + easycam = createEasyCam(); + easycam.state_reset = state; + easycam.setState(state, 2000); + textureMode(NORMAL); + opacity = createSlider(0, 1, 0.5, 0.01); + opacity.position(10, 25); + opacity.style('width', '280px'); + + c1 = createCheckbox('R To B', false); + c2 = createCheckbox('G To B', false); + c1.position(100, 10); + c2.position(200, 10); + + sel = createSelect(); + sel.position(10, 10); + sel.option('Quad'); + sel.option('Triangle'); + sel.option('Circle'); + sel.selected('Quad'); + +} + +function draw() { + background(200); + + resetShader(); + + axes(); + grid(); + translate(0, -70); + rotateY(0.5); + fill(color(255, 0, 255, 125)); + box(30, 50); + translate(70, 70); + fill(color(0, 255, 255, 125)); + sphere(30, 50); + + shader(uvShader); + + uvShader.setUniform('opacity', opacity.value()); + + beginHUD(); + + noStroke(); + + if(sel.value() == "Quad"){ + quad(0, 0, width, 0, width, height, 0, height); + }else if(sel.value() == "Triangle"){ + triangle(0,0,width,0,width/2,height) + }else if (sel.value() == "Circle"){ + circle(width/2,height/2,width) + } + + if(c1.checked()){ + uvShader.setUniform('rtb',true) + uvShader.setUniform('gtb',false) + }else if(c2.checked()){ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',true) + }else{ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',false) + } + + endHUD(); +} + +function mouseWheel(event) { + //comment to enable page scrolling + return false; +} \ No newline at end of file diff --git a/content/sketches/shaders/blend.frag b/content/sketches/shaders/blend.frag new file mode 100644 index 00000000..e554b683 --- /dev/null +++ b/content/sketches/shaders/blend.frag @@ -0,0 +1,10 @@ +precision mediump float; + +// uniforms are emitted from the sketch +// https://p5js.org/reference/#/p5.Shader/setUniform +uniform vec4 uMaterial1; +uniform vec4 uMaterial2; + +void main() { + gl_FragColor = uMaterial1 * uMaterial2; +} diff --git a/content/sketches/shaders/blend.js b/content/sketches/shaders/blend.js new file mode 100644 index 00000000..5482afaa --- /dev/null +++ b/content/sketches/shaders/blend.js @@ -0,0 +1,80 @@ +let blendShader; +let color1, color2; + +function preload() { + blendShader = readShader('../../../../sketches/shaders/blend.frag', { + matrices: Tree.NONE, + varyings: Tree.NONE, + }); +} + +function setup() { + createCanvas(450, 250, WEBGL); + colorMode(RGB,1); + drawControls(); + shader(blendShader); +} + +function drawControls(){ + color1 = createColorPicker(color(255,255,0)); + color1.position(10, 10); + color2 = createColorPicker(color(130,0,130)); + color2.position(width - 45, 10); +} + +function drawTriangle(color, arr) { + blendShader.setUniform('uMaterial1', [ + red(color), + green(color), + blue(color), + 1.0, + ]); + blendShader.setUniform('uMaterial2', [1.0, 1.0, 1.0, 1.0]); + beginShape(); + vertex(arr[0][0], arr[0][1]); + vertex(arr[1][0], arr[1][1]); + vertex(arr[2][0], arr[2][1]); + endShape(); +} + +function drawBlendedTriangle(color1, color2, arr) { + blendShader.setUniform('uMaterial1', [ + red(color1), + green(color1), + blue(color1), + 1.0, + ]); + blendShader.setUniform('uMaterial2', [ + red(color2), + green(color2), + blue(color2), + 1.0, + ]); + beginShape(); + vertex(arr[0][0], arr[0][1]); + vertex(arr[1][0], arr[1][1]); + vertex(arr[2][0], arr[2][1]); + endShape(); +} + +function draw() { + let color1Color = color1.color(); + let color2Color = color2.color(); + background(0); + drawTriangle(color1Color, [ + [-1, 1], + [-1, -1], + [0, 1], + ]); + drawTriangle(color2Color, [ + [0, 1], + [1, 1], + [1, -1], + ]); + + drawBlendedTriangle(color1Color, color2Color, [ + [-1, -1], + [0, 1], + [1, -1], + ]); +} diff --git a/content/sketches/shaders/blendMode.js b/content/sketches/shaders/blendMode.js new file mode 100644 index 00000000..654a5dff --- /dev/null +++ b/content/sketches/shaders/blendMode.js @@ -0,0 +1,57 @@ +let select, selectedMode; + +function setup() { + createCanvas(450, 450); + drawControls(); + selectBlendMode(); +} + +function drawControls() { + select = createSelect(); + select.position(185, height - 20); + select.option('DARKEST'); + select.option('LIGHTEST'); + select.option('MULTIPLY'); + select.option('SOFT_LIGHT'); + select.option('EXCLUSION'); + select.selected('LIGHTEST'); + select.changed(mySelectEvent); +} + +function mySelectEvent() { + selectBlendMode(select.value()); +} + +function selectBlendMode(mode) { + clear(); + switch (mode) { + case 'DARKEST': + blendMode(DARKEST); + break; + case 'LIGHTEST': + blendMode(LIGHTEST); + break; + case 'MULTIPLY': + blendMode(MULTIPLY); + break; + case 'SOFT_LIGHT': + blendMode(SOFT_LIGHT); + break; + case 'EXCLUSION': + blendMode(EXCLUSION); + break; + default: + blendMode(LIGHTEST); + break; + } + resetSketch(); +} +function draw() {} + +function resetSketch() { + strokeWeight(100); + stroke(80, 150, 255); + line(25, 25, width - 25, height - 25); + stroke(255, 50, 50); + line(width - 25, 25, 25, height - 25); +} diff --git a/content/sketches/shaders/colors.frag b/content/sketches/shaders/colors.frag new file mode 100644 index 00000000..aaf9b67b --- /dev/null +++ b/content/sketches/shaders/colors.frag @@ -0,0 +1,57 @@ +precision mediump float; + +uniform bool grey_scale; +uniform bool average; +uniform bool HSVV; +uniform bool HSLL; +uniform bool Tint; + +uniform vec4 colorT; + +uniform sampler2D texture; + +varying vec2 texcoords2; + +float luma(vec3 texel) { + return 0.299 * texel.r + 0.587 * texel.g + 0.114 * texel.b; +} + +float favg(vec3 texel){ + return (texel.r + texel.g + texel.b ) / 3.0; +} + +float HSV (vec3 texel){ + return max(max(texel.r,texel.g),texel.b); ; +} + +float HSL (vec3 texel){ + float CMax = max(max(texel.r,texel.g),texel.b); + float CMin = min(min(texel.r,texel.g),texel.b); + return (CMax + CMin) / 2.0 ; +} + +float Ftint(float channel, float color){ + float N = channel * (color / 255.0); + return N; +} + + +void main() { + + vec4 texel = texture2D(texture, texcoords2); + + if(grey_scale == true){ + gl_FragColor = vec4((vec3(luma(texel.rgb))), 1.0); + }else if(average == true){ + gl_FragColor = vec4((vec3(favg(texel.rgb))), 1.0); + }else if(HSVV== true){ + gl_FragColor = vec4((vec3(HSV(texel.rgb))), 1.0); + }else if(HSLL== true){ + gl_FragColor = vec4((vec3(HSL(texel.rgb))), 1.0); + }else if(Tint == true){ + gl_FragColor = vec4(Ftint(texel.r,colorT.x),Ftint(texel.g,colorT.y),Ftint(texel.b,colorT.z),1.0); + }else{ + gl_FragColor = texel; + } + +} \ No newline at end of file diff --git a/content/sketches/shaders/light.frag b/content/sketches/shaders/light.frag new file mode 100644 index 00000000..51a6fc89 --- /dev/null +++ b/content/sketches/shaders/light.frag @@ -0,0 +1,9 @@ +precision mediump float; + +uniform float brightness; +uniform vec4 uMaterial1; +uniform vec4 uMaterial2; + +void main() { + gl_FragColor = brightness * uMaterial1 * uMaterial2; +} diff --git a/content/sketches/shaders/light.js b/content/sketches/shaders/light.js new file mode 100644 index 00000000..6a986efd --- /dev/null +++ b/content/sketches/shaders/light.js @@ -0,0 +1,93 @@ +let lightShader; +let color1, color2; +let brightness; + +function preload() { + lightShader = readShader('../../../../sketches/shaders/light.frag', { + matrices: Tree.NONE, + varyings: Tree.NONE, + }); +} + +function setup() { + createCanvas(450, 250, WEBGL); + colorMode(RGB, 1); + drawControls(); + + shader(lightShader); +} + +function drawControls() { + color1 = createColorPicker(color(255, 255, 0)); + color1.position(10, 10); + color2 = createColorPicker(color(130, 0, 130)); + color2.position(width - 45, 10); + brightness = createSlider(0, 1, 0.5, 0.05); + brightness.style('width', `${width-10}px`); + brightness.position(10, height - 10); +} + +function drawTriangle(color, arr) { + lightShader.setUniform('uMaterial1', [ + red(color), + green(color), + blue(color), + 1.0, + ]); + lightShader.setUniform('uMaterial2', [1.0, 1.0, 1.0, 1.0]); + lightShader.setUniform('brightness', 1.0); + beginShape(); + vertex(arr[0][0], arr[0][1]); + vertex(arr[1][0], arr[1][1]); + vertex(arr[2][0], arr[2][1]); + endShape(); +} + +function drawBlendedTriangle(color1, color2, brightness, arr) { + lightShader.setUniform('uMaterial1', [ + red(color1), + green(color1), + blue(color1), + 1.0, + ]); + lightShader.setUniform('uMaterial2', [ + red(color2), + green(color2), + blue(color2), + 1.0, + ]); + lightShader.setUniform('brightness', brightness); + + beginShape(); + vertex(arr[0][0], arr[0][1]); + vertex(arr[1][0], arr[1][1]); + vertex(arr[2][0], arr[2][1]); + endShape(); +} + +function draw() { + let color1Color = color1.color(); + let color2Color = color2.color(); + background(0); + drawTriangle(color1Color, [ + [-1, 1], + [-1, -1], + [0, 1], + ]); + drawTriangle(color2Color, [ + [0, 1], + [1, 1], + [1, -1], + ]); + + drawBlendedTriangle( + color1Color, + color2Color, + brightness.value(), + [ + [-1, -1], + [0, 1], + [1, -1], + ] + ); +} diff --git a/content/sketches/shaders/mask.frag b/content/sketches/shaders/mask.frag new file mode 100644 index 00000000..b29a1ac3 --- /dev/null +++ b/content/sketches/shaders/mask.frag @@ -0,0 +1,159 @@ +precision mediump float; + +uniform bool maskmode; +uniform bool coloringmode; +uniform bool lensemode; + +uniform bool grey_scale; +uniform bool average; +uniform bool HSVV; +uniform bool HSLL; +uniform bool Tint; + +uniform vec4 colorT; + +uniform sampler2D texture; + +uniform vec2 texOffset; +uniform float mask[9]; + +varying vec2 texcoords2; + +uniform vec2 mouseData; +uniform vec2 resolution; + +uniform vec4 passerGL; + +uniform float radio; +uniform float scale; + +//-------------------------------------------------------------------------- + +float rim = 2.0; +vec2 handview = vec2(10.0,50.0); + +vec2 curveGen(vec2 toPow, float dist){ + float x = dist/radio; + return toPow * (1.0 - x) * exp (-2.0 * x * x); +} + +void Amplify (){ + + vec2 UV = gl_FragCoord.xy / resolution.xy; + gl_FragColor = texture2D(texture, UV); + + vec2 center = mouseData.xy; + float dist = distance(gl_FragCoord.xy,center); + + vec2 distV = gl_FragCoord.xy - center; + + if (dist > radio && dist < radio + rim){ + gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); + } + + if(abs(distV.x) < (handview.x / 2.0 ) && abs(distV.y + radio) < (handview.y) && dist >= radio + rim){ + gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); + } + + if(dist < radio){ + vec2 trueUV = (gl_FragCoord.xy - (curveGen(distV,dist) * scale)) / resolution.xy ; + gl_FragColor = texture2D(texture, trueUV); + } +} + +//-------------------------------------------------------------------------- + +void Convolution(){ + + vec2 tc0 = texcoords2 + vec2(-texOffset.s, -texOffset.t); + vec2 tc1 = texcoords2 + vec2( 0.0, -texOffset.t); + vec2 tc2 = texcoords2 + vec2(+texOffset.s, -texOffset.t); + vec2 tc3 = texcoords2 + vec2(-texOffset.s, 0.0); + + vec2 tc4 = texcoords2 + vec2( 0.0, 0.0); + vec2 tc5 = texcoords2 + vec2(+texOffset.s, 0.0); + vec2 tc6 = texcoords2 + vec2(-texOffset.s, +texOffset.t); + vec2 tc7 = texcoords2 + vec2( 0.0, +texOffset.t); + vec2 tc8 = texcoords2 + vec2(+texOffset.s, +texOffset.t); + + + vec4 rgba[9]; + rgba[0] = texture2D(texture, tc0); + rgba[1] = texture2D(texture, tc1); + rgba[2] = texture2D(texture, tc2); + rgba[3] = texture2D(texture, tc3); + rgba[4] = texture2D(texture, tc4); + rgba[5] = texture2D(texture, tc5); + rgba[6] = texture2D(texture, tc6); + rgba[7] = texture2D(texture, tc7); + rgba[8] = texture2D(texture, tc8); + + + vec4 convolution; + for (int i = 0; i < 9; i++) { + convolution += rgba[i]*mask[i]; + } + + + gl_FragColor = vec4(convolution.rgb, 1.0); +} + +//-------------------------------------------------------------------------- + +float luma(vec3 texel){ + return 0.299 * texel.r + 0.587 * texel.g + 0.114 * texel.b; + } + +float favg(vec3 texel){ + return (texel.r + texel.g + texel.b ) / 3.0; + } + +float HSV (vec3 texel){ + return max(max(texel.r,texel.g),texel.b); ; + } + +float HSL (vec3 texel){ + float CMax = max(max(texel.r,texel.g),texel.b); + float CMin = min(min(texel.r,texel.g),texel.b); + return (CMax + CMin) / 2.0 ; + } + +float Ftint(float channel, float color){ + float N = channel * (color / 255.0); + return N; + } + +void Coloring(){ + + vec4 texel = texture2D(texture, texcoords2); + + if(grey_scale == true){ + gl_FragColor = vec4((vec3(luma(texel.rgb))), 1.0); + }else if(average == true){ + gl_FragColor = vec4((vec3(favg(texel.rgb))), 1.0); + }else if(HSVV== true){ + gl_FragColor = vec4((vec3(HSV(texel.rgb))), 1.0); + }else if(HSLL== true){ + gl_FragColor = vec4((vec3(HSL(texel.rgb))), 1.0); + }else if(Tint == true){ + gl_FragColor = vec4(Ftint(texel.r,colorT.x),Ftint(texel.g,colorT.y),Ftint(texel.b,colorT.z),1.0); + }else{ + gl_FragColor = texel; + } +} + +//-------------------------------------------------------------------------- + +void main() { + + if(maskmode == true){ + Convolution(); + }else if(coloringmode == true){ + Coloring(); + }else if(lensemode == true){ + Amplify(); + }else{ + gl_FragColor = texture2D(texture, texcoords2); + } + +} \ No newline at end of file diff --git a/content/sketches/shaders/photomosaic.frag b/content/sketches/shaders/photomosaic.frag new file mode 100644 index 00000000..a0a185ff --- /dev/null +++ b/content/sketches/shaders/photomosaic.frag @@ -0,0 +1,88 @@ +precision mediump float; + +const int num_images = 40; + +// source (image or video) is sent by the sketch +uniform sampler2D source; + +// palette is sent by the sketch +uniform sampler2D palette; +// number of cols are sent by sketch +uniform float cols; + +uniform float lumas[num_images]; +uniform float red_palette[num_images]; +uniform float green_palette[num_images]; +uniform float blue_palette[num_images]; + +// toggles debug +uniform bool debug; + +// toggles coloring +uniform bool color_on; +uniform vec4 background; +uniform vec4 foreground; + +// target horizontal & vertical resolution +uniform float resolution; + +// interpolated color (same name and type as in vertex shader) +varying vec4 vVertexColor; +// interpolated texcoord (same name and type as in vertex shader) +varying vec2 vTexCoord; + +float luma(vec3 color) { + return (0.299 * color.r + 0.587 * color.g + 0.114 * color.b); +} + +void main() { + vec2 fontCoord = vTexCoord * resolution; + vec2 srcCoord = floor(fontCoord); + fontCoord = fontCoord - srcCoord; + srcCoord = srcCoord / vec2(resolution); + float mid = 1.0/(2.0*resolution); + srcCoord = srcCoord + vec2(mid); + + vec4 key = texture2D(source, srcCoord); + if (debug) { + gl_FragColor = key; + } else { + // fontCoord.x :-> offset + x + // 1. offset + // luma(key.rgb) * cols) : remap luma to [0.0, cols] ∈ R + // floor(luma(key.rgb) * cols)) : remap luma to [0.0, cols] ∈ Z + // floor(luma(key.rgb) * cols)) / cols : remap luma to [0.0, 1.0] ∈ R + // 2. x (1 / cols : quadrille cell width) + // fontCoord.x / cols : remap fontCoord.x to [0.0, 1 / cols] ∈ R + //vec2 tile = vec2((floor(luma(key.rgb) * cols) + fontCoord.x) / cols, fontCoord.y); + + float lumakey = luma(key.rgb); + float selected = 0.0; + /*for( int i = 0 ; i < 18; i += 1) + { + if((lumas[i]/255.0) < lumakey){ + selected = float(i); + } + }*/ + + bool complete = false; + for(float j = 0.02; j <= 0.5; j += 0.02){ + for(int i = 0 ; i < num_images; i ++) + { + if((red_palette[i]/255.0> (key.r - j) && red_palette[i]/255.0 < (key.r + j)) && (green_palette[i]/255.0> (key.g - j) && green_palette[i]/255.0 < (key.g + j)) && (blue_palette[i]/255.0> (key.b - j) && blue_palette[i]/255.0 < (key.b + j))){ + selected = float(i); + complete = true; + break; + } + } + if(complete){ + break; + } + } + + vec2 tile = vec2((floor(selected) + fontCoord.x) / cols, fontCoord.y); + + vec4 paletteTexel = texture2D(palette, tile); + gl_FragColor = paletteTexel; + } +} \ No newline at end of file diff --git a/content/sketches/shaders/screen.frag b/content/sketches/shaders/screen.frag new file mode 100644 index 00000000..9c8bc773 --- /dev/null +++ b/content/sketches/shaders/screen.frag @@ -0,0 +1,16 @@ +precision mediump float; + +uniform bool rtb; +uniform bool gtb; +uniform float opacity; +varying vec2 texcoords2; + +void main() { + if(rtb==true){ + gl_FragColor = vec4(0.0 ,texcoords2.y,texcoords2.x, opacity); + }else if(gtb==true){ + gl_FragColor = vec4(texcoords2.x , 0.0, texcoords2.y, opacity); + }else{ + gl_FragColor = vec4(texcoords2.xy, 0.0, opacity); + } +} \ No newline at end of file diff --git a/content/sketches/shaders/uv.frag b/content/sketches/shaders/uv.frag new file mode 100644 index 00000000..ea3d1214 --- /dev/null +++ b/content/sketches/shaders/uv.frag @@ -0,0 +1,12 @@ +precision mediump float; + +// the texture coordinates varying was defined in +// the vertex shader by treegl readShader() +// open your console and & see! +varying vec2 texcoords2; + +void main() { + // glsl swizzling is both handy and elegant + // see: https://www.khronos.org/opengl/wiki/Data_Type_(GLSL)#Swizzling + gl_FragColor = vec4(texcoords2.xy, 0.0, 1.0); +} diff --git a/content/sketches/shaders/uvplus.frag b/content/sketches/shaders/uvplus.frag new file mode 100644 index 00000000..d32b376c --- /dev/null +++ b/content/sketches/shaders/uvplus.frag @@ -0,0 +1,15 @@ +precision mediump float; + +uniform bool rtb; +uniform bool gtb; +varying vec2 texcoords2; + +void main() { + if(rtb==true){ + gl_FragColor = vec4(0.0 ,texcoords2.y,texcoords2.x, 1.0); + }else if(gtb==true){ + gl_FragColor = vec4(texcoords2.x , 0.0, texcoords2.y, 1.0); + }else{ + gl_FragColor = vec4(texcoords2.xy, 0.0, 1.0); + } +} \ No newline at end of file diff --git a/content/sketches/sound.js b/content/sketches/sound.js deleted file mode 100644 index eaf69b23..00000000 --- a/content/sketches/sound.js +++ /dev/null @@ -1,62 +0,0 @@ -// Adapted from Learning Processing by Daniel Shiffman -// http://www.learningprocessing.com -// Doorbell sample by Corsica_S via freesound.org, -// Creative Commons BY 3.0 - -// A Class to describe a "doorbell" (really a button) -class Doorbell { - constructor(x_, y_, r_) { - // Location and size - this.x = x_; - this.y = y_; - this.r = r_; - } - // Is a point inside the doorbell? (used for mouse rollover, etc.) - contains(mx, my) { - return dist(mx, my, this.x, this.y) < this.r; - } - - // Show the doorbell (hardcoded colors, could be improved) - display(mx, my) { - if (this.contains(mx, my)) { - fill(100); - } else { - fill(175); - } - stroke(0); - strokeWeight(4); - ellipseMode(RADIUS); - ellipse(this.x, this.y, this.r, this.r); - } -} - -// A sound file object -let dingdong; - -// A doorbell object (that will trigger the sound) -let doorbell; - -function setup() { - createCanvas(200, 200); - - // Load the sound file. - // We have included both an MP3 and an OGG version. - soundFormats('mp3', 'ogg'); - dingdong = loadSound('/showcase/sketches/doorbell.mp3'); - - // Create a new doorbell - doorbell = new Doorbell(width / 2, height / 2, 32); -} - -function draw() { - background(255); - // Show the doorbell - doorbell.display(mouseX, mouseY); -} - -function mousePressed() { - // If the user clicks on the doorbell, play the sound! - if (doorbell.contains(mouseX, mouseY)) { - dingdong.play(); - } -} diff --git a/content/sketches/stepping_feet.js b/content/sketches/stepping_feet.js new file mode 100644 index 00000000..683e3a3c --- /dev/null +++ b/content/sketches/stepping_feet.js @@ -0,0 +1,176 @@ +var canvasWidth = 600; +var canvasHeight = 400; + +var quantity = 2; +var speed = 1; + +var positionXBar1 = 0; +var positionYBar1 = canvasHeight / 3; +var positionYBar2 = (2*canvasHeight) / 3; +var widthBar = 80; +var heightBar = 40; +var colorBar1 = 'yellow'; +var colorBar2 = 'blue'; +var moveBarRight = true; +var isMove = true; +var contrast = true; + +var sliderSpeed; + +function setup() { + createCanvas(canvasWidth, canvasHeight); + background('white'); + drawLayout(); +} + +function draw() { + if(contrast){ + drawBoard(); + }else{ + background(220); + } + updateSpeed(); + drawBar1(); + drawBar2(); +} + +function drawBoard(){ + let position; + + quantity = sliderQuantity.value(); + + let realLines = (canvasWidth / widthBar) * quantity; + let widthLine = widthBar / quantity; + let numberLines = realLines % 2 == 0 ? realLines + 1 : realLines; + + for (let i = 0; i < numberLines; i++) { + position = i * widthLine; + if (i % 2 == 0) { + fill('black'); + rect(position, 0, widthLine, canvasHeight); + } else { + strokeWeight(0) + fill('white'); + rect(position, 0, widthLine, canvasHeight); + } + } +} + +function drawBar1(){ + fill(colorBar1); + rect(positionXBar1, positionYBar1, widthBar, heightBar); + if (moveBarRight) { + positionXBar1 += speed; + if (positionXBar1 + widthBar > canvasWidth) { + moveBarRight = false; + } + } else { + positionXBar1 -= speed; + if (positionXBar1 <= 0) { + moveBarRight = true; + } + } +} + +function drawBar2() { + fill(colorBar2); + rect(positionXBar1, positionYBar2, widthBar, heightBar); + if (moveBarRight) { + positionXBar1 += speed; + if (positionXBar1 + widthBar > canvasWidth) { + moveBarRight = false; + } + } else { + positionXBar1 -= speed; + if (positionXBar1 <= 0) { + moveBarRight = true; + } + } + } + + function updateSpeed() { + if (isMove) { + speed = sliderSpeed.value(); + } + } + +function drawLayout() { + //Reset button + button = createButton('Reset'); + button.position(40, 440); + button.mousePressed(() => { + canvasWidth = 600; + canvasHeight = 400; + quantity = 2; + speed = 1; + positionXBar1 = 0; + positionYBar1 = canvasHeight / 3; + positionXBar2 = 0; + positionYBar2 = (2*canvasHeight) / 3; + widthBar = 80; + heightBar = 40; + moveBarRight = true; + }); + + //Move checkbox + checkbox = createCheckbox('Move', isMove); + checkbox.position(40, 470); + checkbox.mousePressed(() => { + if (speed === 0) { + isMove = true; + speed = sliderSpeed.value(); + } else { + isMove = false; + speed = 0; + } + }); + + //Slider speed + sliderSpeed = createSlider(1, 10, 1); + sliderSpeed.position(40, 500); + sliderSpeed.style('width', '80px'); + + //Slider quantity + sliderQuantity = createSlider(1, 10, 1); + sliderQuantity.position(40, 540); + sliderQuantity.style('width', '80px'); + + //Change color + sel = createSelect(); + sel.position(40, 580); + sel.option('blue-yellow'); + sel.option('red-green'); + sel.option('grey'); + sel.selected('kiwi'); + sel.changed((value) => { + switch(value.target.value) { + case 'blue-yellow': + colorBar1 = 'yellow' + colorBar2 = 'blue' + break; + case 'red-green': + colorBar1 = 'green' + colorBar2 = 'red' + break; + case 'grey': + colorBar1 = 'white' + colorBar2 = 'black' + break; + } + }); + + // Bye Contrast button + button = createButton('Bye contrast'); + button.position(150, 440); + button.mousePressed(() => { + contrast = false; + }); + + // Hi Contrast button + button = createButton('Hi contrast'); + button.position(150, 470); + button.mousePressed(() => { + contrast = true; + }); + +} \ No newline at end of file diff --git a/content/sketches/storm2.png b/content/sketches/storm2.png new file mode 100644 index 00000000..df2d84cd Binary files /dev/null and b/content/sketches/storm2.png differ diff --git a/content/sketches/tools.js b/content/sketches/tools.js new file mode 100644 index 00000000..7b31a56f --- /dev/null +++ b/content/sketches/tools.js @@ -0,0 +1,101 @@ +let lumaShader; +let img; +let grey_scale; +let average; +let HSVV; +let Tint; +let ColorT; + +function preload() { + lumaShader = readShader('/visual_computing/sketches/shaders/colors.frag',{ varyings: Tree.texcoords2}); + img = loadImage('/visual_computing/imgs/car.jpg'); +} + +function drawControls(enabled){ + if(enabled){ + colorT = createColorPicker(color(255,255,255)); + colorT.position(125, 10); + } +} + +function setup() { + createCanvas(700, 500, WEBGL); + noStroke(); + textureMode(NORMAL); + + sel = createSelect(); + sel.position(10, 10); + sel.option('None'); + sel.option('Luma'); + sel.option('Average'); + sel.option('HSV Value V'); + sel.option('HSL Value L'); + sel.option('Tint'); + + sel.selected('None'); + + drawControls(true); + + + +} + +function draw() { + background(0); + + if(sel.value()=="None"){ + shader(lumaShader); + lumaShader.setUniform('texture', img); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('average',false); + + }else if(sel.value()=="Luma"){ + shader(lumaShader); + lumaShader.setUniform('grey_scale',true); + lumaShader.setUniform('average',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value()=="Average"){ + shader(lumaShader); + lumaShader.setUniform('average',true); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="HSV Value V"){ + shader(lumaShader); + lumaShader.setUniform('HSVV',true); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="HSL Value L"){ + shader(lumaShader); + lumaShader.setUniform('HSLL',true); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + }else if(sel.value() =="Tint"){ + shader(lumaShader); + lumaShader.setUniform('Tint',true); + lumaShader.setUniform('HSLL',false); + lumaShader.setUniform('HSVV',false); + lumaShader.setUniform('average',false); + lumaShader.setUniform('grey_scale',false); + lumaShader.setUniform('texture', img); + + let RC = colorT.color(); + lumaShader.setUniform('colorT',[red(RC),green(RC),blue(RC),1.0]); + + } + + quad(-width / 2, -height / 2, width / 2, -height / 2, width / 2, height / 2, -width / 2, height / 2); +} \ No newline at end of file diff --git a/content/sketches/uv_inverse.js b/content/sketches/uv_inverse.js new file mode 100644 index 00000000..cfdacc78 --- /dev/null +++ b/content/sketches/uv_inverse.js @@ -0,0 +1,22 @@ +let uvShader; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/uv.frag', { matrices: Tree.NONE, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(300, 300, WEBGL); + noStroke(); + shader(uvShader); + textureMode(NORMAL); +} + +function draw() { + background(0); + beginShape(); + vertex(-1, -1, 0, 0, 1); + vertex( 1, -1, 0, 1, 1); + vertex( 1, 1, 0, 1, 0); + vertex(-1, 1, 0, 0, 0); + endShape(); +} \ No newline at end of file diff --git a/content/sketches/uvoriginal.js b/content/sketches/uvoriginal.js new file mode 100644 index 00000000..7a683110 --- /dev/null +++ b/content/sketches/uvoriginal.js @@ -0,0 +1,50 @@ +let uvShader; + +function preload() { + // Define geometry directly in clip space (i.e., matrices: Tree.NONE). + // Interpolate only texture coordinates (i.e., varyings: Tree.texcoords2). + // see: https://github.com/VisualComputing/p5.treegl#handling + uvShader = readShader('/visual_computing/sketches/shaders/uv.frag', + { matrices: Tree.NONE, varyings: Tree.texcoords2 }); +} + +function setup() { + // shaders require WEBGL mode to work + createCanvas(300, 300, WEBGL); + noStroke(); + // see: https://p5js.org/reference/#/p5/shader + shader(uvShader); + // https://p5js.org/reference/#/p5/textureMode + // best and simplest is to just always used NORMAL + textureMode(NORMAL); +} + +function draw() { + background(0); + /* + clip-space quad shape, i.e., both x and y vertex coordinates ∈ [-1..1] + since textureMode is NORMAL, texture coordinates ∈ [-1..1] + see: https://p5js.org/reference/#/p5/beginShape + https://p5js.org/reference/#/p5/vertex + y v + | | + (-1,1)| (1,1) (0,1) (1,1) + *_____|_____* *__________* + | | | | | + |_____|_____|__x | texture | + | | | | space | + *_____|_____* *__________*___ u + (-1,-1) (1,-1) (0,0) (1,0) + */ + beginShape(); + vertex(-1, -1, 0, 0, 0); + vertex( 1, -1, 0, 1, 0); + vertex( 1, 1, 0, 1, 1); + vertex(-1, 1, 0, 0, 1); + endShape(); + // ✨ it's worth noting (not mentioned in the p5 api docs though) + // that quad (https://p5js.org/reference/#/p5/quad) also adds the + // texture coords to each of its vertices. Hence: + // quad(-1, -1, 1, -1, 1, 1, -1, 1); + // produce the same results as the above beginShape / endShape +} \ No newline at end of file diff --git a/content/sketches/uvplus.js b/content/sketches/uvplus.js new file mode 100644 index 00000000..9cc9dbea --- /dev/null +++ b/content/sketches/uvplus.js @@ -0,0 +1,46 @@ +let easycam; +let uvShader; +let c1, c2; + +let rtb = false, gtb = false; + +function preload() { + uvShader = readShader('/visual_computing/sketches/shaders/uvplus.frag',{ matrices: Tree.pmvMatrix, varyings: Tree.texcoords2 }); +} + +function setup() { + createCanvas(300, 300, WEBGL); + textureMode(NORMAL); + c1 = createCheckbox('Red To Blue', false); + c2 = createCheckbox('Green To Blue', false); + c1.position(10, 310); + c2.position(150, 310); + shader(uvShader); +} + +function draw() { + background(200); + orbitControl(); + axes(); + push(); + noStroke(); + quad(-width / 2, -height / 2, width / 2, -height / 2, + width / 2, height / 2, -width / 2, height / 2); + pop(); + + if(c1.checked()){ + uvShader.setUniform('rtb',true) + uvShader.setUniform('gtb',false) + }else if(c2.checked()){ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',true) + }else{ + uvShader.setUniform('rtb',false) + uvShader.setUniform('gtb',false) + } +} + +function mouseWheel(event) { + return false; +} + diff --git a/content/sketches/video-canvas.js b/content/sketches/video-canvas.js deleted file mode 100644 index 1935df69..00000000 --- a/content/sketches/video-canvas.js +++ /dev/null @@ -1,21 +0,0 @@ -let fingers; - -function setup() { - createCanvas(710, 400); - // specify multiple formats for different browsers - fingers = createVideo(['/showcase/sketches/fingers.mov', '/showcase/sketches/fingers.webm']); - fingers.hide(); // by default video shows up in separate dom - // element. hide it and draw it to the canvas - // instead -} - -function draw() { - background(150); - image(fingers, 10, 10); // draw the video frame to canvas - filter(GRAY); - image(fingers, 150, 150); // draw a second copy to canvas -} - -function mousePressed() { - fingers.loop(); // set the video to loop and start playing -} \ No newline at end of file diff --git a/content/sketches/video-dom.js b/content/sketches/video-dom.js deleted file mode 100644 index bc457a6a..00000000 --- a/content/sketches/video-dom.js +++ /dev/null @@ -1,17 +0,0 @@ -let vid; -function setup() { - noCanvas(); - - vid = createVideo( - ['/showcase/sketches/fingers.mov', '/showcase/sketches/fingers.webm'], - vidLoad - ); - - vid.size(320, 240); -} - -// This function is called when the video loads -function vidLoad() { - vid.loop(); - vid.volume(0); -} \ No newline at end of file diff --git a/content/vid/drift.mp4 b/content/vid/drift.mp4 new file mode 100644 index 00000000..d6b550ff Binary files /dev/null and b/content/vid/drift.mp4 differ diff --git a/layouts/shortcodes/p5-div.html b/layouts/shortcodes/p5-div.html index cd301353..0b73a36a 100644 --- a/layouts/shortcodes/p5-div.html +++ b/layouts/shortcodes/p5-div.html @@ -8,6 +8,8 @@ + + {{ if isset .Params "lib1" }} {{ end }} {{ if isset .Params "lib2" }} {{ end }} {{ if isset .Params "lib3" }} {{ end }} diff --git a/layouts/shortcodes/p5-global-iframe.html b/layouts/shortcodes/p5-global-iframe.html index 329d0295..8ce4b60d 100644 --- a/layouts/shortcodes/p5-global-iframe.html +++ b/layouts/shortcodes/p5-global-iframe.html @@ -14,6 +14,8 @@ + + {{ if isset .Params "lib1" }} {{ end }} {{ if isset .Params "lib2" }} {{ end }} {{ if isset .Params "lib3" }} {{ end }} diff --git a/layouts/shortcodes/p5-iframe.html b/layouts/shortcodes/p5-iframe.html index 1547b8d2..62bbdbbf 100644 --- a/layouts/shortcodes/p5-iframe.html +++ b/layouts/shortcodes/p5-iframe.html @@ -15,6 +15,8 @@ + + {{ if isset .Params "lib1" }} {{ end }} {{ if isset .Params "lib2" }} {{ end }} {{ if isset .Params "lib3" }} {{ end }} diff --git a/layouts/shortcodes/p5-iframe2.html b/layouts/shortcodes/p5-iframe2.html new file mode 100644 index 00000000..c2d613f0 --- /dev/null +++ b/layouts/shortcodes/p5-iframe2.html @@ -0,0 +1,27 @@ +{{ $defver := `1.4.2` }} +{{ $sketch := .Get `sketch` }} +{{ $lib1 := .Get `lib1` }} +{{ $lib2 := .Get `lib2` }} +{{ $lib3 := .Get `lib3` }} +{{ $lib4 := .Get `lib4` }} +{{ $lib5 := .Get `lib5` }} + + \ No newline at end of file diff --git a/layouts/shortcodes/p5-instance-div.html b/layouts/shortcodes/p5-instance-div.html index 0a5bd134..254ac15f 100644 --- a/layouts/shortcodes/p5-instance-div.html +++ b/layouts/shortcodes/p5-instance-div.html @@ -8,6 +8,8 @@ + + {{ if isset .Params "lib1" }} {{ end }} {{ if isset .Params "lib2" }} {{ end }} {{ if isset .Params "lib3" }} {{ end }} diff --git a/themes/ananke b/themes/ananke new file mode 160000 index 00000000..470ea409 --- /dev/null +++ b/themes/ananke @@ -0,0 +1 @@ +Subproject commit 470ea40982f5036554819253c3ac6ed4a34193f4