-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
490 lines (437 loc) · 16.8 KB
/
script.js
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
var fEdit_Vertex,deleted_evene,copy_mesh,drawMode = false, moveMode = false, vertexEditMode = false, points = [], shapesToExtrude = [], shapesExtruded = [];
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
var scene = new BABYLON.Scene(engine);
const gizmoManager = new BABYLON.GizmoManager(scene);
const camera = new BABYLON.ArcRotateCamera(
"UniversalCamera",
-Math.PI / 2, // alpha (rotation around Y-axis)
Math.PI / 3, // beta (rotation around X-axis)
60, // radius (distance from target)
BABYLON.Vector3.Zero(), // target (look-at point)
scene
);
// Attach the camera to the canvas
camera.attachControl(canvas, true);
// Create a light
const light = new BABYLON.HemisphericLight(
"light",
new BABYLON.Vector3(0, 1, 0),
scene
);
light.intensity = 0.7;
// Create the ground
var ground = BABYLON.MeshBuilder.CreateGround(
"ground",
{ width: 500, height: 400 },
scene
);
// Create a black material for the ground
var groundMaterial = new BABYLON.StandardMaterial("groundMaterial", scene);
groundMaterial.diffuseColor = new BABYLON.Color3(1, 0, 1); // Black color
ground.material = groundMaterial;
// Enable edge rendering for the ground
ground.enableEdgesRendering();
ground.edgesWidth = 5.0; // Set the edge width to 3 units
ground.edgesColor = new BABYLON.Color4(1, 1, 1, 1); // White color for the edges
const gridMaterial = new BABYLON.GridMaterial("gridMaterial", scene);
gridMaterial.majorUnitFrequency = 5; // Distance between major lines
gridMaterial.minorUnitVisibility = 0.5; // Visibility of minor lines (0 to 1)
gridMaterial.gridRatio = 1; // Scale of the grid
gridMaterial.backFaceCulling = false; // Ensure visibility from all angles
gridMaterial.mainColor = new BABYLON.Color3(0, 0, 0); // Background color (black)
gridMaterial.lineColor = new BABYLON.Color3(1, 1, 1); // Line color (white)
ground.material = gridMaterial;
// Handle pointer events
function handlePointer(pointerInfo) {
if (drawMode) {
var pickInfo = pointerInfo.pickInfo;
switch (pointerInfo.type) {
case BABYLON.PointerEventTypes.POINTERDOWN:
// Left-Click then accumulate the points and represent it on screen
if (
pointerInfo.event.inputIndex == 2 &&
pickInfo.pickedMesh &&
(pickInfo.pickedMesh.id === "ground" ||
pickInfo.pickedMesh.id === "lines")
) {
points.push(pickInfo.pickedPoint);
// ---------------drow points from here
// Create a sphere marker
const markerName = `marker_${Date.now()}`; // Use a unique name for the sphere
const sphere = BABYLON.MeshBuilder.CreateSphere(
markerName,
{ diameter: 0.5 },
scene
);
sphere.position = pickInfo.pickedPoint;
// Add material to the sphere
const material = new BABYLON.StandardMaterial(`${markerName}_material`, scene);
material.diffuseColor = new BABYLON.Color3(1, 1, 1); // Pure white color
material.emissiveColor = new BABYLON.Color3(1, 1, 1); // White glow
sphere.material = material;
// ---------------drow points to here
}
// Right-Click then draw the 2-D closed loop shape from points
else if (pointerInfo.event.inputIndex == 4) {
points.push(points[0]);
var idx = shapesToExtrude.length;
var lines = BABYLON.MeshBuilder.CreateLines(
"lines" + idx.toString(),
{ points: points, updatable: true },
scene
);
lines.color = new BABYLON.Color3(1, 0, 0);
shapesToExtrude.push(points);
points = [];
}
break;
}
}
}
function generateExtrusions() {
shapesToExtrude.forEach((currentShape, index) => {
// Ensure each shape is processed only once
if (!shapesExtruded[index]) {
shapesExtruded[index] = true; // Mark shape as processed
// Create a unique identifier for the extrusion
const extrusionId = `extrusion_${index}_${Date.now()}`;
// Perform the extrusion
const extrudedMesh = BABYLON.MeshBuilder.ExtrudePolygon(
extrusionId,
{
shape: currentShape,
depth: 5, // Height of extrusion
updatable: false
},
scene
);
// Position the extruded shape
extrudedMesh.position.y = 5; // Centered vertically for visual consistency
// Apply material with random color
const randomColor = new BABYLON.Color3(Math.random(), Math.random(), Math.random());
const meshMaterial = new BABYLON.StandardMaterial(`${extrusionId}_material`, scene);
meshMaterial.diffuseColor = randomColor; // Base color
meshMaterial.emissiveColor = randomColor.scale(0.5); // Glow effect
extrudedMesh.material = meshMaterial;
// Enable edge rendering with randomized edge properties
extrudedMesh.enableEdgesRendering();
extrudedMesh.edgesWidth = 2.0 + Math.random() * 3.0; // Random edge width between 2 and 5
extrudedMesh.edgesColor = new BABYLON.Color4(0, 0, 0, 1); // Black edges
}
});
for(var i=0;i<4;++i){
scene.meshes.forEach((mesh) => {
// Check if the mesh is a 2D shape by its name or other properties
if (mesh.name.startsWith("lines") || mesh.name.startsWith("marker")) {
mesh.dispose(); // Dispose the mesh
}
});}
}
var startingPoint;
var currentMesh;
var getGroundPosition = function () {
var pickinfo = scene.pick(scene.pointerX, scene.pointerY, function (mesh) { return mesh == ground; });
if (pickinfo.hit) {
return pickinfo.pickedPoint;
}
return null;
}
var pointerDown = function (mesh) {
currentMesh = mesh;
startingPoint = getGroundPosition();
if (startingPoint) { // we need to disconnect camera from canvas
setTimeout(function () {
camera.detachControl(canvas);
}, 0);
}
}
var pointerUp = function () {
if (startingPoint) {
camera.attachControl(canvas, true);
startingPoint = null;
return;
}
}
var pointerMove = function () {
if (!startingPoint) {
return;
}
var current = getGroundPosition();
if (!current) {
return;
}
var diff = current.subtract(startingPoint);
currentMesh.position.addInPlace(diff);
startingPoint = current;
}
function dragMesh(pointerInfo) {
switch (pointerInfo.type) {
case BABYLON.PointerEventTypes.POINTERDOWN:
if (pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh != ground) {
pointerDown(pointerInfo.pickInfo.pickedMesh)
}
break;
case BABYLON.PointerEventTypes.POINTERUP:
pointerUp();
break;
case BABYLON.PointerEventTypes.POINTERMOVE:
pointerMove();
break;
}
}
const textTo3D = (
text,
fontUrl,
size,
depth,
scene,
position = { x: 0, y: 0, z: 0 },
spacing = 0, // Add spacing between characters
color = { diffuse: new BABYLON.Color3(1, 1, 1), emissive: new BABYLON.Color3(0, 0, 0) } // Add more color controls
) => {
opentype.load(fontUrl, (err, font) => {
if (err) {
console.error("Error loading font:", err);
return;
}
let xOffset = 0; // Tracks horizontal position for spacing
const combinedMesh = new BABYLON.Mesh("textMesh", scene); // To combine all characters
[...text].forEach((char) => {
const path = font.getPath(char, 0, 0, size); // Generate a path for the current character
const shape = [];
// Process commands to create a shape for the character
path.commands.forEach((cmd) => {
if (cmd.type === "M") {
// MoveTo starts a new path
shape.push(new BABYLON.Vector3(cmd.x + xOffset, -cmd.y, 0));
} else if (cmd.type === "L") {
// LineTo adds a straight line
shape.push(new BABYLON.Vector3(cmd.x + xOffset, -cmd.y, 0));
} else if (cmd.type === "Q") {
// Quadratic Bezier curve approximation
const control = new BABYLON.Vector3(cmd.x1 + xOffset, -cmd.y1, 0);
const end = new BABYLON.Vector3(cmd.x + xOffset, -cmd.y, 0);
shape.push(control, end);
} else if (cmd.type === "C") {
// Cubic Bezier curve approximation
const control1 = new BABYLON.Vector3(cmd.x1 + xOffset, -cmd.y1, 0);
const control2 = new BABYLON.Vector3(cmd.x2 + xOffset, -cmd.y2, 0);
const end = new BABYLON.Vector3(cmd.x + xOffset, -cmd.y, 0);
shape.push(control1, control2, end);
}
});
// Create a 3D text mesh for the character
const charMesh = BABYLON.MeshBuilder.ExtrudeShape(
`char_${char}`,
{
shape: shape,
path: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, depth)],
cap: BABYLON.Mesh.CAP_ALL,
},
scene
);
// Apply material
const textMaterial = new BABYLON.StandardMaterial(`charMaterial_${char}`, scene);
textMaterial.diffuseColor = color.diffuse; // Diffuse color
textMaterial.emissiveColor = color.emissive; // Emissive color
charMesh.material = textMaterial;
// Combine with the main mesh and position the character
charMesh.position = new BABYLON.Vector3(position.x, position.y, position.z);
charMesh.parent = combinedMesh;
// Update horizontal offset for the next character
xOffset += size + spacing;
});
// Set position of the combined mesh
combinedMesh.position = new BABYLON.Vector3(position.x, position.y, position.z);
});
};
// Call textTo3D
textTo3D(
"Hello", // Text to render
"./Fonts/HostGrotesk-Italic-VariableFont_wght.ttf", // Font URL
15, // Font size
4, // Depth
scene,
{ x: -15, y: 0, z: 5 }, // Position
0, // Spacing between characters
{
diffuse: new BABYLON.Color3(0, 0.5, 1), // Light blue
emissive: new BABYLON.Color3(0.2, 0.2, 0.6) // Subtle glow
}
);
// Function to Enter Edit Mode
function enterEditMode(mesh) {
const scene = mesh.getScene();
let dragging = false;
let pickedFace = null;
let dragStartPoint = null;
scene.onPointerObservable.add((pointerInfo) => {
switch (pointerInfo.type) {
case BABYLON.PointerEventTypes.POINTERDOWN:
const pickResult = scene.pick(scene.pointerX, scene.pointerY);
if (pickResult.hit && pickResult.pickedMesh === mesh) {
const indices = mesh.getIndices();
const positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
pickedFace = pickResult.faceId;
dragStartPoint = pickResult.pickedPoint;
if (pickedFace !== null && indices && positions) {
dragging = true;
}
}
break;
case BABYLON.PointerEventTypes.POINTERUP:
dragging = false;
pickedFace = null;
dragStartPoint = null;
break;
case BABYLON.PointerEventTypes.POINTERMOVE:
if (dragging && pickedFace !== null) {
const indices = mesh.getIndices();
const positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
const pickResult = scene.pick(scene.pointerX, scene.pointerY);
if (pickResult && pickResult.pickedPoint && positions && indices) {
const dragEndPoint = pickResult.pickedPoint;
const dragDelta = dragEndPoint.subtract(dragStartPoint);
dragStartPoint = dragEndPoint;
const vertexIndices = [
indices[pickedFace * 3],
indices[pickedFace * 3 + 1],
indices[pickedFace * 3 + 2],
];
for (let vertexIndex of vertexIndices) {
const i = vertexIndex * 3;
positions[i] += dragDelta.x;
positions[i + 1] += dragDelta.y;
positions[i + 2] += dragDelta.z;
}
mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
}
}
break;
}
});
}
function Edit_Vertex_and_edges(pointerInfo){
if (pointerInfo.type === BABYLON.PointerEventTypes.POINTERPICK) {
const pickInfo = pointerInfo.pickInfo;
if (pickInfo.hit && pickInfo.pickedMesh) {
const selectedMesh = pickInfo.pickedMesh;
enterEditMode(selectedMesh);
}
}
}
function deleted_mesh(pointerInfo){
if (pointerInfo.type === BABYLON.PointerEventTypes.POINTERPICK) {
const pickInfo = pointerInfo.pickInfo;
if (pickInfo.hit && pickInfo.pickedMesh) {
const selectedMesh = pickInfo.pickedMesh;
if(selectedMesh.id!="ground"){
selectedMesh.dispose();
}
}
scene.onPointerObservable.remove(deleted_evene);}
}
function copymesh(pointerInfo){
if (pointerInfo.type === BABYLON.PointerEventTypes.POINTERPICK) {
const pickInfo = pointerInfo.pickInfo;
if (pickInfo.hit && pickInfo.pickedMesh) {
const selectedMesh = pickInfo.pickedMesh;
if(selectedMesh.id!="ground"){
const vertexData = BABYLON.VertexData.ExtractFromMesh(selectedMesh);
// Create a new mesh
const newMesh = new BABYLON.Mesh("newBox", scene);
vertexData.applyToMesh(newMesh);
// Move the new mesh to a new position
newMesh.position.x -= 5;
newMesh.position.y += 5;
scene.onPointerObservable.remove(copy_mesh);
}
}
}
}
function deepcopymesh(pointerInfo){
if (pointerInfo.type === BABYLON.PointerEventTypes.POINTERPICK) {
const pickInfo = pointerInfo.pickInfo;
if (pickInfo.hit && pickInfo.pickedMesh) {
const selectedMesh = pickInfo.pickedMesh;
if(selectedMesh.id!="ground"){
const clonedMesh = selectedMesh.clone("clonedBox");
// Move the cloned mesh to a new position
clonedMesh.position.x += 3;
scene.onPointerObservable.remove(fEdit_Vertex);
}
}
}
}
var Draw_Shape,Move_Shape,Edit_Vertex;
document.getElementById("Draw_Shape").addEventListener("click", () => {
drawMode = true;
moveMode = false;
vertexEditMode = false;
extrudeMode = false;
scene.onPointerObservable.remove(Move_Shape);
scene.onPointerObservable.remove(Edit_Vertex);
Draw_Shape = scene.onPointerObservable.add(handlePointer);
})
document.getElementById("Extrude").addEventListener("click", () => {
drawMode = false;
moveMode = false;
vertexEditMode = false;
extrudeMode = false;
generateExtrusions()
scene.onPointerObservable.remove(Draw_Shape);
scene.onPointerObservable.remove(Edit_Vertex);
scene.onPointerObservable.remove(Move_Shape);
})
document.getElementById("Move_Shape").addEventListener("click", () => {
drawMode = false;
moveMode = true;
vertexEditMode = false;
extrudeMode = false;
scene.onPointerObservable.remove(Draw_Shape);
scene.onPointerObservable.remove(Edit_Vertex);
Move_Shape= scene.onPointerObservable.add(dragMesh);
})
document.getElementById("shapeSelector").addEventListener("click", (event) => {
const selectedShape = event.target.value;
if (selectedShape === "sphere") {
const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: 8 }, scene); // Diameter = 2 * radius
sphere.position.y=4
event.target.value="Select"
} else if (selectedShape === "cube") {
const cube = BABYLON.MeshBuilder.CreateBox("cube", { size: 8 }, scene); // Size = side length
cube.position.y=4
}
});
var temp1=0
document.getElementById("Gizmos").addEventListener("click", () => {
if(temp1%2==0){
gizmoManager.www=true
// Enable translation, rotation, and scaling gizmos
gizmoManager.positionGizmoEnabled = true; // Enables movement gizmo
gizmoManager.rotationGizmoEnabled = true; // Enables rotation gizmo
gizmoManager.scaleGizmoEnabled = true; // Enables scaling gizmo
}
else{
gizmoManager.www=false
// Enable translation, rotation, and scaling gizmos
gizmoManager.positionGizmoEnabled = false; // Enables movement gizmo
gizmoManager.rotationGizmoEnabled = false; // Enables rotation gizmo
gizmoManager.scaleGizmoEnabled = false; // Enables scaling gizmo
}
temp1++
})
document.getElementById("DeleteMesh").addEventListener("click", () => {
deleted_evene=scene.onPointerObservable.add(deleted_mesh);
})
document.getElementById("fMove_Shape").addEventListener("click", () => {
copy_mesh=scene.onPointerObservable.add(copymesh);
})
document.getElementById("fEdit_Vertex").addEventListener("click", () => {
fEdit_Vertex=scene.onPointerObservable.add(deepcopymesh);
})
// Render loop
engine.runRenderLoop(function () {
scene.render();
});