How to implement dynamic reflections in A-Frame - aframe

I have an A-Frame scene consisting of a horizontal plane, some lights and a vertical plane on which a video is playing. I am trying to achieve reflections on the horizontal plane such that the vertical plane above it is reflected. I intend to set reduced opacity on the reflective surface. How can one do this in A-Frame?

I write a mirror component, here is my code:
<script>
AFRAME.registerComponent('mirror', {
schema:{
renderothermirror:{default:true},
},
init: function () {
var scene = this.el.sceneEl;
scene.addEventListener('render-target-loaded',this.OnRenderLoaded.bind(this));
},
OnRenderLoaded: function()
{
var mirrorObj = this.el.getOrCreateObject3D('mesh',THREE.Mesh);
var cameraEl = document.querySelector('a-entity[camera]')
if(!cameraEl)
{
cameraEl = document.querySelector('a-camera');
}
var camera = cameraEl.components.camera.camera;
var scene = this.el.sceneEl;
this.renderer = scene.renderer;
this.mirror = new THREE.Mirror( this.renderer, camera, { clipBias: 0.003, textureWidth: window.innerWidth, textureHeight: window.innerHeight, color: 0x777777 } );
mirrorObj.material =this.mirror.material;
mirrorObj.add(this.mirror);
},
tick: function () {
if(!this.data.renderothermirror)
{
this.mirror.render();
}
else
{
var mirrors = [];
var mirrorEls = document.querySelectorAll("a-entity[mirror]");
for(var i=0;i<mirrorEls.length;i++)
{
if(mirrorEls[i]!=this.el)
{
mirrors.push(mirrorEls[i].components.mirror.mirror);
}
}
if(mirrors.length === 0)
{
this.mirror.render();
}
for(var i = 0; i<mirrors.length;i++)
{
this.mirror.renderWithMirror(mirrors[i]);
}
}
}
});
</script>
You also need to use Mirror.js, you can find it here:Mirror.js
Just attach the mirror component to your planes. e.g. <a-plane mirror>.

Related

Google Maps draggable overlay on touch screen

I have added a custom draggable overlay onto a google map, which works well using a mouse, but doesn't work on touch screens.
The code I am using is from this question : Can we make custom overlays draggable on google maps V3
The code is from #Dr.Molle and shown below.
Is there anything I can do to make it work on a touch screen? The marker shows, but I cannot move it.
DraggableOverlay.prototype = new google.maps.OverlayView();
DraggableOverlay.prototype.onAdd = function () {
var container = document.createElement('div'),
that = this;
if (typeof this.get('content').nodeName !== 'undefined') {
container.appendChild(this.get('content'));
} else {
if (typeof this.get('content') === 'string') {
container.innerHTML = this.get('content');
} else {
return;
}
}
container.style.position = 'absolute';
container.draggable = true;
google.maps.event.addDomListener(this.get('map').getDiv(),
'mouseleave',
function () {
google.maps.event.trigger(container, 'mouseup');
}
);
google.maps.event.addDomListener(container,
'mousedown',
function (e) {
this.style.cursor = 'move';
that.map.set('draggable', false);
that.set('origin', e);
that.moveHandler =
google.maps.event.addDomListener(that.get('map').getDiv(),
'mousemove',
function (e) {
var origin = that.get('origin'),
left = origin.clientX - e.clientX,
top = origin.clientY - e.clientY,
pos = that.getProjection()
.fromLatLngToDivPixel(that.get('position')),
latLng = that.getProjection()
.fromDivPixelToLatLng(new google.maps.Point(pos.x - left,
pos.y - top));
that.set('origin', e);
that.set('position', latLng);
that.draw();
});
}
);
google.maps.event.addDomListener(container, 'mouseup', function () {
that.map.set('draggable', true);
this.style.cursor = 'default';
google.maps.event.removeListener(that.moveHandler);
});
this.set('container', container)
this.getPanes().floatPane.appendChild(container);
};
function DraggableOverlay(map, position, content) {
if (typeof draw === 'function') {
this.draw = draw;
}
this.setValues({
position: position,
container: null,
content: content,
map: map
});
}
DraggableOverlay.prototype.draw = function () {
var pos = this.getProjection().fromLatLngToDivPixel(this.get('position'));
this.get('container').style.left = pos.x + 'px';
this.get('container').style.top = pos.y + 'px';
};
DraggableOverlay.prototype.onRemove = function () {
this.get('container').parentNode.removeChild(this.get('container'));
this.set('container', null)
};
new DraggableOverlay(
map,//maps-instance
latLng,//google.maps.LatLng
'content',//HTML-String or DOMNode
function(){}//optional, function that ovverrides the draw-method
);

