Nov fajl za kegle, nov scenarij

main
Jurij Podgoršek 2023-06-14 13:51:18 +02:00
parent ed9de513fa
commit 652fe8d3a4
11 changed files with 47489 additions and 52 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@ -0,0 +1,28 @@
1. en kegel
samo deformacija, mogoce malo zoom
pulz na zogico,
+ nojz (glasba, rocno?)
- BREZ zogic
- BREZ dodatnih
2. dva kegla
3. ena zogica
4. 2 kegla + zogica
===== VKLOP LUCI ======
reset (calibrate, zoom blizu)
(nojz stran)
(vklopimo zogice)
5. komad: ena zogica!
6. tri zogice
7. band: vkljucimo publiko
+ VKLOP dodatni kegli
TODO:
- barvne palete za zogice (izmenicno levo desno), kegle
- upostevaj velocity zogic
- WW kontroler za vklop / izklop deformacije, ostalih elementov (barva ja / ne)
- postavit kegle v sredino
- postavit zogice v kader

7
2023-06-11.txt 100644
View File

@ -0,0 +1,7 @@
1. FFT noise od blizu, ni rotacije + ko pridejo zogice pulziranje
2. dodamo vrtenjek
Ideje:
1. deformacija po segmentih
2. en kegel v drugem, drug v enem (scale pojacat)

View File

