forked from Blaybus212/backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSceneAssemblyService.java
More file actions
648 lines (559 loc) · 23.6 KB
/
SceneAssemblyService.java
File metadata and controls
648 lines (559 loc) · 23.6 KB
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
package com.blaybus.backend.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.blaybus.backend.domain.alignment.Alignment;
import com.blaybus.backend.domain.alignment.Component;
import com.blaybus.backend.domain.scene.SceneInformation;
import com.blaybus.backend.domain.scene.UserScene;
import com.blaybus.backend.domain.user.User;
import com.blaybus.backend.dto.scene.AssemblyRequestDto;
import com.blaybus.backend.dto.scene.ComponentStateDto;
import com.blaybus.backend.dto.scene.DisassemblyLevelDto;
import com.blaybus.backend.dto.scene.SceneAssemblyDto;
import com.blaybus.backend.dto.scene.SceneConfigDto;
import com.blaybus.backend.dto.scene.SceneNodeDto;
import com.blaybus.backend.dto.scene.SceneSyncDto;
import com.blaybus.backend.repository.AlignmentRepository;
import com.blaybus.backend.repository.ComponentRepository;
import com.blaybus.backend.repository.SceneInformationRepository;
import com.blaybus.backend.repository.UserRepository;
import com.blaybus.backend.repository.UserSceneRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@Transactional
public class SceneAssemblyService {
private final SceneInformationRepository sceneRepository;
private final AlignmentRepository alignmentRepository;
private final ComponentRepository componentRepository;
private final UserRepository userRepository;
private final UserSceneRepository userSceneRepository;
private final ObjectMapper objectMapper;
private final ResourcePatternResolver resourcePatternResolver;
public SceneAssemblyService(
SceneInformationRepository sceneRepository,
AlignmentRepository alignmentRepository,
ComponentRepository componentRepository,
UserRepository userRepository,
UserSceneRepository userSceneRepository,
@Qualifier("objectMapper")
ObjectMapper objectMapper,
ResourcePatternResolver resourcePatternResolver) {
this.sceneRepository = sceneRepository;
this.alignmentRepository = alignmentRepository;
this.componentRepository = componentRepository;
this.userRepository = userRepository;
this.userSceneRepository = userSceneRepository;
this.objectMapper = objectMapper;
this.resourcePatternResolver = resourcePatternResolver;
}
public void saveAssembly(Long userId, SceneAssemblyDto dto) {
// 1. User 조회
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found: " + userId));
// 2. Scene 조회
String filePath = dto.getFile(); // 예: "Drone/Drone.gltf" 또는 "Drone"
String sceneName = extractSceneName(filePath);
SceneInformation scene = sceneRepository.findByEngTitle(sceneName)
.or(() -> sceneRepository.findByTitle(sceneName))
.orElseThrow(() -> new IllegalArgumentException("Scene not found for file: " + filePath));
// 3. Node 처리
for (SceneNodeDto node : dto.getNodes()) {
processNode(user, scene, node);
}
}
public void syncSceneState(Long userId, Long sceneId, SceneSyncDto dto) {
// 1. 공통 User & Scene 조회 (트랜잭션 내에서 한 번만 조회)
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found: " + userId));
SceneInformation scene = sceneRepository.findById(sceneId)
.orElseThrow(() -> new IllegalArgumentException("Scene not found: " + sceneId));
// 2. LookAt 업데이트 (UserScene)
if (dto.getLookAt() != null) {
UserScene userScene = userSceneRepository.findByUserIdAndSceneId(userId, sceneId)
.orElseGet(() -> UserScene.builder()
.user(user)
.scene(scene)
.lookAt("{}") // 필요 시 기본값 설정
.build());
try {
String lookAtJson = objectMapper.writeValueAsString(dto.getLookAt());
UserScene updatedUserScene = UserScene.builder()
.id(userScene.getId())
.user(userScene.getUser())
.scene(userScene.getScene())
.lookAt(lookAtJson)
.note(userScene.getNote())
.build();
userSceneRepository.save(updatedUserScene);
} catch (JsonProcessingException e) {
log.error("LookAt 직렬화 실패", e);
throw new RuntimeException("LookAt serialization failed", e);
}
}
// 3. Components 업데이트 (Alignment)
if (dto.getComponents() != null) {
for (ComponentStateDto compState : dto.getComponents()) {
updateComponentState(user, scene, compState);
}
}
}
private void updateComponentState(User user, SceneInformation scene, ComponentStateDto compState) {
String nodeName = compState.getNodeName();
String matrixJson;
try {
matrixJson = objectMapper.writeValueAsString(compState.getMatrix());
} catch (JsonProcessingException e) {
log.error("Sync를 위한 Matrix 직렬화 실패: {}", nodeName, e);
return;
}
Alignment alignment = alignmentRepository
.findByUserIdAndSceneIdAndNodeName(user.getId(), scene.getId(), nodeName)
.orElse(null);
if (alignment == null) {
// 신규 생성 (Upsert)
String componentName = deriveComponentName(nodeName);
Component component = componentRepository.findByName(componentName)
.orElseGet(() -> {
log.info("Creating new component during sync: {}", componentName);
return componentRepository.save(Component.builder()
.name(componentName)
.description("Auto-generated from sync")
.build());
});
alignment = Alignment.builder()
.user(user)
.scene(scene)
.component(component)
.nodeName(nodeName)
.transformMatrix(matrixJson)
.build();
} else {
// 기존 업데이트
alignment = Alignment.builder()
.id(alignment.getId())
.user(alignment.getUser())
.scene(alignment.getScene())
.component(alignment.getComponent())
.nodeName(alignment.getNodeName())
.transformMatrix(matrixJson)
.build();
}
alignmentRepository.save(alignment);
}
public DisassemblyLevelDto getDisassemblyLevel(Long userId, Long sceneId) {
UserScene userScene = userSceneRepository.findByUserIdAndSceneId(userId, sceneId)
.orElseThrow(() -> new IllegalArgumentException(
"UserScene not found for user " + userId + " and scene " + sceneId));
return DisassemblyLevelDto.builder()
.disassemblyLevel(userScene.getDisassemblyLevel())
.build();
}
public void updateDisassemblyLevel(Long userId, Long sceneId, Integer level) {
if (level < 0 || level > 100) {
throw new IllegalArgumentException("Disassembly level must be between 0 and 100");
}
UserScene userScene = userSceneRepository.findByUserIdAndSceneId(userId, sceneId)
.orElseGet(() -> {
User user = userRepository.findById(userId)
.orElseThrow(() -> new IllegalArgumentException("User not found: " + userId));
SceneInformation scene = sceneRepository.findById(sceneId)
.orElseThrow(() -> new IllegalArgumentException("Scene not found: " + sceneId));
return UserScene.builder()
.user(user)
.scene(scene)
.lookAt("{}")
.disassemblyLevel(level)
.build();
});
// Builder pattern for update because of immutability or preference
UserScene updatedUserScene = UserScene.builder()
.id(userScene.getId())
.user(userScene.getUser())
.scene(userScene.getScene())
.lookAt(userScene.getLookAt())
.note(userScene.getNote())
.lastAccessedAt(userScene.getLastAccessedAt())
.disassemblyLevel(level)
.build();
userSceneRepository.save(updatedUserScene);
}
// ... (existing methods)
public byte[] exportAssembledGltf(Long userId, Long sceneId) {
// 1. 데이터 조회 및 기본 설정 로드
SceneInformation scene = sceneRepository.findById(sceneId)
.orElseThrow(() -> new IllegalArgumentException("Scene not found"));
String assetPath = scene.getAssetPath();
String configPath = "classpath:assets/" + assetPath + "/config/assembly_config.json";
SceneConfigDto baseConfig;
try {
org.springframework.core.io.Resource configResource = resourcePatternResolver.getResource(configPath);
if (!configResource.exists()) {
throw new RuntimeException("Base assembly config not found for scene: " + assetPath);
}
baseConfig = objectMapper.readValue(configResource.getInputStream(), SceneConfigDto.class);
} catch (IOException e) {
throw new RuntimeException("Failed to load base config for scene: " + assetPath, e);
}
List<Alignment> alignments = alignmentRepository.findByUserIdAndSceneId(userId, sceneId);
Map<String, Alignment> alignmentMap = alignments.stream()
.collect(Collectors.toMap(Alignment::getNodeName, alignment -> alignment, (a1, a2) -> a1));
// 2. Node.js용 JSON 준비
// 2-1. Assets 맵 빌드 (Base Config에서 복사하여 기본 매핑 보장)
Map<String, String> assetsMap = new HashMap<>(baseConfig.getAssets());
// 2-2. Instances 리스트 빌드 (Base Config의 인스턴스들을 순회하며 사용자 값 병합)
List<AssemblyRequestDto.AssemblyNodeDto> instanceDtos = baseConfig.getInstances().stream().map(baseInst -> {
String nodeName = baseInst.getName();
String assetId = baseInst.getAssetId();
// 기본값 설정
List<Double> matrix = baseInst.getMatrix();
Map<String, Object> extras = new HashMap<>();
if (baseInst.getExtras() != null) {
extras.putAll(baseInst.getExtras());
}
// 사용자 수정사항(Alignment)이 있으면 오버라이드
Alignment userAlign = alignmentMap.get(nodeName);
if (userAlign != null) {
try {
matrix = objectMapper.readValue(userAlign.getTransformMatrix(),
new TypeReference<List<Double>>() {
/* empty */ });
} catch (JsonProcessingException e) {
log.warn("Failed to parse user matrix for node {}. Using base matrix.", nodeName);
}
}
// DB에서 컴포넌트 메타데이터 조회하여 추가 (Best Effort)
componentRepository.findByName(assetId).ifPresent(comp -> {
extras.put("dbId", comp.getId());
if (comp.getDescription() != null) {
extras.put("description", comp.getDescription());
}
if (comp.getTexture() != null) {
extras.put("texture", comp.getTexture());
}
// DB의 assetPath가 있으면 매핑 업데이트 (우선순위 부여)
if (comp.getAssetPath() != null) {
assetsMap.put(assetId, comp.getAssetPath());
}
});
return AssemblyRequestDto.AssemblyNodeDto.builder()
.name(nodeName)
.matrix(matrix)
.assetId(assetId)
.extras(extras)
.build();
}).collect(Collectors.toList());
AssemblyRequestDto.AssemblyRequestDtoBuilder requestBuilder = AssemblyRequestDto.builder()
.instances(instanceDtos)
.assets(assetsMap);
// 2-3. Scene-level extras (lookAt, note) 추가
// TODO: 추후 viewer 요구사항에 따라 lookAt, note 등의 메타데이터 주입 로직 구현 필요
// 현재는 userSceneRepository 조회 및 주입 로직을 생략함. (별도의 api로 note 정보는 제공 중)
AssemblyRequestDto requestDto = requestBuilder.build();
// 3. 임시 파일 및 스크립트 실행
try {
// Assets을 임시 디렉토리로 복사 (classpath에서)
// Node.js 스크립트는 파일 시스템 경로가 필요하므로, JAR 내부 리소스를 임시 폴더로 추출해야 함.
org.springframework.core.io.Resource[] assetResources = resourcePatternResolver
.getResources("classpath*:assets/" + assetPath + "/**");
if (assetResources.length == 0) {
log.warn("No assets found in classpath for scene: {}. Trying file system...", assetPath);
// Fallback to local file system if classpath fails (can happen in some test
// runners)
File localAssets = new File("src/main/resources/assets/" + assetPath);
if (localAssets.exists()) {
org.springframework.core.io.Resource[] localRes = Arrays.stream(localAssets.listFiles())
.map(org.springframework.core.io.FileSystemResource::new)
.toArray(org.springframework.core.io.Resource[]::new);
assetResources = localRes;
}
}
log.info("Found {} assets for scene {}", assetResources.length, assetPath);
File tempAssetsDir = Files.createTempDirectory("assets_" + sceneId + "_").toFile();
tempAssetsDir.deleteOnExit();
for (org.springframework.core.io.Resource res : assetResources) {
String filename = res.getFilename();
if (filename == null) {
continue;
}
// classpath 리소스 구조를 유지하며 복사할 수 있는지 확인 필요.
// classpath*:assets/Drone/Drone.gltf -> temp/Drone.gltf
// 여기서는 resource.getURI() 등을 파싱하거나, 단순 플랫하게 복사.
// 일단 플랫하게 복사한다고 가정 (하위 디렉토리 구조 복잡성 회피).
// 만약 하위 폴더가 중요하다면 계층 구조 파싱 필요.
// 현재 에셋 구조는 assets/{SceneName}/*.gltf 로 가정.
File destFile = new File(tempAssetsDir, filename);
if (!res.getURI().toString().endsWith("/")) { // 디렉토리가 아닌 경우만 복사
try (java.io.InputStream is = res.getInputStream()) {
Files.copy(is, destFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
}
}
File inputJson = File.createTempFile("assembly_req_" + userId + "_", ".json");
objectMapper.writeValue(inputJson, requestDto);
return executeNodeAssembly(inputJson, tempAssetsDir.getAbsolutePath());
} catch (IOException e) {
throw new RuntimeException("Failed to load assets or create temp file for export", e);
}
}
private byte[] executeNodeAssembly(File inputJson, String assetsDir) {
File workingDir = null;
try {
// Node.js 스크립트도 classpath에서 추출 필요
org.springframework.core.io.Resource scriptResource = resourcePatternResolver
.getResource("classpath:scripts/assemble_pro.js");
if (!scriptResource.exists()) {
throw new RuntimeException("Script not found: classpath:scripts/assemble_pro.js");
}
// ESM 의존성 해결을 위해 node_modules가 있는 곳 근처에 스크립트 배치 필요
File scriptDir = new File("src/main/resources/scripts"); // 로컬 기준
if (!scriptDir.exists()) {
scriptDir = new File("/app"); // Docker 기준
}
if (!scriptDir.exists()) {
scriptDir = new File(System.getProperty("java.io.tmpdir"));
}
File tempScript = File.createTempFile("assemble_pro_", ".js", scriptDir);
try (java.io.InputStream is = scriptResource.getInputStream()) {
Files.copy(is, tempScript.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
File outputFile = File.createTempFile("assembled_output_", ".gltf");
// assetsDir 내부에 .gltf 파일들이 있어야 함.
ProcessBuilder pb = new ProcessBuilder(
"node",
tempScript.getAbsolutePath(),
inputJson.getAbsolutePath(),
assetsDir,
outputFile.getAbsolutePath());
pb.redirectErrorStream(true);
// NODE_PATH 로그 남기기 (디버깅용)
log.debug("Executing node with NODE_PATH: {}", pb.environment().get("NODE_PATH"));
// 작업 디렉토리 설정 (선택 사항)
// pb.directory(new File("."));
// NODE_PATH 보정: 만약 환경 변수에 없으면 기본 경로 시도 (주로 로컬 테스트용)
String nodePath = pb.environment().get("NODE_PATH");
if (nodePath == null || nodePath.isEmpty()) {
// 현재 디렉토리 기준 src/main/resources/scripts/node_modules 시도
File localNodeModules = new File("src/main/resources/scripts/node_modules");
if (localNodeModules.exists()) {
pb.environment().put("NODE_PATH", localNodeModules.getAbsolutePath());
}
}
Process process = pb.start();
String output = new String(process.getInputStream().readAllBytes());
int exitCode = process.waitFor();
// Cleanup script
tempScript.delete();
if (exitCode != 0) {
log.error("Node.js assembly failed. Exit code: {}\nOutput: {}", exitCode, output);
inputJson.delete();
outputFile.delete();
throw new RuntimeException("GLTF assembly process failed.");
}
byte[] resultBytes = Files.readAllBytes(outputFile.toPath());
// Cleanup
inputJson.delete();
outputFile.delete();
return resultBytes;
} catch (IOException | InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Failed to execute Node.js assembly", e);
}
}
public byte[] getViewerZip(Long userId, Long sceneId, String target) {
SceneInformation scene = sceneRepository.findById(sceneId)
.orElseThrow(() -> new IllegalArgumentException("Scene not found"));
Map<String, byte[]> files = new HashMap<>();
String manifestJson = "{}";
Map<String, String> manifestMap = new HashMap<>();
boolean includeDefault = "both".equalsIgnoreCase(target) || "default".equalsIgnoreCase(target);
boolean includeCustom = "both".equalsIgnoreCase(target) || "custom".equalsIgnoreCase(target);
if (includeDefault) {
try {
byte[] defaultGltf = generateDefaultGltf(scene);
files.put("default.gltf", defaultGltf);
manifestMap.put("default", "default.gltf");
} catch (Exception e) {
log.error("Failed to generate default GLTF", e);
// Decide if we should fail hard or just skip.
// For now, let's allow partial success or fail hard depending on requirements.
// Assuming "Viewer" needs requested files, fail hard is safer to detect
// configs.
throw new RuntimeException("Failed to generate default GLTF", e);
}
}
if (includeCustom) {
try {
byte[] customGltf = exportAssembledGltf(userId, sceneId);
files.put("custom.gltf", customGltf);
manifestMap.put("custom", "custom.gltf");
} catch (Exception e) {
log.error("Failed to generate custom GLTF", e);
// If no custom state exists, maybe we shouldn't fail if default worked?
// But exportAssembledGltf throws if no alignments.
// Let's handle "No alignments" gracefully if needed, but for now rethrow.
throw e;
}
}
try {
manifestJson = objectMapper.writeValueAsString(manifestMap);
files.put("manifest.json", manifestJson.getBytes());
return createZip(files);
} catch (IOException e) {
throw new RuntimeException("Failed to create ZIP", e);
}
}
private byte[] generateDefaultGltf(SceneInformation scene) {
String assetPath = scene.getAssetPath();
String configPath = "classpath:assets/" + assetPath + "/config/assembly_config.json";
try {
org.springframework.core.io.Resource configResource = resourcePatternResolver.getResource(configPath);
if (!configResource.exists()) {
throw new RuntimeException("Default assembly config not found at: " + configPath);
}
File tempConfig = File.createTempFile("default_config_", ".json");
try (java.io.InputStream is = configResource.getInputStream()) {
// 기본 설정을 읽어서 DB 메타데이터와 결합
JsonNode root = objectMapper.readTree(is);
ArrayNode instances = (ArrayNode)root.get("instances");
if (instances != null) {
for (JsonNode instance : instances) {
ObjectNode node = (ObjectNode)instance;
String assetId = node.path("assetId").asText();
// assetId와 일치하는 컴포넌트 정보 검색 (베스트 에포트)
componentRepository.findByName(assetId).ifPresent(comp -> {
com.fasterxml.jackson.databind.node.ObjectNode extras = node.putObject("extras");
extras.put("dbId", comp.getId());
extras.put("description", comp.getDescription());
});
}
}
objectMapper.writeValue(tempConfig, root);
}
// Assets 임시 디렉토리 준비
org.springframework.core.io.Resource[] assetResources = resourcePatternResolver
.getResources("classpath*:assets/" + assetPath + "/**");
File tempAssetsDir = Files.createTempDirectory("assets_def_" + scene.getId() + "_").toFile();
tempAssetsDir.deleteOnExit();
for (org.springframework.core.io.Resource res : assetResources) {
String filename = res.getFilename();
if (filename == null) {
continue;
}
if (!res.getURI().toString().endsWith("/")) {
File destFile = new File(tempAssetsDir, filename);
try (java.io.InputStream is = res.getInputStream()) {
Files.copy(is, destFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
}
}
}
return executeNodeAssembly(tempConfig, tempAssetsDir.getAbsolutePath());
} catch (IOException e) {
throw new RuntimeException("Failed to prepare default config temp file", e);
}
}
private byte[] createZip(Map<String, byte[]> files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
for (Map.Entry<String, byte[]> entry : files.entrySet()) {
ZipEntry zipEntry = new ZipEntry(entry.getKey());
zos.putNextEntry(zipEntry);
zos.write(entry.getValue());
zos.closeEntry();
}
}
return baos.toByteArray();
}
private void processNode(User user, SceneInformation scene, SceneNodeDto node) {
String nodeName = node.getName(); // 예: "Arm_gear1"
String componentName = deriveComponentName(nodeName); // 예: "Arm gear"
// Component 조회 또는 생성
Component component = componentRepository.findByName(componentName)
.orElseGet(() -> {
log.info("Creating new component: {}", componentName);
return componentRepository.save(Component.builder()
.name(componentName)
.description("Auto-generated from assembly")
.build());
});
// Matrix 직렬화
String matrixJson;
try {
matrixJson = objectMapper.writeValueAsString(node.getMatrix());
} catch (JsonProcessingException e) {
log.error("Failed to serialize matrix for node: {}", nodeName, e);
throw new RuntimeException("Matrix serialization failed", e);
}
// 기존 Alignment 조회 또는 생성
Alignment alignment = alignmentRepository
.findByUserIdAndSceneIdAndNodeName(user.getId(), scene.getId(), nodeName)
.orElse(Alignment.builder()
.user(user)
.scene(scene)
.component(component)
.nodeName(nodeName)
.build());
// Matrix 업데이트 (필요 시 정의도)
// 신규 생성이면 Builder로 업데이트하지만, 기존이면 값을 설정해야 함.
// Alignment 엔티티는 Setters가 없음(Lombok @Value 또는 Getter/Builder).
// 따라서 다시 저장(save)해야 함. repo.save()는 ID가 있으면 업데이트함.
// 이미 조회했다면 ID가 있음.
// 업데이트를 위해 동일 ID를 가진 새 인스턴스를 생성해야 함.
Alignment toSave = Alignment.builder()
.id(alignment.getId()) // 신규면 null, 조회됐으면 기존 ID
.user(user)
.scene(scene)
.component(component)
.nodeName(nodeName)
.transformMatrix(matrixJson)
.build();
alignmentRepository.save(toSave);
}
private String extractSceneName(String filePath) {
// "Drone/Drone.gltf" -> "Drone"
// "Car.gltf" -> "Car"
if (filePath == null) {
return "";
}
String name = filePath;
int lastSlash = name.lastIndexOf('/');
if (lastSlash >= 0) {
name = name.substring(lastSlash + 1);
}
int dot = name.lastIndexOf('.');
if (dot >= 0) {
name = name.substring(0, dot);
}
return name;
}
private String deriveComponentName(String nodeName) {
// "Arm_gear1" -> "Arm gear"
if (nodeName == null) {
return "Unknown";
}
// Remove trailing numbers
String name = nodeName.replaceAll("\\d+$", "");
// Replace underscores with spaces
name = name.replace('_', ' ');
return name.trim();
}
}