How to add point on polyline somewhere between two vertexes?

The goal is to have an editable polyline with customized markers at every vertex.
As I see Map API V3 does not allows that. So I made editable polyline like this:
let polyline = new self.google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 0.3,
strokeWeight: 3,
editable: false,
path: path,
map: self.map
});
polyline.binder = new MVCArrayBinder(polyline.getPath());
let markers = [];
for (let i = 0; i < path.length; i++) {
let marker = this.getBasicMarker(path[i]);
marker.bindTo('position', polyline.binder, i.toString());
markers.push(marker);
}
getBasicMarker(position){
return new this.google.maps.Marker({
position: position,
map: this.map,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
},
draggable: true,
visible: false
});
}
function MVCArrayBinder(mvcArray) {
this.array_ = mvcArray;
}
MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function (key) {
if (!isNaN(parseInt(key))) {
return this.array_.getAt(parseInt(key));
} else {
this.array_.get(key);
}
};
MVCArrayBinder.prototype.set = function (key, val) {
if (!isNaN(parseInt(key))) {
this.array_.setAt(parseInt(key), val);
} else {
this.array_.set(key, val);
}
};
Final polyline now looks like this: http://sandbox.rubera.ru/img/2019-05-28_17-04-25.jpg. I can drag any existing point. The polyline updating while dragging the point.
Now I have to add new vertex somewhere between two existing.
This is where I'm stuck.
May be there is another solution how to solve the task?
In case anybody face similar task here is a few modifications to my code posted abowe. That helped me finally solve the problem.
MVCArrayBinder.prototype = new google.maps.MVCObject();
MVCArrayBinder.prototype.get = function (key) {
if (!isNaN(parseInt(key))) {
return this.array_.getAt(parseInt(key));
} else {
this.array_.get(key);
}
};
MVCArrayBinder.prototype.set = function (key, val) {
if (!isNaN(parseInt(key))) {
this.array_.setAt(parseInt(key), val);
} else {
this.array_.set(key, val);
}
};
MVCArrayBinder.prototype.insertAt = function (key, val) {
this.array_.insertAt(key, val);
};
google.maps.event.addListener(this.activePoly, 'click', function (e) {
let path = $this.activePoly.getPath(),
inserted = false;
// find line segment
for (let i = 0; i < path.getLength() - 1, !inserted; i++) {
let tempPoly = new google.maps.Polyline({
path: [path.getAt(i), path.getAt(i + 1)]
});
if (google.maps.geometry.poly.isLocationOnEdge(e.latLng, tempPoly, 10e-2)) {
$this.activeRoute.binder.insertAt(i + 1, e.latLng);
inserted = true;
let marker = $this.getBasicMarker(e.latLng);
marker.setVisible(true);
// Add new marker to array
$this.activeRoute.markers.splice(i + 1, 0, marker);
// Have to rebind all markers
$this.activeRoute.markers.forEach((marker, index) => {
marker.bindTo('position', $this.activeRoute.binder, index.toString());
});
}
}
});
My activeRoute is an object with following structure:
{polyline: polyline, markers: markers, binder: polyline.binder}

A-FRAME Extend component

