How do I set/add DRACOLoader and KTX2Loader to tb.loadObject in threebox-plugin? - mapbox-gl-js

I am trying to load a model that is Draco compressed and I am getting this error:
Error: THREE.GLTFLoader: No DRACOLoader instance provided.
How do I set the Draco loader (or enable) in threebox-plugin?
id: item3d.name,
type: 'custom',
renderingMode: '3d',
onAdd: (map, mbxContext) => {
const options = {
obj: item3d.modelPath,
type: 'gltf',
scale: item3d.scale,
units: 'meters',
rotation: { x: 90, y: 0, z: 0 }
}
const ktx2Loader = new KTX2Loader();
ktx2Loader.setTranscoderPath('assets/basis/');
ktx2Loader.detectSupport( window['tb'].renderer );
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('assets/draco/');
// const gltfLoader = new GLTFLoader();
// gltfLoader.setDRACOLoader(dracoLoader);
// gltfLoader.setKTX2Loader(ktx2Loader);
window['tb'].loadObj(options, (model) => {
let loadedItem = model.setCoords([item3d.coordinates['lng'], item3d.coordinates['lat']]);
loadedItem.castShadow = true;
window['tb'].add(loadedItem);
})
},
render: function(gl, matrix) {
}
}```

Related

next-redux-wrapper wrapper.getServerSlideProps error

On my index.tsx page where i shoud get tracks from server:
`
export const getServerSideProps = wrapper.getServerSideProps(async ({store}) => {
const dispatch = store.dispatch as NextThunkDispatch
await dispatch(await fetchTracks())
})
`
Problem
This is Store, also with errors
`
import {Context, createWrapper, MakeStore} from "next-redux-wrapper";
import {AnyAction, applyMiddleware, createStore} from "redux";
import {reducer, RootState} from "./reducers";
import thunk, {ThunkDispatch} from "redux-thunk";
// create a makeStore function
const makeStore: MakeStore<RootState>
= (context: Context) => createStore(reducer, applyMiddleware(thunk));
// export an assembled wrapper
export const wrapper = createWrapper<RootState>(makeStore, {debug: true});
export type NextThunkDispatch = ThunkDispatch<RootState, any, AnyAction>
`
Store error
I guess all this errors send me to thise files:
reducers/index.ts
`
import {combineReducers} from "redux";
import {playerReducer} from "./playerReducer";
import {HYDRATE} from "next-redux-wrapper";
import {trackReducer} from "./trackReducer";
const rootReducer = combineReducers({
player: playerReducer,
track: trackReducer
})
export const reducer = (state:any, action:any) => {
if (action.type === HYDRATE) {
const nextState = {
...state, // use previous state
...action.payload, // apply delta from hydration
};
if (state.count) nextState.count = state.count; // preserve count value on client side navigation
return nextState;
} else {
return rootReducer(state, action);
}
};
export type RootState = ReturnType<typeof rootReducer>
reducers/playerReducer.ts
import {PlayerAction, PlayerActionTypes, PlayerState} from "../../types/player";
const initialState: PlayerState = {
currentTime: 0,
duration: 0,
active: null,
volume: 30,
pause: true
}
export const playerReducer = (state = initialState, action: PlayerAction): PlayerState => {
switch (action.type) {
case PlayerActionTypes.PAUSE:
return {...state, pause:true}
case PlayerActionTypes.PLAY:
return {...state, pause:false}
case PlayerActionTypes.SET_CURRENT_TIME:
return {...state, currentTime: action.payload}
case PlayerActionTypes.SET_VOLUME:
return {...state, volume: action.payload}
case PlayerActionTypes.SET_DURATION:
return {...state, duration: action.payload}
case PlayerActionTypes.SET_ACTIVE:
return {...state, active: action.payload, duration: 0, currentTime: 0}
default:
return state
}
}
reducers/trackReducer.ts
import {TrackAction, TrackActionTypes, TrackState} from "../../types/track";
const initialState: TrackState = {
tracks: [],
error: ''
}
export const trackReducer = (state = initialState, action: TrackAction): TrackState => {
switch (action.type) {
case TrackActionTypes.FETCH_TRACKS_ERROR:
return {...state, error: action.payload}
case TrackActionTypes.FETCH_TRACKS:
return {error: '', tracks: action.payload}
default:
return state
}
}
`
Also console error:
enter image description here
I don't understant a problem, something wrong with types, in result i should get tracks from server

Redux Toolkit - action from one slice to be caught in another slice

There's an action (addOrder) in an orderSlice
orderSlice.js
import { createSlice } from '#reduxjs/toolkit';
const initialState = {
orders: []
};
const ordersSlice = createSlice({
name: 'orders',
initialState,
reducers: {
addOrder: {
reducer: (state, action) => {
state.orders.push(action.payload)
},
prepare: (orderItems, orderTotal) => {
const orderDate = new Date().toDateString();
return { payload: { orderDate, orderItems: orderItems, orderTotal: orderTotal }}
}
}
}
})
export const { addOrder } = ordersSlice.actions;
export default ordersSlice.reducer;
I'd like it to also affect the state in another slice (cartSlice). Once the 'addOrder' is fired, it should also bring the cartReducer to its initial state. Some googling suggested that I should use extrareducers for that but I'm really not getting its syntax. See below (not valid code in extrareducers)
cartSlice
import { createSlice } from '#reduxjs/toolkit';
import { addOrder } from './ordersSlice';
const initialState = {
items: {},
totalAmount: 0
};
const cartSlice = createSlice({
name: 'cart',
initialState: initialState,
reducers: {
addToCart: (state, action) => {
// p = product to be added or amended
const p = action.payload;
if (state.items[p.id]) {
// already exists
state.items[p.id].quantity += 1;
state.items[p.id].sum += p.price;
state.totalAmount += p.price;
} else {
state.items[p.id] = { price: p.price, quantity: 1, title: p.title, sum: p.price};
state.totalAmount += p.price;
}
},
removeFromCart: (state, action) => {
console.log('remove from cart');
console.log(action.payload);
const currentQuantity = state.items[action.payload].quantity;
console.log(currentQuantity);
if (currentQuantity > 1) {
state.items[action.payload].quantity -= 1;
state.items[action.payload].sum -= state.items[action.payload].price;
state.totalAmount -= state.items[action.payload].price;
} else {
state.totalAmount -= state.items[action.payload].price;
delete state.items[action.payload];
}
}
},
extraReducers: (builder) => {
builder
.addCase(addOrder(state) => {
return initialState;
})
}
});
export const { addToCart, removeFromCart } = cartSlice.actions;
export default cartSlice.reducer;
You're almost there! The builder.addCase function takes two arguments. The first is the action creator and the second is the case reducer. So you need a comma after addOrder.
extraReducers: (builder) => {
builder.addCase(addOrder, (state) => {
return initialState;
});
}

IONIC-I cannot convert 'image to base64'

The photo I took using the application camera appears as a black screen. I looked at the other questions and tried some of the answers, but I can't translate the picture to base64. Could you help?
You can see the entire code from the link.
https://pastebin.ubuntu.com/p/4FwYdk5fvD/
takePicture(sourceType: PictureSourceType)
{
var options: CameraOptions = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
this.camera.getPicture(options).then(imagePath => {
if (this.plt.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY)
{
this.filePath.resolveNativePath(imagePath)
.then(filePath => {
let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
});
}
else
{
var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
}
});
}
i sorta had the same issue. I also wanted the name (not the path though), and i also wanted a base 64... so what i did what this:
takePicture(sourceType: PictureSourceType) {
var options: CameraOptions = {
quality: 80,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true,
destinationType: 1,
targetWidth: 1240,
targetHeight: 768,
};
this.camera.getPicture(options)
.then((imageData) => {
this.imgService.convertFilePathToBlob(imageData).subscribe(blob => {
this.image = blob;
});
let correctPath = imageData; // or subStr the parts you want
let currentName = this.image[1]; // grab the name
let currentImage = this.image[0]; // the image itself as base64
}).catch((err) => {
console.warn("takePicture Error: " + err);
});}
and the convert function... remember to import File, FileEntry from '#ionic-native/file/ngx'
convertFilePathToBlob(filePath:string) {
return from(this.file.resolveLocalFilesystemUrl(filePath)).pipe(
mergeMap((fileEntry: FileEntry) => {
return Observable.create(observer => {
fileEntry.file(file => {
const reader = new FileReader();
reader.onloadend = () => {
const imgBlob = new Blob([reader.result], { type: file.type });
observer.next([imgBlob, file.name]); // the name can be grabbed now
observer.complete();
};
reader.readAsArrayBuffer(file);
}, error => {
observer.error(error);
});
});
}));}
This works in my case, but i find it insane i had to do all this, and it took some debugging and googling... i hope it helps you in some way... :)

Openlayer Linestring with two or more lines on the one or more coordinates?

My problem is the following:
Linestring with two or more lines on the one or more coordinates.
With several LineStrings only one string is shown in the map, I know, the LineStrings also use the same coordinates.
Is there a way that the LineStrings can use one and the same coordinates, but a shift of the line (to have for example three lines next to each other) takes place in the structure of the map?
The code is a bit better, which explains a lot:
var logoElement = document.createElement ('a');
logoElement.href = 'http://www.schienenpost.de/';
logoElement.target = '_blank';
var logoImage = document.createElement ('img');
logoImage.src = 'http://www.schienenpost.de/schienenpost.png';
logoElement.appendChild (logoImage);
var iconStyle = new ol.style.Style ({
image: new ol.style.Icon (/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 1.0],
src: 'http://www.schienenpost.de/marker/marker.png'
}))
});
var scaleLineControl = new ol.control.ScaleLine();
var markerStartEnd = function (layer,feature) {
var i, iconFeature, iconFeatures = [], coordinates, nameLine;
coordinates = feature.getGeometry ().getCoordinates ();
nameLine = feature.getProperties () ['name'];
i = 0;
iconFeature = new ol.Feature ({
geometry: new ol.geom.Point (coordinates[i]),
name: 'Start'+nameLine,
});
iconFeature.setStyle (iconStyle);
iconFeatures.push (iconFeature);
i = coordinates.length - 1;
iconFeature = new ol.Feature ({
geometry: new ol.geom.Point (coordinates[i]),
name: 'End'+nameLine,
});
iconFeature.setStyle (iconStyle);
iconFeatures.push (iconFeature);
layer.getSource ().addFeatures (iconFeatures);
};
var layerLines = new ol.layer.Vector ({
source: new ol.source.Vector ({
format: new ol.format.GeoJSON (),
url: 'schienenpost.geojson',
useSpatialIndex: false
}),
style: new ol.style.Style ({stroke: new ol.style.Stroke ({color : 'red', width: 3})}),
});
var layerMarker = new ol.layer.Vector ({
title: 'Marker',
source: new ol.source.Vector ()
});
var element = document.getElementById ('popup');
var popup = new ol.Overlay ({
element: element,
positioning: 'bottom-center',
stopEvent: false,
offset: [0, -0]
});
var map = new ol.Map ({
controls: ol.control.defaults ()
.extend ([
new ol.control.OverviewMap (),
new ol.control.FullScreen (),
scaleLineControl
]),
//target 'map',
target: document.getElementById ('map'),
layers: [
new ol.layer.Tile ({
source: new ol.source.OSM ()
}),
],
view: new ol.View ({
center: ol.proj.fromLonLat ([10.627, 53.620]),
zoom: 8
}),
logo: logoElement
});
map.addOverlay (popup);
map.addLayer (layerLines);
map.addLayer (layerMarker);
map.once ('moveend', function(e) {
layerLines.getSource ().getFeaturesCollection ().forEach (function (feature) {
markerStartEnd (layerMarker,feature);
});
});
map.on ('click', function (evt) {
var feature = map.forEachFeatureAtPixel (evt.pixel,
function (feature) {
return feature;
});
if (feature) {
var coordinates = feature.getGeometry ().getCoordinates ();
var clickpoint = map.getCoordinateFromPixel (evt.pixel);
if (!isNaN (coordinates [0])) { // Punkt
popup.setPosition (coordinates);
} else if (!isNaN (coordinates [0][0])) { // Linie
popup.setPosition (clickpoint);
} else { // kein brauchbares feature
$ (element).popover ('destroy');
return;
}
$ (element).popover ({
'placement': 'top',
'html': true,
'content': feature.get ('name')
});
$ (element).popover ().data ('bs.popover').options.content = feature.get ('name');
$ (element).popover ('show');
} else {
$ (element).popover ('hide');
}
});
map.on ('pointermove', function(e) {
if (e.dragging) {
$ (element).popover ('destroy');
return;
}
var pixel = map.getEventPixel (e.originalEvent);
var hit = map.hasFeatureAtPixel (pixel);
map.getTarget ().style.cursor = hit ? 'pointer' : '';
});

How to close a active MongoDB connection with mongoose after job is done?

As you can see, I am connecting to the database, reading multiple JSON files from a directory and import them into the MongoDB server with help of mongoose.
After this job is done, I would like to close the connection and print out "job is done"
How do I do that?
var mongoose = require('mongoose'),
_ = require('lodash'),
fs = require('fs'),
path = require('path');
mongoose.Promise = require('bluebird'),
mongoose.connect('mongodb://localhost/eclass');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
// create db schema
var EclassSchema = new mongoose.Schema({
xsi: {
xsitype: 'string',
id: 'string'
},
date_of_original_definition: 'string',
date_of_current_version: 'string',
date_of_current_revision: 'string',
revision: 'string',
status: 'string',
source_language: {
country_code: 'string',
language_code: 'string'
},
preferred_name: 'string',
definition: 'string',
its_superclass: 'string',
hierarchical_position: 'string',
//keywords: 'string'
});
// Create model
var Eclass = mongoose.model('Eclass', EclassSchema);
const pjsons = path.join(__dirname, '/../', 'file-operations', 'json-files');
console.log(pjsons);
function readFiles(pjsons, onError) {
fs.readdir(pjsons, function(err, filenames) {
if(err) {
onError(err);
return;
}
filenames.forEach(function(filename) {
fs.readFile(pjsons + '/' + filename, 'utf-8', function(err, data) {
if(err) {
onError(err);
return;
}
data = JSON.parse(data);
// Digging down into the json code
const ontomlOntoml = data['dic:eclass_dictionary']['ontoml:ontoml'];
const onto = _.first(ontomlOntoml);
const dictionary = onto['dictionary'];
const contClasses = _.first(dictionary);
const containedClasses = contClasses['contained_classes'];
const ontClass = _.first(containedClasses);
const ontomlClass = _.find(ontClass);
//Arrays
const xsiArray = _.map(ontomlClass, '$');
const date_of_original_definitionArray = _.map(ontomlClass, 'date_of_original_definition');
const date_of_current_versionArray = _.map(ontomlClass, 'date_of_current_version');
const date_of_current_revisionArray = _.map(ontomlClass, 'date_of_current_revision');
const revisionArray = _.map(ontomlClass, 'revision');
const statusArray = _.map(ontomlClass, 'status');
const sourceLanguageArray = _.map(ontomlClass, 'source_language');
const preferredNameArray = _.map(ontomlClass, 'preferred_name');
const definitionArray = _.map(ontomlClass, 'definition');
const itsSuperclassArray = _.map(ontomlClass, 'its_superclass');
const hierarchical_positionArray = _.map(ontomlClass, 'hierarchical_position');
//const keywordsArray = _.map(ontomlClass, 'keywords');
// Looping and storing the data into mongodb
//for (var i = 0; i < hierarchical_positionArray.length; i++) {
for (var i = 0; i < 2; i++) {
//console.log(hierarchical_positionArray[i]);
var newEclass = new Eclass();
newEclass.xsi.xsitype = xsiArray[i]['xsi:type'];
newEclass.xsi.id = xsiArray[i]['id'];
newEclass.date_of_original_definition = date_of_original_definitionArray[i];
newEclass.date_of_current_version = date_of_current_versionArray[i];
newEclass.date_of_current_revision = date_of_current_revisionArray[i];
newEclass.revision = revisionArray[i];
newEclass.status = statusArray[i];
newEclass.source_language.country_code = sourceLanguageArray[i][0].$.country_code;
newEclass.source_language.language_code = sourceLanguageArray[i][0].$.language_code;
newEclass.preferred_name = preferredNameArray[i][0].label[0]._;
newEclass.definition = definitionArray[i][0].text[0]._;
newEclass.its_superclass = itsSuperclassArray[i][0].$.class_ref;
newEclass.hierarchical_position = hierarchical_positionArray[i];
//newEclass.keywords = keywordsArray[i][0].label[0]._;
newEclass.save(function (err) {});
}
});
});
});
}
readFiles(pjsons);
});
mongoose.disconnect() closes all opened connections. for more
http://mongoosejs.com/docs/api.html#index_Mongoose-disconnect
I solved it like this:
newEclass.save()
.then(function() {
mongoose.disconnect();
})
.catch(function(err) {
console.log('There was an error', err);
});
...
const mongoose = require('mongoose'),
parse = require('csv-parse'),
path = require('path'),
fs = require('fs');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/eclassCSV');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
// create db schema
const EclassSchema = new mongoose.Schema({
codedName: { type: String, min: 10, max: 10 },
preferredName: { type: String, max: 80 },
definition: { type: String, max: 1023 },
level: { type: String, min: 1, max: 1 },
mkSubclass: { type: String, min: 1, max: 1 },
mkKeyword: { type: String, min: 1, max: 1 }
});
// Create MongoDB model with mongoose
const Eclass = mongoose.model('Eclass', EclassSchema);
const p = path.join(__dirname, '/../', 'file-operations', 'csv-files');
//console.log(p);
const parser = parse({delimiter: ';'}, function(err, data){
//console.log(data);
//const supplier = data[0][0];
const codedName = data.map((item,i) => data[i][6]);
const preferredName = data.map((item,i) => data[i][7]);
const definition = data.map((item,i) => data[i][8]);
const level = data.map((item,i) => data[i][13]);
const mkSubclass = data.map((item,i) => data[i][14]);
const mkKeyword = data.map((item,i) => data[i][15]);
// Looping and storing the data into mongodb
//console.log(ontomlClass.length);
for (let i = 0; i < data.length; i++) {
//console.log(hierarchical_positionArray[i]);
const newEclass = new Eclass();
newEclass.codedName = codedName[i];
newEclass.preferredName = preferredName[i];
newEclass.definition = definition[i];
newEclass.level = level[i];
newEclass.mkSubclass = mkSubclass[i];
newEclass.mkKeyword = mkKeyword[i];
newEclass.save()
.then(function() {
mongoose.disconnect();
})
.catch(function(err) {
console.log('There was an error', err);
});
}
});
fs.createReadStream(p + '/One-eClass-10_0_CC_en.csv').pipe(parser);
});