I try to use VTK VR, but When I test it, I cant see controller in room, I can get action from controller like press or somthing, but without its seen for user in VR mode, how I can fix it?
Online Demo From Here.
import 'vtk.js/Sources/favicon';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkCalculator from 'vtk.js/Sources/Filters/General/Calculator';
import vtkConeSource from 'vtk.js/Sources/Filters/Sources/ConeSource';
import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import { AttributeTypes } from 'vtk.js/Sources/Common/DataModel/DataSetAttributes/Constants';
import { FieldDataTypes } from 'vtk.js/Sources/Common/DataModel/DataSet/Constants';
import controlPanel from './controller.html';
// ----------------------------------------------------------------------------
// Standard rendering code setup
// ----------------------------------------------------------------------------
const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
background: [0, 0, 0],
});
const renderer = fullScreenRenderer.getRenderer();
const renderWindow = fullScreenRenderer.getRenderWindow();
// ----------------------------------------------------------------------------
// Example code
// ----------------------------------------------------------------------------
// create a filter on the fly, sort of cool, this is a random scalars
// filter we create inline, for a simple cone you would not need
// this
// ----------------------------------------------------------------------------
const coneSource = vtkConeSource.newInstance({ height: 100.0, radius: 50.0 });
// const coneSource = vtkConeSource.newInstance({ height: 1.0, radius: 0.5 });
const filter = vtkCalculator.newInstance();
filter.setInputConnection(coneSource.getOutputPort());
// filter.setFormulaSimple(FieldDataTypes.CELL, [], 'random', () => Math.random());
filter.setFormula({
getArrays: (inputDataSets) => ({
input: [],
output: [
{
location: FieldDataTypes.CELL,
name: 'Random',
dataType: 'Float32Array',
attribute: AttributeTypes.SCALARS,
},
],
}),
evaluate: (arraysIn, arraysOut) => {
const [scalars] = arraysOut.map((d) => d.getData());
for (let i = 0; i < scalars.length; i++) {
scalars[i] = Math.random();
}
},
});
const mapper = vtkMapper.newInstance();
mapper.setInputConnection(filter.getOutputPort());
const actor = vtkActor.newInstance();
actor.setMapper(mapper);
actor.setPosition(20.0, 0.0, 0.0);
renderer.addActor(actor);
renderer.resetCamera();
renderWindow.render();
// -----------------------------------------------------------
// UI control handling
// -----------------------------------------------------------
fullScreenRenderer.addController(controlPanel);
const representationSelector = document.querySelector('.representations');
const resolutionChange = document.querySelector('.resolution');
const vrbutton = document.querySelector('.vrbutton');
representationSelector.addEventListener('change', (e) => {
const newRepValue = Number(e.target.value);
actor.getProperty().setRepresentation(newRepValue);
renderWindow.render();
});
resolutionChange.addEventListener('input', (e) => {
const resolution = Number(e.target.value);
coneSource.setResolution(resolution);
renderWindow.render();
});
vrbutton.addEventListener('click', (e) => {
if (vrbutton.textContent === 'Send To VR') {
fullScreenRenderer.getOpenGLRenderWindow().startVR();
vrbutton.textContent = 'Return From VR';
} else {
fullScreenRenderer.getOpenGLRenderWindow().stopVR();
vrbutton.textContent = 'Send To VR';
}
});
// -----------------------------------------------------------
// Make some variables global so that you can inspect and
// modify objects in your browser's developer console:
// -----------------------------------------------------------
global.source = coneSource;
global.mapper = mapper;
global.actor = actor;
global.renderer = renderer;
global.renderWindow = renderWindow;
Note: Tested on Latest Version of Chrome & Firefox (64 bit). Controller Type is HTC Vive.
Update 1:
We found this option not development, so that I share updated link now Github Link
Related
This is my first question so I'll try to explain the problem as much as I can.
I'm working on a Vue3 project, where I have a component that receives props, these props are treated as proxys in Vue (reactivity purposes).
The problem comes when reading the data. The proxy's target seems to have data, but when console.log() the object.property, shows undefined:
console.log(this.slideResults)
console.log(JSON.parse(JSON.stringify(this.slideResults)))
My component:
export default defineComponent({
props: {
takenImage: HTMLImageElement,
slideResults: Object, // slideResults = {[opencvResults], [possibleDuplicatedImages]}
},
components: { Swiper, Slide, SwiperSlide },
computed: {
getImages() {
// console.log the prop -> target = Object{canvasResults: canvas, possibleDuplicatedImages: }
console.log(this.slideResults);
const slideResults = JSON.parse(JSON.stringify(this.slideResults));
console.log(slideResults);
console.log(slideResults.canvasResults);
console.log(slideResults.possibleDuplicatedImages);
// To destructure props and don't lose reactivity we need to convert them into ref
// const { slideResults } = toRaw(this.slideResults);
// console.log(slideResults);
// const { canvasResults, possibleDuplicatedImages } = toRaw(
// this.slideResults
// );
// console.log(canvasResults[0]);
// console.log(this.takenImage);
// // In order to pass to a slide the images as: Array<Object> where [{imageFile, canvas}]
// /**
// * #type {Array<{ image: HTMLCanvasElement[], opencvResult: File[] }>}
// */
const images = [];
// for (let i = 0; i < canvasResults.length; i++) {
// images.push({
// image: possibleDuplicatedImages[i],
// opencvResult: canvasResults[i],
// });
// }
// console.log(images);
return images;
},
},
});
I have also tried with this, where the logs return the same as above:
export default defineComponent({
props: {
takenImage: HTMLImageElement,
slideResults: Object, // slideResults = {[opencvResults], [possibleDuplicatedImages]}
},
components: { Swiper, Slide, SwiperSlide },
setup(props) {
/**
* Returns the images to use in the slides
*/
const getImages = () => {
// To destructure props and don't lose reactivity we need to convert them into ref
const { slideResults } = toRefs(props);
const { canvasResults, possibleDuplicatedImages } = toRaw(
slideResults.value
);
console.log(canvasResults);
console.log(possibleDuplicatedImages);
console.log(props.takenImage);
// In order to pass to a slide the images as: Array<Object> where [{imageFile, canvas}]
/**
* #type {Array<{ image: HTMLCanvasElement[], opencvResult: File[] }>}
*/
const images = [];
for (let i = 0; i < canvasResults.length; i++) {
images.push({
image: possibleDuplicatedImages[i],
opencvResult: canvasResults[i],
});
}
console.log(images);
return images;
};
return {
modules: [Autoplay, Keyboard, Pagination, Zoom, Navigation],
getImages,
};
},
});
I have a file index.ts which has below two functions in it.
index.ts-
import { parseExpression } from 'cron-parser';
const previousMillisecondTimestamp = (cron: string, endTime: number): number => {
try {
return parseExpression(cron, {
endDate: new Date(endTime),
currentDate: new Date(endTime),
utc: true
}).prev().getTime()
} catch(e) {
return 0;
}
}
const setNextRun = (nextRunTimestampMilliseconds: number, startTimestampMilliseconds: number = new Date().getTime()) => (x: JobScheduleDto): JobScheduleDto[] => {
const scheduleIterator = parseExpression(x.cron, {
/* Line1 */
startDate: new Date(x.last_run > 900 ? x.last_run - 900 : startTimestampMilliseconds),
utc: true
});
let schedule = scheduleIterator.next();
let jobQueue: JobScheduleDto[] = [
{
...x,
next_run: x.next_run ? x.next_run : startTimestampMilliseconds
}
];
for (; schedule.getTime() < nextRunTimestampMilliseconds ; schedule = scheduleIterator.next()) {
if(x.next_run === schedule.getTime() || (!x.next_run && startTimestampMilliseconds === schedule.getTime())) {
continue;
}
jobQueue = [...jobQueue, {
...x,
last_run: previousMillisecondTimestamp(x.cron, schedule.getTime()),
next_run: schedule.getTime()
}];
}
console.log('Values', previousMillisecondTimestamp);
/* Line2 */
const updatedLastRun = previousMillisecondTimestamp(x.cron, schedule.getTime()) || schedule.getTime() || x.last_run;
jobQueue = [...jobQueue, {
...x,
last_run: updatedLastRun,
next_run: schedule.getTime()
}];
return jobQueue;
}
export const testModules = {
setNextRun,
previousMillisecondTimestamp,
}
Both the functions are exported in an object named as testModules (Required only for testing).
Now in order to increase the branch test coverage, I have to cover lines Line1 and Line2 (Commented in above file).
In order to do so in my index.spec.ts file, I want to mock functions previousMillisecondTimestamp and parseExpression(External module cron-parser) in my setNextRun function calls. So I can return the output accordingly (undefined or null) in order to cover all branches.
index.spec.ts-
import { testModules } from "../../src/index";
import { parseExpression } from 'cron-parser';
const currentTime = new Date().getTime();
const nextRunIntervalInMilliseconds = 10 * 60 * 1000;
describe.only('setNextRun function test coverage Test', () => {
it('setNextRun without parameters nextRunTimestampMilliseconds and startTimestampMilliseconds as null and JobScheduleDto object', () => {
const mockedPreviousMillisecondTimestamp = jest.spyOn(testModules, 'previousMillisecondTimestamp').mockImplementationOnce(() => null);
console.log('mockedPreviousMillisecondTimestamp', mockedPreviousMillisecondTimestamp);
const params = { pk: "T5", sk: workdayJobSchedule, last_run: 0, next_run: 0, status: 1, cron: "0 0 4 4 * *", schedule_description: "Desc1" }
try {
testModules.setNextRun(currentTime + nextRunIntervalInMilliseconds)(params);
} catch(error) {
expect(error.message).toBe("Cannot read property 'cron' of undefined");
}
mockedPreviousMillisecondTimestamp.mockRestore();
});
});
So in the above file when I writing below the line I want to mock the functionality for previousMillisecondTimestamp function and to return null.
const mockedPreviousMillisecondTimestamp = jest.spyOn(testModules, 'previousMillisecondTimestamp').mockImplementationOnce(() => null);
Just below that, I am doing a console.log of function to check if the function has been mocked or not and in that console, I am getting that it is mocked which is fine.
But when it goes inside setNextRun call and there I have a console which gives it as a Normal function.
console.log('Values', previousMillisecondTimestamp);
So I have 2 questions -
What is the right way to mock previousMillisecondTimestamp function in my index.spec.ts file?
How I can mock parseExpression function from cron-parser third-party module?
I would like to use this text-highlighting library in my Vue project. Here's an example from their website of how it can be used:
import TextHighlighter from '#perlego/text-highlighter';
import { isDuplicate } from './utils';
import highlightsApi from './services/highlights-api';
class ArticleView {
constructor(data) {
this.data = data;
const pageElement = document.getElementById("article");
this.highlighter = new TextHighlighter(
pageElement,
{
version: "independencia",
onBeforeHighlight: this.onBeforeHighlight,
onAfterHighlight: this.onAfterHighlight,
preprocessDescriptors: this.preprocessDescriptors,
onRemoveHighlight: this.onRemoveHighlight
});
}
onBeforeHighlight = (range) => {
return !isDuplicate(range)
}
onRemoveHighlight = (highlightElement) => {
const proceed = window.confirm("Are you sure you want to remove this highlight?");
return proceed;
}
preprocessDescriptors = (range, descriptors, timestamp) => {
// Add an ID to the class list to identify each highlight
// (A highlight can be represented by a group of elements in the DOM).
const uniqueId = `hlt-${Math.random()
.toString(36)
.substring(2, 15) +
Math.random()
.toString(36)
.substring(2, 15)}`;
const descriptorsWithIds = descriptors.map(descriptor => {
const [wrapper, ...rest] = descriptor;
return [
wrapper.replace(
'class="highlighted"',
`class="highlighted ${uniqueId}"`
),
...rest
];
});
return { descriptors: descriptorsWithIds, meta: { id: uniqueId } };
}
onAfterHighlight = (range, descriptors, timestamp, meta) => {
highlightsApi.saveBatch(meta.id, descriptorsWithIds)
.then((result) => {
// Do something with the highlights that have been saved.
})
.catch((err) => console.error(err));
}
render = () => {
// Code that takes the data for the article and adds it to the DOM
// based on a html template here.
}
}
Using the above example, I would like to setup the highlighter (similar to the above code, but in a different file, for example ./utils/highlighter.js) with all the default options I want (onBeforeHighlight, onRemoveHighlight, etc.), and then be able to import it from there and override the options for which I don't want to use the defaults, so it looks something like this in the importing file:
import highlighter from "../utils/highlighter.js";
const overridingOptions = {
onAfterHighlight: (range, descriptors, timestamp, meta) => {
console.log(range, descriptors, timestamp, meta);
}
};
const target = document.getElementsByClassName("testme")[0];
highlighter(target, overridingOptions);
For some reason, I am not able to understand how to modify the ArticleView example to fit my needs, so I think I need to see this done once. How should the code in ./utils/highlighter.js look to make this possible?
I have an issue with #turf/turf the last version, in my react native app
"react-native": "0.58.0",
"#turf/turf": "^5.1.6"
I just followed the same example in the README.md but it's not working with me anymore.
The issue is when I import turf like this
import * as turf from '#turf/turf';
and write the function here is
handleNearby = () => {
const { region, providers } = this.state;
let currentPoint = [region.longitude, region.latitude]
let points = _.map(providers, p => {
console.log('#p', p);
const to = [p.coordinates.longitude, p.coordinates.latitude];
const distance = turf.distance(currentPoint, to, { units: 'kilometers' });
return { coords: p.coordinates, name: p.username, id: p.id, distance }
});
const sortPoints = _.sortBy(points, ['distance']);
this.setState({ sortedMarkers: sortPoints });
console.log('##points', sortPoints);
return;
}
and run the app I have this error
attempting to a configurable attribute of a configurable property
But when I run the debugger on the browser the app works well I don't know why! any help?
I'm trying to add a constructor, which I call ctor, to Project, so I can add to it some properties when it's instantiated.
Here's the (absolutely ghastly) hack I'm using on Item to make this tick:
const canvas = document.querySelector('canvas')
paper.setup(canvas)
paper.Item.inject({
ctor: function(args) {
console.log('Item constructed!')
}
})
// All Items are supposed to call `_initialize` so we "hook" there.
const Item_initialize = paper.Item.prototype._initialize
const Item_ctor = paper.Item.prototype.ctor
paper.Item.prototype._initialize = function(...args) {
const initializer = Item_initialize.apply(this, args)
if (Item_ctor) Item_ctor.apply(this)
return initializer
}
const path = new paper.Path.Line({
strokeColor: 'black',
strokeWidth: 5,
from: 100,
to: 50
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.0/paper-core.js"></script>
<canvas></canvas>
Unfortunately the above trick doesn't work on Project:
const canvas = document.querySelector('canvas')
paper.setup(canvas)
paper.Project.inject({
ctor: function(args) {
// Not called
console.log('Project constructed!')
}
})
const Project_initialize = paper.Project.prototype._initialize
const Project_ctor = paper.Project.prototype.ctor
paper.Project.prototype._initialize = function(...args) {
const initializer = Project_initialize.apply(this, args)
if (Project_ctor) Project_ctor.apply(this)
return initializer
}
const project = new paper.Project(canvas)
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.0/paper-core.js"></script>
<canvas></canvas>
What am I missing here?