Spaces:
Build error
Build error
File size: 36,428 Bytes
30c32c8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 |
const Cast = require('../../util/cast');
const Clone = require('../../util/clone');
const ExtensionInfo = require("./info");
const Three = require("three");
const BufferGeometryUtils = require('three/examples/jsm/utils/BufferGeometryUtils');
const { ConvexGeometry } = require('three/examples/jsm/geometries/ConvexGeometry');
const { OBJLoader } = require('three/examples/jsm/loaders/OBJLoader.js');
const { GLTFLoader } = require('three/examples/jsm/loaders/GLTFLoader.js');
const { FBXLoader } = require('three/examples/jsm/loaders/FBXLoader.js');
const Color = require('../../util/color');
const MeshLoaders = {
OBJ: new OBJLoader(),
GLTF: new GLTFLoader(),
FBX: new FBXLoader(),
}
function toRad(deg) {
return deg * (Math.PI / 180);
}
function toDeg(rad) {
return rad * (180 / Math.PI);
}
function normalize(vec) {
const length = Math.sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
return new Three.Vector3(vec.x / length, vec.y / length, vec.z / length);
}
function toDegRounding(rad) {
const result = toDeg(rad);
if (!String(result).includes('.')) return result;
const split = String(result).split('.');
const endingDecimals = split[1].substring(0, 3);
if ((endingDecimals === '999') && (split[1].charAt(3) === '9')) return Number(split[0]) + 1;
return Number(split[0] + '.' + endingDecimals);
}
/**
* Class for 3D blocks
* @constructor
*/
class Jg3DBlocks {
constructor(runtime) {
/**
* The runtime instantiating this block package.
* @type {Runtime}
*/
this.runtime = runtime;
this.three = Three;
// expose addons and that for the funnis
this.BufferGeometryUtils = BufferGeometryUtils;
this.ConvexGeometry = ConvexGeometry;
this.OBJLoader = OBJLoader;
this.GLTFLoader = GLTFLoader;
this.FBXLoader = FBXLoader;
// prism has screenshots, lets tell it to use OUR canvas for them
this.runtime.prism_screenshot_checkForExternalCanvas = true;
this.runtime.prism_screenshot_externalCanvas = null;
// Three.js requirements
/**
* @type {Three.Scene}
*/
this.scene = null;
/**
* @type {Three.Camera}
*/
this.camera = null;
/**
* @type {Three.WebGLRenderer}
*/
this.renderer = null;
this.existingSceneObjects = [];
this.existingSceneLights = [];
// extras
this.lastStageSizeWhenRendering = {
width: 0,
height: 0
}
this.savedMeshes = {};
this.sceneLayer = "front";
this.lastStageColor = [255, 255, 255, 0];
// event recievers
// stop button clicked or project restarted, dispose of all objects
this.runtime.on('PROJECT_STOP_ALL', () => {
this.dispose();
this.sceneLayer = "front";
this.updateScratchCanvasRelayering();
});
}
/**
* Dispose of the scene, camera & renderer (and any objects)
*/
dispose() {
this.existingSceneObjects = [];
this.existingSceneLights = [];
if (this.scene) {
this.scene.remove();
this.scene = null;
}
if (this.camera) {
this.camera.remove();
this.camera = null;
}
if (this.renderer) {
if (this.renderer.domElement) {
this.renderer.domElement.remove();
}
this.renderer.dispose();
this.renderer = null;
this.runtime.prism_screenshot_externalCanvas = null;
}
}
/**
* Displays a message for stack blocks.
* @param {BlockUtility} util
*/
stackWarning(util, message) {
if (!util) return;
if (!util.thread) return;
if (!util.thread.stackClick) return;
const block = util.thread.blockGlowInFrame;
this.runtime.visualReport(block, message);
}
/**
* @returns {object} metadata for this extension and its blocks.
*/
getInfo() {
return ExtensionInfo;
}
// utilities
getScratchCanvas() {
return this.runtime.renderer.canvas;
}
restyleExternalCanvas(canvas) {
canvas.style.position = "absolute"; // position above canvas without pushing it down
canvas.style.width = "100%";
canvas.style.height = "100%";
// we have no reason to register clicks on the three.js canvas,
// so make it click on the scratch canvas instead
canvas.style.pointerEvents = "none";
}
appendElementAboveScratchCanvas(element) {
element.style.zIndex = 450;
if (this.sceneLayer === 'back') {
element.style.zIndex = 0;
}
this.getScratchCanvas().parentElement.prepend(element);
}
updateScratchCanvasRelayering() {
const canvas = this.getScratchCanvas();
canvas.style.backgroundColor = "transparent";
canvas.style.position = "relative"; // allows zIndex changes
if (Cast.toNumber(canvas.style.zIndex) < 1) {
canvas.style.zIndex = 1;
}
// _backgroundColor4f[3] controls opacity
let lastOpacity = this.runtime.renderer._backgroundColor4f[3];
if (this.sceneLayer === 'front') {
this.runtime.renderer.setBackgroundColor(
this.lastStageColor[0],
this.lastStageColor[1],
this.lastStageColor[2],
1
);
}
if (this.sceneLayer === 'back') {
if (
this.runtime.renderer._backgroundColor4f[0] !== this.lastStageColor[0]
|| this.runtime.renderer._backgroundColor4f[1] !== this.lastStageColor[1]
|| this.runtime.renderer._backgroundColor4f[2] !== this.lastStageColor[2]
) {
// color likely changed to sum else
console.log("updated stage color");
this.lastStageColor = this.runtime.renderer._backgroundColor4f;
}
this.runtime.renderer.setBackgroundColor(0, 0, 0, 0);
}
// update if changed
if (lastOpacity !== this.runtime.renderer._backgroundColor4f[3]) {
this.runtime.renderer.dirty = true;
}
}
needsToResizeCanvas() {
const stage = {
width: this.runtime.stageWidth,
height: this.runtime.stageHeight
}
return stage !== this.lastStageSizeWhenRendering;
}
mergeVertices(geometry) {
const vertices = geometry.attributes.position.array;
const vertexMap = {};
const mergedVertices = [];
const newIndices = [];
let newIndex = 0;
for (let i = 0; i < vertices.length; i += 3) {
const x = vertices[i];
const y = vertices[i + 1];
const z = vertices[i + 2];
const key = `${x},${y},${z}`;
if (vertexMap[key] === undefined) {
vertexMap[key] = newIndex;
mergedVertices.push(x, y, z);
newIndices.push(newIndex);
newIndex++;
} else {
newIndices.push(vertexMap[key]);
}
}
geometry.setAttribute('position', new Three.Float32BufferAttribute(mergedVertices, 3));
geometry.setIndex(new Three.Uint32BufferAttribute(newIndices, 1));
return geometry;
}
performRaycast(raycaster, object) {
const geometry = object.geometry;
const mergedGeometry = this.mergeVertices(geometry);
const boundingGeometry = new Three.BufferGeometry().copy(mergedGeometry);
boundingGeometry.computeBoundingBox();
boundingGeometry.boundingBox.applyMatrix4(object.matrixWorld);
const intersection = raycaster.intersectObject(object, true);
return intersection.length > 0;
}
initialize() {
// dispose of the previous scene
this.dispose();
this.scene = new Three.Scene();
this.renderer = new Three.WebGLRenderer({ preserveDrawingBuffer: true, alpha: true });
this.renderer.penguinMod = {
backgroundColor: 0x000000,
backgroundOpacity: 1
}
this.renderer.setClearColor(0x000000, 1);
// add renderer canvas ontop of scratch canvas
const canvas = this.renderer.domElement;
this.runtime.prism_screenshot_externalCanvas = canvas;
this.restyleExternalCanvas(canvas);
this.appendElementAboveScratchCanvas(canvas);
this.updateScratchCanvasRelayering();
/* dev: test rendering by drawing a cube and see if it appears
// const geometry = new Three.BoxGeometry(1, 1, 1);
// const material = new Three.MeshBasicMaterial({ color: 0x00ff00 });
// const cube = new Three.Mesh(geometry, material);
// this.scene.add(cube)
dev update: it worked W
*/
}
render() {
if (!this.renderer) return;
if (!this.scene) return;
if (!this.camera) return;
if (this.needsToResizeCanvas()) {
this.lastStageSizeWhenRendering = {
width: this.runtime.stageWidth,
height: this.runtime.stageHeight
}
/*
multiply sizes because the stage looks like doo doo xd
we dont need to worry about multiplying 1920 * 2 since projects
shouldnt be using that large of a stage but instead a smaller size
with the same aspect ratio, penguinmod even says that
*/
this.renderer.setSize(this.lastStageSizeWhenRendering.width * 2, this.lastStageSizeWhenRendering.height * 2);
this.restyleExternalCanvas(this.renderer.domElement);
}
// when switching between project page & editor, we need to move the canvas again since it gets lost
/* todo: create layers so that iframe appears above 3d every time this is done */
this.appendElementAboveScratchCanvas(this.renderer.domElement);
this.updateScratchCanvasRelayering();
return new Promise((resolve) => {
// we do this to avoid HUGE lag when not waiting 1 tick
// and because it waits if the tab isnt focused
requestAnimationFrame(() => {
// renderer might not exist anymore
if (!this.renderer) return;
resolve(this.renderer.render(this.scene, this.camera));
})
})
}
setCameraPerspective2(args) {
if (this.camera) {
// remove existing camera
this.camera.remove();
this.camera = null;
}
const fov = Cast.toNumber(args.FOV);
const aspect = Cast.toNumber(args.AR);
const near = Cast.toNumber(args.NEAR);
const far = Cast.toNumber(args.FAR);
this.camera = new Three.PerspectiveCamera(fov, aspect, near, far);
}
setCameraPerspective1(args) {
/* todo: make near and far be the same as the existing camera if there is one */
const near = 0.1;
const far = 1000;
return this.setCameraPerspective2({
FOV: args.FOV,
AR: args.AR,
NEAR: near,
FAR: far
})
}
setCameraPerspective0(args) {
/* todo: make ar, near and far be the same as the existing camera if there is one */
const ar = this.runtime.stageWidth / this.runtime.stageHeight;
const near = 0.1;
const far = 1000;
return this.setCameraPerspective2({
FOV: args.FOV,
AR: ar,
NEAR: near,
FAR: far
})
}
setCameraPosition(args) {
if (!this.camera) return;
const position = {
x: Cast.toNumber(args.X),
y: Cast.toNumber(args.Y),
z: Cast.toNumber(args.Z),
}
this.camera.position.set(position.x, position.y, position.z);
}
setCameraRotation(args) {
if (!this.camera) return;
const rotation = {
x: Cast.toNumber(args.X),
y: Cast.toNumber(args.Y),
z: Cast.toNumber(args.Z),
}
// const euler = new Three.Euler(toRad(rotation.x), toRad(rotation.y), toRad(rotation.z));
// this.camera.setRotationFromEuler(euler);
const euler = new Three.Euler(0, 0, 0);
this.camera.setRotationFromEuler(euler);
this.camera.rotateY(toRad(rotation.y));
this.camera.rotateX(toRad(rotation.x));
this.camera.rotateZ(toRad(rotation.z));
}
getCameraPosition(args) {
if (!this.camera) return "";
const v = args.VECTOR3;
if (!v) return "";
if (!["x", "y", "z"].includes(v)) return "";
return Cast.toNumber(this.camera.position[v]);
}
getCameraRotation(args) {
if (!this.camera) return "";
const v = args.VECTOR3;
if (!v) return "";
if (!["x", "y", "z"].includes(v)) return "";
const rotation = Cast.toNumber(this.camera.rotation[v]);
// rotation is in radians, convert to degrees but round it
// a bit so that we get 46 instead of 45.999999999999996
return toDegRounding(rotation);
}
setSceneLayer(args) {
if (!this.renderer) return;
let lastSceneLayer = this.sceneLayer;
this.sceneLayer = "front";
if (Cast.toString(args.SIDE) === 'back') {
this.sceneLayer = "back";
}
if (this.sceneLayer !== lastSceneLayer) {
this.lastStageColor = this.runtime.renderer._backgroundColor4f;
}
this.appendElementAboveScratchCanvas(this.renderer.domElement);
this.updateScratchCanvasRelayering();
}
setSceneBackgroundColor(args) {
if (!this.renderer) return;
const rgb = Cast.toRgbColorObject(args.COLOR);
const color = Color.rgbToDecimal(rgb);
this.renderer.penguinMod.backgroundColor = color;
this.renderer.setClearColor(color, this.renderer.penguinMod.backgroundOpacity);
}
setSceneBackgroundOpacity(args) {
if (!this.renderer) return;
let opacity = Cast.toNumber(args.OPACITY);
if (opacity > 100) opacity = 100;
if (opacity < 0) opacity = 0;
const backgroundOpac = 1 - (opacity / 100);
this.renderer.penguinMod.backgroundOpacity = backgroundOpac;
this.renderer.setClearColor(this.renderer.penguinMod.backgroundColor, backgroundOpac);
}
show3d() {
this.renderer.domElement.style.display = ""
}
hide3d() {
this.renderer.domElement.style.display = "none"
}
is3dVisible() {
return this.renderer.domElement.style.display === "" || this.renderer.domElement.style.display === "absolute"
}
getCameraZoom() {
if (!this.camera) return "";
return Cast.toNumber(this.camera.zoom) * 100;
}
setCameraZoom(args) {
if (!this.camera) return;
this.camera.zoom = Cast.toNumber(args.ZOOM) / 100;
this.camera.updateProjectionMatrix();
}
getCameraClipPlane(args) {
if (!this.camera) return "";
const plane = args.CLIPPLANE;
if (!["near", "far"].includes(plane)) return "";
return this.camera[plane];
}
getCameraAspectRatio() {
if (!this.camera) return "";
return Cast.toNumber(this.camera.aspect);
}
getCameraFov() {
if (!this.camera) return "";
return Cast.toNumber(this.camera.fov);
}
isCameraPerspective() {
if (!this.camera) return false;
return Cast.toBoolean(this.camera.isPerspectiveCamera);
}
isCameraOrthographic() {
if (!this.camera) return false;
return Cast.toBoolean(!this.camera.isPerspectiveCamera);
}
doesObjectExist(args) {
if (!this.scene) return false;
const name = Cast.toString(args.NAME);
// !! is easier to type than if (...) { return true; } return false;
return !!this.scene.getObjectByName(name);
}
createGameObject(args, util, type) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
if (this.scene.getObjectByName(name)) return this.stackWarning(util, 'An object with this name already exists!');
const position = {
x: Cast.toNumber(args.X),
y: Cast.toNumber(args.Y),
z: Cast.toNumber(args.Z),
};
let object;
switch (type) {
case 'sphere': {
const geometry = new Three.SphereGeometry(1);
const material = new Three.MeshStandardMaterial({ color: 0xffffff });
const sphere = new Three.Mesh(geometry, material);
object = sphere;
break;
}
case 'plane': {
const geometry = new Three.PlaneGeometry(1, 1);
const material = new Three.MeshStandardMaterial({ color: 0xffffff });
const plane = new Three.Mesh(geometry, material);
object = plane;
break;
}
case 'mesh': {
const url = Cast.toString(args.URL);
// switch loaders based on file type
let fileType = 'obj';
switch (Cast.toString(args.FILETYPE)) {
case '.glb / .gltf':
fileType = 'glb';
break;
case '.fbx':
fileType = 'fbx';
break;
}
// we need to do a promise here so that stack continues on load
return new Promise((resolve) => {
let loader = MeshLoaders.OBJ;
switch (fileType) {
case 'glb':
loader = MeshLoaders.GLTF;
break;
case 'fbx':
loader = MeshLoaders.FBX;
break;
}
if (url in this.savedMeshes) {
const mesh = this.savedMeshes[url];
object = mesh.clone();
object.name = name;
this.existingSceneObjects.push(name);
object.isPenguinMod = true;
object.isMeshObj = true;
object.position.set(position.x, position.y, position.z);
this.scene.add(object);
resolve();
return;
}
else {
loader.load(url, (object) => {
// success
if (loader === MeshLoaders.GLTF) {
object = object.scene;
}
if (loader === MeshLoaders.OBJ) {
const material = new Three.MeshStandardMaterial({ color: 0xffffff });
material.wireframe = false;
this.updateMaterialOfObjObject(object, material);
this.savedMeshes[url] = object;
}
object.name = name;
console.log(object);
this.existingSceneObjects.push(name);
object.isPenguinMod = true;
object.isMeshObj = true;
object.position.set(position.x, position.y, position.z);
this.scene.add(object);
resolve();
}, () => { }, (error) => {
console.warn('Failed to load 3D mesh obj;', error);
this.stackWarning(util, 'Failed to get the 3D mesh!');
resolve();
})
}
});
}
case 'light': {
const type = Cast.toString(args.LIGHTTYPE);
// switch type because there are different types of lights
let light;
switch (type) {
default: {
light = new Three.PointLight(0xffffff, 1, 100);
break;
}
}
object = light;
this.existingSceneLights.push(name);
break;
}
default: {
const geometry = new Three.BoxGeometry(1, 1, 1);
const material = new Three.MeshStandardMaterial({ color: 0xffffff });
const cube = new Three.Mesh(geometry, material);
object = cube;
break;
}
}
object.name = name;
this.existingSceneObjects.push(name);
object.isPenguinMod = true;
object.position.set(position.x, position.y, position.z);
this.scene.add(object);
}
createCubeObject(args, util) {
this.createGameObject(args, util, 'cube');
}
createSphereObject(args, util) {
this.createGameObject(args, util, 'sphere');
}
createPlaneObject(args, util) {
this.createGameObject(args, util, 'plane');
}
createMeshObject(args, util) {
this.createGameObject(args, util, 'mesh');
}
createMeshObjectFileTyped(args, util) {
this.createGameObject(args, util, 'mesh');
}
createLightObject(args, util) {
this.createGameObject(args, util, 'light');
}
getMaterialOfObjObject(object) {
let material;
object.traverse((child) => {
if (child instanceof Three.Mesh) {
material = child.material;
}
});
return material;
}
updateMaterialOfObjObject(object, material) {
object.traverse((child) => {
if (child instanceof Three.Mesh) {
child.material = material;
}
});
}
setObjectPosition(args) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
const position = {
x: Cast.toNumber(args.X),
y: Cast.toNumber(args.Y),
z: Cast.toNumber(args.Z),
};
const object = this.scene.getObjectByName(name);
if (!object) return;
object.position.set(position.x, position.y, position.z);
}
setObjectRotation(args) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
const rotation = {
x: Cast.toNumber(args.X),
y: Cast.toNumber(args.Y),
z: Cast.toNumber(args.Z),
};
const object = this.scene.getObjectByName(name);
if (!object) return;
// const euler = new Three.Euler(toRad(rotation.x), toRad(rotation.y), toRad(rotation.z));
// object.setRotationFromEuler(euler);
const euler = new Three.Euler(0, 0, 0);
object.setRotationFromEuler(euler);
object.rotateY(toRad(rotation.y));
object.rotateX(toRad(rotation.x));
object.rotateZ(toRad(rotation.z));
}
setObjectSize(args) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
const size = {
x: Cast.toNumber(args.X) / 100,
y: Cast.toNumber(args.Y) / 100,
z: Cast.toNumber(args.Z) / 100,
};
const object = this.scene.getObjectByName(name);
if (!object) return;
object.scale.set(size.x, size.y, size.z);
}
moveObjectUnits(args) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
const object = this.scene.getObjectByName(name);
if (!object) return;
const amount = Cast.toNumber(args.AMOUNT);
const direction = new Three.Vector3();
object.getWorldDirection(direction);
object.position.add(direction.multiplyScalar(amount));
}
getObjectPosition(args) {
if (!this.scene) return "";
const name = Cast.toString(args.NAME);
const object = this.scene.getObjectByName(name);
if (!object) return '';
const v = args.VECTOR3;
if (!v) return "";
if (!["x", "y", "z"].includes(v)) return "";
return Cast.toNumber(object.position[v]);
}
getObjectRotation(args) {
if (!this.scene) return "";
const name = Cast.toString(args.NAME);
const object = this.scene.getObjectByName(name);
if (!object) return '';
const v = args.VECTOR3;
if (!v) return "";
if (!["x", "y", "z"].includes(v)) return "";
const rotation = Cast.toNumber(object.rotation[v]);
// rotation is in radians, convert to degrees but round it
// a bit so that we get 46 instead of 45.999999999999996
return toDegRounding(rotation);
}
getObjectSize(args) {
if (!this.scene) return "";
const name = Cast.toString(args.NAME);
const object = this.scene.getObjectByName(name);
if (!object) return '';
const v = args.VECTOR3;
if (!v) return "";
if (!["x", "y", "z"].includes(v)) return "";
return Cast.toNumber(object.scale[v]) * 100;
}
getObjectColor(args) {
if (!this.scene) return "";
const name = Cast.toString(args.NAME);
const object = this.scene.getObjectByName(name);
if (!object) return '';
return "#" + object.material.color.getHexString()
}
deleteObject(args) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
const object = this.scene.getObjectByName(name);
if (!object) return;
const isLight = object.isLight;
object.clear();
this.scene.remove(object);
const idx = this.existingSceneObjects.indexOf(name);
this.existingSceneObjects.splice(idx, 1);
if (isLight) {
const lidx = this.existingSceneLights.indexOf(name);
this.existingSceneLights.splice(lidx, 1);
}
}
setObjectColor(args) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
const rgb = Cast.toRgbColorObject(args.COLOR);
const color = Color.rgbToDecimal(rgb);
const object = this.scene.getObjectByName(name);
if (!object) return;
if (object.isLight) {
object.color.set(color);
return
}
if (object.isMeshObj) {
const material = this.getMaterialOfObjObject(object);
if (!material) return;
material.color.set(color);
this.updateMaterialOfObjObject(object, material);
return;
}
object.material.color.set(color);
}
setObjectShading(args) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
const on = Cast.toString(args.ONOFF) === 'on';
const object = this.scene.getObjectByName(name);
if (!object) return;
if (object.isLight) return;
if (object.isMeshObj) {
const material = this.getMaterialOfObjObject(object);
if (!material) return;
const color = '#' + material.color.getHexString();
let newMat;
if (on) {
newMat = new Three.MeshStandardMaterial({ color: color });
} else {
newMat = new Three.MeshBasicMaterial({ color: color });
}
newMat.color.set(color);
this.updateMaterialOfObjObject(object, newMat);
return;
}
const color = '#' + object.material.color.getHexString();
if (on) {
object.material = new Three.MeshStandardMaterial({ color: color });
} else {
object.material = new Three.MeshBasicMaterial({ color: color });
}
}
setObjectWireframe(args) {
if (!this.scene) return;
const name = Cast.toString(args.NAME);
const on = Cast.toString(args.ONOFF) === 'on';
const object = this.scene.getObjectByName(name);
if (!object) return;
if (object.isLight) return;
if (object.isMeshObj) {
const material = this.getMaterialOfObjObject(object);
if (!material) return;
material.wireframe = on;
this.updateMaterialOfObjObject(object, material);
return;
}
object.material.wireframe = on;
}
existingObjectsArray(args) {
const listType = Cast.toString(args.OBJECTLIST);
const validOptions = ["objects", "physical objects", "lights"];
if (!validOptions.includes(listType)) return '[]';
switch (listType) {
case 'objects':
return JSON.stringify(this.existingSceneObjects);
case 'lights':
return JSON.stringify(this.existingSceneLights);
case 'physical objects': {
const physical = this.existingSceneObjects.filter(objectName => {
return !this.existingSceneLights.includes(objectName);
});
return JSON.stringify(physical);
}
default:
return '[]';
}
}
objectTouchingObject(args) {
if (!this.scene) return false;
const name1 = Cast.toString(args.NAME1);
const name2 = Cast.toString(args.NAME2);
const object1 = this.scene.getObjectByName(name1);
const object2 = this.scene.getObjectByName(name2);
if (!object1) return false;
if (!object2) return false;
if (object1.isLight) return false; // currently lights are not supported for collisions
if (object2.isLight) return false; // currently lights are not supported for collisions
const box1 = new Three.Box3().setFromObject(object1);
const box2 = new Three.Box3().setFromObject(object2);
const collision = box1.intersectsBox(box2);
return collision;
}
pointTowardsObject(args) {
if (!this.scene) return false;
const name1 = Cast.toString(args.NAME1);
const name2 = Cast.toString(args.NAME2);
const object1 = this.scene.getObjectByName(name1);
const object2 = this.scene.getObjectByName(name2);
if (!object1) return false;
if (!object2) return false;
object1.lookAt(object2.position);
}
pointTowardsXYZ(args) {
if (!this.scene) return false;
const name = Cast.toString(args.NAME);
const object = this.scene.getObjectByName(name);
if (!object) return false;
const position = {
x: Cast.toNumber(args.X),
y: Cast.toNumber(args.Y),
z: Cast.toNumber(args.Z)
};
object.lookAt(position.x, position.y, position.z);
}
MoveCameraBy(args) {
if (!this.camera) return;
const amount = Cast.toNumber(args.AMOUNT);
// comment so it updates bc github was having problems
const direction = new Three.Vector3();
this.camera.getWorldDirection(direction);
this.camera.position.add(direction.multiplyScalar(amount));
}
changeCameraPosition(args) {
if (!this.camera) return;
this.camera.position.x += Cast.toNumber(args.X);
this.camera.position.y += Cast.toNumber(args.Y);
this.camera.position.z += Cast.toNumber(args.Z);
}
changeCameraRotation(args) {
if (!this.camera) return;
this.camera.rotation.x += Cast.toNumber(args.X);
this.camera.rotation.y += Cast.toNumber(args.Y);
this.camera.rotation.z += Cast.toNumber(args.Z);
}
raycastResultToReadable(result) {
const newResult = Clone.simple(result).map((intersection) => {
console.log(intersection.object.object.name);
return intersection.object.object.name;
})
return newResult;
}
rayCollision(args) {
if (!this.scene) return '';
const ray = new Three.Raycaster();
const origin = {
x: Cast.toNumber(args.X),
y: Cast.toNumber(args.Y),
z: Cast.toNumber(args.Z),
};
const direction = normalize({
x: toRad(Cast.toNumber(args.DX)),
y: toRad(Cast.toNumber(args.DY)),
z: toRad(Cast.toNumber(args.DZ)),
});
ray.set(new Three.Vector3(origin.x, origin.y, origin.z), new Three.Vector3(direction.x, direction.y, direction.z));
const intersects = ray.intersectObjects(this.scene.children, true);
if (intersects.length === 0) return '';
const first = intersects[0];
return first.object.name;
}
rayCollisionCamera() {
if (!this.scene) return '';
if (!this.camera) return '';
const ray = new Three.Raycaster();
ray.setFromCamera(new Three.Vector2(), this.camera);
const intersects = ray.intersectObjects(this.scene.children, true);
if (intersects.length === 0) return '';
const first = intersects[0];
return first.object.name;
}
rayCollisionArray(args) {
if (!this.scene) return '[]';
const ray = new Three.Raycaster();
const origin = {
x: Cast.toNumber(args.X),
y: Cast.toNumber(args.Y),
z: Cast.toNumber(args.Z),
};
const direction = normalize({
x: toRad(Cast.toNumber(args.DX)),
y: toRad(Cast.toNumber(args.DY)),
z: toRad(Cast.toNumber(args.DZ)),
});
ray.set(new Three.Vector3(origin.x, origin.y, origin.z), new Three.Vector3(direction.x, direction.y, direction.z));
const intersects = ray.intersectObjects(this.scene.children, true);
if (intersects.length === 0) return '[]';
//const result = this.raycastResultToReadable(intersects);
return JSON.stringify(intersects);
}
rayCollisionCameraArray() {
if (!this.scene) return '[]';
if (!this.camera) return '[]';
const ray = new Three.Raycaster();
ray.setFromCamera(new Three.Vector2(), this.camera);
const intersects = ray.intersectObjects(this.scene.children, true);
if (intersects.length === 0) return '[]';
//const result = this.raycastResultToReadable(intersects);
return JSON.stringify(intersects);
}
rayCollisionDistance(args) {
if (!this.scene) return '';
const origin = new Three.Vector3(
Cast.toNumber(args.X),
Cast.toNumber(args.Y),
Cast.toNumber(args.Z),
);
const direction = normalize(new Three.Vector3(
toRad(Cast.toNumber(args.DX)),
toRad(Cast.toNumber(args.DY)),
toRad(Cast.toNumber(args.DZ)),
));
const ray = new Three.Raycaster(origin, direction, 0, args.DIS);
const intersects = ray.intersectObjects(this.scene.children, true);
if (intersects.length === 0) return '';
const first = intersects[0];
return first.object.name;
}
rayCollisionArrayDistance(args) {
if (!this.scene) return '[]';
const origin = new Three.Vector3(
Cast.toNumber(args.X),
Cast.toNumber(args.Y),
Cast.toNumber(args.Z),
);
const direction = normalize(new Three.Vector3(
toRad(Cast.toNumber(args.DX)),
toRad(Cast.toNumber(args.DY)),
toRad(Cast.toNumber(args.DZ)),
));
const ray = new Three.Raycaster(origin, direction, 0, args.DIS);
const intersects = ray.intersectObjects(this.scene.children, true);
if (intersects.length === 0) return '[]';
const result = this.raycastResultToReadable(intersects);
return JSON.stringify(result);
}
getObjectParent(args) {
if (!this.scene) return '';
const name = Cast.toString(args.NAME);
const object = this.scene.getObjectByName(name);
if (!object) return '';
if (!object.parent) return '';
return object.parent.name;
}
}
module.exports = Jg3DBlocks;
|