Consider this:
<a-entity id="player">
<a-entity id="camera" camera look-controls></a-entity>
<a-entity id="leftHand" oculus-touch-controls="hand: left"></a-entity>
<a-entity id="rightHand" oculus-touch-controls="hand: right"></a-entity>
</a-entity>
If I want to move my player through the scene, I would add wasd-controls to #player. Doing that, disregards the orientation of the head (camera): W always moves "north", wherever you are looking at. If I add wasd-controls to #camera, the head moves correctly but the controllers are left behind.
So I thought of creating a custom wasd-controls, but I am unable to extend that component. I have been successful copying and pasting all the code, but that is very nasty.
This did not work: AFrame extend component and override.
Any idea?
my-wasd-controls.js
var KEYCODE_TO_CODE = require('aframe/src/constants').keyboardevent.KEYCODE_TO_CODE;
var AFRAME = require('aframe');
var THREE = require('aframe/src/lib/three');
var utils = require('aframe/src/utils');
var bind = utils.bind;
var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
var CLAMP_VELOCITY = 0.00001;
var MAX_DELTA = 0.2;
var KEYS = [
'KeyW', 'KeyA', 'KeyS', 'KeyD',
'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
];
/**
* WASD component to control entities using WASD keys.
*/
module.exports.Component = AFRAME.registerComponent('my-wasd-controls', {
schema: {
acceleration: {default: 65},
adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
adEnabled: {default: true},
adInverted: {default: false},
easing: {default: 20},
enabled: {default: true},
fly: {default: false},
head: {type: 'selector'},
wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
wsEnabled: {default: true},
wsInverted: {default: false}
},
init: function () {
// To keep track of the pressed keys.
this.keys = {};
this.position = {};
this.velocity = new THREE.Vector3();
// Bind methods and add event listeners.
this.onBlur = bind(this.onBlur, this);
this.onFocus = bind(this.onFocus, this);
this.onKeyDown = bind(this.onKeyDown, this);
this.onKeyUp = bind(this.onKeyUp, this);
this.onVisibilityChange = bind(this.onVisibilityChange, this);
this.attachVisibilityEventListeners();
},
tick: function (time, delta) {
var currentPosition;
var data = this.data;
var el = this.el;
var movementVector;
var position = this.position;
var velocity = this.velocity;
if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
isEmptyObject(this.keys)) { return; }
// Update velocity.
delta = delta / 1000;
this.updateVelocity(delta);
if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
// Get movement vector and translate position.
currentPosition = el.getAttribute('position');
movementVector = this.getMovementVector(delta);
position.x = currentPosition.x + movementVector.x;
position.y = currentPosition.y + movementVector.y;
position.z = currentPosition.z + movementVector.z;
el.setAttribute('position', position);
},
remove: function () {
this.removeKeyEventListeners();
this.removeVisibilityEventListeners();
},
play: function () {
this.attachKeyEventListeners();
},
pause: function () {
this.keys = {};
this.removeKeyEventListeners();
},
updateVelocity: function (delta) {
var acceleration;
var adAxis;
var adSign;
var data = this.data;
var keys = this.keys;
var velocity = this.velocity;
var wsAxis;
var wsSign;
adAxis = data.adAxis;
wsAxis = data.wsAxis;
// If FPS too low, reset velocity.
if (delta > MAX_DELTA) {
velocity[adAxis] = 0;
velocity[wsAxis] = 0;
return;
}
// Decay velocity.
if (velocity[adAxis] !== 0) {
velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
}
if (velocity[wsAxis] !== 0) {
velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
}
// Clamp velocity easing.
if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
if (!data.enabled) { return; }
// Update velocity using keys pressed.
acceleration = data.acceleration;
if (data.adEnabled) {
adSign = data.adInverted ? -1 : 1;
if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
}
if (data.wsEnabled) {
wsSign = data.wsInverted ? -1 : 1;
if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
}
},
getMovementVector: (function () {
var directionVector = new THREE.Vector3(0, 0, 0);
var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
return function (delta) {
var rotation = (this.data.head || this.el).getAttribute('rotation');
var velocity = this.velocity;
var xRotation;
directionVector.copy(velocity);
directionVector.multiplyScalar(delta);
// Absolute.
if (!rotation) { return directionVector; }
xRotation = this.data.fly ? rotation.x : 0;
// Transform direction relative to heading.
rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
directionVector.applyEuler(rotationEuler);
return directionVector;
};
})(),
attachVisibilityEventListeners: function () {
window.addEventListener('blur', this.onBlur);
window.addEventListener('focus', this.onFocus);
document.addEventListener('visibilitychange', this.onVisibilityChange);
},
removeVisibilityEventListeners: function () {
window.removeEventListener('blur', this.onBlur);
window.removeEventListener('focus', this.onFocus);
document.removeEventListener('visibilitychange', this.onVisibilityChange);
},
attachKeyEventListeners: function () {
window.addEventListener('keydown', this.onKeyDown);
window.addEventListener('keyup', this.onKeyUp);
},
removeKeyEventListeners: function () {
window.removeEventListener('keydown', this.onKeyDown);
window.removeEventListener('keyup', this.onKeyUp);
},
onBlur: function () {
this.pause();
},
onFocus: function () {
this.play();
},
onVisibilityChange: function () {
if (document.hidden) {
this.onBlur();
} else {
this.onFocus();
}
},
onKeyDown: function (event) {
var code;
if (!shouldCaptureKeyEvent(event)) { return; }
code = event.code || KEYCODE_TO_CODE[event.keyCode];
if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
},
onKeyUp: function (event) {
var code;
code = event.code || KEYCODE_TO_CODE[event.keyCode];
delete this.keys[code];
}
});
function isEmptyObject (keys) {
var key;
for (key in keys) { return false; }
return true;
}
I would still recommend copy and pasting it. If you ever upgrade A-Frame later, and wasd-controls changes, your extensions will probably break.
Changing the prototype should work (e.g., AFRAME.components['wasd-controls'].Component.prototype.foo = () => {}). The prototype methods are writable.
Another alternative is to overwrite the method on the component instance. el.components['wasd-controls'].foo = () => {}.

