gameobject module dev

This commit is contained in:
2024-11-04 20:26:27 +02:00
parent 53350ef548
commit 2978f11869
20 changed files with 1391 additions and 114 deletions
+3 -1
View File
@@ -1,6 +1,8 @@
.DS_Store .DS_Store
node_modules node_modules
/dist /dist
/out
/repo
# local env files # local env files
.env.local .env.local
@@ -20,4 +22,4 @@ pnpm-debug.log*
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
.cert .cert
+3
View File
@@ -0,0 +1,3 @@
JSDOC:
jsdoc ./backend/app/Db.js -t "D:\IMI\ProNature\jsdoc-releases-4.0\templates\haruki" -d console -q format=xml
+23 -1
View File
@@ -3,10 +3,13 @@ import { ObjectId, MongoClient } from 'mongodb';
let db; let db;
let dbo; let dbo;
/**
* Manages database operations
*/
class Db { class Db {
name = 'db'; name = 'db';
init(app){ init(app){
this.app = app;
} }
async start(app){ async start(app){
@@ -23,6 +26,12 @@ class Db {
} }
} }
/**
* Inserts a record in a db collection
* @param {string} collection The name of the collection
* @param {Object} value The object to insert
* @returns Inserted Id
*/
async create(collection, value){ async create(collection, value){
try { try {
delete value._id; delete value._id;
@@ -31,6 +40,13 @@ class Db {
} }
} }
/**
* Loads a record from db collection
* @param {string} collection The name of the collection
* @param {Object} key Record identifier
* @param {Object} projection What data to take from the object
* @returns A record
*/
async get(collection, key, projection){ async get(collection, key, projection){
try { try {
let res = await dbo.collection(collection).findOne(key, projection ? {projection} : undefined) let res = await dbo.collection(collection).findOne(key, projection ? {projection} : undefined)
@@ -39,6 +55,12 @@ class Db {
} }
} }
/**
* Performs a database query
* @param {string} collection Collection name
* @param {Object} query A mongo db query
* @returns Array of records
*/
async list(collection, query){ async list(collection, query){
try { try {
let cursor = dbo.collection(collection).find(query.query, query.project ? {projection: query.project} : undefined); let cursor = dbo.collection(collection).find(query.query, query.project ? {projection: query.project} : undefined);
+170
View File
@@ -0,0 +1,170 @@
import decompress from "decompress";
import sharp from 'sharp';
import fs from 'fs';
import path from 'path';
const collection = 'assets';
/**
* Application layer manager
*/
class GameObjectsManager{
name = 'gameObject';
/**
* Plugin initializer
* @param {App} app The Application
*/
init(app){
const {db, config} = app;
/**
* Gets last asset Id from database
* @returns {Number} Last Asset Id
*/
this.getLastId = async function(){
let ag = await db.aggregate(collection, [
{
$group:{
_id: null,
max: {
$max: "$id",
},
},
},
]);
return ag.max || 0;
}
/**
* Creates a game object
* @param {Context} ctx Request context
* @param {GameObject} data Asset data
*/
this.create = async function(ctx, data){
data.id = (await this.getLastId()) + 1;
await db.create(collection, data);
if (ctx.files?.file){
await this.addFile(data, ctx.files.file)
await fs.promises.unlink(ctx.files.file.path)
await db.update(collection, {id: data.id}, data);
}
return data;
}
/**
* Retrieves game object from database
* @param {Number} id Game object ID
* @returns {GameObject} The game object
*/
this.read = async function(id){
id = parseInt(id);
return await db.get(collection, {id});
}
/**
* Updates game object into the database
* @param {Context} ctx Request context
* @param {GameObject} data Game object
*/
this.update = async function(ctx, data){
data.id = parseInt(data.id);
let object = await this.read(data.id);
data = Object.assign(object, data);
if (ctx.files?.file){
await this.addFile(data, ctx.files.file)
await fs.promises.unlink(ctx.files.file.path)
}if (ctx.files?.thumb){
await this.addThumb(data, ctx.files.thumb.path);
await fs.promises.unlink(ctx.files.thumb.path)
}
await db.update(collection, {id: data.id}, data);
return data;
}
/**
* Removes game object from database
* @param {Number} id Game object ID
*/
this.remove = async function(id){
id = parseInt(id);
await db.remove(collection, {id});
}
/**
* Assigns a file to a game object
* @param {GameObject} object Game object
* @param {File} tmpFile A file
*/
this.addFile = async function(object, tmpFile){
let i = tmpFile;
let ofn = i.name;
let ext = path.extname(ofn).toLowerCase();
let src = `${config.fs.repo}/source/${object.id}${ext}`;
let def = `${config.fs.repo}/default/${object.id}`;
await fs.promises.copyFile(i.path, src);
object.asset = {
ofn,
name: `${object.id}${ext}`
}
if (ext == '.zip'){
let result = await decompress(src, def);
object.asset.list = result.map(f=>f.path);
object.asset.type = 'bundle';
}else{
object.asset.type = 'single';
await fs.promises.copyFile(src, def + ext);
await this.addThumb(object, src);
}
}
/**
* Assigns a thumbnail to a game object
* @param {GameObject} object Game object
* @param {File} thumbSrc A thumbnail
*/
this.addThumb = async function(object, thumbSrc){
let dest = `${config.fs.repo}/thumb/${object.id}.webp`;
await sharp(thumbSrc).resize({height: 250}).toFile(dest);
object.asset.thumb = `${object.id}.webp`;
}
/**
* Returns list of GameObjects
* @param {Object} query Query to DB
* @returns {GameObject[]} Array of game objects
*/
this.list = async function(query){
return await db.list(collection, {
query: {},
project: { name:1, id:1, type:1, asset:1}
});
}
}
/**
* Class starter
* @param {App} app The application
*/
async start(app){
}
}
/**
* GameObject entity
*/
class GameObject {
/**
* Game object name
* @type string
*/
name = null;
type = null;
file = null;
}
export { GameObjectsManager }
+27
View File
@@ -0,0 +1,27 @@
import express from 'express';
class AssetController{
name = 'assetController'
route = '/asset'
init(app){
const router = express.Router();
const {config} = app;
router.get('/:where/:id(*)', async (req, res)=>{
res.sendFile(config.fs.repo + req.params.where + '/' + req.params.id, (err)=>{
if (err){
console.error('Error retreiving file', req.params, err.code, err.message);
if (req.params.where == 'thumb'){
res.redirect(302, '/empty.png');
}else res.status(404).end();
}
});
})
app.webServer.xapp.use(this.route, router);
}
}
export {AssetController}
-25
View File
@@ -1,25 +0,0 @@
import express from 'express';
import fs from 'fs';
import { v4 as uuidv4 } from 'uuid';
import multipart from 'connect-multiparty';
const multipartMiddleware = multipart();
class GameObjectsApi{
name = 'gameObjectsApi'
route = '/api/game-object'
init(app){
const { am, config } = app;
const router = express.Router();
router.put('/', multipartMiddleware, async (req, res)=>{
try{
}catch(err){
}
});
app.webServer.xapp.use(this.route, router);
}
}
export {GameObjectsApi}
@@ -0,0 +1,49 @@
import express from 'express';
import multipart from 'connect-multiparty';
const multipartMiddleware = multipart();
class GameObjectsController{
name = 'gameObjectsApi'
route = '/api/game-object'
init(app){
const { gameObject } = app;
const router = express.Router();
/**
* Create & update
*/
router.put('/', multipartMiddleware, async (req, res)=>{
try{
let data = req.body;
let object = await gameObject[data.id? 'update' : 'create'](req, data)
res.json({status: 'OK', object});
}catch(err){
console.error(err);
res.status(500).json({status: 'ERR', err});
}
});
/**
* List
*/
router.post('/', async (req, res)=>{
let result = await gameObject.list(req.body);
res.json(result);
})
router.get('/', async (req, res)=>{
})
router.get('/:id', async (req, res)=>{
let object = await gameObject.read(parseInt(req.params.id));
res.json(object);
})
app.webServer.xapp.use(this.route, router);
}
}
export {GameObjectsController}
+3 -1
View File
@@ -11,8 +11,10 @@ import App from './app/App.js';
const modules = [ const modules = [
{name:'Config', path:'app/Config.js'}, {name:'Config', path:'app/Config.js'},
{name:'Db', path:'app/Db.js'}, {name:'Db', path:'app/Db.js'},
{name:'GameObjectsManager', path:'app/bl/GameObjectsManager.js'},
{name:'WebServer', path:'app/WebServer.js'}, {name:'WebServer', path:'app/WebServer.js'},
{name:'GameObjectsApi', path:'controllers/api/GameObjects.js'}, {name: 'AssetController', path: 'controllers/AssetController.js'},
{name:'GameObjectsController', path:'controllers/api/GameObjectsController.js'},
] ]
process.on('uncaughtException', err => { process.on('uncaughtException', err => {
+953 -5
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -18,12 +18,14 @@
"connect-multiparty": "^2.2.0", "connect-multiparty": "^2.2.0",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
"core-js": "^3.37.1", "core-js": "^3.37.1",
"decompress": "^4.2.1",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.21.1", "express": "^4.21.1",
"express-session": "^1.18.1", "express-session": "^1.18.1",
"helmet": "^8.0.0", "helmet": "^8.0.0",
"mongodb": "^6.10.0", "mongodb": "^6.10.0",
"roboto-fontface": "*", "roboto-fontface": "*",
"sharp": "^0.33.5",
"three": "^0.169.0", "three": "^0.169.0",
"uuid": "^11.0.2", "uuid": "^11.0.2",
"vue": "^3.4.31", "vue": "^3.4.31",
+1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,7 +1,7 @@
<template> <template>
<v-app> <v-app>
<v-main> <v-main>
<router-view /> <router-view :key="$route.fullPath"/>
</v-main> </v-main>
</v-app> </v-app>
</template> </template>
+16 -8
View File
@@ -7,29 +7,37 @@
<v-btn icon="mdi-plus" variant="text" v-bind="props"></v-btn> <v-btn icon="mdi-plus" variant="text" v-bind="props"></v-btn>
</template> </template>
<v-list> <v-list>
<v-list-item to="/game-objects/">Нов игрови обект</v-list-item> <v-list-item to="/game-objects/add">Нов игрови обект</v-list-item>
<v-list-item>Нов сценарий</v-list-item> <v-list-item>Нов сценарий</v-list-item>
<v-list-item>Нова игра</v-list-item> <v-list-item>Нова игра</v-list-item>
</v-list> </v-list>
</v-menu> </v-menu>
</v-app-bar> </v-app-bar>
<v-navigation-drawer :location="$vuetify.display.mobile ? 'bottom' : undefined" expand-on-hover rail> <v-navigation-drawer class="bg-secondary" ocation="$vuetify.display.mobile ? 'bottom' : undefined" expand-on-hover rail>
<v-list> <v-list>
<v-list-item prepend-avatar="/logo.webp" subtitle="Admin Console" title="ProNature"></v-list-item> <v-list-item prepend-avatar="/logo.webp" subtitle="Admin Console" title="ProNature"></v-list-item>
</v-list> </v-list>
<v-divider></v-divider> <v-divider></v-divider>
<v-list nav> <v-list nav>
<v-list-item prepend-icon="mdi-database" to="/game-objects" title="Game Objects"></v-list-item> <v-list-item prepend-icon="mdi-database" to="/game-objects/list" :title="$l.gameObjects"></v-list-item>
<v-list-item prepend-icon="mdi-receipt-text-edit-outline" title="Game Scenarios"></v-list-item> <v-list-item prepend-icon="mdi-receipt-text-edit-outline" :title="$l.gameScenarios"></v-list-item>
<v-list-item prepend-icon="mdi-cogs" title="Game Rules"></v-list-item> <v-list-item prepend-icon="mdi-cogs" :title="$l.gameRules"></v-list-item>
<v-list-item prepend-icon="mdi-controller" title="Games"></v-list-item> <v-divider></v-divider>
<v-list-item prepend-icon="mdi-controller" :title="$l.games"></v-list-item>
</v-list>
<v-divider></v-divider>
<v-list nav>
<v-list-item @click="toggleTheme" prepend-icon="mdi-theme-light-dark" :title="$l.darkMode"></v-list-item>
</v-list> </v-list>
</v-navigation-drawer> </v-navigation-drawer>
</template> </template>
<script setup> <script setup>
import { ref } from 'vue' import { useTheme } from 'vuetify'
const drawer = ref(false); const theme = useTheme()
function toggleTheme () {
theme.global.name.value = theme.global.current.value.dark ? 'light' : 'dark'
}
</script> </script>
-2
View File
@@ -21,13 +21,11 @@ class GameEngine {
mesh.rotation.y = time / 1000; mesh.rotation.y = time / 1000;
renderer.render(scene, camera); renderer.render(scene, camera);
} }
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true }); const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setSize(width, height); renderer.setSize(width, height);
renderer.setAnimationLoop(animate); renderer.setAnimationLoop(animate);
document.body.appendChild(renderer.domElement);
this.renderer = renderer; this.renderer = renderer;
} }
+91
View File
@@ -0,0 +1,91 @@
<template>
<v-card :title="id =='add' ? $l.createGameObject : $l.editGameObject" class="container my-3">
<v-form class="pa-4" v-model="valid">
<v-text-field :label="$l.name" v-model="object.name" :rules="[rules.required]"></v-text-field>
<v-select :label="$l.objectType" v-model="object.type" :items="objectTypes" :rules="[rules.required]">
</v-select>
<v-file-input :label="$l.objectFile" v-model="object.file" :rules="[rules.requiredFile]"></v-file-input>
<div v-if="object.asset?.name">{{ object.asset.name }}</div>
</v-form>
<v-card-actions>
<v-btn @click="saveAndPreview" :loading="loading" prepend-icon="mdi-content-save" color="primary"
:disabled="!valid">
{{ $l.saveAndPreview }}
</v-btn>
<v-btn @click="captureThumbnail" v-if="object.asset?.type == 'bundle'" prepend-icon="mdi-camera" color="secondary">{{ $l.captureThumbnail }}</v-btn>
<v-btn @click="publish" prepend-icon="mdi-publish" color="success" v-if="false && object.id">{{ $l.publish }}</v-btn>
</v-card-actions>
</v-card>
<v-card :title="$l.preview" class="container my-3" v-if="object.asset">
<div ref="target" v-if="object?.asset?.type == 'bundle'"></div>
<v-img v-else :src="`/asset/default/${object.asset?.name}`"></v-img>
</v-card>
</template>
<script>
import { GameEngine } from '@/gameEngine';
const gameEngine = new GameEngine();
export default {
data() {
return {
object: {},
valid: false,
rules: {
required: v => v ? true : this.$l.fieldRequired,
requiredFile: v => (v?.length || this.id != 'add') ? true : this.$l.fieldRequired
},
objectTypes: ['panorama2d', 'environment3d', 'object3d', 'object2d', 'player3d', 'audio'].map(e => ({
title: this.$l[e],
value: e
})),
loading: false
}
},
async created(){
if (this.id && this.id != 'add'){
this.object = (await this.$api.gameObject.load(this.id)).data;
}
},
mounted() {
//this.$refs.target?.appendChild(gameEngine.renderer.domElement);
},
computed: {
fileToUpload(){
return this.object?.file instanceof File
},
id(){
return this.$route.params?.id;
}
},
methods: {
async saveAndPreview() {
this.loading = true;
try {
let fd = new FormData();
let keys = ['name', 'type'];
if (this.fileToUpload) keys.push('file');
if (this.id != 'add') keys.push('id');
keys.forEach(e=>fd.append(e, this.object[e]))
let result = await this.$api.gameObject.save(fd);
Object.assign(this.object, result.data.object);
if (this.id == 'add'){
this.$router.replace({ params: {id: this.object.id} });
}
} catch (err) {
console.error(err);
}
this.loading = false
},
captureThumbnail() {
},
async publish() {
}
}
}
</script>
-67
View File
@@ -1,67 +0,0 @@
<template>
<v-card :title="$l.createGameObject" class="container my-3">
<v-form class="pa-4" v-model="valid">
<v-text-field :label="$l.name" v-model="name" :rules="[rules.required]"></v-text-field>
<v-select :label="$l.objectType" v-model="type" :items="objectTypes" :rules="[rules.required]">
</v-select>
<v-file-input :label="$l.objectFile" v-model="file" :rules="[rules.requiredFile]"></v-file-input>
</v-form>
<v-card-actions>
<v-btn @click="saveAndPreview" :loading="loading" prepend-icon="mdi-content-save" color="primary" :disabled="!valid">
{{ $l.saveAndPreview }}
</v-btn>
<v-btn @click="captureThumbnail" prepend-icon="mdi-camera" color="secondary">{{$l.captureThumbnail}}</v-btn>
<v-btn @click="publish" prepend-icon="mdi-publish" color="success">{{$l.publish}}</v-btn>
</v-card-actions>
</v-card>
<v-card title="Preview" class="container my-3">
<div ref="target"></div>
</v-card>
</template>
<script>
import { GameEngine } from '@/gameEngine';
const gameEngine = new GameEngine();
export default {
data(){
return {
name: null,
type: null,
file: null,
valid: false,
rules:{
required: v=> v ? true : this.$l.fieldRequired,
requiredFile: v=> v?.length ? true : this.$l.fieldRequired
},
objectTypes: ['panorama2d', 'environment3d', 'object3d', 'object2d', 'player3d', 'audio'].map(e=>({
title: this.$l[e],
value: e
})),
loading:false
}
},
mounted() {
this.$refs.target.appendChild(gameEngine.renderer.domElement);
},
methods: {
async saveAndPreview() {
this.loading = true;
let fd = new FormData();
fd.append('file', this.file);
fd.append('name', this.name);
fd.append('type', this.type);
let result = await this.$api.gameObject.save(fd)
this.loading = false
},
captureThumbnail() {
},
async publish(){
}
}
}
</script>
+27
View File
@@ -0,0 +1,27 @@
<template>
<v-container>
<v-row>
<v-col v-for="(v, i) in items" :key="i" cols="3">
{{ v.name }}
<span class="font-weight-thin">{{ v.type }}</span>
<v-btn density="compact" variant="text" icon="mdi-pencil-outline" :to="`/game-objects/${v.id}`"></v-btn>
<v-img :src="`/asset/thumb/${v.asset?.thumb}`"></v-img>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
data(){
return {
items: []
}
},
async created(){
this.items = (await this.$api.gameObject.search()).data.data
},
}
</script>
+6
View File
@@ -10,6 +10,12 @@ export default {
gameObject:{ gameObject:{
async save(data){ async save(data){
return await $ax.put('/game-object', data); return await $ax.put('/game-object', data);
},
async load(id){
return await $ax.get(`/game-object/${id}`);
},
async search(query){
return await $ax.post('/game-object', query);
} }
} }
} }
+8 -1
View File
@@ -1,6 +1,7 @@
const lang = { const lang = {
bg: { bg: {
createGameObject: 'Добавяне на игрови обект', createGameObject: 'Добавяне на игрови обект',
editGameObject: 'Редактиране на игрови обект',
name: 'Име', name: 'Име',
fieldRequired: 'Полето е задължително', fieldRequired: 'Полето е задължително',
objectType: 'Тип обект', objectType: 'Тип обект',
@@ -12,8 +13,14 @@ const lang = {
audio: 'Аудио', audio: 'Аудио',
player3d: 'Играч', player3d: 'Играч',
saveAndPreview: 'Запис и преглед', saveAndPreview: 'Запис и преглед',
preview: 'Преглед',
captureThumbnail: 'Capture thumbnail', captureThumbnail: 'Capture thumbnail',
publish: 'Публикуване' publish: 'Публикуване',
gameObjects: 'Обекти',
gameScenarios: 'Сценарии',
gameRules: 'Правила',
games: 'Игри',
darkMode: 'Тъмен режим'
}, },
en: { en: {
+8 -2
View File
@@ -35,8 +35,14 @@ export default createVuetify({
themes: { themes: {
light: { light: {
colors: { colors: {
// primary: '#1867C0', primary: '#497d95',
// secondary: '#5CBBF6', secondary: '#63963a',
},
},
dark: {
colors: {
primary: '#497d95',
secondary: '#63963a',
}, },
}, },
}, },