@ -0,0 +1,120 @@
////////////////////////////////////////////////////////////////////////////
//
// This file is part of RTIMULib-Arduino
//
// Copyright (c) 2014-2015, richards-tech
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <Wire.h>
#include "I2Cdev.h"
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "CalLib.h"
#include <EEPROM.h>
RTIMU *imu; // the IMU object
RTIMUSettings settings; // the settings object
CALLIB_DATA calData; // the calibration data
// SERIAL_PORT_SPEED defines the speed to use for the debug serial port
#define SERIAL_PORT_SPEED 115200
void setup()
{
Serial.begin(SERIAL_PORT_SPEED);
Serial.println("ArduinoMagCal starting");
// Init EEPROM based on magnet calibration size requirement
EEPROM.begin(512);
Serial.print("CalData size: "); Serial.print(sizeof(calData)); Serial.println(" bytes");
calLibRead(0, &calData); // pick up existing mag data if there
Serial.println("Existing calibration data: ");
Serial.println(calData.validL);
Serial.println(calData.validH);
Serial.println(calData.magValid);
Serial.println(calData.pad);
Serial.println(calData.magMin[0]);
Serial.println(calData.magMin[1]);
Serial.println(calData.magMin[2]);
Serial.println(calData.magMin[0]);
Serial.println(calData.magMin[1]);
Serial.println(calData.magMin[2]);
calData.magValid = false;
for (int i = 0; i < 3; i++) {
calData.magMin[i] = 10000000; // init mag cal data
calData.magMax[i] = -10000000;
}
Serial.println("Enter s to save current data to EEPROM");
Wire.begin();
imu = RTIMU::createIMU(&settings); // create the imu object
imu->IMUInit();
imu->setCalibrationMode(true); // make sure we get raw data
Serial.print("ArduinoIMU calibrating device "); Serial.println(imu->IMUName());
}
void loop()
{
boolean changed;
RTVector3 mag;
if (imu->IMURead()) { // get the latest data
changed = false;
mag = imu->getCompass();
for (int i = 0; i < 3; i++) {
if (mag.data(i) < calData.magMin[i]) {
calData.magMin[i] = mag.data(i);
changed = true;
}
if (mag.data(i) > calData.magMax[i]) {
calData.magMax[i] = mag.data(i);
changed = true;
}
}
if (changed) {
Serial.println("-------");
Serial.print("minX: "); Serial.print(calData.magMin[0]);
Serial.print(" maxX: "); Serial.print(calData.magMax[0]); Serial.println();
Serial.print("minY: "); Serial.print(calData.magMin[1]);
Serial.print(" maxY: "); Serial.print(calData.magMax[1]); Serial.println();
Serial.print("minZ: "); Serial.print(calData.magMin[2]);
Serial.print(" maxZ: "); Serial.print(calData.magMax[2]); Serial.println();
}
}
if (Serial.available()) {
if (Serial.read() == 's') { // save the data
calData.magValid = true;
calLibWrite(0, &calData);
EEPROM.commit();
Serial.print("Mag cal data saved for device "); Serial.println(imu->IMUName());
Serial.println("Testing saved data...");
if (imu->getCalibrationValid())
Serial.println("Compass calibration is valid");
else
Serial.println("No valid compass calibration data");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -2,11 +2,11 @@
#include <esp_wifi.h>
#include <WiFi.h>
#include "RTMath.h"
#include <OSCBundle.h>
#include <OSCBoards.h>
//#define DEBUG
#ifdef BOARD_HAS_USB_SERIAL
#include <SLIPEncodedUSBSerial.h>
SLIPEncodedUSBSerial SLIPSerial( thisBoardsSerialUSB );
@ -20,68 +20,77 @@ SLIPEncodedSerial SLIPSerial(Serial); // Change to Serial1 or Serial2 etc. for b
uint8_t newMACAddress[] = {0x08, 0x3A, 0xF2, 0x50, 0xEF, 0x6C};
typedef struct sensor_msg {
int id;
RTFLOAT aX;
RTFLOAT aY;
RTFLOAT aZ;
RTFLOAT qX;
RTFLOAT qY;
RTFLOAT qZ;
RTFLOAT qW;
}sensor_msg;
#include <SLIPEncodedSerial.h>
uint8_t id;
int16_t aX;
int16_t aY;
int16_t aZ;
float qX;
float qY;
float qZ;
float qW;
} sensor_msg;
sensor_msg odcitek;
//sensor_msg odcitek;
sensor_msg odcitekA;
sensor_msg odcitekB;
// Maksimalno stevilo
#define ST_KEGLOV 10
#define ST_KEGLOV 2
sensor_msg odcitki[ST_KEGLOV] = {odcitekA, odcitekB};
bool poslji[ST_KEGLOV] = {false, false};
int odcitekId;
sensor_msg odcitki[ST_KEGLOV];
bool poslji[ST_KEGLOV];
void prejemPodatkov(const uint8_t * mac_addr, const uint8_t * drugiPodatki, int len) {
void prejemPodatkov(const uint8_t * mac_addr, const uint8_t * noviPodatki, int len) {
char macNaslov[18];
//Serial.print("Prejel podatke od ");
snprintf(macNaslov, sizeof(macNaslov), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
//Serial.println(macNaslov);
memcpy(&odcitek, drugiPodatki, sizeof(odcitek));
//Serial.printf("Board ID %u: %u bytes\n", odcitek.id, len);
// Update the structures with the new incoming data
odcitki[odcitek.id-1].aX = odcitek.aX;
odcitki[odcitek.id-1].aY = odcitek.aY;
odcitki[odcitek.id-1].aZ = odcitek.aZ;
odcitki[odcitek.id-1].qX = odcitek.qX;
odcitki[odcitek.id-1].qY = odcitek.qY;
odcitki[odcitek.id-1].qZ = odcitek.qZ;
odcitki[odcitek.id-1].qW = odcitek.qW;
/*
Serial.printf("aX: %f \n", odcitki[odcitek.id-1].aX);
Serial.printf("aY: %f \n", odcitki[odcitek.id-1].aY);
Serial.printf("aZ: %f \n", odcitki[odcitek.id-1].aZ);
Serial.printf("qX: %f \n", odcitki[odcitek.id-1].qX);
Serial.printf("qY: %f \n", odcitki[odcitek.id-1].qY);
Serial.printf("qZ: %f \n", odcitki[odcitek.id-1].qZ);
Serial.printf("qW: %f \n", odcitki[odcitek.id-1].qW);
#ifdef DEBUG
Serial.print("Prejel podatke od ");
Serial.println(macNaslov);
#endif
// ID odcitka je na prvem mestu!
memcpy(&odcitekId, noviPodatki, sizeof(uint8_t));
#ifdef DEBUG
Serial.print("RAZBIRAM ID ");
Serial.println(odcitekId);
#endif
memcpy(&odcitki[odcitekId], noviPodatki, sizeof(sensor_msg));
#ifdef DEBUG
Serial.printf("aX: %i \n", odcitki[odcitekId].aX);
Serial.printf("aY: %i \n", odcitki[odcitekId].aY);
Serial.printf("aZ: %i \n", odcitki[odcitekId].aZ);
Serial.printf("qX: %f \n", odcitki[odcitekId].qX);
Serial.printf("qY: %f \n", odcitki[odcitekId].qY);
Serial.printf("qZ: %f \n", odcitki[odcitekId].qZ);
Serial.printf("qW: %f \n", odcitki[odcitekId].qW);
Serial.println();
*/
poslji[odcitek.id-1] = true;
#endif
poslji[odcitekId] = true;
}
void setup() {
// put your setup code here, to run once:
//Serial.begin(115200);
SLIPSerial.begin(115200);
// Ne posiljaj preden se podatki napolnijo
for (int i = 0; i < ST_KEGLOV; i++) {
poslji[0] = false;
}
Serial.println("Inicializiram WIFI...");
WiFi.mode(WIFI_STA);
esp_wifi_set_mac(WIFI_IF_STA, &newMACAddress[0]);
if (esp_now_init() != ESP_OK) {
esp_err_t result = esp_now_init();
if (result != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
Serial.println(result);
return;
}
Serial.print("MAC naslov: ");
@ -89,33 +98,50 @@ void setup() {
esp_now_register_recv_cb(prejemPodatkov);
}
/* OSC MSG channels */
OSCBundle bundle;
char glava[32];
void loop() {
// put your main code here, to run repeatedly:
/* OSC MSG channels */
OSCBundle bundle;
char glava[32];
for (int i = 0; i < ST_KEGLOV; i++) {
if (poslji[i]) {
sprintf(glava, "/ww/%d/accel", i);
/*
Serial.print("Posiljam ");
Serial.println(glava);
*/
bundle.add(glava)
.add(odcitki[i].aX)
.add(odcitki[i].aY)
.add(odcitki[i].aZ);
sprintf(glava, "/ww/%d/quaternion", i);
/*
Serial.print("Posiljam ");
Serial.println(glava);
*/
bundle.add(glava)
.add(odcitki[i].qW)
.add(odcitki[i].qX)
.add(odcitki[i].qY)
.add(odcitki[i].qZ);
/*
Serial.printf("XaX: %i \n", odcitki[i].aX);
Serial.printf("XaY: %i \n", odcitki[i].aY);
Serial.printf("XaZ: %i \n", odcitki[i].aZ);
Serial.printf("XqX: %f \n", odcitki[i].qX);
Serial.printf("XqY: %f \n", odcitki[i].qY);
Serial.printf("XqZ: %f \n", odcitki[i].qZ);
Serial.printf("XqW: %f \n", odcitki[i].qW);
Serial.println();
*/
SLIPSerial.beginPacket();
bundle.send(SLIPSerial);
SLIPSerial.endPacket();
bundle.empty();
bundle.empty();
poslji[i] = false;
}
}

17
kegli.html 100644
View File

@ -0,0 +1,17 @@
<html>
<head>
<meta charset="UTF-8">
<title>glasbena miza</title>
<style type="text/css">
body { margin: 0; }
</style>
</head>
<body>
<div id="anim-container"></div>
<script src="node_modules/three/build/three.min.js"></script>
<script src="node_modules/osc/dist/osc-browser.js"></script>
<script src="kegli.js"></script>
<script src="osctl.js"></script>
</body>
</html>

720
kegli.js 100644
View File

@ -0,0 +1,720 @@
console.log("Hello, Sky!");
/**** ******
/ Test skripta *
************/
// Ker kegel imamo?
var izbranKegel = 1;
if (window.location.hash.indexOf('kegel') > -1) {
izbranKegel = window.location.hash.split('=')[1];
console.log('definiran kegel!');
}
console.log('izbran kegel: ', izbranKegel);
// Vidni kot
var FOV = 90;
// Parametri rotacije (euler)
var rotacijaX = 0.000;
var rotacijaY = 0.000;
var rotacijaZ = 0.000;
// Parametri pospeska
var accX = 0.000;
var accY = 0.000;
var accZ = 0.000;
var deformiraj = 0;
// Analiza zvoka
const fftSize = 64
const bufferSize = 32
const stolpicki = new Uint8Array(bufferSize)
let analyser = null
// "Napihni" kegle?
let napihni = 1
// Scena, kamera in render
var scene = new THREE.Scene;
window.scene = scene;
/*
const axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );
*/
var camera = new THREE.PerspectiveCamera(FOV, window.innerWidth / window.innerHeight, 0.1, 2000);
window.camera = camera;
// Polozaj kamere
camera.position.z = 10;
var renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
// Belo ozadje
renderer.setClearColor(0xFFFFFF, 1);
// Črno ozadje
//renderer.setClearColor(0x000000, 1);
//var skupina = new THREE.Group();
/********
* KEGEL *
*********/
// Sirina in visina test objekta
var width = 16;
var height = 128;
var radialnihSegmentov = 4;
var visinskihSegmentov = 128;
var geo = new THREE.BufferGeometry();
var offset = width;
var polozaji = [];
// visina: 128 segmentov
// sirina: 9 segmentov
var sirinaSegmentov = 9;
// Najprej "spodnja buba"
var faktor = [
2/sirinaSegmentov, 2/sirinaSegmentov
];
// Pol rocaj (1.4 do 2.8 segmenta, dolgo 62 segmentov)
var rocajSegmentov = 46;
for (var i = 0; i <= rocajSegmentov; i++) {
faktor.push((1.4 + i / rocajSegmentov * 1.4) / sirinaSegmentov);
}
// pol stresica dol (2.8 do 7.4 segmenta)
var stresicaSegmentov = 48;
for (i = 0; i <= stresicaSegmentov; i++) {
faktor.push((2.8 + i / stresicaSegmentov * 4.6) / sirinaSegmentov);
}
// Pa se zadnji naklon (7.4 do 3 segmente)
var konecSegmentov = 30;
for (i = 0; i <= konecSegmentov; i++) {
faktor.push((7.4 - i / konecSegmentov * 4.4) / sirinaSegmentov);
}
// spodnji krog
for (var s = 0; s < radialnihSegmentov; s++) {
polozaji.push(
0.0,
0.0,
0.0,
Math.sin(2 * Math.PI * s / radialnihSegmentov) * width * faktor[0],
Math.cos(2 * Math.PI * s / radialnihSegmentov) * width * faktor[0],
0.0,
Math.sin(2 * Math.PI * (s + 1) / radialnihSegmentov) * width * faktor[0],
Math.cos(2 * Math.PI * (s + 1) / radialnihSegmentov) * width * faktor[0],
0.0
);
}
// vmesni segmenti
for (var h = 0; h < visinskihSegmentov; h++) {
for (s = 0; s < radialnihSegmentov; s++) {
polozaji.push(
Math.sin(2 * Math.PI * s / radialnihSegmentov) * width * faktor[h],
Math.cos(2 * Math.PI * s / radialnihSegmentov) * width * faktor[h],
h * height / visinskihSegmentov,
Math.sin(2 * Math.PI * (s + 1) / radialnihSegmentov) * width * faktor[h],
Math.cos(2 * Math.PI * (s + 1) / radialnihSegmentov) * width * faktor[h],
h * height / visinskihSegmentov,
Math.sin(2 * Math.PI * (s + 1) / radialnihSegmentov) * width * faktor[h],
Math.cos(2 * Math.PI * (s + 1) / radialnihSegmentov) * width * faktor[h],
(h + 1) * height / visinskihSegmentov,
);
}
}
// zgornji krog
for (s = 0; s < radialnihSegmentov; s++) {
polozaji.push(
0,
0,
height,
Math.sin(2 * Math.PI * s / radialnihSegmentov) * width * faktor[31],
Math.cos(2 * Math.PI * s / radialnihSegmentov) * width * faktor[31],
height,
Math.sin(2 * Math.PI * (s + 1) / radialnihSegmentov) * width * faktor[31],
Math.cos(2 * Math.PI * (s + 1) / radialnihSegmentov) * width * faktor[31],
height
);
}
for (i = 0; i < polozaji.length; i++) {
if (i % 3 == 2) {
polozaji[i] -= height / 2;
}
}
// Spremeni v vertexe
var vertices = new Float32Array(polozaji);
geo.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
window.geo = geo;
var barva = new THREE.Color(0, 0, 0);
var barvaDodatni = new THREE.Color();
barvaDodatni.setHSL(0.6, 1.0, 0.5);
var mat = new THREE.MeshBasicMaterial({
//color: 0xff00ff,
color: barva,
wireframe: true,
transparent: true
});
window.mat = mat;
//var mat = new THREE.LineBasicMaterial({ color: 0xff00ff });
var kegel = new THREE.Mesh(geo.clone(), mat);
kegel.position.z = 20; // gor / dol
kegel.position.y = -30; // levo / desno
kegel.position.x = 12; // levo / desno drugic
if (izbranKegel == 1) {
kegel.position.x -= 10;
kegel.position.y += 8;
kegel.position.z += 3;
}
var barvnePalete = [
[0x0a2d2e, 0x1c4e4f, 0x436e6f, 0x6a8e8f, 0x879693, 0xa49e97, 0xdeae9f, 0xefd7cf, 0xf7ebe7, 0xffffff],
// https://colorkit.co/palette/0a2d2e-1c4e4f-436e6f-6a8e8f-879693-a49e97-deae9f-efd7cf-f7ebe7-ffffff/
[0x80558c, 0xaf7ab3, 0xcba0ae, 0xd8b9a0, 0xe4d192],
// https://colorkit.co/palette/80558c-af7ab3-cba0ae-d8b9a0-e4d192/
[0xf68aa2, 0xcf6d93, 0xa85183, 0x813474, 0x5a1765],
// https://colorkit.co/palette/f68aa2-cf6d93-a85183-813474-5a1765/
[0x03071e, 0x211c1b, 0x3d3019, 0x594417, 0x745814, 0x906b12, 0xac7f0f, 0xc8930d, 0xe3a60a, 0xffba08]
// https://colorkit.co/palette/03071e-211c1b-3d3019-594417-745814-906b12-ac7f0f-c8930d-e3a60a-ffba08/
]
var barvnePaleteIdx = [0, 0, 0, 0]
/*********
* ZOGICE *
*********/
var zogice = false
var kegli = false
/*
var barvnaPaleta = [
new THREE.Color(0x003F5C),
new THREE.Color(0x58508D),
new THREE.Color(0xBC5090),
new THREE.Color(0xFF6361),
new THREE.Color(0xFFA600),
// Simetrija
new THREE.Color(0xFF6361),
new THREE.Color(0xBC5090),
new THREE.Color(0x58508D),
];
console.log(barvnaPaleta);
var barvnaPaletaIdx = 0;
*/
var barvaKrogleO = new THREE.Color();
barvaKrogleO.setHSL(Math.random(), 0.8, 0.5);
function novaKrogla () {
//var barvaKrogle = barvaKrogleO.clone();
var bId = izbranKegel == 0 ? 2 : 3
console.log('id barve:', bId);
var barvaKrogle = new THREE.Color(barvnePalete[bId][barvnePaleteIdx[bId]]);
var mat = new THREE.MeshBasicMaterial({
color: barvaKrogle,
wireframe: true,
transparent: true
});
var velikost = 1 + Math.random() * 5;
var kroglaGeo = new THREE.SphereGeometry(velikost, 12, 12);
var krogla = new THREE.Mesh(kroglaGeo, mat);
krogla.position.x = (Math.random() - 1) * 200;
krogla.position.y = (Math.random() - 1) * 10;
krogla.position.z = (Math.random() - 1) * 300;
krogla.position.y -= 100;
krogla.position.x += 150;
krogla.position.z += 230; // gor/dol
//krogla.position.y += 200;
scene.add(krogla);
krogle.push(krogla);
}
function spremeniZoom (kolicina) {
const noviZum = camera.position.z * (1 + kolicina / 25)
console.log(noviZum)
if ((noviZum > 0.1) && (noviZum < 300)) {
camera.position.z = noviZum
}
}
function spremeniDeformiraj (kolicina) {
const noviDeformiraj = deformiraj + (kolicina / 2)
//console.log('deform', noviDeformiraj)
if (noviDeformiraj > 0) {
deformiraj = noviDeformiraj
} else {
deformiraj = 0
}
}
//skupina.add(kegel);
// Za pospeskomer - os X
var gAX = new THREE.CylinderGeometry(10, 10, 10, 16);
var mAX = new THREE.MeshBasicMaterial({ color: 0xff000055 });
var AX = new THREE.Mesh(gAX, mAX);
//skupina.add(AX);
// Damo vse skupaj v kader
// scene.add(skupina);
scene.add(kegel);
// Quaternioni za rotacijo in kalibracijo
var qWW = new THREE.Quaternion();
var qPrej = new THREE.Quaternion();
var qObj = new THREE.Quaternion();
var qStart = new THREE.Quaternion();
var reset = false;
var calibrate = true;
var objekti = [kegel];
var dodatniObjekti = [];
var krogle = [];
var stevec = 0;
// Zacetna orientacija kegla
scene.rotation.x = 90;
scene.rotation.z = 270;
//skupina.position.z = 32;
//skupina.position.y = -100;
var cakajDeformiraj = false
var cakajZogice = false
var cakajKegli = false
let analiziramZvok = false
function inputHandle () {
if (kbdPressed.c) {
calibrate = true;
sendAll('/ww/calibrate');
}
if (kbdPressed['-']) {
sendAll('/ww/reload');
window.location.reload();
}
/*
if (kbdPressed.d && !cakajDeformiraj) {
deformiraj = !deformiraj
cakajDeformiraj = true
const args = [{
type: "f",
value: deformiraj
}];
sendAll('/ww/zoom', args)
setTimeout(() => cakajDeformiraj = false, 200)
}
*/
if (kbdPressed.g && !cakajZogice) {
zogice = !zogice
cakajZogice = true
const args = [{
type: "i",
value: zogice ? 1 : 0
}];
sendAll('/ww/zogice', args)
setTimeout(() => cakajZogice = false, 200)
}
if (kbdPressed['l'] && !cakajKegli) {
kegli = !kegli
console.log('sprememba kegli', kegli)
cakajKegli = true
const args = [{
type: "i",
value: kegli ? 1 : 0
}];
sendAll('/ww/kegli', args)
setTimeout(() => cakajKegli = false, 200)
}
}
function render () {
requestAnimationFrame(render);
renderer.render(scene, camera);
stevec += 1;
objAnim();
inputHandle();
while (krogle.length > 50) {
scene.remove(krogle[0]);
krogle.shift();
}
};
var cakajDodatni = false
// Funkcija za animacijo objektov
function objAnim() {
// Rotacija kegla
objekti.map(function (obj) {
// Apliciramo rotacijo (po quaternionih - eulerji zajebavajo.)
qObj = qWW.clone();
qObj.multiply(qStart);
obj.setRotationFromQuaternion(qObj);
AX.scale.x = accX / 1000;
if (analyser) {
analyser.getByteFrequencyData(stolpicki)
deformiraj = (stolpicki[3] + stolpicki[4] + stolpicki[5]) / 30
//console.log('FFT!', stolpicki)
//napihni = 1 + stolpicki[0] / 10
}
obj.scale.z = napihni
if (napihni > 1) {
obj.scale.x = napihni * 2
obj.scale.y = napihni * 2
napihni = Math.max(napihni * 0.9, 1)
} else {
obj.scale.x = 1
obj.scale.y = 1
}
// Deformiranje kegla!
// Random 500 zamaknemo
var koti = obj.geometry.attributes.position.array;
var faktorD = 5;
/*
// Random deformacija
for (var i = 0; i < 500; i++) {
koti[Math.floor(Math.random() * koti.length)] += (Math.random() - 1) * deformiraj;
}
*/
// Deformacija po stolpickih FFT
for (var i = 0; i < koti.length / 10; i += 1) {
const stolpLen = 10;
const stolpOffset = 0;
const offset = Math.floor(Math.random() * 3)
const vrednost = stolpicki[Math.floor(i * 10 / koti.length * stolpLen) + stolpOffset]
/*
if (i % 1000 == 0) {
console.log('+', i, vrednost)
}
*/
const neg = (Math.random() > 0.5) ? 1 : -1
//console.log(offset, vrednost, neg)
koti[koti.length - (i * 10 + offset)] += vrednost / 50 * neg
}
// In priblizamo osnovni geometriji
for (var i = 0; i < koti.length; i++) {
// Tole zamika cel kegel stran @TODO
//koti[i] = (geo.attributes.position.array[i] - koti[i]) * 0.75;
koti[i] = (geo.attributes.position.array[i] - koti[i]) * 0.75;
}
obj.geometry.attributes.position.needsUpdate = true;
});
// Ce jih je prevec, pucaj
while (dodatniObjekti.length > 100) {
scene.remove(dodatniObjekti[0]);
dodatniObjekti.shift();
}
dodatniObjekti.map(function (obj) {
// Apliciramo rotacijo (po quaternionih - eulerji zajebavajo.)
qObj = qWW.clone();
//qObj.multiply(obj.qStart).multiply(qStart);
//obj.setRotationFromQuaternion(qObj);
obj.translateOnAxis(obj.premakniAxis, obj.premakniKolicina);
// obj.material.color.offsetHSL(0, 0, 0.003);
obj.material.opacity *= 0.998;
obj.premakniKolicina *= 0.98;
var dQ = obj.quaternion.multiply(obj.rotirajQ);
/*
dQ.multiply(obj.rotirajQ);
obj.setRotationFromQuaternion(dQ);
*/
/*
obj.premakni.x *= 1.1;
obj.premakni.y *= 1.1;
obj.premakni.z *= 1.1;
*/
obj.material.opacity *= 0.98;
});
barvaKrogleO.offsetHSL(-(2/1000), 0, 0);
krogle.map(function (obj) {
obj.material.opacity *= 0.98;
var scaleF = 0.05;
obj.scale.x += scaleF;
obj.scale.y += scaleF;
obj.scale.z += scaleF;
});
// Kalibracija rotacije kegla
if (calibrate) {
qStart = qWW.clone();
qStart.conjugate();
calibrate = false;
console.log("RESET!");
}
// rotiramo skupino da se vidi
//skupina.rotation.x += 0.003;
//skupina.rotation.y += 0.005;
//skupina.rotation.z += 0.007;
if (kegel.scale.x > 1) {
kegel.scale.x *= 0.95;
}
if (kegel.scale.z > 1) {
kegel.scale.z *= 0.95;
}
// kegel.material.color.offsetHSL(2 / 1000, 0, 0);
// Dupliranje keglov
if (kegli) {
var vsota = Math.abs(accX) + Math.abs(accZ)
if (vsota > 2 && !cakajDodatni) {
cakajDodatni = true
var dodatni = kegel.clone();
dodatni.renderOrder = stevec;
var dodatniMat = kegel.material.clone();
//var dodatniBarva = barvaDodatni.clone();
var bId = izbranKegel == 0 ? 0 : 1
var dodatniBarva = new THREE.Color(barvnePalete[bId][barvnePaleteIdx[bId]])
dodatniMat.color = dodatniBarva;
dodatni.material = dodatniMat;
dodatni.premakniAxis = new THREE.Vector3(
Math.random(),
Math.random(),
Math.random()
);
dodatni.premakniKolicina = vsota;
var rQ = qWW.clone();
rQ.invert();
rQ.multiply(qPrej);
dodatni.rotirajQ = rQ;
//dodatni.qStart = kegel.quaternion.clone();
dodatniObjekti.push(dodatni);
scene.add(dodatni);
barvnePaleteIdx[bId] = (barvnePaleteIdx[bId] + 1) % barvnePalete[bId].length;
}
if (cakajDodatni && vsota < 1) {
cakajDodatni = false
}
}
};
// Inicializiraj
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
document.getElementById("anim-container").appendChild(renderer.domElement);
render();
}
};
// Lep risajz
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener('resize', onWindowResize, false);
// Poslusaj OSC evente
var keysPressed = [0, 0, 0, 0];
const getVal = function (msg) {
return msg.value;
}
var prepend = `/ww/0/ww/${izbranKegel}`;
console.log('prepend!', prepend);
var oscCallbacks = {};
oscCallbacks[`${prepend}'/keys`] = function(args) {
keysPressed = args.map(getVal);
};
oscCallbacks[`${prepend}/quaternion`] = function (args) {
// Popravimo osi (w x y z po defaultu HMM)
[qPrej.w, qPrej.x, qPrej.y, qPrej.z] = [qWW.w, qWW.x, qWW.y, qWW.z];
[qWW.w, qWW.x, qWW.y, qWW.z] = args.map(getVal);
};
oscCallbacks[`${prepend}/accel`] = function (args) {
[accX, accY, accZ] = args.map(getVal);
};
oscCallbacks[`${prepend}/gyro`] = function (args) {
[rotacijaX, rotacijaY, rotacijaZ] = args.map(getVal);
};
oscCallbacks['/ww/calibrate'] = function () {
calibrate = true;
};
oscCallbacks['/ww/reload'] = function () {
window.location.reload();
};
oscCallbacks['/ww/zoom'] = args => {
const [kolicina] = args.map(getVal)
spremeniZoom(kolicina)
}
oscCallbacks['/ww/deformiraj'] = args => {
const [kolicina] = args.map(getVal)
spremeniDeformiraj(kolicina)
}
oscCallbacks['/ww/kegli'] = args => {
const [ali] = args.map(getVal)
kegli = ali
}
oscCallbacks['/ww/zogice'] = args => {
const [ali] = args.map(getVal)
zogice = ali
}
function zogicaCB(args) {
console.log("MAMOMO MIDI!", args[0].value, args[1].value, args[2].value);
var minus = (izbranKegel == 1) ? -1 : 1;
// kegel.material.color.offsetHSL(minus * args[2].value / 1000, 0, 0);
barvaDodatni.offsetHSL(minus * args[2].value / 1000, 0, 0);
if (Math.random() < 0.5) {
kegel.scale.x *= 2;
} else {
kegel.scale.z *= 2;
}
//kegel.scale.y *= 1 + (args[2] / 100000);
//kegel.scale.z *= 1 + (args[2] / 100000);
if (zogice) {
novaKrogla();
var bId = izbranKegel == 0 ? 2 : 3
console.log('id barve:', bId)
barvnePaleteIdx[bId] = (barvnePaleteIdx[bId] + 1) % barvnePalete[bId].length;
}
napihni = 3
}
oscCallbacks['/midi-in/0'] = zogicaCB
const kbdPressed = {
a: false,
s: false,
d: false,
f: false,
c: false
};
window.addEventListener('keydown', e => {
kbdPressed[e.key] = true
})
window.addEventListener('keyup', e => {
if (e.key in kbdPressed) {
kbdPressed[e.key] = false
}
})
window.addEventListener('mousedown', e => {
e.preventDefault()
switch (e.button) {
case 0:
kbdPressed['miska'] = true
if (!analiziramZvok) {
zacniAnalizo()
}
break;
case 2:
kbdPressed['miskaD'] = true
}
return false
})
window.addEventListener('mouseup', e => {
if ('miska' in kbdPressed) {
kbdPressed['miska'] = false
}
if ('miskaD' in kbdPressed) {
kbdPressed['miskaD'] = false
}
})
var skrolam = false;
var zadnjiSkrol = 0;
window.addEventListener('mousemove', e => {
if (kbdPressed['miska']) {
const sprememba = (e.movementX + e.movementY) / 10
spremeniZoom(sprememba)
const args = [{
type: "f",
value: sprememba
}];
sendAll('/ww/zoom', args)
}
if (kbdPressed['miskaD']) {
const sprememba = (e.movementX + e.movementY) / 10
spremeniDeformiraj(sprememba)
const args = [{
type: "f",
value: sprememba
}];
sendAll('/ww/deformiraj', args)
}
})
// Zacni audio analizo
function zacniAnalizo() {
if (!analiziramZvok) {
// Analiza zvoka
const audioCtx = new AudioContext()
const mikrofon = navigator.mediaDevices.getUserMedia({ audio: true }).then(
(stream) => {
const source = audioCtx.createMediaStreamSource(stream)
analyser = audioCtx.createAnalyser()
analyser.minDecibels = -90;
analyser.maxDecibels = -10;
analyser.smoothingTimeConstant = 0.85;
analyser.fftSize = fftSize
source.connect(analyser)
//analyser.connect(audioCtx.destination)
},
() => {
console.log('napaka nalaganja mikrofona', arguments)
analiziramZvok = false
}
)
analiziramZvok = true
}
}

View File

@ -0,0 +1,180 @@
#include "SLIPEncodedBluetoothSerial.h"
#include "BluetoothSerial.h"
/*
CONSTRUCTOR
*/
//instantiate with the tranmission layer
//use BluetoothSerial
SLIPEncodedBluetoothSerial::SLIPEncodedBluetoothSerial(BluetoothSerial &s){
serial = &s;
rstate = CHAR;
}
static const uint8_t eot = 0300;
static const uint8_t slipesc = 0333;
static const uint8_t slipescend = 0334;
static const uint8_t slipescesc = 0335;
/*
SERIAL METHODS
*/
bool SLIPEncodedBluetoothSerial::endofPacket()
{
if(rstate == SECONDEOT)
{
rstate = CHAR;
return true;
}
if (rstate==FIRSTEOT)
{
if(serial->available())
{
uint8_t c =serial->peek();
if(c==eot)
{
serial->read(); // throw it on the floor
}
}
rstate = CHAR;
return true;
}
return false;
}
int SLIPEncodedBluetoothSerial::available(){
back:
int cnt = serial->available();
if(cnt==0)
return 0;
if(rstate==CHAR)
{
uint8_t c =serial->peek();
if(c==slipesc)
{
rstate = SLIPESC;
serial->read(); // throw it on the floor
goto back;
}
else if( c==eot)
{
rstate = FIRSTEOT;
serial->read(); // throw it on the floor
goto back;
}
return 1; // we may have more but this is the only sure bet
}
else if(rstate==SLIPESC)
return 1;
else if(rstate==FIRSTEOT)
{
if(serial->peek()==eot)
{
rstate = SECONDEOT;
serial->read(); // throw it on the floor
return 0;
}
rstate = CHAR;
}else if (rstate==SECONDEOT) {
rstate = CHAR;
}
return 0;
}
//reads a byte from the buffer
int SLIPEncodedBluetoothSerial::read(){
back:
uint8_t c = serial->read();
if(rstate==CHAR)
{
if(c==slipesc)
{
rstate=SLIPESC;
goto back;
}
else if(c==eot){
return -1; // xxx this is an error
}
return c;
}
else
if(rstate==SLIPESC)
{
rstate=CHAR;
if(c==slipescend)
return eot;
else if(c==slipescesc)
return slipesc;
else {
// insert some error code here
return -1;
}
}
else
return -1;
}
// as close as we can get to correct behavior
int SLIPEncodedBluetoothSerial::peek(){
uint8_t c = serial->peek();
if(rstate==SLIPESC)
{
if(c==slipescend)
return eot;
else if(c==slipescesc)
return slipesc;
}
return c;
}
//the arduino and wiring libraries have different return types for the write function
#if defined(WIRING) || defined(BOARD_DEFS_H)
//encode SLIP
void SLIPEncodedBluetoothSerial::write(uint8_t b){
if(b == eot){
serial->write(slipesc);
return serial->write(slipescend);
} else if(b==slipesc) {
serial->write(slipesc);
return serial->write(slipescesc);
} else {
return serial->write(b);
}
}
void SLIPEncodedBluetoothSerial::write(const uint8_t *buffer, size_t size) { while(size--) write(*buffer++); }
#else
//encode SLIP
size_t SLIPEncodedBluetoothSerial::write(uint8_t b){
if(b == eot){
serial->write(slipesc);
return serial->write(slipescend);
} else if(b==slipesc) {
serial->write(slipesc);
return serial->write(slipescesc);
} else {
return serial->write(b);
}
}
size_t SLIPEncodedBluetoothSerial::write(const uint8_t *buffer, size_t size) { size_t result=0; while(size--) result = write(*buffer++); return result; }
#endif
void SLIPEncodedBluetoothSerial::begin(String name){
serial->begin(name);
}
//SLIP specific method which begins a transmitted packet
void SLIPEncodedBluetoothSerial::beginPacket() { serial->write(eot); }
//signify the end of the packet with an EOT
void SLIPEncodedBluetoothSerial::endPacket(){
serial->write(eot);
}
void SLIPEncodedBluetoothSerial::flush(){
serial->flush();
}

View File

@ -0,0 +1,62 @@
/*
Extends the Serial class to encode SLIP over serial
*/
#ifndef SLIPEncodedBluetoothSerial_h
#define SLIPEncodedBluetoothSerial_h
#include "Arduino.h"
#include <Stream.h>
#include "BluetoothSerial.h"
class SLIPEncodedBluetoothSerial: public Stream{
private:
enum erstate {CHAR, FIRSTEOT, SECONDEOT, SLIPESC } rstate;
//the serial port used
BluetoothSerial * serial;
public:
//the serial port used
SLIPEncodedBluetoothSerial(BluetoothSerial & );
int available();
int read();
int peek();
void flush();
//same as Serial.begin
void begin(String);
//SLIP specific method which begins a transmitted packet
void beginPacket();
//SLIP specific method which ends a transmittedpacket
void endPacket();
// SLIP specific method which indicates that an EOT was received
bool endofPacket();
//the arduino and wiring libraries have different return types for the write function
#if defined(WIRING) || defined(BOARD_DEFS_H)
void write(uint8_t b);
void write(const uint8_t *buffer, size_t size);
#else
//overrides the Stream's write function to encode SLIP
size_t write(uint8_t b);
size_t write(const uint8_t *buffer, size_t size);
//using Print::write;
#endif
};
#endif

View File

@ -0,0 +1,190 @@
// ESP32 Dev Module
#include <Wire.h>
// ID kegla mora bit unikaten za vsakega! (se poslje poleg parametrov)
#define KEGEL_ID 2
// IMU libraries
#include "I2Cdev.h"
#include "RTIMUSettings.h"
#include "RTIMU.h"
#include "RTFusionRTQF.h"
#include "CalLib.h"
#include <EEPROM.h>
//#include "RTMath.h"
#include <esp_now.h>
#include <WiFi.h>
uint8_t sprejemnikMac[] = {0x08, 0x3A, 0xF2, 0x50, 0xEF, 0x6C };
typedef struct sensor_msg {
int id;
RTFLOAT aX;
RTFLOAT aY;
RTFLOAT aZ;
RTFLOAT qX;
RTFLOAT qY;
RTFLOAT qZ;
RTFLOAT qW;
}sensor_msg;
sensor_msg odcitek;
esp_now_peer_info_t peerInfo;
#define DISPLAY_INTERVAL 5 // interval between pose displays
// Motion sensor objects
RTIMU *imu; // the IMU object
RTFusionRTQF fusion; // the fusion object
RTIMUSettings settings; // the settings object
unsigned long lastDisplay;
unsigned long lastRate;
int sampleCount;
RTQuaternion gravity;
bool reset; // For quaternion calibration
void setup() {
int errcode;
// Basic(debug) serial init
Serial.begin(115200);
//Serial.begin(115200); // set this as high as you can reliably run on your platform
Serial.println("Starting up...");
// Init EEPROM based on magnet calibration size requirement
EEPROM.begin(512);
// I2C init
Wire.begin();
Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
// create the imu object
imu = RTIMU::createIMU(&settings);
Serial.print("ArduinoIMU starting using device "); Serial.println(imu->IMUName());
if ((errcode = imu->IMUInit()) < 0) {
Serial.print("Failed to init IMU: "); Serial.println(errcode);
}
if (imu->getCalibrationValid())
Serial.println("Using compass calibration");
else
Serial.println("No valid compass calibration data");
// Gravity obj
gravity.setScalar(0);
gravity.setX(0);
gravity.setY(0);
gravity.setZ(1);
/*
fusion.setSlerpPower(0.02);
fusion.setGyroEnable(true);
fusion.setAccelEnable(true);
fusion.setCompassEnable(true);
*/
lastDisplay = lastRate = millis();
sampleCount = 0;
// WIFI init
WiFi.mode(WIFI_STA);
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
//esp_now_register_send_cb(paketPoslan);
memcpy(peerInfo.peer_addr, sprejemnikMac, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("WIFI registracija ni uspela");
return;
}
}
void paketPoslan(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nStanje poslanega paketa:\t");
if (status == ESP_NOW_SEND_SUCCESS) {
Serial.println("Uspesno poslano!");
} else {
Serial.println("Napaka pri posiljanju...");
}
}
void loop() {
unsigned long now = millis();
unsigned long delta;
RTVector3 realAccel;
RTQuaternion rotatedGravity;
RTQuaternion fusedConjugate;
RTQuaternion qTemp;
int loopCount = 0;
// get the latest data if ready yet
while (imu->IMURead()) {
// this flushes remaining data in case we are falling behind
if (++loopCount >= 10)
continue;
fusion.newIMUData(imu->getGyro(), imu->getAccel(), imu->getCompass(), imu->getTimestamp());
// do gravity rotation and subtraction
// create the conjugate of the pose
fusedConjugate = fusion.getFusionQPose().conjugate();
// now do the rotation - takes two steps with qTemp as the intermediate variable
qTemp = gravity * fusion.getFusionQPose();
rotatedGravity = fusedConjugate * qTemp;
// now adjust the measured accel and change the signs to make sense
realAccel.setX(-(imu->getAccel().x() - rotatedGravity.x()));
realAccel.setY(-(imu->getAccel().y() - rotatedGravity.y()));
realAccel.setZ(-(imu->getAccel().z() - rotatedGravity.z()));
sampleCount++;
if ((delta = now - lastRate) >= 1000) {
//Serial.print("Sample rate: "); Serial.print(sampleCount);
if (!imu->IMUGyroBiasValid()) {
// Serial.println(", calculating gyro bias");
} else {
// Serial.println();
}
sampleCount = 0;
lastRate = now;
}