Alpha Animation in Aframe for a-object-model

I have one 3d object with its obj and mtl file which is displayed using in Aframe. I want to apply animation on it which change its Alpha value gradually for Fade out effect.
I went through AFrame doc. but couldn't find anything related to 3d object alpha animation.
The built-in material component primarily works with primitives, so material="opacity: 0.5" and similarly opacity="0.5" will not work here. You'll need to modify the THREE.js materials created by your model, using a custom component. Example:
AFRAME.registerComponent('model-opacity', {
schema: {default: 1.0},
init: function () {
this.el.addEventListener('model-loaded', this.update.bind(this));
},
update: function () {
var mesh = this.el.getObject3D('mesh');
var data = this.data;
if (!mesh) { return; }
mesh.traverse(function (node) {
if (node.isMesh) {
node.material.opacity = data;
node.material.transparent = data < 1.0;
node.material.needsUpdate = true;
}
});
}
});
You can then use, and animate, the component like this:
<a-entity obj-model="obj: model.obj; mtl: model.mtl;" model-opacity="1">
<a-animation attribute="model-opacity"
dur="10000"
from="1"
to="0"
repeat="indefinite"></a-animation>
</a-entity>
For more on how this works, see the docs on THREE.Material and writing a component.
For me, the material was all white, so I had to change the component by Don to support a number:
AFRAME.registerComponent("model-opacity", {
schema: {
opacity: { type: "number", default: 0.5 }
},
init: function() {
this.el.addEventListener("model-loaded", this.update.bind(this));
},
update: function() {
var mesh = this.el.getObject3D("mesh");
var data = this.data;
if (!mesh) {
return;
}
mesh.traverse(function(node) {
if (node.isMesh) {
console.log(node);
node.material.opacity = data.opacity;
node.material.transparent = data.opacity < 1.0;
node.material.needsUpdate = true;
}
});
}
});
I had to modify the above examples as mine had multiple materials, so I had to use forEach and adjust for all of them:
AFRAME.registerComponent("model-opacity", {
schema: {
opacity: { type: "number", default: 0.5 }
},
init: function() {
this.el.addEventListener("model-loaded", this.update.bind(this));
},
update: function() {
var mesh = this.el.getObject3D("mesh");
var data = this.data;
if (!mesh) {
return;
}
mesh.traverse(function(node) {
if (node.isMesh) {
console.log(node);
node.material.forEach( (mtl) =>{
mtl.opacity = data.opacity;
mtl.transparent = data.opacity < 1.0;
mtl.needsUpdate = true;
})
}
});
}
});

Google Map Tooltip

I wonder whether someone may be able to help me please.
I've been working on a tooltip for markers that I place on a google map. I can get this to work showing the information that I would like the user to see, in this case the fields name and address, so the code line is title: name+address.
Could someone please tell me how I could put a space between these so the tooltip would read 'name address' rather than 'nameaddress'.
I've tried all sorts of things using e.g.title: name'_'+ address, title: name' '+address and I can't get it to work.
Any help would be greatly appreciated.
Many thanks
Chris
You can try this
name + ' ' + address
NB: you need a space in the quotes and a + on either side.
I use this function to initialize started values:
//Inicialize map values
function initialize() {
latCenterMap=41.50347;
lonCenterMap=-5.74638;
zommCeneterMap=14;
latPoint=41.50347;
lonPoint=-5.74638;
//Values default initialize
var latlng = new google.maps.LatLng(latCenterMap, lonCenterMap);
var mapOptions = {
zoom: zommCeneterMap,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas_'), mapOptions);
codePoint(map, lat, lon);
}
I used this function to set values point position into map
//Get position by Latitude and Longitude
function codePoint(map, lat, lon) {
var latlng = new google.maps.LatLng(parseFloat(lat), parseFloat(lon));
var title = "Your text";
var iconPoint = new google.maps.MarkerImage('images/pointBlue.png',
//Measure image
new google.maps.Size(25,25),
new google.maps.Point(0,0),
//Half measure image
new google.maps.Point(12.5,12.5)
);
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: iconPoint,
tooltip: title
});
customTooltip(marker);
}
I use this function to create a tooltip to point position
//TOOLTIP
function customTooltip(marker){
// Constructor function
function Tooltip(opts, marker) {
// Initialization
this.setValues(opts);
this.map_ = opts.map;
this.marker_ = marker;
var div = this.div_ = document.createElement("div");
// Class name of div element to style it via CSS
div.className = "tooltip";
this.markerDragging = false;
}
Tooltip.prototype = {
// Define draw method to keep OverlayView happy
draw: function() {},
visible_changed: function() {
var vis = this.get("visible");
this.div_.style.visibility = vis ? "visible" : "hidden";
},
getPos: function(e) {
var projection = this.getProjection();
// Position of mouse cursor
var pixel = projection.fromLatLngToDivPixel(e.latLng);
var div = this.div_;
// Adjust the tooltip's position
var gap = 15;
var posX = pixel.x + gap;
var posY = pixel.y + gap;
var menuwidth = div.offsetWidth;
// Right boundary of the map
var boundsNE = this.map_.getBounds().getNorthEast();
boundsNE.pixel = projection.fromLatLngToDivPixel(boundsNE);
if (menuwidth + posX > boundsNE.pixel.x) {
posX -= menuwidth + gap;
}
div.style.left = posX + "px";
div.style.top = posY + "px";
if (!this.markerDragging) {
this.set("visible", true);
}
},
// This is added to avoid using listener (Listener is not working when Map is quickly loaded with icons)
getPos2: function(latLng) {
var projection = this.getProjection();
// Position of mouse cursor
var pixel = projection.fromLatLngToDivPixel(latLng);
var div = this.div_;
// Adjust the tooltip's position
var gap = 5;
var posX = pixel.x + gap;
var posY = pixel.y + gap;
var menuwidth = div.offsetWidth;
// Right boundary of the map
var boundsNE = this.map_.getBounds().getNorthEast();
boundsNE.pixel = projection.fromLatLngToDivPixel(boundsNE);
if (menuwidth + posX > boundsNE.pixel.x) {
posX -= menuwidth + gap;
}
div.style.left = posX + "px";
div.style.top = posY + "px";
if (!this.markerDragging) {
this.set("visible", true);
}
},
addTip: function() {
var me = this;
var g = google.maps.event;
var div = me.div_;
div.innerHTML = me.get("text").toString();
// Tooltip is initially hidden
me.set("visible", false);
// Append the tooltip's div to the floatPane
me.getPanes().floatPane.appendChild(this.div_);
// In IE this listener gets randomly lost after it's been cleared once.
// So keep it out of the listeners array.
g.addListener(me.marker_, "dragend", function() {
me.markerDragging = false; });
// Register listeners
me.listeners = [
// g.addListener(me.marker_, "dragend", function() {
// me.markerDragging = false; }),
g.addListener(me.marker_, "position_changed", function() {
me.markerDragging = true;
me.set("visible", false); }),
g.addListener(me.map_, "mousemove", function(e) {
me.getPos(e); })
];
},
removeTip: function() {
// Clear the listeners to stop events when not needed.
if (this.listeners) {
for (var i = 0, listener; listener = this.listeners[i]; i++) {
google.maps.event.removeListener(listener);
}
delete this.listeners;
}
// Remove the tooltip from the map pane.
var parent = this.div_.parentNode;
if (parent) parent.removeChild(this.div_);
}
};
function inherit(addTo, getFrom) {
var from = getFrom.prototype; // prototype object to get methods from
var to = addTo.prototype; // prototype object to add methods to
for (var prop in from) {
if (typeof to[prop] == "undefined") to[prop] = from[prop];
}
}
// Inherits from OverlayView from the Google Maps API
inherit(Tooltip, google.maps.OverlayView);
var tooltip = new Tooltip({map: map}, marker);
tooltip.bindTo("text", marker, "tooltip");
google.maps.event.addListener(marker, 'mouseover', function() {
tooltip.addTip();
tooltip.getPos2(marker.getPosition());
});
google.maps.event.addListener(marker, 'mouseout', function() {
tooltip.removeTip();
});
}
I use this style to css file
//CSS
.tooltip {
position:absolute;
top:0;
left:0;
z-index: 300;
width: 11.5em;
padding: 5px;
font-size: 12pt;
font-family: klavika;
color: #fff;
background-color: #04A2CA;
border-radius: 10px;
box-shadow: 2px 2px 5px 0 rgba(50, 50, 50, 0.75);
}

Resources