149 Commits

Author SHA1 Message Date
Jedd Morgan b18e7a4149 Added CI workflow for marketplace deployment (#65) 2022-07-26 18:56:44 +01:00
JR-Morgan 41684060c0 Merge branch 'main' into graphql-improvements 2022-06-27 02:50:35 +01:00
JR-Morgan 3f612bfc9d Automation tests for graphql nodes 2022-06-27 02:48:52 +01:00
Jedd Morgan 3d6f16d52b Merge pull request #64 from specklesystems/graphql-improvements
Stream/Branch/Commit fetching editor UI and graphql blueprint
2022-06-27 01:58:07 +01:00
JR-Morgan 8e8beb1baf Stream/Branch/Commit fetching editor UI and graphql blueprint 2022-06-22 01:47:00 +01:00
Jedd Morgan 43a84bd7f6 Merge pull request #63 from specklesystems/stream-operations
Stream/Branch/Commit Fetching
2022-06-13 14:21:51 +01:00
JR-Morgan c908bd7152 Merge remote-tracking branch 'origin' into stream-operations 2022-06-10 03:38:36 +01:00
JR-Morgan 2857e87860 Generalised graphQL query code and removed globals fetching 2022-06-09 23:43:38 +01:00
JR-Morgan 8159860223 - Removed branch/stream/etc/ fetching from transports.
- Aligned names with .NET core.
- Added DP checks for error/edge cases.
- Tried to cleanup/reduce duplicated code.
2022-06-07 16:12:07 +01:00
Jedd Morgan 45266db151 Merge pull request #60 from specklesystems/cross-platform-build-fix
Fixed linux building with CLang compiler
2022-05-25 01:16:08 +01:00
JR-Morgan 8f38794dd1 Fixed linux building with CLang compiler 2022-05-24 17:10:43 +01:00
Dimitrios Ververidis 2431b33726 Fetch also collaborators with ReceiveStreamOperation 2022-05-24 16:03:03 +03:00
Dimitrios Ververidis 8b70cbba64 Receive Globals Operation : Done 2022-05-24 09:06:45 +03:00
Dimitrios Ververidis db2ba86e6d Receive My User Data also working 2022-05-23 16:16:36 +03:00
Dimitrios Ververidis 618d480acf Receive List of Commits done! 2022-05-23 12:42:16 +03:00
Dimitrios Ververidis 26d5afc2c0 Fetch Branches : Done ! 2022-05-20 14:47:38 +03:00
Dimitrios Ververidis dc0495dd24 Merge branch 'specklesystems:main' into main 2022-05-20 13:53:40 +03:00
Dimitrios Ververidis a75fb3a0c7 First Working version that receives all Streams 2022-05-20 09:52:35 +03:00
Dimitrios Ververidis 434c9a7b96 Managed to run my own ReceiveOperation for Streams 2022-05-19 18:25:52 +03:00
Dimitrios Ververidis aa400d19ee Try 3 Delegate 2022-05-19 17:54:04 +03:00
Dimitrios Ververidis 5f9eb61228 Minor 2022-05-18 13:58:37 +03:00
Dimitrios Ververidis 63bba7063c Try 1 List of Streams 2022-05-18 13:46:33 +03:00
Jedd Morgan b5076d5d7b Merge pull request #56 from specklesystems/marketplace
Fixed issue with receiving nested arrays from grashopper
2022-05-17 18:48:03 +01:00
JR-Morgan 2bacc0f1fb Fixed issue with receiving nested arrays from Grashopper 2022-05-17 18:38:40 +01:00
Dimitrios Ververidis da962e28f0 JSON list of Streams has been fetched 2022-05-17 15:42:57 +03:00
Dimitrios Ververidis 41a0d79229 Minor comments and line changes for easy reading 2022-05-17 09:27:19 +03:00
Dimitrios Ververidis 980fe124b2 Added some comments 2022-05-16 14:48:29 +03:00
JR-Morgan 4b31169776 Added copyright headder 2022-05-15 22:53:32 +01:00
JR-Morgan f2a035c23c Fixed fatal issue with static mesh conversion with overlapping quads/n-gons in UE5 2022-05-13 16:50:43 +01:00
JR-Morgan 68f6aea6d7 IWYU compatiblity with non-unity builds 2022-05-11 22:10:29 +01:00
Jedd Morgan d6a7bdfb28 Merge pull request #55 from specklesystems/UE5-fix
Fixed issues with UE 5.0.1
2022-05-10 22:54:03 +01:00
JR-Morgan 832df1ef65 Fixed build warnings 2022-05-10 22:43:55 +01:00
Jedd Morgan 0d97cc3e07 Merge pull request #54 from specklesystems/jrm/2.5.0-update
Progress bar + server transport rework!
2022-04-22 00:57:13 +01:00
JR-Morgan 7671523547 Fixed UE5 fast mesh build 2022-04-22 00:56:01 +01:00
JR-Morgan e109007a41 Progress bar + server transport rework! 2022-04-21 20:18:18 +01:00
JR-Morgan e4b8f786f8 Set MaterialConverter version from 5 to 4 2022-03-25 14:36:55 +00:00
Jedd Morgan 25c147aa7d Update README.md 2022-03-24 20:29:50 +00:00
Jedd Morgan 31bf9bbb2b Merge pull request #52 from specklesystems/converter-refactor
Tutorial update
2022-03-24 20:24:56 +00:00
JR-Morgan 81c702959e Merge branch 'converter-refactor' of https://github.com/specklesystems/speckle-unreal into converter-refactor 2022-03-24 20:00:11 +00:00
JR-Morgan f45d89346d Added IsValid check on material overrides in converter 2022-03-24 19:56:20 +00:00
JR-Morgan 9b68685cd3 Added IsValid check on material overrides in converter 2022-03-24 19:54:10 +00:00
JR-Morgan d1c744b188 Added camera converter, and RH->LH coordnate conversion now happens in converters. 2022-03-24 19:44:29 +00:00
Jedd Morgan 6f777a5f13 Merge pull request #45 from specklesystems/converter-refactor
Converter refactor
2022-03-17 01:52:35 +00:00
JR-Morgan a52de21d6f Metatag specifiers on converter 2022-03-16 23:34:20 +00:00
JR-Morgan b8d633d499 ProceduralMesh bug fixes 2022-03-15 17:34:31 +00:00
JR-Morgan 81206c63b3 Fixed bug with null render materials 2022-03-13 23:34:04 +00:00
JR-Morgan e18e622fa5 Base registrar is no longer a super class of Base
- Also added various comments etc.
2022-03-13 21:26:14 +00:00
JR-Morgan f0c7550477 Material converter is now an ISpeckleConverter 2022-03-11 01:11:04 +00:00
JR-Morgan f3a821ea95 Fixed blocks and point cloud conversion 2022-03-09 22:21:38 +00:00
JR-Morgan fd580cd2c5 Added blueprint receiving example. 2022-02-21 12:54:23 +00:00
JR-Morgan e528e2ba50 Reintroduced c++ manager and various polish 2022-02-21 13:24:49 +01:00
JR-Morgan ebb0fd83cb Added Blueprint implementation of Speckle Unreal Manager 2022-02-13 02:39:19 +00:00
JR-Morgan 7d7d605bd2 Fixing regressions 2022-02-13 02:17:06 +00:00
JR-Morgan aa8d17268e Fixed blueprint editor-time callback issue 2022-02-11 19:20:33 +00:00
JR-Morgan dca71560fe Async blueprint receive operations 2022-02-11 17:59:15 +00:00
JR-Morgan 52bcad5911 RenderMaterial abstraction 2022-02-08 23:44:52 +00:00
JR-Morgan 6af2765508 Converter Factory improvements 2022-02-08 00:27:33 +00:00
JR-Morgan 2827595511 Re implemented block conversion 2022-02-01 02:18:25 +00:00
JR-Morgan d6730b01fc Added support for DisplayValue object conversion 2022-01-31 21:54:23 +00:00
JR-Morgan 7601863e3c Refactor mostly complete, needs bug testing and blocks reimplementing 2022-01-11 01:27:18 +00:00
JR-Morgan 89b6b2bdfc Fixing converison to work with new deserialisation refactor 2022-01-10 23:32:25 +00:00
JR-Morgan c598aa787b Conversion refactor 2022-01-10 21:04:56 +00:00
JR-Morgan 4a451fec3b Deserialiser logic 2022-01-07 17:46:36 +00:00
JR-Morgan 1ff924eea4 Implementing SpeckleConverterComponent 2022-01-06 16:43:02 +00:00
Jedd Morgan 303eb7fb6a Merge pull request #42 from specklesystems/ue5-objects-fix
Ue5 objects fix
2022-01-05 21:20:00 +00:00
JR-Morgan 9ce2117a0a Moved all ConverterFactory classes into the same header file 2022-01-03 23:56:46 +00:00
JR-Morgan 2ac94215ee Reverted temporary change to texture coordinate scaling for webinar 2022-01-03 02:31:13 +00:00
JR-Morgan 2dac706ca5 Asset Factory classes for Conversion classes 2022-01-03 02:27:34 +00:00
JR-Morgan af950a569e Refactor of conversion functions to seperate conversion from native actors 2021-12-31 03:56:19 +00:00
JR-Morgan 6e900af1fa Temp changes for webinar 2021-12-08 14:30:16 +00:00
JR-Morgan 66741730e0 ditto 2021-12-07 17:00:04 +00:00
JR-Morgan a595b773ba Added explicit Category specifier for Objects member properties. 2021-12-07 16:56:13 +00:00
Jedd Morgan da1989d676 Merge pull request #40 from specklesystems/material-asset-fix
Fixed issue with materials assets not being properly created.
2021-12-01 20:55:03 +00:00
JR-Morgan a89655f7e0 Fixed issue with materials assets not being properly created. 2021-12-01 19:40:20 +00:00
Jedd Morgan a1c53ff063 Merge pull request #39 from specklesystems/ue5-build-test
UE5 Static Mesh Fix
2021-11-29 21:09:54 +00:00
JR-Morgan edafa74bac Ensured UE4 compatiblity 2021-11-29 20:59:52 +00:00
JR-Morgan 8ca9f46c8a Testing building with UE5 preview 2 2021-11-29 20:19:07 +00:00
Jedd Morgan f3d100bbcb Merge pull request #36 from specklesystems/point-cloud-fix
Point cloud fix
2021-11-23 15:34:57 +00:00
JR-Morgan bbe0a8eead Re-added inverted X for point cloud parsing 2021-11-23 15:32:39 +00:00
JR-Morgan cfead600a9 Merge remote-tracking branch 'origin/point-cloud-fix' 2021-11-23 15:24:55 +00:00
JR-Morgan 5a1c145cf2 Fixed issue with point clouds scaling incorrectly 2021-11-23 15:23:14 +00:00
Jedd Morgan c34f39d44c Merge pull request #35 from specklesystems/asset-PIE-fix
Asset registry on PIE fix
2021-11-23 15:22:53 +00:00
JR-Morgan 9982d55cfb Asset registry only in PIE fix 2021-11-23 13:16:18 +00:00
JR-Morgan 2f2bbd06e6 Scaling poing cloud size. 2021-11-23 13:06:20 +00:00
JR-Morgan bdbe31b429 Tided up class dependency declerationa 2021-11-21 23:54:56 +00:00
JR-Morgan 7a96022ad3 Merge branch 'main' of https://github.com/specklesystems/speckle-unreal into master 2021-11-20 17:12:47 +00:00
JR-Morgan 67b0a961a5 standalone build hotfix 2021-11-20 17:11:11 +00:00
Jedd Morgan 99d7a42c89 Merge pull request #30 from specklesystems/point-clouds2
Re-implemented pointcloud support
2021-11-19 21:31:56 +00:00
JR-Morgan 70b092050d Re-implemented pointcloud support 2021-11-19 21:25:07 +00:00
Jedd Morgan e4994a2612 Merge pull request #24 from specklesystems/lighting-performance2
Improved lighting performace by allowing meshes to import as `StaticMeshComponent`
2021-11-19 17:20:04 +00:00
JR-Morgan 9c87d944ea Merge remote-tracking branch 'origin' into lighting-performance2 2021-11-19 17:12:20 +00:00
Jedd Morgan 801b91b33f Merge pull request #28 from specklesystems/repo-restructure
Restructure repo to be uplugin rather than uproject
2021-11-19 17:00:30 +00:00
JR-Morgan 051fbd589f Fixed issues with non-editor builds 2021-11-18 23:01:39 +00:00
JR-Morgan 20a93d1c10 Implemented StaticMesh importing, slight issue with material reloading 2021-11-18 22:17:49 +00:00
JR-Morgan 877b9b7ecb Now using FEditorScriptExecutionGuard to allow editor calling of interface methods 2021-11-18 14:01:07 +00:00
JR-Morgan 02929d6904 Fixed issue with calling interface functions in editor 2021-11-18 13:58:17 +00:00
JR-Morgan 26706c6cbd Started refactor of project to allow for both Procedural and Static mesh conversion 2021-11-18 01:04:54 +00:00
JR-Morgan 746dadcc71 Restructured repo so uplugin is in root dir 2021-11-17 13:22:35 +00:00
Jedd Morgan fa3eec6f10 Merge pull request #27 from specklesystems/build-fix
Fixed issue with non-editor builds caused by call to SetActorLabel
2021-11-03 14:45:36 +00:00
JR-Morgan ad6cb36915 Fixed issue with non-editor builds caused by call to SetActorLabel 2021-11-03 14:38:11 +00:00
JR-Morgan c5ce7d37a5 Fixed asset package path not being unique for each mesh. 2021-10-31 21:16:51 +00:00
JR-Morgan 611470db41 Experimenting with Asset build options 2021-10-24 18:57:46 +01:00
JR-Morgan ce9980e408 Added local transformations to meshes 2021-10-22 21:05:13 +01:00
JR-Morgan 5f7a6573aa Added option to use full editor build process when creating meshes 2021-10-22 17:24:14 +01:00
JR-Morgan a1843dfb50 ASpeckleUnrealManager will now correctly handle edge case where its World is null when trying to Receive, for example, on scene reload 2021-10-20 15:26:29 +01:00
JR-Morgan 1f2b77c41c Fixed issue with runtime crashes due to incorrectly registered mesh assets 2021-10-20 14:49:40 +01:00
JR-Morgan 39ef6a70cf Experimentation with asset registery 2021-10-18 13:04:18 +01:00
JR-Morgan 5212528156 Merge branch 'master' into lighting-performance2 2021-10-15 17:24:34 +01:00
JR-Morgan 510ddd1c01 Added check for recieving invalid polygons to prevent assertion fail 2021-10-15 17:22:03 +01:00
JR-Morgan 8119083cab Added backwards compatibity for non-chunked mesh lists 2021-10-14 20:50:39 +01:00
Jedd Morgan 307993e648 Merge pull request #23 from specklesystems/analytics
Matomo tracking
2021-10-13 22:04:34 +01:00
JR-Morgan 8230ec2540 Added Matomo Analytics 2021-10-13 21:48:07 +01:00
JR-Morgan 0d38a533cc Added support for converting texture coordinates that are index by vertex index rather than sequentially 2021-10-13 20:21:55 +01:00
JR-Morgan f2fdf86e62 Fixed inverted normals 2021-10-13 13:07:17 +01:00
JR-Morgan 4c62bc3005 Added support for n-gon faces and fixed conversion of texture coordinates. 2021-10-13 12:34:19 +01:00
JR-Morgan 5d9bfaa19f User agent and IDs 2021-10-12 18:11:38 +01:00
JR-Morgan cebdca009c Static mesh building now works however, lighmap UVs are overlapping 2021-10-12 11:21:24 +01:00
JR-Morgan 7549927e67 Experimentation with Static Mesh generation 2021-10-11 00:50:16 +01:00
Jedd Morgan 80293fe975 Merge pull request #21 from specklesystems/texture-coords
Added support for Texture Coordinate conversion and Block Instances
2021-10-08 12:23:44 +01:00
JR-Morgan 2ba59cbfcc Fixed bug with actor initialisation order 2021-10-07 11:42:36 +01:00
JR-Morgan 9ed3d1713a Added WorldToMeter conversion allowing for custom world Units
- Also tidied up commented out code.
2021-10-06 20:30:03 +01:00
JR-Morgan 76444ced3c Tempoarly dissabled object caching due to regression caused by block instances 2021-10-06 14:47:48 +01:00
JR-Morgan 8d07def00f Fixed incorrect Normal conversion caused by left to right handed coordinate systems 2021-10-05 12:21:44 +01:00
JR-Morgan 3efc7a4c49 Block definitions with block instance children will now correctly be converted
- Fixed transform issues with left -> right handed coordinate system
 - Fixed issue with null texture-coordinate arrays not being handled.
2021-10-05 11:57:24 +01:00
JR-Morgan 267fafb5a4 Block Nesting 2021-10-04 13:37:41 +01:00
Matteo Cominetti 8b15e39ff7 Create close-issue.yml 2021-10-02 17:15:58 +01:00
Matteo Cominetti 75f4575813 Create open-issue.yml 2021-10-02 17:15:45 +01:00
JR-Morgan 5e491c622f Adding support for conversion of Block instances 2021-10-01 21:02:24 +01:00
JR-Morgan fdcc06c025 Added Support for UV texture-coordinate conversion 2021-09-30 21:21:59 +01:00
JR-Morgan 7ff7d66c5a Small refactor of object convertion to allow for other types of conversion other than mesh. 2021-09-19 07:36:36 +01:00
JR-Morgan fbdcf6a419 Updated default material opacity from 0 to 0.1 2021-09-16 13:23:08 +01:00
JR-Morgan adc64ac2b5 Updated default materials to include PBR properties 2021-09-16 13:19:30 +01:00
Jedd Morgan dbc36e5553 Merge pull request #16 from specklesystems/materials
Support for PBR Material conversion from Blender, Revit, and Rhino
2021-09-16 12:37:28 +01:00
JR-Morgan d1114770f7 Actor naming and removed unnessary null check for agent parenting. 2021-09-15 16:42:16 +01:00
Jedd Morgan 438a5990b1 Merge pull request #15 from specklesystems/object-chunking
Fix: Chunked object lists will now be correctly handled
2021-09-14 15:55:04 +01:00
JR-Morgan 5a70dda7bf Added material overriding by name, and identical converted materials will be reused. 2021-09-13 12:27:11 +01:00
JR-Morgan 51fcef121e Meshes with no RenderMaterial will take the RenderMaterial of their parent
- Allows support for materials from Revit
2021-09-10 12:44:18 +01:00
JR-Morgan dde7f0d08c Added support for overriding materials by name.
- Materials can be added to `SpeckleManager.MaterialOverrides : TMap` and will take priority over the Speckle `RenderMaterial` material.
2021-09-09 11:32:36 +01:00
JR-Morgan a73414f22e Material properties are now correctly converted.
- Fixed an issue caused by converting ARGB values to FColor
2021-09-08 18:07:17 +01:00
JR-Morgan 7e98e1aa28 Experimentation with material conversion 2021-09-08 16:52:11 +01:00
JR-Morgan c1924dce25 Chunked object lists will now be correctly handled
Added protected ASpeckleUnrealManager::CombineChunks function to combine chunked objects
2021-09-06 17:13:23 +01:00
Cristian Balas c9e978351d Merge pull request #1 from PanMig/RootActor
Spawning speckle meshes under a root actor
2021-05-06 12:59:57 +03:00
Panagiotis Migkotzidis 6a35f502b8 refactoring and BP_SpeckleManager
- BP SpeckleManager added in contents browser

- Speckle Manager code refactoring:

Spawning meshes under root is performed directly under the mesh creation process, rather that a separate method.

- Minor updates in the project solution
2021-05-05 13:49:18 +03:00
Panagiotis Migkotzidis ce1b5a5fe1 Root actor update
Places each imported speckle mesh under a root base actor, for easier transformation actions
2021-04-28 15:09:21 +03:00
Cristian Balas 295d0e67c6 Added a screencast in readme 2021-04-14 16:43:22 +03:00
Cristian Balas 789fba6a12 Added .vs to gitignore 2021-04-14 15:34:31 +03:00
Dimitrie Stefanescu d3c0e0699f Update LICENSE 2021-04-14 13:22:35 +01:00
Dimitrie Stefanescu d9afb5574f Update README.md 2021-04-14 13:21:22 +01:00
Cristian Balas 52a2a153ca Speckle v2 integration 2021-04-14 15:16:04 +03:00
134 changed files with 6386 additions and 792 deletions
+94
View File
@@ -0,0 +1,94 @@
version: 2.1
orbs:
aws-s3: circleci/aws-s3@2.0.0
commands:
zip-source:
parameters:
target:
type: string
outputdir:
type: string
steps:
- run:
name: "Create Archive"
command: |
\cp -r ".pluginconfig/<<parameters.target>>/." "./"
mkdir -p "<<parameters.outputdir>>/"
stashName=`git stash create`;
git archive -o "<<parameters.outputdir>>/speckle-unreal-UE<<parameters.target>>.zip" --worktree-attributes --prefix="speckle-unreal/" $stashName
jobs:
generate-source-zip:
docker:
- image: cimg/base:stable
parameters:
target:
type: string
steps:
- checkout
- zip-source:
target: <<parameters.target>>
outputdir: "output/unreal/<<parameters.target>>"
- store_artifacts:
path: "output/unreal/<<parameters.target>>"
destination: "unreal-marketplace/<<parameters.target>>"
- persist_to_workspace:
root: ./
paths:
- "output/unreal/<<parameters.target>>"
marketplace-deploy:
docker:
- image: cimg/base:stable
steps:
- attach_workspace:
at: ./
- aws-s3/copy:
arguments: "--recursive --endpoint=https://$SPACES_REGION.digitaloceanspaces.com --acl public-read"
aws-access-key-id: SPACES_KEY
aws-region: SPACES_REGION
aws-secret-access-key: SPACES_SECRET
from: '"output"'
to: s3://speckle-releases/installers/
workflows:
marketplace-publish:
jobs:
- generate-source-zip:
name: "Generate Source Archive UE4.26"
target: "4.26"
filters:
branches:
ignore: /.*/
tags:
only: /^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-\w+)?(\/all)?$/
- generate-source-zip:
name: "Generate Source Archive UE4.27"
target: "4.27"
filters:
branches:
ignore: /.*/
tags:
only: /^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-\w+)?(\/all)?$/
- generate-source-zip:
name: "Generate Source Archive UE5.0"
target: "5.0"
filters:
branches:
ignore: /.*/
tags:
only: /^([0-9]+)\.([0-9]+)\.([0-9]+)(?:-\w+)?(\/all)?$/
- hold:
type: approval
requires:
- "Generate Source Archive UE4.26"
- "Generate Source Archive UE4.27"
- "Generate Source Archive UE5.0"
- marketplace-deploy:
name: "Deploy to marketplace"
requires:
- hold
+4
View File
@@ -0,0 +1,4 @@
.gitattributes export-ignore
.github/* export-ignore
.circleci/* export-ignore
.pluginconfig/* export-ignore
+78
View File
@@ -0,0 +1,78 @@
name: Update issue Status
on:
issues:
types: [closed]
jobs:
update_issue:
runs-on: ubuntu-latest
steps:
- name: Get project data
env:
GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}}
ORGANIZATION: specklesystems
PROJECT_NUMBER: 9
run: |
gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query='
query($org: String!, $number: Int!) {
organization(login: $org){
projectNext(number: $number) {
id
fields(first:20) {
nodes {
id
name
settings
}
}
}
}
}' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json
echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
echo "$PROJECT_ID"
echo "$STATUS_FIELD_ID"
echo 'DONE_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .settings | fromjson | .options[] | select(.name== "Done") | .id' project_data.json) >> $GITHUB_ENV
echo "$DONE_ID"
- name: Add Issue to project #it's already in the project, but we do this to get its node id!
env:
GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}}
ISSUE_ID: ${{ github.event.issue.node_id }}
run: |
item_id="$( gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query='
mutation($project:ID!, $id:ID!) {
addProjectNextItem(input: {projectId: $project, contentId: $id}) {
projectNextItem {
id
}
}
}' -f project=$PROJECT_ID -f id=$ISSUE_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
- name: Update Status
env:
GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}}
ISSUE_ID: ${{ github.event.issue.node_id }}
run: |
gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query='
mutation($project:ID!, $status:ID!, $id:ID!, $value:String!) {
set_status: updateProjectNextItemField(
input: {
projectId: $project
itemId: $id
fieldId: $status
value: $value
}
) {
projectNextItem {
id
}
}
}' -f project=$PROJECT_ID -f status=$STATUS_FIELD_ID -f id=$ITEM_ID -f value=${{ env.DONE_ID }}
+50
View File
@@ -0,0 +1,50 @@
name: Move new issues into Project
on:
issues:
types: [opened]
jobs:
track_issue:
runs-on: ubuntu-latest
steps:
- name: Get project data
env:
GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}}
ORGANIZATION: specklesystems
PROJECT_NUMBER: 9
run: |
gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query='
query($org: String!, $number: Int!) {
organization(login: $org){
projectNext(number: $number) {
id
fields(first:20) {
nodes {
id
name
settings
}
}
}
}
}' -f org=$ORGANIZATION -F number=$PROJECT_NUMBER > project_data.json
echo 'PROJECT_ID='$(jq '.data.organization.projectNext.id' project_data.json) >> $GITHUB_ENV
echo 'STATUS_FIELD_ID='$(jq '.data.organization.projectNext.fields.nodes[] | select(.name== "Status") | .id' project_data.json) >> $GITHUB_ENV
- name: Add Issue to project
env:
GITHUB_TOKEN: ${{secrets.GHPROJECT_TOKEN}}
ISSUE_ID: ${{ github.event.issue.node_id }}
run: |
item_id="$( gh api graphql --header 'GraphQL-Features: projects_next_graphql' -f query='
mutation($project:ID!, $id:ID!) {
addProjectNextItem(input: {projectId: $project, contentId: $id}) {
projectNextItem {
id
}
}
}' -f project=$PROJECT_ID -f id=$ISSUE_ID --jq '.data.addProjectNextItem.projectNextItem.id')"
echo 'ITEM_ID='$item_id >> $GITHUB_ENV
+7 -6
View File
@@ -31,9 +31,10 @@
*.out
*.app
*.umap
SpeckleUnrealProject/Binaries/
SpeckleUnrealProject/Intermediate/
SpeckleUnrealProject/Plugins/SpeckleUnreal/Binaries/
SpeckleUnrealProject/Plugins/SpeckleUnreal/Intermediate/
SpeckleUnrealProject/Saved/
SpeckleUnrealProject/.vs/
Binaries/
Intermediate/
Saved/
.idea/
.vs/
+42
View File
@@ -0,0 +1,42 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "2.6.0",
"FriendlyName": "Speckle Unreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the MIT license, is customizable, and available in the cloud or via a self-hosted server. It allows users to exchange data between various AEC modelling and content creation platforms.",
"Category": "AEC",
"CreatedBy": "Speckle",
"CreatedByURL": "https://speckle.systems/",
"DocsURL": "https://github.com/specklesystems/speckle-unreal",
"MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81",
"SupportURL": "https://speckle.community/",
"CanContainContent": true,
"IsBetaVersion": true,
"IsExperimentalVersion": false,
"Installed": false,
"EngineVersion": "4.26",
"Modules": [
{
"Name": "SpeckleUnreal",
"Type": "Runtime",
"LoadingPhase": "Default",
"WhitelistPlatforms": [ "Win64", "Linux", "Mac" ]
},
{
"Name": "SpeckleUnrealEditor",
"Type": "Editor",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [ "Win64", "Linux", "Mac" ]
}
],
"Plugins": [
{
"Name": "ProceduralMeshComponent",
"Enabled": true
},
{
"Name": "LidarPointCloud",
"Enabled": true
}
]
}
+42
View File
@@ -0,0 +1,42 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "2.6.0",
"FriendlyName": "Speckle Unreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the MIT license, is customizable, and available in the cloud or via a self-hosted server. It allows users to exchange data between various AEC modelling and content creation platforms.",
"Category": "AEC",
"CreatedBy": "Speckle",
"CreatedByURL": "https://speckle.systems/",
"DocsURL": "https://github.com/specklesystems/speckle-unreal",
"MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81",
"SupportURL": "https://speckle.community/",
"CanContainContent": true,
"IsBetaVersion": true,
"IsExperimentalVersion": false,
"Installed": false,
"EngineVersion": "4.27",
"Modules": [
{
"Name": "SpeckleUnreal",
"Type": "Runtime",
"LoadingPhase": "Default",
"WhitelistPlatforms": [ "Win64", "Linux", "Mac" ]
},
{
"Name": "SpeckleUnrealEditor",
"Type": "Editor",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [ "Win64", "Linux", "Mac" ]
}
],
"Plugins": [
{
"Name": "ProceduralMeshComponent",
"Enabled": true
},
{
"Name": "LidarPointCloud",
"Enabled": true
}
]
}
+42
View File
@@ -0,0 +1,42 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "2.6.0",
"FriendlyName": "Speckle Unreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the MIT license, is customizable, and available in the cloud or via a self-hosted server. It allows users to exchange data between various AEC modelling and content creation platforms.",
"Category": "AEC",
"CreatedBy": "Speckle",
"CreatedByURL": "https://speckle.systems/",
"DocsURL": "https://github.com/specklesystems/speckle-unreal",
"MarketplaceURL": "com.epicgames.launcher://ue/marketplace/product/98770ce9d4f143de8dd7882a707a6f81",
"SupportURL": "https://speckle.community/",
"CanContainContent": true,
"IsBetaVersion": true,
"IsExperimentalVersion": false,
"Installed": false,
"EngineVersion": "5.0",
"Modules": [
{
"Name": "SpeckleUnreal",
"Type": "Runtime",
"LoadingPhase": "Default",
"WhitelistPlatforms": [ "Win64", "Linux", "Mac" ]
},
{
"Name": "SpeckleUnrealEditor",
"Type": "Editor",
"LoadingPhase": "PostEngineInit",
"WhitelistPlatforms": [ "Win64", "Linux", "Mac" ]
}
],
"Plugins": [
{
"Name": "ProceduralMeshComponent",
"Enabled": true
},
{
"Name": "LidarPointCloud",
"Enabled": true
}
]
}
-3
View File
@@ -1,3 +0,0 @@
{
"CurrentProjectSetting": "No Configurations"
}
Binary file not shown.
Binary file not shown.
-8
View File
@@ -1,8 +0,0 @@
{
"ExpandedNodes": [
"",
"\\SpeckleUnreal",
"\\SpeckleUnreal\\Source"
],
"PreviewInSolutionExplorer": false
}
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+197 -17
View File
@@ -1,21 +1,201 @@
MIT License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2020 mobiusnode
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021 AEC Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+13 -35
View File
@@ -1,56 +1,34 @@
# SpeckleUnreal
# Speckle Unreal
[![Version](https://img.shields.io/badge/Version-v0.1.0-orange)](https://github.com/mobiusnode/SpeckleUnreal) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen)](http://makeapullrequest.com)
[![Twitter Follow](https://img.shields.io/twitter/follow/SpeckleSystems?style=social)](https://twitter.com/SpeckleSystems) [![Community forum users](https://img.shields.io/discourse/users?server=https%3A%2F%2Fspeckle.community&style=flat-square&logo=discourse&logoColor=white)](https://speckle.community) [![website](https://img.shields.io/badge/https://-speckle.systems-royalblue?style=flat-square)](https://speckle.systems) [![docs](https://img.shields.io/badge/docs-speckle.guide-orange?style=flat-square&logo=read-the-docs&logoColor=white)](https://speckle.guide/dev/)
Our Team is developing a Speckle plugin and interoperability transport schema for UE4. Our goal is to enable Revit/Dynamo and Rhino/Grasshopper to send + receive geometry to UE4 for visualization. Our current priority is to establish and release a data sender (TO UE4). Were also working on receiver methods, however our initial focus is on Rhino/Grasshopper to UE4 translation and the attachment of UE4-specific metadata to the core JSON blobs in transport.
Plugin for Unreal Engine to import objects from Speckle v2.
In this repository you will find the source code, assets and project settings of the SpeckleUnreal plugin for Unreal Engine app development (Unreal Engine 4.25.1 or newer recommended).
# Useful Links
Use the following links to access resources related to bug reporting, issues, feature requests, and general questions regarding SpeckleUnreal. Future releases may not contain these links & note.
Screencast of an example: https://user-images.githubusercontent.com/2551138/114720093-61403e00-9d40-11eb-8045-6e8ca656554d.mp4
## Speckle Unreal Server
https://speckle.mobiusnode.io
## Discourse Forums (Bugs, Issues, etc.)
https://discourse.mobiusnode.io
## SpeckleUnreal Slack Workspace
https://speckle-works-unreal.slack.com
## YouTub Demo & Tutorial - Getting Started
https://bit.ly/3ehHQE6
## NOTICE
* Tested on Windows and MacOS and Linux.
* Only displays meshes. Breps are converted using their display values.
* Our Unreal Connector is in an beta stage of development. Currently we only support receiving objects, and there is no UI to fetch lists of streams/commits/branches.
* We officially support Unreal Engine 4.26 and 4.27, and have experimental support for UE5.
* Does not use the Speckle Kit workflow as conversions all happen in C++.
## How To Install
1. Clone the repository or download it as a zip file.
2. Navigate to `SpeckleUnrealProject` > `Plugins` and copy the `SpeckleUnreal` folder
3. Paste the folder into your Unreal project under `YourUnrealProjectFolder` > `Plugins` (Create a `Plugins` folder if you don't already have one).
4. Reopen your project.
1. Download `speckle-unreal` repository archive from https://github.com/specklesystems/speckle-unreal/archive/refs/heads/main.zip
1. Extract the downloaded archive into your project's `Plugins` directory (if your project directory doesn't contain a directory called Plugins, you should create it)
1. Open your UE project (or restart the editor if you already have it opened). This will build the plugin in your environment.
We will eventually look to distributing the plugin officially on the Unreal Engine Marketplace but for now you'll need to install the plugin manually like this.
---
See our [docs](https://speckle.guide/user/unreal.html) for usage instructions.
## Roadmap
## Credits
Based off the original Unreal integration for Speckle v1 by Mark and Jak which can be found here: [https://github.com/mobiusnode/SpeckleUnreal](https://github.com/mobiusnode/SpeckleUnreal).
> Roadmap is subject to change. Last reviewed 10th of July 2020.
https://user-images.githubusercontent.com/2551138/114720051-571e3f80-9d40-11eb-9099-d3394747a1d3.mp4
| Version | Defining Feature |
| ------- | -------------------------------------------------------------------------------- |
| ~0.1~ | ~First prototype release as Unreal Engine plugin~ |
| 0.2 | New component workflow and custom materials assigned via inspector~ |
| 0.3 | Spawn geometry in transform heirarchy based on layer data |
| 0.4 | User login API, get Stream API and no dependency on a local install of Speckle |
| 0.5 | Rendering Rule API |
| 0.6 | Support Lines, Points, Numbers and Text|
| 0.7 | Local caching of Speckle streams |
| 0.8 | Implement Sender API |
| 1.0 | Production ready (out of preview) |
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

@@ -0,0 +1,192 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "API/ClientAPI.h"
#include "HttpModule.h"
#include "JsonObjectConverter.h"
#include "Interfaces/IHttpResponse.h"
#include "LogSpeckle.h"
#include "Mixpanel.h"
void FClientAPI::MakeGraphQLRequest(const FString& ServerUrl, const FString& AuthToken,
const FString& ResponsePropertyName,
const FString& PostPayload, const FString& RequestLogName,
const FAPIResponceDelegate OnCompleteAction, const FErrorDelegate OnErrorAction)
{
auto OnError = [=](const FString& Message) mutable
{
UE_LOG(LogSpeckle, Warning, TEXT("%s: failed - %s"), *RequestLogName , *Message);
ensureAlwaysMsgf(OnErrorAction.ExecuteIfBound(Message), TEXT("%s: Unhandled error - %s"), *RequestLogName , *Message);
};
auto ResponseHandler = [=](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable
{
if(CheckRequestFailed(bWasSuccessful, Response, RequestLogName, OnError)) return;
TSharedPtr<FJsonObject> Obj;
if(!GetResponseAsJSON(Response, RequestLogName, Obj, OnError)) return;
const TSharedPtr<FJsonObject>* DataObjectPtr;
if(!Obj->TryGetObjectField("data", DataObjectPtr))
{
OnError(TEXT("%s responce was invalid, expected to find a \"data\" property in response"));
return;
}
const TSharedPtr<FJsonObject> DataObject = *DataObjectPtr;
const TSharedPtr<FJsonObject>* RequestedJson;
if(!DataObject->TryGetObjectField(ResponsePropertyName, RequestedJson))
{
//Requested property has a null or non-object value
if(DataObject->HasField(ResponsePropertyName))
{
FString Message = FString::Printf(TEXT("%s: Response data contained the requested property \"%s\", but the value was null was or not an object."),
*RequestLogName, *ResponsePropertyName);
OnError(Message);
return;
}
//Requested property was missing
TArray<FString> Options;
Options.Reserve(DataObject->Values.Num());
for(const auto& Properties : DataObject->Values)
{
Options.Add(FString::Printf(TEXT("\"%s\" "), *Properties.Key));
}
FString Message = FString::Printf(TEXT("%s: Could not find the requested property name \"%s\" in responce data.\n Got { %s} instead."),
*RequestLogName, *ResponsePropertyName, *FString::Join(Options, TEXT(", ")));
OnError(Message);
return;
}
FString OutputString;
const TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&OutputString);
ensureAlways(FJsonSerializer::Serialize(RequestedJson->ToSharedRef(), Writer));
// Commented out, deserialisation done by caller
//void* DeserializedData;
//FSpeckleUser DeserializedData = FSpeckleUser( UserJSONObject );
// if(!FJsonObjectConverter::JsonObjectToUStruct(*RequestedJson, OutStructType::StaticStruct(), &DeserializedData, 0, 0))
// {
// OnError("Failed to deserialize user object");
// return;
// }
UE_LOG(LogSpeckle, Log, TEXT("Operation %s completed successfully"), *RequestLogName);
ensureAlwaysMsgf(OnCompleteAction.ExecuteIfBound(OutputString), TEXT("%s: Complete handler was not bound properly"), *RequestLogName);
};
const FHttpRequestRef Request = CreatePostRequest(ServerUrl, AuthToken, PostPayload);
Request->OnProcessRequestComplete().BindLambda(ResponseHandler);
if(Request->ProcessRequest())
{
UE_LOG(LogSpeckle, Log, TEXT("POST Request %s to %s was sent, awaiting response"), *RequestLogName, *Request->GetURL() );
}
else
{
UE_LOG(LogSpeckle, Warning, TEXT("POST Request %s to %s failed to send"), *RequestLogName, *Request->GetURL() );
}
FAnalytics::TrackEvent(Request->GetURL(), "NodeRun", TMap<FString, FString> { {"name", __FUNCTION__}});
}
bool FClientAPI::GetResponseAsJSON(const FHttpResponsePtr Response, const FString& RequestLogName, TSharedPtr<FJsonObject>& OutObject, const TFunctionRef<void(const FString& Message)> OnErrorAction)
{
const FString JsonResponse = Response->GetContentAsString();
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(JsonResponse);
if(!FJsonSerializer::Deserialize(Reader, OutObject))
{
const FString Message = FString::Printf(
TEXT("Recieved a response from \"%s\" for \"%s\" request, but the response failed to deserialize: %s"),
*Response->GetURL(), *RequestLogName, *JsonResponse);
OnErrorAction(Message);
return false;
}
FString Error;
if(CheckForOperationErrors(OutObject, Error))
{
OnErrorAction(Error);
return false;
}
return true;
}
FHttpRequestRef FClientAPI::CreatePostRequest(const FString& ServerUrl, const FString AuthToken, const FString& PostPayload, const FString& Encoding)
{
FHttpRequestRef Request = FHttpModule::Get().CreateRequest();
Request->SetURL(ServerUrl + "/graphql");
Request->SetVerb(TEXT("POST"));
Request->SetHeader("Accept-Encoding", Encoding);
Request->SetHeader("Content-Type", TEXT("application/json"));
Request->SetHeader("Authorization", "Bearer " + AuthToken);
Request->SetContentAsString(PostPayload);
return Request;
}
bool FClientAPI::CheckRequestFailed(bool bWasSuccessful, FHttpResponsePtr Response, const FString& RequestLogName, const TFunctionRef<void(const FString& Message)> OnErrorAction)
{
//Check the request was sent
if(!bWasSuccessful)
{
FString Message = FString::Printf(TEXT("Request \"%s\" to \"%s\" was unsuccessful: %s"),
*RequestLogName, *Response->GetURL(), *Response->GetContentAsString());
OnErrorAction(Message);
return true;
}
//Check Response code
const int32 ResponseCode = Response->GetResponseCode();
if (ResponseCode != 200)
{
FString Message = FString::Printf(TEXT("Request \"%s\" to \"%s\" failed with HTTP response %d - %s"),
*RequestLogName, *Response->GetURL(), ResponseCode, *Response->GetContentAsString());
OnErrorAction(Message);
return true;
}
UE_LOG(LogSpeckle, Log, TEXT("Operation %s recieved a response from %s"), *RequestLogName, *Response->GetURL());
return false;
}
bool FClientAPI::CheckForOperationErrors(const TSharedPtr<FJsonObject> GraphQLResponse, FString& OutErrorMessage)
{
check(GraphQLResponse != nullptr);
bool WasError = false;
const TArray<TSharedPtr<FJsonValue>>* Errors;
if(GraphQLResponse->TryGetArrayField(TEXT("errors"), Errors))
{
for(const TSharedPtr<FJsonValue>& e : *Errors)
{
FString Message;
const TSharedPtr<FJsonObject>* ErrorObject;
bool HadMessage = e->TryGetObject(ErrorObject)
&& (*ErrorObject)->TryGetStringField("message", Message);
if(!HadMessage)
{
Message = "An operation error occured but had no message!\n";
UE_LOG(LogSpeckle, Warning, TEXT("%s"), *Message);
}
OutErrorMessage.Append(Message + "\n");
WasError = true;
}
}
return WasError;
}
@@ -0,0 +1,92 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "API/Operations/ReceiveOperation.h"
#include "Dom/JsonObject.h"
#include "Transports/Transport.h"
#include "API/SpeckleSerializer.h"
#include "Objects/Base.h"
#include "Mixpanel.h"
UReceiveOperation* UReceiveOperation::ReceiveOperation(UObject* WorldContextObject,
const FString& ObjectId,
TScriptInterface<ITransport> RemoteTransport,
TScriptInterface<ITransport> LocalTransport)
{
UReceiveOperation* Node = NewObject<UReceiveOperation>();
Node->ObjectId = ObjectId;
Node->RemoteTransport = RemoteTransport;
Node->LocalTransport = LocalTransport;
Node->RegisterWithGameInstance(WorldContextObject);
return Node;
}
void UReceiveOperation::Activate()
{
FAnalytics::TrackEvent("unknown", "NodeRun", TMap<FString, FString> { {"name", StaticClass()->GetName()} });
Receive();
}
void UReceiveOperation::Receive()
{
check(LocalTransport != nullptr);
// 1. Try and get object from local transport
auto Obj = LocalTransport->GetSpeckleObject(ObjectId);
if (Obj != nullptr )
{
HandleReceive(Obj);
return;
}
// 2. Try and get object from remote transport
if(RemoteTransport == nullptr)
{
FString ErrorMessage = TEXT(
"Could not find specified object using the local transport, and you didn't provide a fallback remote from which to pull it.");
HandleError(ErrorMessage);
return;
}
FTransportCopyObjectCompleteDelegate CompleteDelegate;
CompleteDelegate.BindUObject(this, &UReceiveOperation::HandleReceive);
FTransportErrorDelegate ErrorDelegate;
ErrorDelegate.BindUObject(this, &UReceiveOperation::HandleError);
RemoteTransport->CopyObjectAndChildren(ObjectId, LocalTransport, CompleteDelegate, ErrorDelegate);
}
void UReceiveOperation::HandleReceive(TSharedPtr<FJsonObject> Object)
{
check(IsInGameThread())
FEditorScriptExecutionGuard ScriptGuard;
if(Object == nullptr)
{
OnError.Broadcast(nullptr, FString::Printf(TEXT("Failed to get object %s from transport"), *ObjectId));
}
else
{
UBase* Res = USpeckleSerializer::DeserializeBase(Object, LocalTransport);
if(IsValid(Res))
OnReceiveSuccessfully.Broadcast(Res, "");
else
OnError.Broadcast(nullptr, FString::Printf(TEXT("Root Speckle Object %s failed to deserialize"), *ObjectId));
}
SetReadyToDestroy();
}
void UReceiveOperation::HandleError(FString& Message)
{
FEditorScriptExecutionGuard ScriptGuard;
OnError.Broadcast(nullptr, Message);
SetReadyToDestroy();
}
@@ -0,0 +1,22 @@
#include "API/Operations/SendOperation.h"
// USendOperation* USendOperation::SendOperation(UObject* WorldContextObject, UBase* Base, TScriptArray<TScriptInterface<ITransport>> Transports)
// {
// USendOperation* Node = NewObject<USendOperation>();
// Node->Base = Base;
// Node->Transports = Transports;
//
// Node->RegisterWithGameInstance(WorldContextObject);
// return Node;
// }
//
// void USendOperation::Activate()
// {
// check(Transports.Num() > 0);
//
// //TODO implement
// unimplemented();
//
// }
@@ -0,0 +1,69 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "API/Operations/SpeckleStreamAPIOperation.h"
#include "JsonObjectConverter.h"
#include "Mixpanel.h"
#include "LogSpeckle.h"
#include "API/ClientAPI.h"
USpeckleStreamAPIOperation* USpeckleStreamAPIOperation::SpeckleStreamAPIOperation(
const FString& ServerUrl,
const FString& AuthToken,
const FString& GraphQlQuery,
const FString& ResponsePropertyName,
const FString& RequestLogName)
{
USpeckleStreamAPIOperation* Node = NewObject<USpeckleStreamAPIOperation>();
Node->ServerUrl = ServerUrl.TrimEnd();
Node->AuthToken = AuthToken.TrimEnd();
Node->Query = GraphQlQuery;
Node->ResponsePropertyName = ResponsePropertyName;
Node->RequestLogName = RequestLogName;
return Node;
}
void USpeckleStreamAPIOperation::Activate()
{
FAnalytics::TrackEvent(ServerUrl, "NodeRun", TMap<FString, FString> { {"name", RequestLogName} });
Request();
}
void USpeckleStreamAPIOperation::Request()
{
FString Payload = FString::Printf(TEXT("{\"query\": \"%s\"}"), *Query.ReplaceCharWithEscapedChar());
FAPIResponceDelegate CompleteDelegate;
CompleteDelegate.BindUObject(this, &USpeckleStreamAPIOperation::HandleReceive);
FErrorDelegate ErrorDelegate;
ErrorDelegate.BindUObject(this, &USpeckleStreamAPIOperation::HandleError);
FClientAPI::MakeGraphQLRequest(ServerUrl, AuthToken, ResponsePropertyName, Payload,RequestLogName , CompleteDelegate, ErrorDelegate);
}
void USpeckleStreamAPIOperation::HandleReceive(const FString& ResponseJson)
{
check(IsInGameThread());
UE_LOG(LogSpeckle, Log, TEXT("%s to %s Succeeded"), *StaticClass()->GetName(), *ServerUrl);
FEditorScriptExecutionGuard ScriptGuard;
OnReceiveSuccessfully.Broadcast(ResponseJson, "");
SetReadyToDestroy();
}
void USpeckleStreamAPIOperation::HandleError(const FString& Message)
{
check(IsInGameThread());
UE_LOG(LogSpeckle, Warning, TEXT("%s failed - %s"), *StaticClass()->GetName(), *Message);
FEditorScriptExecutionGuard ScriptGuard;
OnError.Broadcast("", Message);
SetReadyToDestroy();
}
@@ -0,0 +1,60 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "API/SpeckleAPIFunctions.h"
#include "JsonObjectConverter.h"
bool USpeckleAPIFunctions::DeserializeResponse(const FString& JsonString, int32& OutStruct)
{
// We should never hit this! stubs to avoid NoExport on the class.
check(0);
return false;
}
bool USpeckleAPIFunctions::GenericDeserializeResponse(const FString& JsonString, const UScriptStruct* StructType,
void* OutStruct)
{
//see FJsonObjectConverter::JsonObjectStringToUStruct
TSharedPtr<FJsonObject> JsonObject;
TSharedRef<TJsonReader<> > JsonReader = TJsonReaderFactory<>::Create(JsonString);
if (!FJsonSerializer::Deserialize(JsonReader, JsonObject) || !JsonObject.IsValid())
{
UE_LOG(LogJson, Warning, TEXT("JsonObjectStringToUStruct - Unable to parse json=[%s]"), *JsonString);
return false;
}
if (!FJsonObjectConverter::JsonObjectToUStruct(JsonObject.ToSharedRef(), StructType, OutStruct, 0, 0))
{
UE_LOG(LogJson, Warning, TEXT("JsonObjectStringToUStruct - Unable to deserialize. json=[%s]"), *JsonString);
return false;
}
return true;
}
void USpeckleAPIFunctions::CommitReceived(FSpeckleCommit& Commit)
{
//TODO send read read receipt
//FString Query = FString::Printf(TEXT("mutation{ commitReceive(input:%s) }"), );
}
DEFINE_FUNCTION(USpeckleAPIFunctions::execDeserializeResponse)
{
// Get JsonString
P_GET_PROPERTY(FStrProperty, JsonString);
// Get OutStruct
Stack.MostRecentPropertyAddress = nullptr;
Stack.StepCompiledIn<FStructProperty>(nullptr);
void* OutBlueprintDataPtr = Stack.MostRecentPropertyAddress;
FStructProperty* StructProp = CastField<FStructProperty>(Stack.MostRecentProperty);
UScriptStruct* StructType = StructProp->Struct;
P_FINISH;
P_NATIVE_BEGIN;
*static_cast<bool*>(RESULT_PARAM) = GenericDeserializeResponse(JsonString, StructType, OutBlueprintDataPtr);
P_NATIVE_END;
}
@@ -0,0 +1,68 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "API/SpeckleSerializer.h"
#include "Objects/Base.h"
#include "LogSpeckle.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Objects/ObjectModelRegistry.h"
#include "Templates/SubclassOf.h"
#include "Transports/Transport.h"
#include "UObject/Package.h"
UBase* USpeckleSerializer::DeserializeBase(const TSharedPtr<FJsonObject> Obj,
const TScriptInterface<ITransport> ReadTransport)
{
if(Obj == nullptr) return nullptr;
// Handle Detached Objects
TSharedPtr<FJsonObject> DetachedObject;
if(USpeckleObjectUtils::ResolveReference(Obj, ReadTransport, DetachedObject))
{
return DeserializeBase(DetachedObject, ReadTransport);
}
FString SpeckleType;
if (!Obj->TryGetStringField("speckle_type", SpeckleType)) return nullptr;
FString ObjectId = "";
Obj->TryGetStringField("id", ObjectId);
TSubclassOf<UBase> BaseType;
FString WorkingType(SpeckleType);
int32 Tries = 1000;
while(ensure(Tries-- > 0))
{
//Try and deserialize
if(UObjectModelRegistry::TryGetRegisteredType(WorkingType, BaseType))
{
UBase* Base = NewObject<UBase>(GetTransientPackage(), BaseType);
if(Base->Parse(Obj, ReadTransport))
return Base;
}
//If we couldn't even deserialize this to a Base
if(WorkingType == "Base" || BaseType == UBase::StaticClass())
{
UE_LOG(LogSpeckle, Warning, TEXT("Skipping deserilization of %s id: %s - object could not be deserilaized to Base"), *SpeckleType, *ObjectId );
return nullptr;
}
//Try the next type
if(!UObjectModelRegistry::ParentType(WorkingType, WorkingType))
{
WorkingType = "Base";
UE_LOG(LogSpeckle, Verbose, TEXT("Unrecognised SpeckleType %s - Object id: %s Will be deserialized as Base"), *SpeckleType, *ObjectId );
}
}
return nullptr;
}
UBase* USpeckleSerializer::DeserializeBaseById(const FString& ObjectId,
const TScriptInterface<ITransport> ReadTransport)
{
auto Obj = ReadTransport->GetSpeckleObject(ObjectId);
return DeserializeBase(Obj, ReadTransport);
}
@@ -0,0 +1,96 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Mixpanel.h"
#include "Containers/UnrealString.h"
#include "HttpModule.h"
#include "Kismet/GameplayStatics.h"
#include "LogSpeckle.h"
#include "Interfaces/IHttpResponse.h"
#include "Launch/Resources/Version.h"
#include "Misc/Base64.h"
#include "Policies/CondensedJsonPrintPolicy.h"
#include "Serialization/JsonSerializerMacros.h"
#include "Serialization/JsonWriter.h"
const FString FAnalytics::MixpanelToken = TEXT("acd87c5a50b56df91a795e999812a3a4");
const FString FAnalytics::MixpanelServer = TEXT("https://analytics.speckle.systems");
const FString FAnalytics::VersionedApplicationName = FString::Printf(TEXT("Unreal Engine %d.%d"), ENGINE_MAJOR_VERSION, ENGINE_MINOR_VERSION);
void FAnalytics::TrackEvent(const FString& Server, const FString& EventName)
{
#if !SUPPRESS_SPECKLE_ANALYTICS
const TMap<FString, FString> CustomProperties;
TrackEvent( Server, EventName, CustomProperties);
#endif
}
void FAnalytics::TrackEvent(const FString& Server, const FString& EventName, const TMap<FString, FString>& CustomProperties)
{
#if !SUPPRESS_SPECKLE_ANALYTICS
//Since we don't have access to users email address, we will hash the system user name instead (better than not tracking users at all)
const FString Email = FString(FGenericPlatformProcess::ComputerName()) + FString(FGenericPlatformProcess::UserName());
TrackEvent(Email, Server, EventName, CustomProperties);
#endif
}
void FAnalytics::TrackEvent(const FString& Email, const FString& Server, const FString& EventName, const TMap<FString, FString>& CustomProperties)
{
#if !SUPPRESS_SPECKLE_ANALYTICS
FString HashedEmail = "@" + Hash(Email); //prepending an @ so we distinguish logged and non-logged users
FString HashedServer = Hash(Server);
TMap<FString, FString> Properties
{
{ "distinct_id", HashedEmail },
{ "server_id", HashedServer },
{ "token", MixpanelToken },
{ "hostApp", "Unreal Engine" },
{ "hostAppVersion", VersionedApplicationName },
{ "$os", *UGameplayStatics::GetPlatformName() },
{ "type", "action" }
};
Properties.Append(CustomProperties);
FString Json;
{
auto Writer = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&Json);
FJsonSerializerWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>> Serializer(Writer);
Serializer.StartObject();
FString EventNameString = EventName;
Serializer.Serialize(TEXT("event"), EventNameString);
Serializer.SerializeMap(TEXT("properties"), Properties);
Serializer.EndObject();
Writer->Close();
}
const FString Data = FBase64::Encode(Json);
// Create Request
const FHttpRequestRef Request = FHttpModule::Get().CreateRequest();
{
Request->SetURL(MixpanelServer + "/track?ip=1&data=" + Data);
Request->SetHeader("Content-Type", "application/x-www-form-urlencoded");
Request->SetHeader("Accept", TEXT("text/plain"));
Request->SetVerb("POST");
}
Request->OnProcessRequestComplete().BindLambda([](FHttpRequestPtr, FHttpResponsePtr Response, bool)
{
UE_LOG(LogSpeckle, Verbose, TEXT("Recieved Mixpanel resonse %d"), Response->GetResponseCode());
});
const bool RequestSent = Request->ProcessRequest();
if(!RequestSent)
{
UE_LOG(LogSpeckle, Log, TEXT("Failed to send Mixpanel event to %s"), *MixpanelServer);
}
#endif
}
FString FAnalytics::Hash(const FString& Input)
{
return FMD5::HashAnsiString(*Input.ToLower());
}
@@ -0,0 +1,138 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Conversion/Converters/AggregateConverter.h"
#include "LogSpeckle.h"
#include "Templates/SubclassOf.h"
void UAggregateConverter::OnConvertersChangeHandler()
{
SpeckleTypeMap.Empty();
for(int i = 0; i < SpeckleConverters.Num(); i++)
{
const UObject* Converter = SpeckleConverters[i];
if(Converter != nullptr && !Converter->GetClass()->ImplementsInterface(USpeckleConverter::StaticClass()))
{
UE_LOG(LogSpeckle, Warning, TEXT("Converter {%s} is not a valid converter, Expected to implement interface %s"), *Converter->GetClass()->GetName(), *USpeckleConverter::StaticClass()->GetName())
SpeckleConverters.RemoveAt(i);
i--;
}
}
}
#if WITH_EDITOR
void UAggregateConverter::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
if (PropertyChangedEvent.GetPropertyName() == GET_MEMBER_NAME_CHECKED(UAggregateConverter, SpeckleConverters))
{
OnConvertersChangeHandler();
}
}
#endif
UBase* UAggregateConverter::ConvertToSpeckle_Implementation(const UObject* Object)
{
//TODO implement ToSpeckle
unimplemented();
return nullptr;
}
UObject* UAggregateConverter::ConvertToNative_Implementation(const UBase* Object, UWorld* World, TScriptInterface<ISpeckleConverter>& )
{
return ConvertToNativeInternal(Object, World);
}
UObject* UAggregateConverter::ConvertToNativeInternal(const UBase* Object, UWorld* World)
{
check(IsInGameThread());
if(!IsValid(Object)) return nullptr;
const TSubclassOf<UBase> Type = Object->GetClass();
UObject* Converter = GetConverter(Type).GetObject();
if(!IsValid(Converter))
{
if(Type != UBase::StaticClass())
{
UE_LOG(LogSpeckle, Warning, TEXT("Skipping Object %s: No conversion functions exist for %s"), *Object->Id, *Type->GetName());
}
return nullptr;
}
UE_LOG(LogSpeckle, Log, TEXT("Converting object of type: %s id: %s"), *Type->GetName(), *Object->Id);
FEditorScriptExecutionGuard ScriptGuard;
TScriptInterface<ISpeckleConverter> MainConverter = this;
check(Converter->IsValidLowLevel());
return Execute_ConvertToNative(Converter, Object, World, MainConverter);
}
bool UAggregateConverter::CanConvertToNative_Implementation(TSubclassOf<UBase> BaseType)
{
return GetConverter(BaseType).GetInterface() != nullptr;
}
TScriptInterface<ISpeckleConverter> UAggregateConverter::GetConverter(const TSubclassOf<UBase> BaseType)
{
// Check if this SpeckleType has a known converter.
if(SpeckleTypeMap.Contains(BaseType))
{
return SpeckleTypeMap[BaseType];
}
// Try and find one that can convert this SpeckleType.
FEditorScriptExecutionGuard ScriptGuard;
for(UObject* Converter : SpeckleConverters)
{
if(!CheckValidConverter(Converter)) continue;
if(Execute_CanConvertToNative(Converter, BaseType))
{
//Found a Converter! Save this mapping for next time.
SpeckleTypeMap.Add(BaseType, Converter);
return Converter;
}
}
// SpeckleType has no conversions.
SpeckleTypeMap.Add(BaseType, nullptr);
return nullptr;
}
void UAggregateConverter::FinishConversion_Implementation()
{
FinishConversion_Internal();
}
void UAggregateConverter::FinishConversion_Internal()
{
for (UObject* Converter : SpeckleConverters)
{
if(!CheckValidConverter(Converter)) continue;
Execute_FinishConversion(Converter);
}
OnConvertersChangeHandler();
}
bool UAggregateConverter::CheckValidConverter(const UObject* Converter, bool LogWarning)
{
if(Converter == nullptr) return false;
if(Converter->Implements<USpeckleConverter>()) return true;
if(LogWarning)
{
UE_LOG(LogSpeckle, Warning, TEXT("Converter {%s} is not a valid converter, Expected to implement interface {%s}"), *Converter->GetClass()->GetName(), *USpeckleConverter::StaticClass()->GetName())
}
return false;
}
@@ -0,0 +1,55 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Conversion/Converters/BlockConverter.h"
#include "Objects/Other/BlockInstance.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Engine/World.h"
UBlockConverter::UBlockConverter()
{
SpeckleTypes.Add(UBlockInstance::StaticClass());
BlockInstanceActorType = AActor::StaticClass();
ActorMobility = EComponentMobility::Static;
}
UObject* UBlockConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>&)
{
const UBlockInstance* Block = Cast<UBlockInstance>(SpeckleBase);
if(Block == nullptr) return nullptr;
return BlockToNative(Block, World);
}
AActor* UBlockConverter::BlockToNative(const UBlockInstance* Block, UWorld* World)
{
AActor* BlockActor = CreateEmptyActor(World, USpeckleObjectUtils::CreateTransform(Block->Transform));
//Return the block actor as is,
//Other converter logic will convert child geometries because UBlockInstance intentionally left them as dynamic properties
return BlockActor;
}
AActor* UBlockConverter::CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters)
{
AActor* Actor = World->SpawnActor<AActor>(BlockInstanceActorType, Transform, SpawnParameters);
if(!Actor->HasValidRootComponent())
{
USceneComponent* Scene = NewObject<USceneComponent>(Actor, "Root");
Scene->SetRelativeTransform(Transform);
Actor->SetRootComponent(Scene);
Scene->RegisterComponent();
}
USceneComponent* RootComponent = Actor->GetRootComponent();
RootComponent->SetMobility(ActorMobility);
return Actor;
}
UBase* UBlockConverter::ConvertToSpeckle_Implementation(const UObject* Object)
{
unimplemented();
return nullptr; //TODO implement
}
@@ -0,0 +1,178 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Conversion/Converters/MaterialConverter.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "Materials/MaterialInstanceConstant.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "Objects/Other/RenderMaterial.h"
#include "UObject/ConstructorHelpers.h"
UMaterialConverter::UMaterialConverter()
{
static ConstructorHelpers::FObjectFinder<UMaterial> SpeckleMaterial(TEXT("Material'/SpeckleUnreal/SpeckleMaterial.SpeckleMaterial'"));
static ConstructorHelpers::FObjectFinder<UMaterial> SpeckleGlassMaterial(TEXT("Material'/SpeckleUnreal/SpeckleGlassMaterial.SpeckleGlassMaterial'"));
DefaultMeshMaterial = SpeckleMaterial.Object;
BaseMeshOpaqueMaterial = SpeckleMaterial.Object;
BaseMeshTransparentMaterial = SpeckleGlassMaterial.Object;
#if WITH_EDITORONLY_DATA
UseConstMaterials = NotPlay;
#endif
SpeckleTypes.Add(URenderMaterial::StaticClass());
}
UObject* UMaterialConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld*, TScriptInterface<ISpeckleConverter>&)
{
const URenderMaterial* m = Cast<URenderMaterial>(SpeckleBase);
if(m == nullptr) return DefaultMeshMaterial;
return GetMaterial(m);
}
UMaterialInterface* UMaterialConverter::GetMaterial(const URenderMaterial* SpeckleMaterial)
{
if(SpeckleMaterial == nullptr || SpeckleMaterial->Id == "") return DefaultMeshMaterial; //Material is invalid
// 1. Check Overrides
UMaterialInterface* NativeMaterial;
if(TryGetOverride(SpeckleMaterial, NativeMaterial))
return NativeMaterial;
// 2. Check transient cache
if(ConvertedMaterials.Contains(SpeckleMaterial->Id))
{
return ConvertedMaterials[SpeckleMaterial->Id];
}
// 3. Check Assets
UPackage* Package = GetPackage(SpeckleMaterial->Id);
NativeMaterial = Cast<UMaterialInterface>(Package->FindAssetInPackage());
if(IsValid(NativeMaterial))
{
return NativeMaterial;
}
// 4. Convert
return RenderMaterialToNative(SpeckleMaterial, Package);
}
bool UMaterialConverter::TryGetOverride(const URenderMaterial* SpeckleMaterial, UMaterialInterface*& OutMaterial) const
{
const auto MaterialID = SpeckleMaterial->Id;
//Override by id
if(MaterialOverridesById.Contains(MaterialID))
{
OutMaterial = MaterialOverridesById[MaterialID];
return true;
}
//Override by name
const FString Name = SpeckleMaterial->Name;
for (const UMaterialInterface* Mat : MaterialOverridesByName)
{
if(ensureAlways(IsValid(Mat)) && Mat->GetName() == Name)
{
OutMaterial = MaterialOverridesById[MaterialID];
return true;
}
}
return false;
}
FString UMaterialConverter::RemoveInvalidFileChars(const FString& InString) const
{
return FPaths::MakeValidFileName(InString.Replace(TEXT("."), TEXT("_"), ESearchCase::CaseSensitive));
}
UMaterialInterface* UMaterialConverter::RenderMaterialToNative(const URenderMaterial* SpeckleMaterial, UPackage* Package)
{
UMaterialInterface* MaterialBase = SpeckleMaterial->Opacity >= 1
? BaseMeshOpaqueMaterial
: BaseMeshTransparentMaterial;
UMaterialInstance* MaterialInstance;
#if WITH_EDITOR
if (ShouldCreateConstMaterial(UseConstMaterials))
{
const FName Name = MakeUniqueObjectName(Package, UMaterialInstanceConstant::StaticClass(), *RemoveInvalidFileChars(SpeckleMaterial->Name));
//TStrongObjectPtr< UMaterialInstanceConstantFactoryNew > MaterialFact( NewObject< UMaterialInstanceConstantFactoryNew >() );
//MaterialFact->InitialParent = MaterialBase;
//UMaterialInstanceConstant* ConstMaterial = Cast< UMaterialInstanceConstant >( MaterialFact->FactoryCreateNew( UMaterialInstanceConstant::StaticClass(), Package, Name, RF_Public, nullptr, GWarn ) );
UMaterialInstanceConstant* ConstMaterial = NewObject<UMaterialInstanceConstant>(Package, Name, RF_Public | RF_Standalone);
MaterialInstance = ConstMaterial;
ConstMaterial->SetParentEditorOnly(MaterialBase);
ConstMaterial->SetScalarParameterValueEditorOnly(FMaterialParameterInfo("Opacity"), SpeckleMaterial->Opacity);
ConstMaterial->SetScalarParameterValueEditorOnly(FMaterialParameterInfo("Metallic"), SpeckleMaterial->Metalness);
ConstMaterial->SetScalarParameterValueEditorOnly(FMaterialParameterInfo("Roughness"), SpeckleMaterial->Roughness);
ConstMaterial->SetVectorParameterValueEditorOnly(FMaterialParameterInfo("BaseColor"), SpeckleMaterial->Diffuse);
ConstMaterial->SetVectorParameterValueEditorOnly(FMaterialParameterInfo("EmissiveColor"), SpeckleMaterial->Emissive);
//ConstMaterial->InitStaticPermutation();
ConstMaterial->MarkPackageDirty();
FAssetRegistryModule::AssetCreated(MaterialInstance);
}
else
#endif
{
UMaterialInstanceDynamic* DynMaterial = UMaterialInstanceDynamic::Create(MaterialBase, Package, FName(SpeckleMaterial->Name));
MaterialInstance = DynMaterial;
DynMaterial->SetScalarParameterValue("Opacity", SpeckleMaterial->Opacity);
DynMaterial->SetScalarParameterValue("Metallic", SpeckleMaterial->Metalness);
DynMaterial->SetScalarParameterValue("Roughness", SpeckleMaterial->Roughness);
DynMaterial->SetVectorParameterValue("BaseColor", SpeckleMaterial->Diffuse);
DynMaterial->SetVectorParameterValue("EmissiveColor", SpeckleMaterial->Emissive);
DynMaterial->SetFlags(RF_Public);
}
ConvertedMaterials.Add(SpeckleMaterial->Id, MaterialInstance);
return MaterialInstance;
}
void UMaterialConverter::FinishConversion_Implementation()
{
ConvertedMaterials.Empty();
}
UPackage* UMaterialConverter::GetPackage(const FString& ObjectID ) const
{
const FString PackagePath = FPaths::Combine(TEXT("/Game/Speckle/Materials"), ObjectID);
return CreatePackage(*PackagePath);
}
#if WITH_EDITOR
bool UMaterialConverter::ShouldCreateConstMaterial(TEnumAsByte<EConstMaterialOptions> Options)
{
if(!GIsEditor) return false;
switch(Options)
{
case Never:
return false;
case NotPlay:
return !FApp::IsGame();
case Always:
return true;
default:
unimplemented();
return false;
}
}
#endif
@@ -0,0 +1,94 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Conversion/Converters/PointCloudConverter.h"
#include "LidarPointCloudActor.h"
#include "LidarPointCloudComponent.h"
#include "Objects/Geometry/PointCloud.h"
UPointCloudConverter::UPointCloudConverter()
{
SpeckleTypes.Add(UPointCloud::StaticClass());
PointCloudActorType = ALidarPointCloudActor::StaticClass();
ActorMobility = EComponentMobility::Static;
}
UObject* UPointCloudConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>&)
{
const UPointCloud* p = Cast<UPointCloud>(SpeckleBase);
if(p == nullptr) return nullptr;
return PointCloudToNative(p, World);
}
ALidarPointCloudActor* UPointCloudConverter::PointCloudToNative(const UPointCloud* SpecklePointCloud, UWorld* World)
{
TArray<FLidarPointCloudPoint> LidarPoints;
LidarPoints.Reserve(SpecklePointCloud->Points.Num());
for(int i = 0; i < SpecklePointCloud->Points.Num(); i++)
{
FColor c = SpecklePointCloud->Colors.Num() > i? SpecklePointCloud->Colors[i] : FColor::White;
#if ENGINE_MAJOR_VERSION >= 5
FVector3f Point = FVector3f(SpecklePointCloud->Points[i]);
#else
FVector Point = SpecklePointCloud->Points[i];
#endif
FLidarPointCloudPoint p(Point, c, true, 0);
LidarPoints.Add(p);
}
ULidarPointCloud* PointCloud = NewObject<ULidarPointCloud>();
PointCloud->Initialize(FBox(SpecklePointCloud->Points));
PointCloud->InsertPoints(LidarPoints, ELidarPointCloudDuplicateHandling::Ignore, false, FVector::ZeroVector);
PointCloud->CenterPoints();
PointCloud->RefreshBounds();
return CreateActor(World, PointCloud);
}
ALidarPointCloudActor* UPointCloudConverter::CreateActor(UWorld* World, ULidarPointCloud* PointCloudData)
{
ALidarPointCloudActor* Actor = World->SpawnActor<ALidarPointCloudActor>(PointCloudActorType);
Actor->SetPointCloud(PointCloudData);
Actor->GetRootComponent()->SetMobility(ActorMobility);
return Actor;
}
UBase* UPointCloudConverter::ConvertToSpeckle_Implementation(const UObject* Object)
{
const ULidarPointCloudComponent* P = Cast<ULidarPointCloudComponent>(Object);
if(P == nullptr)
{
const AActor* A = Cast<AActor>(Object);
if(A != nullptr)
{
P = A->FindComponentByClass<ULidarPointCloudComponent>();
}
}
if(P == nullptr) return nullptr;
return PointCloudToSpeckle(P);
}
UPointCloud* UPointCloudConverter::PointCloudToSpeckle(const ULidarPointCloudComponent* Object)
{
return nullptr; //TODO implement ToSpeckle function
}
@@ -0,0 +1,145 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Conversion/Converters/ProceduralMeshConverter.h"
#include "ProceduralMeshComponent.h"
#include "Conversion/Converters/MaterialConverter.h"
#include "Materials/MaterialInstance.h"
#include "Objects/DisplayValueElement.h"
#include "Objects/Geometry/Mesh.h"
#include "Objects/Other/RenderMaterial.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
UProceduralMeshConverter::UProceduralMeshConverter()
{
SpeckleTypes.Add(UMesh::StaticClass());
SpeckleTypes.Add(UDisplayValueElement::StaticClass());
MeshActorType = AActor::StaticClass();
ActorMobility = EComponentMobility::Static;
}
UObject* UProceduralMeshConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World,
TScriptInterface<ISpeckleConverter>& AvailableConverters )
{
const UMesh* m = Cast<UMesh>(SpeckleBase);
if(m != nullptr)
return MeshToNative(m, World, AvailableConverters);
const UDisplayValueElement* d = Cast<UDisplayValueElement>(SpeckleBase);
if(d)
{
AActor* Parent = CreateEmptyActor(World, FTransform());
for(const UMesh* Child : d->DisplayValue)
{
AActor* ChildActor = MeshToNative(Child, World, AvailableConverters);
if(IsValid(ChildActor))
{
#if WITH_EDITOR
ChildActor->SetActorLabel(FString::Printf(TEXT("%s - %s"), *Child->SpeckleType, *Child->Id));
#endif
ChildActor->GetRootComponent()->SetMobility(ActorMobility);
ChildActor->AttachToActor(Parent, FAttachmentTransformRules::KeepRelativeTransform);
ChildActor->SetOwner(Parent);
}
}
return Parent;
}
return nullptr;
}
AActor* UProceduralMeshConverter::MeshToNative(const UMesh* SpeckleMesh,
UWorld* World,
TScriptInterface<ISpeckleConverter>& MaterialConverter)
{
AActor* MeshActor = CreateEmptyActor(World, USpeckleObjectUtils::CreateTransform(SpeckleMesh->Transform));
UProceduralMeshComponent* MeshComponent = NewObject<UProceduralMeshComponent>(MeshActor, FName("SpeckleMeshComponent"));
MeshComponent->SetupAttachment(MeshActor->GetRootComponent());
MeshComponent->RegisterComponent();
TArray<int32> Faces;
int32 i = 0;
while (i < SpeckleMesh->Faces.Num())
{
int32 n = SpeckleMesh->Faces[i];
if(n < 3) n += 3; // 0 -> 3, 1 -> 4
if (n == 3) //Triangles
{
Faces.Add(SpeckleMesh->Faces[i + 3]);
Faces.Add(SpeckleMesh->Faces[i + 2]);
Faces.Add(SpeckleMesh->Faces[i + 1]);
}
else if(n == 4) // Quads
{
Faces.Add(SpeckleMesh->Faces[i + 4]);
Faces.Add(SpeckleMesh->Faces[i + 3]);
Faces.Add(SpeckleMesh->Faces[i + 1]);
Faces.Add(SpeckleMesh->Faces[i + 3]);
Faces.Add(SpeckleMesh->Faces[i + 2]);
Faces.Add(SpeckleMesh->Faces[i + 1]);
}
else
{
// n-gons shall be ignored
}
i += n + 1;
}
const TArray<FVector> Normals;
const TArray<FProcMeshTangent> Tangents;
MeshComponent->CreateMeshSection(
0,
SpeckleMesh->Vertices,
Faces,
Normals,
SpeckleMesh->TextureCoordinates,
SpeckleMesh->VertexColors,
Tangents,
true);
UMaterialInterface* Material = Cast<UMaterialInstance>(Execute_ConvertToNative(MaterialConverter.GetObject(), SpeckleMesh->RenderMaterial, World, MaterialConverter));
ensure(Material != nullptr);
MeshComponent->SetMaterial(0, Material);
return MeshActor;
}
AActor* UProceduralMeshConverter::CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters)
{
AActor* Actor = World->SpawnActor<AActor>(MeshActorType, Transform, SpawnParameters);
USceneComponent* Scene = NewObject<USceneComponent>(Actor, "Root");
Actor->SetRootComponent(Scene);
Scene->RegisterComponent();
Scene->SetMobility(ActorMobility);
return Actor;
}
UBase* UProceduralMeshConverter::ConvertToSpeckle_Implementation(const UObject* Object)
{
const UProceduralMeshComponent* M = Cast<UProceduralMeshComponent>(Object);
if(M == nullptr)
{
const AActor* A = Cast<AActor>(Object);
if(A != nullptr)
{
M = A->FindComponentByClass<UProceduralMeshComponent>();
}
}
if(M == nullptr) return nullptr;
return MeshToSpeckle(M);
}
UMesh* UProceduralMeshConverter::MeshToSpeckle(const UProceduralMeshComponent* Object)
{
return nullptr; //TODO implement ToSpeckle function
}
@@ -0,0 +1,426 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Conversion/Converters/StaticMeshConverter.h"
#include "MeshDescriptionBase.h"
#include "StaticMeshDescription.h"
#include "MeshTypes.h"
#include "StaticMeshOperations.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "Engine/StaticMeshActor.h"
#include "Objects/Geometry/Mesh.h"
#include "LogSpeckle.h"
#include "API/SpeckleSerializer.h"
#include "Conversion/Converters/MaterialConverter.h"
#include "Misc/ScopedSlowTask.h"
#include "Objects/DisplayValueElement.h"
#include "Objects/Other/RenderMaterial.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule"
UStaticMeshConverter::UStaticMeshConverter()
{
SpeckleTypes.Add(UMesh::StaticClass());
SpeckleTypes.Add(UDisplayValueElement::StaticClass());
#if WITH_EDITORONLY_DATA
UseFullBuild = true;
DisplayBuildProgressBar = true;
AllowCancelBuild = false;
#endif
Transient = false;
BuildSimpleCollision = true;
BuildReversedIndexBuffer = true;
UseFullPrecisionUVs = false;
RemoveDegeneratesOnBuild = true;
MinLightmapResolution = 64;
MeshActorType = AStaticMeshActor::StaticClass();
ActorMobility = EComponentMobility::Static;
}
AActor* UStaticMeshConverter::CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters)
{
AActor* Actor = World->SpawnActor<AActor>(MeshActorType, Transform, SpawnParameters);
if(Actor->HasValidRootComponent())
Actor->GetRootComponent()->SetMobility(EComponentMobility::Movable); //Create actor as movable for now, we will change it later to the desired mobility
return Actor;
}
UObject* UStaticMeshConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>& AvailableConverters)
{
const UMesh* m = Cast<UMesh>(SpeckleBase);
if(m != nullptr)
{
//Handle Single Mesh
return MeshToNativeActor(m, World, AvailableConverters);
}
const UDisplayValueElement* d = Cast<UDisplayValueElement>(SpeckleBase);
if(d != nullptr)
{
//Handle Element with Display Values
return MeshesToNativeActor(d, d->DisplayValue, World, AvailableConverters);
}
return nullptr;
}
AActor* UStaticMeshConverter::MeshToNativeActor(const UMesh* SpeckleMesh, UWorld* World, TScriptInterface<ISpeckleConverter>& MaterialConverter)
{
TArray<UMesh*> Meshes = {const_cast<UMesh*>(SpeckleMesh)};
return MeshesToNativeActor(SpeckleMesh, Meshes, World, MaterialConverter);
}
AActor* UStaticMeshConverter::MeshesToNativeActor(const UBase* Parent, const TArray<UMesh*>& SpeckleMeshes, UWorld* World, TScriptInterface<ISpeckleConverter>& RenderMaterialConverter)
{
check(RenderMaterialConverter.GetInterface() != nullptr);
ensureMsgf(Execute_CanConvertToNative(RenderMaterialConverter.GetObject(), URenderMaterial::StaticClass()), TEXT("StaticMeshConverter expects a valid RenderMaterial converter to be avaiable"));
const FString PackagePath = FPaths::Combine(TEXT("/Game/Speckle/Geometry"), Parent->Id);
UPackage* Package = CreatePackage(*PackagePath);
//Find existing mesh
UStaticMesh* Mesh = Cast<UStaticMesh>(Package->FindAssetInPackage());
if(!IsValid(Mesh))
{
//No existing mesh was found, try and convert SpeckleMesh
Mesh = MeshesToNativeMesh(Package, Parent, SpeckleMeshes, RenderMaterialConverter);
}
FMatrix Transform = FMatrix::Identity;
// For single mesh, we check for transform
//TODO figure out how to handle DisplayValueElement with transform. Maybe we just grab transform from parent unconditionally? How does this affect blocks?
if(Parent == SpeckleMeshes[0])
{
Transform = SpeckleMeshes[0]->Transform;
}
AActor* Actor = CreateEmptyActor(World, USpeckleObjectUtils::CreateTransform(Transform));
TInlineComponentArray<UStaticMeshComponent*> Components;
Actor->GetComponents<UStaticMeshComponent>(Components);
UStaticMeshComponent* MeshComponent;
if(Components.Num() > 0) MeshComponent = Components[0];
else
{
// MeshActorType doesn't have a UStaticMeshComponent, so we will add one
MeshComponent = NewObject<UStaticMeshComponent>(Actor, FName("SpeckleMeshComponent"));
MeshComponent->SetupAttachment(Actor->GetRootComponent());
MeshComponent->RegisterComponent();
}
MeshComponent->SetStaticMesh(Mesh);
int i = 0;
for(const UMesh* DisplayMesh : SpeckleMeshes)
{
URenderMaterial* MaterialToConvert = DisplayMesh->RenderMaterial;
if(!MaterialToConvert)
{
//Try and grab a material from the parent
const auto* MaterialProperty = Parent->DynamicProperties.Find("renderMaterial");
const TSharedPtr<FJsonObject>* MaterialObject;
if(MaterialProperty && (*MaterialProperty)->TryGetObject(MaterialObject))
{
//TODO giving a nullptr transport is pretty unsafe and relies on the deserializer not to have to dereference a detached property.
MaterialToConvert = Cast<URenderMaterial>(USpeckleSerializer::DeserializeBase(*MaterialObject, nullptr));
}
}
UMaterialInterface* Material = GetMaterial(MaterialToConvert, World, RenderMaterialConverter);
ensure(IsValid(Material));
MeshComponent->SetMaterial(i, Material);
i++;
}
if(Actor->HasValidRootComponent())
Actor->GetRootComponent()->SetMobility(ActorMobility);
return Actor;
}
UMaterialInterface* UStaticMeshConverter::GetMaterial(const URenderMaterial* SpeckleMaterial, UWorld* World, TScriptInterface<ISpeckleConverter>& MaterialConverter) const
{
if(!SpeckleMaterial)
{
// Create a fake render material, (since nullptr doesn't have a type, speckle converters don't know how to convert it)
// If the converter wants to handle this specially, The material has an empty Id
SpeckleMaterial = NewObject<URenderMaterial>(GetTransientPackage(), "NullSpeckleMaterial");
}
return Cast<UMaterialInterface>(Execute_ConvertToNative(MaterialConverter.GetObject(), SpeckleMaterial, World, MaterialConverter));
}
UStaticMesh* UStaticMeshConverter::MeshToNativeMesh(UObject* Outer, const UMesh* SpeckleMesh, TScriptInterface<ISpeckleConverter>& MaterialConverter)
{
TArray<UMesh*> Meshes;
Meshes.Add(const_cast<UMesh*>(SpeckleMesh));
return MeshesToNativeMesh(Outer, SpeckleMesh, Meshes, MaterialConverter);
}
UStaticMesh* UStaticMeshConverter::MeshesToNativeMesh(UObject* Outer, const UBase* Parent, const TArray<UMesh*>& SpeckleMeshes, TScriptInterface<ISpeckleConverter>& MaterialConverter)
{
if(SpeckleMeshes.Num() == 0) return nullptr;
EObjectFlags ObjectFags = Transient? RF_Transient | RF_Public : RF_Public;
#if ENGINE_MAJOR_VERSION >= 5
ObjectFags |= RF_Standalone; //TODO maybe all versions should have RF_Standalone?
#endif
UStaticMesh* Mesh = NewObject<UStaticMesh>(Outer, FName(Parent->Id), ObjectFags);
Mesh->InitResources();
Mesh->SetLightingGuid();
UStaticMeshDescription* StaticMeshDescription = Mesh->CreateStaticMeshDescription(Outer);
FMeshDescription& BaseMeshDescription = StaticMeshDescription->GetMeshDescription();
//Build Settings
#if WITH_EDITOR
{
FStaticMeshSourceModel& SrcModel = Mesh->AddSourceModel();
SrcModel.BuildSettings.bRecomputeNormals = true;
SrcModel.BuildSettings.bRecomputeTangents = true;
SrcModel.BuildSettings.bRemoveDegenerates = RemoveDegeneratesOnBuild;
SrcModel.BuildSettings.bUseHighPrecisionTangentBasis = false;
SrcModel.BuildSettings.bBuildReversedIndexBuffer = BuildReversedIndexBuffer;
SrcModel.BuildSettings.bUseFullPrecisionUVs = UseFullPrecisionUVs;
SrcModel.BuildSettings.bGenerateLightmapUVs = GenerateLightmapUV;
SrcModel.BuildSettings.SrcLightmapIndex = 0;
SrcModel.BuildSettings.DstLightmapIndex = 1;
SrcModel.BuildSettings.MinLightmapResolution = MinLightmapResolution;
}
#endif
UStaticMesh::FBuildMeshDescriptionsParams MeshParams;
GenerateMeshParams(MeshParams);
for(const UMesh* SpeckleMesh : SpeckleMeshes)
{
const size_t NumberOfVertices = SpeckleMesh->Vertices.Num();
const size_t NumberOfFacesIndices = SpeckleMesh->Faces.Num();
// Convert Vertices
if(NumberOfVertices == 0 || NumberOfFacesIndices == 0) continue;
StaticMeshDescription->ReserveNewVertices(NumberOfVertices);
TArray<FVertexID> Vertices;
Vertices.Reserve(NumberOfVertices);
for(const FVector VertexPosition : SpeckleMesh->Vertices)
{
const FVertexID VertID = StaticMeshDescription->CreateVertex();
StaticMeshDescription->SetVertexPosition(VertID, VertexPosition);
Vertices.Add(VertID);
}
// Convert Material
UMaterialInterface* Material = GetMaterial(SpeckleMesh->RenderMaterial, GetWorld(), MaterialConverter);
const FName MaterialSlotName = Mesh->AddMaterial(Material);;
BaseMeshDescription.PolygonGroupAttributes().RegisterAttribute<FName>(MeshAttribute::PolygonGroup::ImportedMaterialSlotName, 1, MaterialSlotName, EMeshAttributeFlags::None);
// Convert Faces
const FPolygonGroupID PolygonGroupID = StaticMeshDescription->CreatePolygonGroup();
StaticMeshDescription->SetPolygonGroupMaterialSlotName(PolygonGroupID, MaterialSlotName);
#if ENGINE_MAJOR_VERSION >= 5
StaticMeshDescription->VertexInstanceAttributes().RegisterAttribute<FVector2f>(MeshAttribute::VertexInstance::TextureCoordinate, 2, FVector2f::ZeroVector, EMeshAttributeFlags::None);
#else
StaticMeshDescription->VertexInstanceAttributes().RegisterAttribute<FVector2D>(MeshAttribute::VertexInstance::TextureCoordinate, 2, FVector2D::ZeroVector, EMeshAttributeFlags::None);
#endif
{
// Reserve space assuming faces will all be triangles //TODO (maybe it's better to assume something higher?)
const int32 EstimatedNumberOfFaces = SpeckleMesh->Faces.Num() / 4 * 3;
StaticMeshDescription->ReserveNewTriangles(EstimatedNumberOfFaces);
StaticMeshDescription->ReserveNewPolygons(EstimatedNumberOfFaces);
StaticMeshDescription->ReserveNewVertexInstances(FGenericPlatformMath::Max(EstimatedNumberOfFaces * 3, SpeckleMesh->Vertices.Num()));
}
int32 i = 0;
while (i < NumberOfFacesIndices)
{
int32 n = SpeckleMesh->Faces[i];
if(n < 3) n += 3; // 0 -> 3, 1 -> 4
TArray<FVertexInstanceID> VertexInstances;
VertexInstances.Reserve(n);
TSet<FVertexID> Verts;
Verts.Reserve(n);
for(int j = 0; j < n; j ++)
{
int32 VertIndex = SpeckleMesh->Faces[i + 1 + j];
if(VertIndex < 0 || VertIndex >= Vertices.Num())
{
UE_LOG(LogSpeckle, Warning, TEXT("Invalid Polygon while creating mesh %s - index %d was outside the bounds of the vertex array, face is ignored"), *SpeckleMesh->Id, VertIndex);
continue;
}
FVertexID Vert = Vertices[VertIndex];
bool AlreadyInSet;
Verts.Add(Vert, &AlreadyInSet);
if(AlreadyInSet)
{
UE_LOG(LogSpeckle, Warning, TEXT("Invalid Polygon while creating mesh %s - vertex at index %d appears more than once in a face, duplicate vertices will be ignored"), *SpeckleMesh->Id, VertIndex);
continue;
}
FVertexInstanceID VertexInstance = StaticMeshDescription->CreateVertexInstance(Vert);
VertexInstances.Add(VertexInstance);
if(SpeckleMesh->TextureCoordinates.Num() > VertIndex)
StaticMeshDescription->SetVertexInstanceUV(VertexInstance, SpeckleMesh->TextureCoordinates[VertIndex]);
//if(SpeckleMesh->VertexColors.Num() > VertIndex)
// //TODO set vertex colors
}
i += n + 1;
if(VertexInstances.Num() < 3)
{
UE_LOG(LogTemp, Warning, TEXT("Invalid Polygon while creating mesh %s - face has fewer than 3 verts, this face will be ignored"), *SpeckleMesh->Id);
continue;
}
TArray<FEdgeID> Edges;
Edges.Reserve(n);
const FPolygonID PolygonID = StaticMeshDescription->CreatePolygon(PolygonGroupID, VertexInstances, Edges);
for (const FEdgeID EdgeID : Edges)
{
StaticMeshDescription->GetEdgeHardnesses()[EdgeID] = true;
}
}
}
if(StaticMeshDescription->Vertices().Num() == 0
|| StaticMeshDescription->VertexInstances().Num() == 0
|| StaticMeshDescription->Triangles().Num() == 0)
{
UE_LOG(LogSpeckle, Warning, TEXT("Skipping %s $s, converted mesh is empty!"), *Parent->SpeckleType, *Parent->Id);
return nullptr;
}
BaseMeshDescription.TriangulateMesh();
#if ENGINE_MAJOR_VERSION >= 5
FStaticMeshOperations::ComputeTriangleTangentsAndNormals(BaseMeshDescription);
#else
BaseMeshDescription.PolygonAttributes().RegisterAttribute<FVector>(MeshAttribute::Polygon::Normal, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient);
BaseMeshDescription.PolygonAttributes().RegisterAttribute<FVector>(MeshAttribute::Polygon::Tangent, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient);
BaseMeshDescription.PolygonAttributes().RegisterAttribute<FVector>(MeshAttribute::Polygon::Binormal, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient);
BaseMeshDescription.PolygonAttributes().RegisterAttribute<FVector>(MeshAttribute::Polygon::Center, 1, FVector::ZeroVector, EMeshAttributeFlags::Transient);
FStaticMeshOperations::ComputePolygonTangentsAndNormals(BaseMeshDescription);
#endif
FStaticMeshOperations::ComputeTangentsAndNormals(BaseMeshDescription, EComputeNTBsFlags::Normals | EComputeNTBsFlags::Tangents);
//Mesh->PreEditChange(nullptr);
#if ENGINE_MAJOR_VERSION >= 5 || ( ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 27 )
Mesh->SetLightMapCoordinateIndex(1);
#else
Mesh->LightMapCoordinateIndex = 1;
#endif
Mesh->BuildFromMeshDescriptions(TArray<const FMeshDescription*>{&BaseMeshDescription}, MeshParams);
#if WITH_EDITOR
if(UseFullBuild)
{
FScopeLock Lock(&Lock_StaticMeshesToBuild);
StaticMeshesToBuild.Add(Mesh);
}
if (!FApp::IsGame())
{
Mesh->MarkPackageDirty();
FAssetRegistryModule::AssetCreated(Mesh);
}
#endif
//Mesh->PostEditChange(); //This doesn't seem to be required
return Mesh;
}
void UStaticMeshConverter::GenerateMeshParams(UStaticMesh::FBuildMeshDescriptionsParams& MeshParams) const
{
MeshParams.bBuildSimpleCollision = BuildSimpleCollision;
MeshParams.bCommitMeshDescription = true;
MeshParams.bMarkPackageDirty = true;
MeshParams.bUseHashAsGuid = false;
#if !WITH_EDITOR && ENGINE_MAJOR_VERSION >= 5
MeshParams.bFastBuild = true;
#endif
}
UBase* UStaticMeshConverter::ConvertToSpeckle_Implementation(const UObject* Object)
{
const UStaticMeshComponent* M = Cast<UStaticMeshComponent>(Object);
if(M == nullptr)
{
const AActor* A = Cast<AActor>(Object);
if(A != nullptr)
{
M = A->FindComponentByClass<UStaticMeshComponent>();
}
}
if(M == nullptr) return nullptr;
return MeshToSpeckle(M);
}
UBase* UStaticMeshConverter::MeshToSpeckle(const UStaticMeshComponent* Object)
{
return nullptr; //TODO implement ToSpeckle function
}
void UStaticMeshConverter::FinishConversion_Implementation()
{
if(StaticMeshesToBuild.Num() <= 0) return;
FScopeLock Lock(&Lock_StaticMeshesToBuild);
#if WITH_EDITOR
FFormatNamedArguments Args;
Args.Add( TEXT("Path"), FText::FromString( GetPathName() ) );
const FText StatusUpdate = FText::Format( LOCTEXT("BeginStaticMeshBuildingTask", "({Path}) Building"), Args );
FScopedSlowTask Progress(StaticMeshesToBuild.Num(), StatusUpdate, DisplayBuildProgressBar);
Progress.MakeDialog(AllowCancelBuild);
auto ProgressAction = [&Progress](UStaticMesh*) -> bool
{
Progress.EnterProgressFrame(1);
return !Progress.ShouldCancel();
};
UStaticMesh::BatchBuild(StaticMeshesToBuild, !DisplayBuildProgressBar, ProgressAction);
#endif
StaticMeshesToBuild.Empty();
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,181 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Conversion/SpeckleConverterComponent.h"
#include "ActorEditorUtils.h"
#include "API/SpeckleSerializer.h"
#include "Conversion/Converters/AggregateConverter.h"
#include "Conversion/Converters/BlockConverter.h"
#include "Conversion/Converters/PointCloudConverter.h"
#include "Conversion/Converters/StaticMeshConverter.h"
#include "Conversion/Converters/MaterialConverter.h"
#include "Misc/ScopedSlowTask.h"
#include "UObject/ConstructorHelpers.h"
#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule"
USpeckleConverterComponent::USpeckleConverterComponent()
{
//TODO consider using an object library for default converters
static ConstructorHelpers::FObjectFinder<UStaticMeshConverter> MeshConverter(TEXT("StaticMeshConverter'/SpeckleUnreal/Converters/DefaultStaticMeshConverter.DefaultStaticMeshConverter'"));
static ConstructorHelpers::FObjectFinder<UPointCloudConverter> PointCloudConverter(TEXT("PointCloudConverter'/SpeckleUnreal/Converters/DefaultPointCloudConverter.DefaultPointCloudConverter'"));
static ConstructorHelpers::FObjectFinder<UBlockConverter> BlockConverter(TEXT("BlockConverter'/SpeckleUnreal/Converters/DefaultBlockConverter.DefaultBlockConverter'"));
static ConstructorHelpers::FObjectFinder<UMaterialConverter> MaterialConverter(TEXT("MaterialConverter'/SpeckleUnreal/Converters/DefaultMaterialConverter.DefaultMaterialConverter'"));
static ConstructorHelpers::FObjectFinder<UObject> CameraConverter(TEXT("CameraConverter'/SpeckleUnreal/Converters/DefaultCameraConverter.DefaultCameraConverter'"));
//static ConstructorHelpers::FObjectFinder<ULightConverter> LightConverter(TEXT("LightConverter'/SpeckleUnreal/Converters/DefaultLightConverter.DefaultLightConverter'"));
SpeckleConverter = CreateDefaultSubobject<UAggregateConverter>(TEXT("Objects Converter"));
SpeckleConverter->SpeckleConverters.Add(MeshConverter.Object);
SpeckleConverter->SpeckleConverters.Add(PointCloudConverter.Object);
SpeckleConverter->SpeckleConverters.Add(BlockConverter.Object);
SpeckleConverter->SpeckleConverters.Add(MaterialConverter.Object);
SpeckleConverter->SpeckleConverters.Add(CameraConverter.Object);
//SpeckleConverter->SpeckleConverters.Add(LightConverter.Object);
PrimaryComponentTick.bCanEverTick = false;
}
AActor* USpeckleConverterComponent::RecursivelyConvertToNative(AActor* AOwner, const UBase* Base,
const TScriptInterface<ITransport>& LocalTransport, bool DisplayProgressBar, TArray<AActor*>& OutActors)
{
float ObjectsToConvert{};
Base->TryGetDynamicNumber("totalChildrenCount", ObjectsToConvert);
// Progress bar
FScopedSlowTask Progress(ObjectsToConvert + 2,
LOCTEXT("SpeckleConvertoNative","Converting Speckle Objects to Native"), DisplayProgressBar);
#if WITH_EDITOR
Progress.MakeDialog(true, false);
#endif
AActor* RootActor = RecursivelyConvertToNative_Internal(AOwner, Base, LocalTransport, &Progress, OutActors);
FinishConversion();
return RootActor;
}
AActor* USpeckleConverterComponent::RecursivelyConvertToNative_Internal(AActor* AOwner, const UBase* Base,
const TScriptInterface<ITransport>& LocalTransport,
FSlowTask* Task,
TArray<AActor*>& OutActors)
{
check(IsValid(AOwner));
if(!IsValid(Base)) return nullptr;
// Convert Speckle Object
UObject* Converted = SpeckleConverter->ConvertToNativeInternal(Base, AOwner->GetWorld());
AttachConvertedToOwner(AOwner, Base, Converted);
// Handle new actors
AActor* ConvertedAsActor = Cast<AActor>(Converted);
AActor* NextOwner = IsValid(ConvertedAsActor) ? ConvertedAsActor : AOwner;
if(NextOwner != AOwner)
{
OutActors.Add(NextOwner);
OutActors.Append(NextOwner->Children);
}
Task->EnterProgressFrame(1);
if(Task->ShouldCancel()) return AOwner;
//Convert Children
TMap<FString, TSharedPtr<FJsonValue>> PotentialChildren = Base->DynamicProperties;
for (const auto& Kvp : PotentialChildren)
{
if(Task->ShouldCancel()) break;
ConvertChild(Kvp.Value, NextOwner, LocalTransport, Task, OutActors);
}
return AOwner;
}
void USpeckleConverterComponent::ConvertChild(const TSharedPtr<FJsonValue> Object, AActor* AOwner,
const TScriptInterface<ITransport>& LocalTransport, FSlowTask* Task,
TArray<AActor*>& OutActors)
{
//Handle child object
const TSharedPtr<FJsonObject>* ChildObj;
if (Object->TryGetObject(ChildObj))
{
const UBase* Child = USpeckleSerializer::DeserializeBase(*ChildObj, LocalTransport);
RecursivelyConvertToNative_Internal(AOwner, Child, LocalTransport, Task, OutActors);
return;
}
//Handle child array object
const TArray<TSharedPtr<FJsonValue>>* ChildArr;
if (Object->TryGetArray(ChildArr))
{
for (const auto& v : *ChildArr)
{
ConvertChild(v, AOwner, LocalTransport, Task, OutActors);
}
}
};
void USpeckleConverterComponent::AttachConvertedToOwner(AActor* AOwner, const UBase* Base, UObject* Converted)
{
// Case Actor
{
AActor* NativeActor = Cast<AActor>(Converted);
if(IsValid(NativeActor))
{
#if WITH_EDITOR
{
FString Name;
FText _Discard;
if( !(Base->TryGetDynamicString("name", Name) && FActorEditorUtils::ValidateActorName(FText::FromString(Name), _Discard)) )
{
Name = FString::Printf(TEXT("%s - %s"), *Base->SpeckleType, *Base->Id);
}
NativeActor->SetActorLabel(Name);
}
#endif
// Ensure actor has a valid mobility for its owner
if(NativeActor->HasValidRootComponent())
{
uint8 CurrentMobility = NativeActor->GetRootComponent()->Mobility;
uint8 OwnerMobility = AOwner->GetRootComponent()->Mobility;
if(CurrentMobility < OwnerMobility)
{
NativeActor->GetRootComponent()->SetMobility(AOwner->GetRootComponent()->Mobility);
}
}
NativeActor->AttachToActor(AOwner, FAttachmentTransformRules::KeepRelativeTransform);
NativeActor->SetOwner(AOwner);
return;
}
}
// Case ActorComponent
{
UActorComponent* NativeComponent = Cast<UActorComponent>(Converted);
if(IsValid(NativeComponent))
{
if(!AOwner->HasValidRootComponent()) AOwner->SetRootComponent(NewObject<USceneComponent>(AOwner));
USceneComponent* SceneComponent = Cast<USceneComponent>(Converted);
if(IsValid(SceneComponent)) SceneComponent->SetupAttachment(AOwner->GetRootComponent());
NativeComponent->RegisterComponent();
return;
}
}
}
void USpeckleConverterComponent::FinishConversion()
{
SpeckleConverter->FinishConversion_Internal();
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,6 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "LogSpeckle.h"
#include "Logging/LogMacros.h"
DEFINE_LOG_CATEGORY(LogSpeckle);
@@ -0,0 +1,57 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Objects/DisplayValueElement.h"
#include "API/SpeckleSerializer.h"
#include "Objects/Geometry/Mesh.h"
TArray<FString> UDisplayValueElement::DisplayValueAliasStrings = {
"displayValue",
"@displayValue",
"displayMesh"
"@displayMesh"
};
bool UDisplayValueElement::AddDisplayValue(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
UMesh* DisplayMesh = Cast<UMesh>(USpeckleSerializer::DeserializeBase(Obj, ReadTransport));
const bool Valid = IsValid(DisplayMesh);
if(Valid)
this->DisplayValue.Add(DisplayMesh);
return Valid;
}
bool UDisplayValueElement::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
if(!Super::Parse(Obj, ReadTransport)) return false;
//Find display values
for(const FString& Alias : DisplayValueAliasStrings)
{
const TSharedPtr<FJsonObject>* SubObjectPtr;
if (Obj->TryGetObjectField(Alias, SubObjectPtr))
{
AddDisplayValue(*SubObjectPtr, ReadTransport);
DynamicProperties.Remove(Alias);
continue;
}
const TArray<TSharedPtr<FJsonValue>>* SubArrayPtr;
if (Obj->TryGetArrayField(Alias, SubArrayPtr))
{
for (const auto& ArrayElement : *SubArrayPtr)
{
const TSharedPtr<FJsonObject>* ArraySubObjPtr;
if (ArrayElement->TryGetObject(ArraySubObjPtr))
{
AddDisplayValue(*ArraySubObjPtr, ReadTransport);
}
}
DynamicProperties.Remove(Alias);
}
}
return DisplayValue.Num() > 0;
}
@@ -0,0 +1,149 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Objects/Geometry/Mesh.h"
#include "Objects/Other/RenderMaterial.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Transports/Transport.h"
bool UMesh::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
if(!Super::Parse(Obj, ReadTransport)) return false;
const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units);
//Parse optional Transform
if(USpeckleObjectUtils::TryParseTransform(Obj, Transform))
{
Transform.ScaleTranslation(FVector(ScaleFactor));
DynamicProperties.Remove("transform");
}
else
{
Transform = FMatrix::Identity;
}
//Parse Vertices
{
TArray<TSharedPtr<FJsonValue>> ObjectVertices = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField("vertices"), ReadTransport);
const int32 NumberOfVertices = ObjectVertices.Num() / 3;
Vertices.Reserve(NumberOfVertices);
for (size_t i = 0, j = 0; i < NumberOfVertices; i++, j += 3)
{
Vertices.Add(Transform.InverseTransformPosition(FVector
(
ObjectVertices[j].Get()->AsNumber(),
-ObjectVertices[j + 1].Get()->AsNumber(),
ObjectVertices[j + 2].Get()->AsNumber()
) * ScaleFactor ));
}
DynamicProperties.Remove("vertices");
}
//Parse Faces
{
const TArray<TSharedPtr<FJsonValue>> FaceVertices = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField("faces"), ReadTransport);
Faces.Reserve(FaceVertices.Num());
for(const auto& VertIndex : FaceVertices)
{
Faces.Add(VertIndex->AsNumber());
}
DynamicProperties.Remove("faces");
}
//Parse TextureCoords
{
const TArray<TSharedPtr<FJsonValue>>* TextCoordArray;
if(Obj->TryGetArrayField("textureCoordinates", TextCoordArray))
{
TArray<TSharedPtr<FJsonValue>> TexCoords = USpeckleObjectUtils::CombineChunks(*TextCoordArray, ReadTransport);
TextureCoordinates.Reserve(TexCoords.Num() / 2);
for (int32 i = 0; i + 1 < TexCoords.Num(); i += 2)
{
TextureCoordinates.Add(FVector2D
(
TexCoords[i].Get()->AsNumber(),
TexCoords[i + 1].Get()->AsNumber()
));
}
DynamicProperties.Remove("textureCoordinates");
}
}
//Parse VertexColors
{
const TArray<TSharedPtr<FJsonValue>>* ColorArray;
if(Obj->TryGetArrayField("colors", ColorArray))
{
TArray<TSharedPtr<FJsonValue>> Colors = USpeckleObjectUtils::CombineChunks(*ColorArray, ReadTransport);
VertexColors.Reserve(Colors.Num());
for (int32 i = 0; i + 1 < Colors.Num(); i ++)
{
VertexColors.Add(FColor(Colors[i].Get()->AsNumber()));
}
DynamicProperties.Remove("colors");
}
}
//Parse Optional RenderMaterial
if (Obj->HasField("renderMaterial"))
{
RenderMaterial = NewObject<URenderMaterial>();
RenderMaterial->Parse(Obj->GetObjectField("renderMaterial"), ReadTransport);
DynamicProperties.Remove("renderMaterial");
}
AlignVerticesWithTexCoordsByIndex();
return Vertices.Num() > 0 && Faces.Num() > 0;
}
void UMesh::AlignVerticesWithTexCoordsByIndex()
{
if(TextureCoordinates.Num() == 0) return;
if(TextureCoordinates.Num() == Vertices.Num()) return; //Tex-coords already aligned as expected
TArray<int> FacesUnique;
FacesUnique.Reserve(Faces.Num());
TArray<FVector> VerticesUnique;
VerticesUnique.Reserve(TextureCoordinates.Num());
const bool HasColor = VertexColors.Num() > 0;
TArray<FColor> ColorsUnique;
if(HasColor) ColorsUnique.Reserve(TextureCoordinates.Num());
int32 NIndex = 0;
while(NIndex < Faces.Num())
{
int32 n = Faces[NIndex];
if (n < 3) n += 3; // 0 -> 3, 1 -> 4
if (NIndex + n >= Faces.Num()) break; //Malformed face list
FacesUnique.Add(n);
for (int32 i = 1; i <= n; i++)
{
const int32 VertIndex = Faces[NIndex + i];
const int32 NewVertIndex = VerticesUnique.Num();
VerticesUnique.Add(Vertices[VertIndex]);
if(HasColor) ColorsUnique.Add(VertexColors[NewVertIndex]);
FacesUnique.Add(NewVertIndex);
}
NIndex += n + 1;
}
Vertices = VerticesUnique;
VertexColors = ColorsUnique;
Faces = FacesUnique;
}
@@ -0,0 +1,58 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Objects/Geometry/PointCloud.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Transports/Transport.h"
bool UPointCloud::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
if(!Super::Parse(Obj, ReadTransport)) return false;
const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units);
//Parse Points
{
TArray<TSharedPtr<FJsonValue>> ObjectPoints = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField("points"), ReadTransport);
Points.Reserve(ObjectPoints.Num() / 3);
for (int32 i = 2; i < ObjectPoints.Num(); i += 3)
{
Points.Add(FVector
(
ObjectPoints[i - 2].Get()->AsNumber(),
ObjectPoints[i - 1].Get()->AsNumber(),
ObjectPoints[i].Get()->AsNumber()
) * ScaleFactor);
}
DynamicProperties.Remove("points");
}
//Parse Colors
{
TArray<TSharedPtr<FJsonValue>> ObjectColors = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField("colors"), ReadTransport);
Colors.Reserve(ObjectColors.Num());
for (int32 i = 0; i < ObjectColors.Num(); i += 1)
{
Colors.Add( FColor(ObjectColors[i].Get()->AsNumber()) );
}
DynamicProperties.Remove("colors");
}
//Parse Sizes
{
TArray<TSharedPtr<FJsonValue>> ObjectSizes = USpeckleObjectUtils::CombineChunks(Obj->GetArrayField("sizes"), ReadTransport);
Sizes.Reserve(ObjectSizes.Num());
for (int32 i = 0; i < ObjectSizes.Num(); i += 1)
{
Sizes.Add( ObjectSizes[i].Get()->AsNumber() * ScaleFactor);
}
DynamicProperties.Remove("sizes");
}
return Points.Num() >= 0;
}
@@ -0,0 +1,86 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Objects/ObjectModelRegistry.h"
#include "Objects/Base.h"
#include "Templates/SubclassOf.h"
#include "UObject/UObjectIterator.h"
TMap<FString, TSubclassOf<UBase>> UObjectModelRegistry::TypeRegistry;
void UObjectModelRegistry::GenerateTypeRegistry()
{
//TypeRegistry.Reset();
TypeRegistry.Empty();
//TypeRegistry = TMap<FString, TSubclassOf<UBase>>();
//check(TypeRegistry.IsSet());
//Find every class : UBase and add to Registry
for (TObjectIterator<UClass> It; It; ++It)
{
const UClass* Class = *It;
if (Class->IsChildOf(UBase::StaticClass()) &&
!Class->HasAnyClassFlags(CLASS_Abstract))
{
const FString& SpeckleType = Class->GetDefaultObject<UBase>()->SpeckleType;;
ensureAlwaysMsgf(!TypeRegistry.Contains(SpeckleType),
TEXT("Base class: %s conflicts with: %s for SpeckleType: %s"),
*Class->GetName(),
*TypeRegistry[SpeckleType]->GetName(),
*SpeckleType);
TypeRegistry.Add(SpeckleType, *It);
}
}
}
TSubclassOf<UBase> UObjectModelRegistry::FindClosestType(const FString& SpeckleType)
{
FString TypeString(SpeckleType);
TSubclassOf<UBase> Type = nullptr;
while(!TryGetRegisteredType(TypeString, Type))
{
if(!ParentType(TypeString, TypeString)) return nullptr;
}
return Type;
}
bool UObjectModelRegistry::ParentType(const FString& Type, FString& NextType)
{
int32 DotSplitIndex;
Type.FindLastChar('.', DotSplitIndex);
int32 ColonSplitIndex;
Type.FindLastChar(':', ColonSplitIndex);
const int32 SplitIndex = FGenericPlatformMath::Max(DotSplitIndex, ColonSplitIndex);
if(SplitIndex <= 0) return false;
NextType = Type.Left(SplitIndex);
return true;
}
TSubclassOf<UBase> UObjectModelRegistry::GetRegisteredType(const FString& SpeckleType)
{
TSubclassOf<UBase> Type = nullptr;
TryGetRegisteredType(SpeckleType, Type);
return Type;
}
bool UObjectModelRegistry::TryGetRegisteredType(const FString& SpeckleType, TSubclassOf<UBase>& OutType)
{
if(TypeRegistry.Num() == 0) GenerateTypeRegistry();
const bool Contains = TypeRegistry.Contains(SpeckleType);
if(Contains)
{
OutType = *TypeRegistry.Find(SpeckleType);
}
return Contains;
}
@@ -0,0 +1,60 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Objects/Other/BlockInstance.h"
#include "LogSpeckle.h"
#include "API/SpeckleSerializer.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Transports/Transport.h"
bool UBlockInstance::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
if(!Super::Parse(Obj, ReadTransport)) return false;
const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units);
//Transform
if(!USpeckleObjectUtils::TryParseTransform(Obj, Transform)) return false;
Transform.ScaleTranslation(FVector(ScaleFactor));
DynamicProperties.Remove("Transform");
//Geometries
const TSharedPtr<FJsonObject>* BlockDefinitionPtr;
if(!Obj->TryGetObjectField("blockDefinition", BlockDefinitionPtr)) return false;
const FString RefID = BlockDefinitionPtr->operator->()->GetStringField("referencedId");
const TSharedPtr<FJsonObject> BlockDefinition = ReadTransport->GetSpeckleObject(RefID);
if(BlockDefinition->TryGetStringField("name", Name)) DynamicProperties.Remove("Name");
const auto Geometries = BlockDefinition->GetArrayField("geometry");
if(Geometries.Num() <= 0)
{
UE_LOG(LogSpeckle, Warning, TEXT("Block definition has no geometry. id: %s"), *RefID)
return false;
}
for(const auto& Geo : Geometries)
{
const TSharedPtr<FJsonObject> MeshReference = Geo->AsObject();
const FString ChildId = MeshReference->GetStringField("referencedId");
if(ReadTransport->HasObject(ChildId))
{
UBase* Child = USpeckleSerializer::DeserializeBase(ReadTransport->GetSpeckleObject(ChildId), ReadTransport);
if(IsValid(Child))
Geometry.Add(Child);
}
else UE_LOG(LogSpeckle, Warning, TEXT("Block definition references an unknown object id: %s"), *ChildId)
}
DynamicProperties.Remove("geometry");
// Intentionally don't remove blockDefinition from dynamic properties,
// because we want the converter to create the child geometries for us
//DynamicProperties.Remove("blockDefinition");
return true;
}
@@ -0,0 +1,36 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Objects/Other/View3D.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
bool UView3D::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
if(!Super::Parse(Obj, ReadTransport)) return false;
const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units);
// Parse optional Name property
if(Obj->TryGetStringField("name", Name)) DynamicProperties.Remove("name");
// Parse Origin
if(!USpeckleObjectUtils::ParseVectorProperty(Obj, "origin", ReadTransport, Origin)) return false;
Origin *= ScaleFactor;
DynamicProperties.Remove("origin");
// Parse UpDirection
if(!USpeckleObjectUtils::ParseVectorProperty(Obj, "upDirection", ReadTransport, UpDirection)) return false;
UpDirection *= ScaleFactor;
DynamicProperties.Remove("upDirection");
// Parse ForwardDirection
if(!USpeckleObjectUtils::ParseVectorProperty(Obj, "forwardDirection", ReadTransport, ForwardDirection)) return false;
ForwardDirection *= ScaleFactor;
DynamicProperties.Remove("forwardDirection");
// Parse IsOrthogonal
if(!Obj->TryGetBoolField("isOrthogonal", IsOrthogonal)) return false;
DynamicProperties.Remove("isOrthogonal");
return true;
}
@@ -0,0 +1,172 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "API/SpeckleSerializer.h"
#include "Engine/World.h"
#include "Objects/Geometry/Mesh.h"
#include "Transports/Transport.h"
TArray<TSharedPtr<FJsonValue>> USpeckleObjectUtils::CombineChunks(const TArray<TSharedPtr<FJsonValue>>& ArrayField, const TScriptInterface<ITransport> Transport)
{
TArray<TSharedPtr<FJsonValue>> ObjectPoints;
for(int32 i = 0; i < ArrayField.Num(); i++)
{
FString Index;
if(ArrayField[i]->AsObject()->TryGetStringField("referencedId", Index))
{
if(!ensureAlwaysMsgf(Transport->HasObject(Index), TEXT("Failed to Dechunk array, Could not find chunk %s in transport"), *Index))
continue;
const auto Chunk = Transport->GetSpeckleObject(Index)->GetArrayField("data");;
ObjectPoints.Append(Chunk);
}
else
{
return ArrayField; //Array was never chunked to begin with
}
}
return ObjectPoints;
}
bool USpeckleObjectUtils::ResolveReference(const TSharedPtr<FJsonObject> Object, const TScriptInterface<ITransport> Transport, TSharedPtr<FJsonObject>& OutObject)
{
FString SpeckleType;
FString ReferenceID;
if (Object->TryGetStringField("speckle_type", SpeckleType)
&& SpeckleType == "reference"
&& Object->TryGetStringField("referencedId",ReferenceID))
{
check(Transport != nullptr && Transport.GetObject() != nullptr)
OutObject = Transport->GetSpeckleObject(ReferenceID);
return OutObject != nullptr;
}
return false;
}
float USpeckleObjectUtils::ParseScaleFactor(const FString& UnitsString)
{
static const auto ParseUnits = [](const FString& LUnits) -> float
{
if (LUnits == "millimeters" || LUnits == "millimeter" || LUnits == "millimetres" || LUnits == "millimetre" || LUnits == "mm")
return 0.1;
if (LUnits == "centimeters" || LUnits == "centimeter" ||LUnits == "centimetres" || LUnits == "centimetre" || LUnits == "cm")
return 1;
if (LUnits == "meters" || LUnits == "meter" || LUnits == "metres" || LUnits == "metre" || LUnits == "m")
return 100;
if (LUnits == "kilometers" || LUnits == "kilometres" || LUnits == "km")
return 100000;
if (LUnits == "inches" || LUnits == "inch" || LUnits == "in")
return 2.54;
if (LUnits == "feet" || LUnits == "foot" || LUnits == "ft")
return 30.48;
if (LUnits == "yards" || LUnits == "yard"|| LUnits == "yd")
return 91.44;
if (LUnits == "miles" || LUnits == "mile" || LUnits == "mi")
return 160934.4;
return 100;
};
return ParseUnits(UnitsString.ToLower()); // * WorldToCentimeters; //TODO take into account world units
}
FTransform USpeckleObjectUtils::CreateTransform(UPARAM(ref) const FMatrix& TransformMatrix)
{
FTransform Transform(TransformMatrix);
Transform.ScaleTranslation(FVector(1,-1,1));
FVector Rot = Transform.GetRotation().Euler();
FVector NewRot(-Rot.X, Rot.Y, -Rot.Z);
Transform.SetRotation(FQuat::MakeFromEuler(NewRot));
return Transform;
}
bool USpeckleObjectUtils::TryParseTransform(const TSharedPtr<FJsonObject> SpeckleObject, FMatrix& OutMatrix)
{
const TSharedPtr<FJsonObject>* TransformObject;
const TArray<TSharedPtr<FJsonValue>>* TransformData;
if(SpeckleObject->TryGetArrayField("transform", TransformData)) //Handle transform as array
{ }
else if(SpeckleObject->TryGetObjectField("transform", TransformObject)
&& (*TransformObject)->TryGetArrayField("value", TransformData)) //Handle transform as object
{ }
else return false;
FMatrix TransformMatrix;
for(int32 Row = 0; Row < 4; Row++)
for(int32 Col = 0; Col < 4; Col++)
{
TransformMatrix.M[Row][Col] = TransformData->operator[](Row * 4 + Col)->AsNumber();
}
OutMatrix = TransformMatrix.GetTransposed();
return true;
}
bool USpeckleObjectUtils::ParseVectorProperty(const TSharedPtr<FJsonObject> Base, const FString& PropertyName,
const TScriptInterface<ITransport> ReadTransport, FVector& OutObject)
{
const TSharedPtr<FJsonObject>* OriginObject;
if(Base->TryGetObjectField(PropertyName, OriginObject)
&& ParseVector(*OriginObject, ReadTransport, OutObject))
{
return true;
}
return false;
}
bool USpeckleObjectUtils::ParseVector(const TSharedPtr<FJsonObject> Object,
const TScriptInterface<ITransport> Transport, FVector& OutObject)
{
if(!ensure(Object != nullptr)) return false;
TSharedPtr<FJsonObject> Obj;
if(!ResolveReference(Object, Transport, Obj)) Obj = Object;
double x = 0, y = 0, z = 0;
if(!(Obj->TryGetNumberField("x", x)
&& Obj->TryGetNumberField("y", y)
&& Obj->TryGetNumberField("z", z))) return false;
OutObject = FVector(x,y,z);
//return true;
UMesh* Mesh;
return ParseSpeckleObject<UMesh>(Obj, Transport, Mesh);
}
template <typename TBase>
bool USpeckleObjectUtils::ParseSpeckleObject(const TSharedPtr<FJsonObject> Object,
const TScriptInterface<ITransport> Transport, TBase*& OutObject)
{
static_assert(TIsDerivedFrom<TBase, UBase>::IsDerived, "Type TBase must inherit UBase");
TSharedPtr<FJsonObject> Obj;
if(!ResolveReference(Object, Transport, Obj)) Obj = Object;
UBase* b = USpeckleSerializer::DeserializeBase(Object, Transport);
OutObject = Cast<TBase>(b);
return OutObject == nullptr;
}
AActor* USpeckleObjectUtils::SpawnActorInWorld(const UObject* WorldContextObject, const TSubclassOf<AActor> Class, UPARAM(ref) const FTransform& Transform)
{
return WorldContextObject->GetWorld()->SpawnActor(Class, &Transform, FActorSpawnParameters());
}
FString USpeckleObjectUtils::DisplayAsString(const FString& msg, const TSharedPtr<FJsonObject> Obj)
{
FString OutputString;
TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&OutputString);
FJsonSerializer::Serialize(Obj.ToSharedRef(), Writer);
UE_LOG(LogSpeckle, Display, TEXT("resulting jsonString from %s -> %s"), *msg, *OutputString);
return OutputString;
}
@@ -0,0 +1,428 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "ReceiveSelectionComponent.h"
#include "JsonObjectConverter.h"
#include "LogSpeckle.h"
#include "API/ClientAPI.h"
#include "API/Models/SpeckleUser.h"
#if WITH_EDITOR
void UReceiveSelectionComponent::PostEditChangeProperty(FPropertyChangedEvent& e)
{
Super::PostEditChangeProperty(e);
const FName PropertyName = (e.Property != nullptr) ? e.Property->GetFName() : NAME_None;
PropertyChangeHandler(PropertyName);
}
#endif
void UReceiveSelectionComponent::PropertyChangeHandler(const FName& PropertyName)
{
if(bManualMode) return;
if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, bManualMode))
{
Refresh();
}
else if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, AuthToken)
|| PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, ServerUrl))
{
IsAccountValid = !AuthToken.IsEmpty() && !ServerUrl.IsEmpty();
if(IsAccountValid)
{
//TODO maybe we should check URL is a valid URL?
ServerUrl.TrimEndInline();
while(ServerUrl.RemoveFromEnd("/")) { }
AuthToken.TrimEndInline();
}
UpdateStreams();
}
else if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, SelectedStreamText)
&& !SelectedStreamText.IsEmpty())
{
IsStreamValid = Streams.Contains(SelectedStreamText);
if(IsStreamValid)
{
SelectStream(SelectedStreamText);
}
else UpdateStreams();
}
else if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, SelectedBranchText)
&& !SelectedBranchText.IsEmpty())
{
IsBranchValid = Branches.Contains(SelectedBranchText);
if(IsBranchValid)
{
SelectBranch(SelectedBranchText);
}
else UpdateBranches();
}
else if (PropertyName == GET_MEMBER_NAME_CHECKED(UReceiveSelectionComponent, SelectedCommitText)
&& !SelectedCommitText.IsEmpty())
{
IsCommitValid = Commits.Contains(SelectedCommitText);
if(IsCommitValid)
{
SelectCommit(SelectedCommitText);
}
else UpdateCommits();
}
}
void UReceiveSelectionComponent::Refresh()
{
IsAccountValid = !AuthToken.IsEmpty() && !ServerUrl.IsEmpty();
UpdateStreams();
}
bool UReceiveSelectionComponent::TryGetSelectedCommit(FSpeckleCommit& OutCommit) const
{
if(!bManualMode && IsCommitValid)
{
OutCommit = Commits.FindRef(SelectedCommitText);
return true;
}
return false;
}
bool UReceiveSelectionComponent::TryGetSelectedBranch(FSpeckleBranch& OutBranch) const
{
if(!bManualMode && IsBranchValid)
{
OutBranch = Branches.FindRef(SelectedBranchText);
return true;
}
return false;
}
bool UReceiveSelectionComponent::TryGetSelectedStream(FSpeckleStream& OutStream) const
{
if(!bManualMode && IsStreamValid)
{
OutStream = Streams.FindRef(SelectedStreamText);
return true;
}
return false;
}
void UReceiveSelectionComponent::OpenURLInBrowser() const
{
const FString URL = GetUrl();
if(!ensure(FPlatformProcess::CanLaunchURL(*URL))) return;
FString LaunchErrors;
FPlatformProcess::LaunchURL(*URL, nullptr, &LaunchErrors);
if(LaunchErrors.IsEmpty())
{
UE_LOG(LogSpeckle, Log, TEXT("Launched URL \"%s\" in browser"), *URL);
}
else
{
UE_LOG(LogSpeckle, Warning, TEXT("Failed to launched URL \"%s\" in browser - %s"), *URL, *LaunchErrors);
}
}
bool UReceiveSelectionComponent::IsSelectionComplete(FString& OutStatusMessage) const
{
if(bManualMode)
{
if(ServerUrl.IsEmpty()) OutStatusMessage = TEXT("Server Url is invalid, must specify a valid url");
else if(StreamId.IsEmpty()) OutStatusMessage = TEXT("Stream id is invalid, must specify a streamId");
else if(ObjectId.IsEmpty()) OutStatusMessage = TEXT("Object id is invalid, must specify a objectId");
else
{
OutStatusMessage = TEXT("Ready to recieve object");
return true;
}
}
else
{
if(!IsAccountValid) OutStatusMessage = TEXT("Account is invalid, please specify a valid server URL and token. (tokens can be created from your Speckle profiles page)");
else if(!IsStreamValid) OutStatusMessage = TEXT("Selected stream is invalid");
else if(!IsBranchValid) OutStatusMessage = TEXT("Selected branch is invalid");
else if(!IsCommitValid) OutStatusMessage = TEXT("Selected commit is invalid");
else
{
ensure(!ServerUrl.IsEmpty());
ensure(!StreamId.IsEmpty());
ensure(!ObjectId.IsEmpty());
OutStatusMessage = TEXT("Ready to recieve commit");
return true;
}
}
return false;
}
FString UReceiveSelectionComponent::GetUrl() const
{
if(bManualMode)
{
return FString::Printf(TEXT("%s/streams/%s/objects/%s"),
*ServerUrl, *StreamId, *ObjectId);
}
if(!IsStreamValid) return ServerUrl;
if(!IsBranchValid)
return FString::Printf(TEXT("%s/streams/%s/"),
*ServerUrl, *GetSelectedStream().ID);
if(!IsCommitValid)
return FString::Printf(TEXT("%s/streams/%s/branches/%s"),
*ServerUrl, *GetSelectedStream().ID, *GetSelectedBranch().Name);
return FString::Printf(TEXT("%s/streams/%s/commits/%s"),
*ServerUrl, *GetSelectedStream().ID, *GetSelectedCommit().ID);
}
TArray<FString> UReceiveSelectionComponent::GetStreamsOptions() const
{
TArray<FString> Options;
Streams.GetKeys(Options);
return Options;
}
bool UReceiveSelectionComponent::SelectStream(const FString& DisplayId)
{
const bool IsValid = !DisplayId.IsEmpty() && Streams.Contains(DisplayId);
if(IsValid && !bManualMode)
{
SelectedStreamText = DisplayId;
IsStreamValid = true;
StreamId = GetSelectedStream().ID;
}
else
{
SelectedStreamText = "";
IsStreamValid = false;
}
UpdateBranches();
return IsStreamValid;
}
void UReceiveSelectionComponent::UpdateStreams()
{
Streams.Reset();
SelectStream("");
if(!IsAccountValid || bManualMode) return;
const FString LogName(__FUNCTION__);
const FString Payload = FString::Printf(TEXT("{\"query\": \"query{user{id streams(limit: %d){items{id name}}}}\"}"), Limit);
//Response Handling
auto OnComplete = [&](const FString& ResponseJson)
{
if(bManualMode) return;
FSpeckleUser Response;
if(!ensure(FJsonObjectConverter::JsonObjectStringToUStruct(*ResponseJson, &Response, 0, 0))) return;
const TArray<FSpeckleStream>& AvailableStreams = Response.Streams.Items;
//Assemble stream map
Streams.Reserve(AvailableStreams.Num());
for(const auto& s : Response.Streams.Items)
{
FString DisplayId = FString::Printf(TEXT("%s - %s"), *s.Name, *s.ID);
Streams.Add(DisplayId, s);
}
//Set default selection
if(AvailableStreams.Num() > 0)
{
const FSpeckleStream& s = AvailableStreams[0];
FString DisplayId = FString::Printf(TEXT("%s - %s"), *s.Name, *s.ID);
SelectStream(DisplayId);
}
UE_LOG(LogSpeckle, Verbose, TEXT("%s was successful"), *LogName);
};
FAPIResponceDelegate CompleteDelegate;
CompleteDelegate.BindLambda(OnComplete);
//On error
FErrorDelegate ErrorDelegate;
ErrorDelegate.BindStatic(LogError, LogName);
FClientAPI::MakeGraphQLRequest(ServerUrl, AuthToken, "user", Payload, LogName, CompleteDelegate, ErrorDelegate);
}
FSpeckleStream UReceiveSelectionComponent::GetSelectedStream() const
{
return Streams[SelectedStreamText];
}
TArray<FString> UReceiveSelectionComponent::GetBranchOptions()
{
TArray<FString> Options;
Branches.GetKeys(Options);
return Options;
}
bool UReceiveSelectionComponent::SelectBranch(const FString& DisplayId)
{
const bool IsValid = !DisplayId.IsEmpty() && Branches.Contains(DisplayId);
if(IsValid && !bManualMode)
{
SelectedBranchText = DisplayId;
IsBranchValid = true;
}
else
{
SelectedBranchText = "";
IsBranchValid=false;
}
UpdateCommits();
return IsBranchValid;
}
void UReceiveSelectionComponent::UpdateBranches()
{
Branches.Reset();
SelectBranch("");
if(!IsStreamValid || bManualMode) return;
const FString LogName(__FUNCTION__);
const FString Payload = FString::Printf(TEXT("{\"query\": \"query{stream(id: \\\"%s\\\"){branches(limit: %d){items{id name}}}}\"}"), *GetSelectedStream().ID, Limit);
//Response Handling
auto OnComplete = [&](const FString& ResponseJson)
{
if(bManualMode) return;
FSpeckleStream Response;
if(!ensure(FJsonObjectConverter::JsonObjectStringToUStruct(*ResponseJson, &Response, 0, 0))) return;
const TArray<FSpeckleBranch>& AvailableBranches = Response.Branches.Items;
//Assemble stream map
Branches.Reserve(AvailableBranches.Num());
for(const auto& b : AvailableBranches)
{
FString DisplayId = FString::Printf(TEXT("%s"), *b.Name);
Branches.Add(DisplayId, b);
}
UE_LOG(LogSpeckle, Verbose, TEXT("%s was successful"), *LogName);
//Set default selection
if(AvailableBranches.Num() > 0)
{
const FSpeckleBranch& b = AvailableBranches[0];
FString DisplayId = FString::Printf(TEXT("%s"), *b.Name);
SelectBranch(DisplayId);
}
};
FAPIResponceDelegate CompleteDelegate;
CompleteDelegate.BindLambda(OnComplete);
//On error
FErrorDelegate ErrorDelegate;
ErrorDelegate.BindStatic(LogError, LogName);
FClientAPI::MakeGraphQLRequest(ServerUrl, AuthToken, "stream", Payload,LogName, CompleteDelegate, ErrorDelegate);
}
FSpeckleBranch UReceiveSelectionComponent::GetSelectedBranch() const
{
return Branches[SelectedBranchText];
}
TArray<FString> UReceiveSelectionComponent::GetCommitOptions()
{
TArray<FString> Options;
Commits.GetKeys(Options);
return Options;
}
bool UReceiveSelectionComponent::SelectCommit(const FString& DisplayId)
{
const bool IsValid = !DisplayId.IsEmpty() && Commits.Contains(DisplayId);
if(IsValid && !bManualMode)
{
SelectedCommitText = DisplayId;
IsCommitValid = true;
ObjectId = GetSelectedCommit().ReferencedObject;
}
else
{
SelectedCommitText = "";
IsCommitValid=false;
ObjectId = "";
}
return IsCommitValid;
}
void UReceiveSelectionComponent::UpdateCommits()
{
Commits.Reset();
SelectCommit("");
if(!IsBranchValid || bManualMode) return;
const FString LogName(__FUNCTION__);
const FString Payload = FString::Printf(TEXT("{\"query\": \"query{stream(id: \\\"%s\\\"){branch(name: \\\"%s\\\"){commits(limit: %d){items{id message referencedObject}}}}}\"}"), *GetSelectedStream().ID, *GetSelectedBranch().Name, Limit);
//Response Handling
auto OnComplete = [&](const FString& ResponseJson)
{
if(bManualMode) return;
FSpeckleStream Response;
if(!ensure(FJsonObjectConverter::JsonObjectStringToUStruct(*ResponseJson, &Response, 0, 0))) return;
const TArray<FSpeckleCommit>& AvailableCommits = Response.Branch.Commits.Items;
//Assemble stream map
for(const auto& c :AvailableCommits)
{
FString DisplayId = FString::Printf(TEXT("%s - %s"), *c.Message, *c.ID);
Commits.Add(DisplayId, c);
}
UE_LOG(LogSpeckle, Verbose, TEXT("%s was successful"), *LogName);
//Set default selection
if(AvailableCommits.Num() > 0)
{
const FSpeckleCommit& c = AvailableCommits[0];
FString DisplayId = FString::Printf(TEXT("%s - %s"), *c.Message, *c.ID);
SelectCommit(DisplayId);
}
};
FAPIResponceDelegate CompleteDelegate;
CompleteDelegate.BindLambda(OnComplete);
//On error
FErrorDelegate ErrorDelegate;
ErrorDelegate.BindStatic(LogError, LogName);
FClientAPI::MakeGraphQLRequest(ServerUrl, AuthToken, "stream", Payload,LogName, CompleteDelegate, ErrorDelegate);
}
FSpeckleCommit UReceiveSelectionComponent::GetSelectedCommit() const
{
return Commits[SelectedCommitText];
}
void UReceiveSelectionComponent::LogError(const FString& Message, const FString LogName)
{
UE_LOG(LogSpeckle, Warning, TEXT("%s: %s"), *LogName, *Message)
}
@@ -1,4 +1,4 @@
// Copyright Epic Games, Inc. All Rights Reserved.
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "SpeckleUnreal.h"
@@ -6,13 +6,14 @@
void FSpeckleUnrealModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
// This code will execute after your module is loaded into memory.
// The exact timing is specified in the .uplugin file per-module
}
void FSpeckleUnrealModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
// This function may be called during shutdown to clean up your module.
// For modules that support dynamic reloading, we call this function before unloading the module.
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,147 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "SpeckleUnrealManager.h"
#include "ReceiveSelectionComponent.h"
#include "API/Operations/ReceiveOperation.h"
#include "Transports/MemoryTransport.h"
#include "Transports/ServerTransport.h"
#include "LogSpeckle.h"
#include "API/SpeckleSerializer.h"
#include "Conversion/SpeckleConverterComponent.h"
#include "Misc/ScopedSlowTask.h"
#include "Objects/Base.h"
#include "Mixpanel.h"
#include "API/SpeckleAPIFunctions.h"
#include "Engine/Engine.h"
#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule"
// Sets default values
ASpeckleUnrealManager::ASpeckleUnrealManager()
{
SetRootComponent(CreateDefaultSubobject<USceneComponent>(TEXT("Root")));
RootComponent->SetRelativeScale3D(FVector(1,1,1));
RootComponent->SetMobility(EComponentMobility::Static);
Converter = CreateDefaultSubobject<USpeckleConverterComponent>(FName("Converter"));
ReceiveSelection = CreateDefaultSubobject<UReceiveSelectionComponent>(FName("ReceiveSelection"));
KeepCache = true;
DisplayProgressBar = true;
}
void ASpeckleUnrealManager::BeginPlay()
{
Super::BeginPlay();
if(ImportAtRuntime) Receive();
}
void ASpeckleUnrealManager::Receive()
{
// Check object to receive has been specified properly
FString StatusMessage;
if(!ReceiveSelection->IsSelectionComplete(StatusMessage))
{
HandleError(StatusMessage);
return;
}
// Delete all actors from previous receive operations
DeleteObjects();
const FString ServerUrl = ReceiveSelection->ServerUrl;
const FString AuthToken = ReceiveSelection->AuthToken;
const FString StreamId = ReceiveSelection->StreamId;
const FString ObjectId = ReceiveSelection->ObjectId;
FAnalytics::TrackEvent( ServerUrl, "NodeRun", TMap<FString, FString> { {"name", StaticClass()->GetName() }, {"worldType", FString::FromInt(GetWorld()->WorldType)}});
FString Message = FString::Printf(TEXT("Fetching Objects from Speckle Server: %s"), *ServerUrl);
PrintMessage(Message);
// Setup network transports
UServerTransport* ServerTransport = UServerTransport::CreateServerTransport(ServerUrl,StreamId,AuthToken);
if(!KeepCache && LocalObjectCache)
{
LocalObjectCache.GetObjectRef()->ConditionalBeginDestroy();
LocalObjectCache = UMemoryTransport::CreateEmptyMemoryTransport();
}
if(!LocalObjectCache) LocalObjectCache = UMemoryTransport::CreateEmptyMemoryTransport();
// Setup delegate callbacks
FTransportErrorDelegate ErrorDelegate;
ErrorDelegate.BindUObject(this, &ASpeckleUnrealManager::HandleError);
FTransportCopyObjectCompleteDelegate CompleteDelegate;
CompleteDelegate.BindUObject(this, &ASpeckleUnrealManager::HandleReceive, DisplayProgressBar);
// Send request for objects
ServerTransport->CopyObjectAndChildren(ObjectId, LocalObjectCache, CompleteDelegate, ErrorDelegate);
// Read receipt (if receiving a commit object)
FSpeckleCommit Commit;
if(ReceiveSelection->TryGetSelectedCommit(Commit))
{
//TODO read receipt
USpeckleAPIFunctions::CommitReceived(Commit);
}
}
void ASpeckleUnrealManager::HandleReceive(TSharedPtr<FJsonObject> RootObject, bool DisplayProgress)
{
if(RootObject == nullptr) return;
const UBase* Res = USpeckleSerializer::DeserializeBase(RootObject, LocalObjectCache);
if(IsValid(Res))
{
Converter->RecursivelyConvertToNative(this, Res, LocalObjectCache, DisplayProgress, Actors);
FString Message = FString::Printf(TEXT("Converted %d Actors"), Actors.Num());
PrintMessage(Message);
}
else
{
FString Id;
RootObject->TryGetStringField("id", Id);
FString Message = FString::Printf(TEXT("Failed to deserialise root object: %s"), *Id);
HandleError(Message);
}
}
void ASpeckleUnrealManager::HandleError(FString& Message)
{
PrintMessage(Message, true);
}
void ASpeckleUnrealManager::PrintMessage(FString& Message, bool IsError) const
{
if(IsError)
{
UE_LOG(LogSpeckle, Error, TEXT("%s"), *Message);
}
else
{
UE_LOG(LogSpeckle, Log, TEXT("%s"), *Message);
}
FColor Color = IsError? FColor::Red : FColor::Green;
GEngine->AddOnScreenDebugMessage(0, 5.0f, Color, Message);
}
void ASpeckleUnrealManager::DeleteObjects()
{
Converter->FinishConversion();
for (AActor* a : Actors)
{
if(IsValid(a)) a->Destroy();
}
Actors.Empty();
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,79 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "LogSpeckle.h"
#include "Misc/AutomationTest.h"
#include "ReceiveSelectionComponent.h"
#include "Tests/AutomationCommon.h"
#if WITH_DEV_AUTOMATION_TESTS
class UMock : public UReceiveSelectionComponent
{
friend class FReceiveSelectionComponentTest;
friend class FCheckValidSelection;
friend class FCheckLimitMatch;
};
DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FCheckValidSelection, FAutomationTestBase*, Test, UMock*, SelectionComponent);
bool FCheckValidSelection::Update()
{
const UMock* s = SelectionComponent;
Test->TestTrue(TEXT("Account valid on set"), s->IsAccountValid);
Test->TestTrue(TEXT("Stream valid on set"), s->IsStreamValid);
Test->TestTrue(TEXT("Branch valid on set"), s->IsBranchValid);
Test->TestTrue(TEXT("Commit valid on set"), s->IsCommitValid);
return true;
}
DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FCheckLimitMatch, FAutomationTestBase*, Test, UMock*, SelectionComponent);
bool FCheckLimitMatch::Update()
{
const UMock* s = SelectionComponent;
Test->TestTrue(TEXT("Fetched streams is less than limit"), s->Streams.Num() <= s->Limit);
Test->TestTrue(TEXT("Fetched branches is less than limit"), s->Branches.Num() <= s->Limit);
Test->TestTrue(TEXT("Fetched commits is less than limit"), s->Commits.Num() <= s->Limit);
return true;
}
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FReceiveSelectionComponentTest, "SpeckleUnreal.ReceiveSelectionComponentTest", EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter)
bool FReceiveSelectionComponentTest::RunTest(const FString& Parameters)
{
#ifdef TEST_AUTH_TOKEN
UMock* s = NewObject<UMock>();
//Test initialisation
TestFalse(TEXT("Account valid on initialise"), s->IsAccountValid);
TestFalse(TEXT("Stream valid on initialise"), s->IsStreamValid);
TestFalse(TEXT("Branch valid on initialise"), s->IsBranchValid);
TestFalse(TEXT("Commit valid on initialise"), s->IsCommitValid);
s->AuthToken = TEST_AUTH_TOKEN;
s->ServerUrl = TEXT("https://latest.speckle.dev");
s->bManualMode = false;
s->Refresh();
//wait 5 seconds for HTTP requests to finish
ADD_LATENT_AUTOMATION_COMMAND(FWaitLatentCommand(5.0f));
ADD_LATENT_AUTOMATION_COMMAND(FCheckValidSelection(this, s));
ADD_LATENT_AUTOMATION_COMMAND(FCheckLimitMatch(this, s));
#else
TestTrue(TEXT("TEST_AUTH_TOKEN definition exists"), false);
return false;
#endif
return true;
}
#endif
@@ -0,0 +1,62 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Misc/AutomationTest.h"
#include "Objects/Base.h"
#include "Transports/MemoryTransport.h"
#if WITH_DEV_AUTOMATION_TESTS
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FMemoryTransportTest, "SpeckleUnreal.Transports.MemoryTransport", EAutomationTestFlags::EditorContext | EAutomationTestFlags::SmokeFilter)
bool FMemoryTransportTest::RunTest(const FString& Parameters)
{
UMemoryTransport* Transport = UMemoryTransport::CreateEmptyMemoryTransport();
// Test Construction
{
TestNotNull(TEXT("Constructed object"), Transport);
TestTrue(TEXT("Constructed object is valid"), IsValid(Transport));
}
TSharedPtr<FJsonObject> MockObj = MakeShareable(new FJsonObject());
FString TestId = TEXT("testidlalalala");
FString TestPayloadName = TEXT("Playload");
FString TestPayload = TEXT("MyPayloadValue!");
MockObj->SetStringField(TestPayloadName, TestPayload);
// Test Save
{
Transport->SaveObject(TestId, MockObj);
TestTrue(TEXT("Transport with save object to HasObject"), Transport->HasObject(TestId));
auto Value = Transport->GetSpeckleObject(TestId);
TestNotNull(TEXT("Return of getting saved object"), Value.Get());
TestEqual(TEXT("Return of getting saved object"), Value, MockObj);
TestTrue(TEXT("Returned object to have payload"), Value->HasField(TestPayloadName));
TestEqual(TEXT("Returned object's playload"), Value->GetStringField(TestPayloadName), TestPayload);
}
// Test Ids are missing
{
TArray<FString> MissingIds = {
TEXT("NoObjectsWithThisId"),
TEXT("testidla"),
TEXT("testidlalalalaextrala"),
TEXT("testidrararara"),
TEXT(""),
};
for(const FString& Id : MissingIds)
{
TestFalse(TEXT("transport has unknown id -") + Id, Transport->HasObject(Id));
auto ValueM = Transport->GetSpeckleObject(Id);
TestNull(TEXT("return of unknown id -") + Id, ValueM.Get());
}
}
return true;
}
#endif
@@ -0,0 +1,22 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Transports/MemoryTransport.h"
#include "LogSpeckle.h"
bool UMemoryTransport::HasObject(const FString& ObjectId) const
{
return SpeckleObjects.Contains(ObjectId);
}
TSharedPtr<FJsonObject> UMemoryTransport::GetSpeckleObject(const FString& ObjectId) const
{
return SpeckleObjects.FindRef(ObjectId);
}
void UMemoryTransport::SaveObject(const FString& ObjectId, const TSharedPtr<FJsonObject> SerializedObject)
{
SpeckleObjects.Add(ObjectId, SerializedObject);
UE_LOG(LogSpeckle, Verbose, TEXT("Added %s to in memory transport, now %d objects total "), *ObjectId, SpeckleObjects.Num());
}
@@ -0,0 +1,254 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Transports/ServerTransport.h"
#include "LogSpeckle.h"
#include "Mixpanel.h"
#include "JsonObjectConverter.h"
#include "HttpModule.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"
#include "Policies/CondensedJsonPrintPolicy.h"
TSharedPtr<FJsonObject> UServerTransport::GetSpeckleObject(const FString& ObjectId) const
{
unimplemented();
return nullptr;
}
void UServerTransport::SaveObject(const FString& ObjectId, const TSharedPtr<FJsonObject> SerializedObject)
{
unimplemented(); //TODO implement
}
bool UServerTransport::HasObject(const FString& ObjectId) const
{
unimplemented(); //TODO implement
return false;
}
void UServerTransport::HandleRootObjectResponse(const FString& RootObjSerialized,
TScriptInterface<ITransport> TargetTransport,
const FString& ObjectId) const
{
TSharedPtr<FJsonObject> RootObj;
if(!LoadJson(RootObjSerialized, RootObj))
{
FString Message = FString::Printf( TEXT("A Root Object %s was recieved but was invalid and could not be deserialied"), *ObjectId);
InvokeOnError(Message);
return;
}
TargetTransport->SaveObject(ObjectId, RootObj);
// Find children are not already in the target transport
const auto Closures = RootObj->GetObjectField("__closure")->Values;
TArray<FString> ChildrenIds;
Closures.GetKeys(ChildrenIds);
TArray<FString> NewChildrenIds;
for(const FString& Id : ChildrenIds)
{
if(TargetTransport->HasObject(Id)) continue;
NewChildrenIds.Add(Id);
}
FetchChildren(TargetTransport, ObjectId, NewChildrenIds);
}
void UServerTransport::CopyObjectAndChildren(const FString& ObjectId,
TScriptInterface<ITransport> TargetTransport,
const FTransportCopyObjectCompleteDelegate& OnCompleteAction,
const FTransportErrorDelegate& OnErrorAction)
{
this->OnComplete = OnCompleteAction;
this->OnError = OnErrorAction;
// Create Request for Root Object
const FHttpRequestRef Request = FHttpModule::Get().CreateRequest();
const FString Endpoint = FString::Printf(TEXT("%s/objects/%s/%s/single"), *ServerUrl, *StreamId, *ObjectId);
Request->SetVerb("GET");
Request->SetURL(Endpoint);
Request->SetHeader("Accept", TEXT("text/plain"));
Request->SetHeader("Authorization", "Bearer " + AuthToken);
// Response Callback
auto ResponseHandler = [=](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable
{
if(!bWasSuccessful)
{
FString Message = FString::Printf(TEXT("Request for root object at %s was unsuccessful: %s"), *Response->GetURL(), *Response->GetContentAsString());
InvokeOnError(Message);
return;
}
const int32 ResponseCode = Response->GetResponseCode();
if (ResponseCode != 200)
{
FString Message = FString::Printf(TEXT("Request for root object at %s failed with HTTP response %d"), *Response->GetURL(), ResponseCode);
InvokeOnError(Message);
return;
}
HandleRootObjectResponse(Response->GetContentAsString(), TargetTransport, ObjectId);
};
Request->OnProcessRequestComplete().BindLambda(ResponseHandler);
// Send request
const bool RequestSent = Request->ProcessRequest();
if(!RequestSent)
{
FString Message = FString::Printf(TEXT("Request for root object at %s failed: \nHTTP request failed to start"), *Endpoint);
InvokeOnError(Message);
return;
}
UE_LOG(LogSpeckle, Verbose, TEXT("GET Request sent for root object at %s, awaiting response"), *Endpoint );
FAnalytics::TrackEvent(ServerUrl, "Receive");
}
void UServerTransport::FetchChildren(TScriptInterface<ITransport> TargetTransport, const FString& ObjectId,
const TArray<FString>& ChildrenIds, int32 CStart) const
{
// Check if all children have been fetched
if(ChildrenIds.Num() <= CStart)
{
UE_LOG(LogSpeckle, Log, TEXT("Finished fetching child Speckle objects"));
ensureAlwaysMsgf(this->OnComplete.ExecuteIfBound(TargetTransport->GetSpeckleObject(ObjectId)),
TEXT("Complete handler was not bound properly"));
return;
}
// Assemble list of ids to ask for in this request
// We want to avoid making requests too large
const int32 CEnd = FGenericPlatformMath::Min(ChildrenIds.Num(), CStart + MaxNumberOfObjectsPerRequest);
FString ChildrenIdsString;
{
auto Writer = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&ChildrenIdsString);
Writer->WriteArrayStart();
for (int32 i = CStart; i < CEnd; i++)
{
Writer->WriteValue(ChildrenIds[i]);
} Writer->WriteArrayEnd();
Writer->Close();
}
FString Body;
{
auto Writer = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&Body);
Writer->WriteObjectStart();
Writer->WriteValue(TEXT("objects"), ChildrenIdsString);
Writer->WriteObjectEnd();
Writer->Close();
}
// Create Request
const FHttpRequestRef Request = FHttpModule::Get().CreateRequest();
{
const FString EndPoint = FString::Printf(TEXT("%s/api/getobjects/%s"), *ServerUrl, *StreamId);
Request->SetVerb("POST");
Request->SetURL(EndPoint);
Request->SetHeader("Accept", TEXT("text/plain"));
Request->SetHeader("Authorization", "Bearer " + AuthToken);
Request->SetHeader("Content-Type", "application/json");
Request->SetContentAsString(Body);
}
// Response Callback
auto ResponseHandler = [=](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable
{
// Request Fail
if(!bWasSuccessful)
{
FString Message = FString::Printf(TEXT("Request for children of root object %s/%s failed: %s"),
*StreamId, *ObjectId, *Response->GetContentAsString());
InvokeOnError(Message);
return;
}
// Any HTTP Fail
const int32 ResponseCode = Response->GetResponseCode();
if (ResponseCode != 200)
{
FString Message = FString::Printf(
TEXT("Request for children of root object %s/%s failed:\nHTTP response %d"),
*StreamId, *ObjectId, ResponseCode);
InvokeOnError(Message);
return;
}
// Success: Start parsing
TArray<FString> Lines;
const int32 LineCount = SplitLines(Response->GetContentAsString(), Lines);
UE_LOG(LogSpeckle, Verbose, TEXT("Parsing %d downloaded objects..."), LineCount)
// Warning: Fewer/More objects then expected
if(LineCount != CEnd - CStart)
{
UE_LOG(LogSpeckle, Warning, TEXT("Requested %d objects, but received %d"), CEnd - CStart, LineCount);
}
// Load JSON as objects
for (const FString& Line : Lines)
{
FString Id, ObjectJson;
if (!Line.Split("\t", &Id, &ObjectJson))
continue;
TSharedPtr<FJsonObject> JsonObject;
if(!LoadJson(ObjectJson, JsonObject)) continue;
TargetTransport->SaveObject(Id, JsonObject);
}
UE_LOG(LogSpeckle, Log, TEXT("Processed %d/%d Child objects"), CEnd, ChildrenIds.Num())
//Iterate again for any missing children
FetchChildren(TargetTransport, ObjectId, ChildrenIds, CEnd);
};
Request->OnProcessRequestComplete().BindLambda(ResponseHandler);
// Send request for children
const bool RequestSent = Request->ProcessRequest();
if(!RequestSent)
{
FString Message = FString::Printf(TEXT("Failed to fetch children of root object %s/%s:\nHTTP request failed to start"), *StreamId, *ObjectId);
InvokeOnError(Message);
return;
}
UE_LOG(LogSpeckle, Verbose, TEXT("Requesting %d child objects"), CEnd - CStart);
}
void UServerTransport::InvokeOnError(FString& Message) const
{
ensureAlwaysMsgf(this->OnError.ExecuteIfBound(Message), TEXT("ServerTransport: Unhandled error - %s"), *Message);
}
int32 UServerTransport::SplitLines(const FString& Content, TArray<FString>& OutLines)
{
int32 LineCount = 0;
for (const TCHAR* ptr = *Content; *ptr; ptr++)
if (*ptr == '\n')
LineCount++;
OutLines.Reserve(LineCount);
Content.ParseIntoArray(OutLines, TEXT("\n"), true);
return LineCount;
}
bool UServerTransport::LoadJson(const FString& StringJson, TSharedPtr<FJsonObject>& OutJsonObject)
{
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(StringJson);
return FJsonSerializer::Deserialize(Reader, OutJsonObject);
}
@@ -0,0 +1,52 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "Interfaces/IHttpRequest.h"
DECLARE_DELEGATE_OneParam(FErrorDelegate, const FString&);
DECLARE_DELEGATE_OneParam(FAPIResponceDelegate, const FString&);
/**
* C++ wrapper of Speckle's GraphQL API
* Encapsulates sending HTTP requests with GraphQL Queries for specific resources
*
* Used to send GraphQL requests for commits, branches, streams, user info, collaborators etc.
*
* See `API/Operations` for usage examples
*/
class FClientAPI
{
public:
/**
* Creates and sends a graphql query to the specified url.
* Will check HTTP response for errors,
* and unpack the response "data" object.
* @param ServerUrl URL of the Speckle Server endpoint
* @param AuthToken
* @param ResponsePropertyName Property name of the requested object. This will be the first name in the query (e.g. "stream", "streams", "user", etc)
* @param PostPayload The POST payload containing the GraphQL request
* @param RequestLogName Friendly name for this request (for error handling and logging)
* @param OnCompleteAction Callback invoked on successful completion of the request, with the request object (as a JSON string)
* @param OnErrorAction Callback invoked on any fatal error with, the error message.
*/
static void MakeGraphQLRequest(const FString& ServerUrl, const FString& AuthToken, const FString& ResponsePropertyName,
const FString& PostPayload, const FString& RequestLogName,
const FAPIResponceDelegate OnCompleteAction, const FErrorDelegate OnErrorAction);
//protected:
/// Helper function for creating post requests with a GraphQL query
static FHttpRequestRef CreatePostRequest(const FString& ServerUrl, FString AuthToken, const FString& PostPayload,
const FString& Encoding = TEXT("gzip"));
static bool GetResponseAsJSON(const FHttpResponsePtr Response, const FString& RequestLogName, TSharedPtr<FJsonObject>& OutObject, const TFunctionRef<void(const FString& Message)> OnErrorAction);
static bool CheckForOperationErrors(const TSharedPtr<FJsonObject> GraphQLResponse, FString& OutErrorMessage);
static bool CheckRequestFailed(bool bWasSuccessful, FHttpResponsePtr Response, const FString& RequestName, const TFunctionRef<void(const FString& Message)> OnErrorAction);
};
@@ -0,0 +1,46 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "SpeckleCommit.h"
#include "SpeckleBranch.generated.h"
/*
* GraphQL model for Branch data
* Properties are only when they explicitly requested (through the GraphQL request)
* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs
*/
USTRUCT(BlueprintType)
struct FSpeckleBranch
{
GENERATED_BODY()
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString ID;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Name;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Description;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FSpeckleCommits Commits;
};
USTRUCT(BlueprintType)
struct FSpeckleBranches
{
GENERATED_BODY();
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
int32 TotalCount;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Cursor;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
TArray<FSpeckleBranch> Items;
};
@@ -0,0 +1,30 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "SpeckleCollaborator.generated.h"
/*
* GraphQL model for Collaborator data
* Properties are only when they explicitly requested (through the GraphQL request)
* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs
*/
USTRUCT(BlueprintType)
struct FSpeckleCollaborator
{
GENERATED_BODY()
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Id;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Name;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Role;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Avatar;
};
@@ -0,0 +1,66 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "SpeckleCommit.generated.h"
/*
* GraphQL model for Commit data
* Properties are only when they explicitly requested (through the GraphQL request)
* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs
*/
USTRUCT(BlueprintType)
struct FSpeckleCommit
{
GENERATED_BODY();
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString ID;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Message;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString BranchName;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString AuthorName;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString AuthorId;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString AuthorAvatar;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString CreatedAt;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString SourceApplication;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models", DisplayName="Referenced Object Id")
FString ReferencedObject;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString TotalChildrenCount;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
TArray<FString> Parents;
};
USTRUCT(BlueprintType)
struct FSpeckleCommits
{
GENERATED_BODY();
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
int32 TotalCount;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Cursor;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
TArray<FSpeckleCommit> Items;
};
@@ -0,0 +1,78 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "SpeckleBranch.h"
#include "SpeckleCollaborator.h"
#include "SpeckleStream.generated.h"
/*
* GraphQL model for Stream data
* Properties are only when they explicitly requested (through the GraphQL request)
* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs
*/
USTRUCT(BlueprintType)
struct FSpeckleStream
{
GENERATED_BODY()
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models", DisplayName="Stream Id")
FString ID;
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
FString Name;
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
FString Description;
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
bool IsPublic;
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
FString Role;
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
FString CreatedAt;
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
FString UpdatedAt;
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
FString FavoritedDate;
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
TArray<FSpeckleCollaborator> Collaborators;
// Object properties are only set if explicitly requested by a custom GraphQL request
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
FSpeckleBranches Branches;
// Object properties are only set if explicitly requested by a custom GraphQL request
UPROPERTY(BlueprintReadOnly, DisplayName="Branch (Request Only)", Category="Speckle|API Models", AdvancedDisplay)
FSpeckleBranch Branch;
// Object properties are only set if explicitly requested by a custom GraphQL request
UPROPERTY(BlueprintReadOnly, DisplayName="Commit (Request Only)", Category="Speckle|API Models", AdvancedDisplay)
FSpeckleCommit Commit;
// Object properties are only set if explicitly requested by a custom GraphQL request
UPROPERTY(BlueprintReadOnly, Category="Speckle|API Models")
FSpeckleCommits Commits;
};
USTRUCT(BlueprintType)
struct FSpeckleStreams
{
GENERATED_BODY();
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
int32 TotalCount;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Cursor;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
TArray<FSpeckleStream> Items;
};
@@ -0,0 +1,45 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "SpeckleStream.h"
#include "SpeckleUser.generated.h"
/*
* GraphQL model for User data
* Properties are only when they explicitly requested (through the GraphQL request)
* see https://github.com/specklesystems/speckle-sharp/blob/main/Core/Core/Api/GraphQL/Models.cs
*/
USTRUCT(BlueprintType)
struct FSpeckleUser
{
GENERATED_BODY()
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Id;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Email;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Name;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Bio;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Company;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Avatar;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Role;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FSpeckleStreams Streams;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FSpeckleStreams FavoriteStreams;
};
@@ -0,0 +1,59 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "ReceiveOperation.generated.h"
class ITransport;
class UBase;
class FJsonObject;
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FRecieveOperationHandler, UBase*, RootBase, FString, ErrorMessage);
/**
*
*/
UCLASS()
class SPECKLEUNREAL_API UReceiveOperation : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable)
FRecieveOperationHandler OnReceiveSuccessfully;
/// Called when the total number of children is known
//UPROPERTY(BlueprintAssignable)
//FRecieveOperationHandler OnChildrenCountKnown;
/// Called when some deserilization progress is made and TotalConverted has changed
//UPROPERTY(BlueprintAssignable)
//FRecieveOperationHandler OnProgress;
/// Called when receive operation has aborted due to some error
UPROPERTY(BlueprintAssignable)
FRecieveOperationHandler OnError;
UFUNCTION(BlueprintCallable, BlueprintInternalUseOnly, Category = "Speckle|Operations", meta = (WorldContext = "WorldContextObject"))
static UReceiveOperation* ReceiveOperation(UObject* WorldContextObject, const FString& ObjectId,
TScriptInterface<ITransport> RemoteTransport, TScriptInterface<ITransport> LocalTransport);
virtual void Activate() override;
protected:
void Receive();
FString ObjectId;
TScriptInterface<ITransport> RemoteTransport;
TScriptInterface<ITransport> LocalTransport;
void HandleReceive(TSharedPtr<FJsonObject> Object);
void HandleError(FString& Message);
};
@@ -0,0 +1,47 @@
// // Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
//
// #pragma once
//
// #include "CoreMinimal.h"
// #include "Kismet/BlueprintAsyncActionBase.h"
//
// #include "SendOperation.generated.h"
//
//
// class ITransport;
// class UBase;
//
// DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FSendOperationHandler, const FString&, Id, const FString&, ErrorMessage);
//
// /**
// *
// */
// UCLASS()
// class SPECKLEUNREAL_API USendOperation : public UBlueprintAsyncActionBase
// {
// GENERATED_BODY()
//
// public:
//
// UPROPERTY(BlueprintAssignable)
// FSendOperationHandler OnSendSuccessfully;
//
//
// UPROPERTY(BlueprintAssignable)
// FSendOperationHandler OnErrorAction;
//
//
// UFUNCTION(BlueprintCallable, Category = "Speckle|Operations", meta = (WorldContext = "WorldContextObject"))
// static USendOperation* SendOperation(UObject* WorldContextObject, UBase* Base, TArray<TScriptInterface<ITransport>> Transports);
//
// virtual void Activate() override;
//
// protected:
//
//
// TWeakObjectPtr<UBase> Base;
//
// TScriptArray<TScriptInterface<ITransport>> Transports;
//
//
// };
@@ -0,0 +1,63 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintAsyncActionBase.h"
#include "SpeckleStreamAPIOperation.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FAPIResponseHandler, FString, JsonResponse, FString, ErrorMessage);
/**
* Allows sending GraphQL queries to the Speckle GraphQL API
*
*/
UCLASS()
class SPECKLEUNREAL_API USpeckleStreamAPIOperation : public UBlueprintAsyncActionBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable)
FAPIResponseHandler OnReceiveSuccessfully;
UPROPERTY(BlueprintAssignable)
FAPIResponseHandler OnError;
/**
* Sends an GraphQL queries to a speckle server's "/graphql" endpoint
* E.g. for fetching stream/branch/commit/user info.
*
* @param ServerUrl The URL of the Speckle server
* @param AuthToken The auth token of the user (optional for unprivilaged requests)
* @param GraphQlQuery The GraphQl query (starting with `query{ }`)
* @param ResponsePropertyName The name of the root property being requested. (e.g. for a "query{user{...}" query, then the property name is "user")
* @param RequestLogName A friendly name for this request (logging and analytics)
*/
UFUNCTION(BlueprintCallable, BlueprintInternalUseOnly, Category = "Speckle|Operations")
static USpeckleStreamAPIOperation* SpeckleStreamAPIOperation(
const FString& ServerUrl,
const FString& AuthToken,
const FString& GraphQlQuery,
const FString& ResponsePropertyName,
const FString& RequestLogName);
virtual void Activate() override;
protected:
void Request();
FString ServerUrl;
FString AuthToken;
FString Query;
FString RequestLogName;
FString ResponsePropertyName;
void HandleReceive(const FString& ResponseJson);
void HandleError(const FString& Message);
};
@@ -0,0 +1,32 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "SpeckleAPIFunctions.generated.h"
struct FSpeckleCommit;
/**
* Blueprint function library for Speckle API
*/
UCLASS()
class SPECKLEUNREAL_API USpeckleAPIFunctions : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, CustomThunk, Category="Speckle|API", meta=(CustomStructureParam="OutStruct", ExpandBoolAsExecs="ReturnValue"))
static UPARAM(DisplayName = "WasSucessful") bool DeserializeResponse(const FString& JsonString, int32& OutStruct);
DECLARE_FUNCTION(execDeserializeResponse);
static bool GenericDeserializeResponse(const FString& JsonString, const UScriptStruct* StructType, void* OutStruct);
static void CommitReceived(FSpeckleCommit& Commit);
};
@@ -0,0 +1,26 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "SpeckleSerializer.generated.h"
class UBase;
class ITransport;
class FJsonObject;
UCLASS()
class USpeckleSerializer : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintPure, Category="Speckle|Serialization")
static UBase* DeserializeBaseById(const FString& ObjectId, const TScriptInterface<ITransport> ReadTransport);
static UBase* DeserializeBase(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport);
};
@@ -0,0 +1,59 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "Conversion/SpeckleConverter.h"
#include "AggregateConverter.generated.h"
/**
* An Aggregate Converter stores multiple ISpeckleConverter instances.
* This allows you to use many converters as one
*/
UCLASS()
class SPECKLEUNREAL_API UAggregateConverter : public UObject, public ISpeckleConverter
{
GENERATED_BODY()
protected:
// A lazily initialised mapping of SpeckleType -> converters.
TMap<TSubclassOf<UBase>, TScriptInterface<ISpeckleConverter>> SpeckleTypeMap;
public:
// Array of converters, must be of type ISpeckleConverter
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle|Conversion")
TArray<UObject*> SpeckleConverters;
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion")
virtual UObject* ConvertToNativeInternal(const UBase* Object, UWorld* World);
virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>&) override;
virtual bool CanConvertToNative_Implementation(TSubclassOf<UBase> BaseType) override;
virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override;
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion")
virtual TScriptInterface<ISpeckleConverter> GetConverter(const TSubclassOf<UBase> BaseType);
// Validates a given object is a valid ISpeckleConverter
static bool CheckValidConverter(const UObject* Converter, bool LogWarning = true);
void FinishConversion_Internal();
virtual void FinishConversion_Implementation() override;
// Validates changes to SpeckleConverters property, Should be called after modifying SpeckleConverters
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion")
virtual void OnConvertersChangeHandler();
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
};
@@ -0,0 +1,44 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "Conversion/SpeckleConverter.h"
#include "Engine/EngineTypes.h"
#include "Engine/World.h"
#include "BlockConverter.generated.h"
class UBlockInstance;
/**
* Converts Speckle Block Instance objects empty native actors with transform.
* The Block Definition can then be converted by other converters
*/
UCLASS()
class SPECKLEUNREAL_API UBlockConverter : public UObject, public ISpeckleConverter
{
GENERATED_BODY()
CONVERTS_SPECKLE_TYPES()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TSubclassOf<AActor> BlockInstanceActorType;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TEnumAsByte<EComponentMobility::Type> ActorMobility;
UBlockConverter();
virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>& AvailableConverters) override;
virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override;
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual AActor* BlockToNative(const UBlockInstance* Block, UWorld* World);
protected:
virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters());
};
@@ -0,0 +1,99 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Conversion/SpeckleConverter.h"
#include "UObject/Object.h"
#include "MaterialConverter.generated.h"
class URenderMaterial;
class UMaterialInterface;
UENUM()
enum EConstMaterialOptions
{
Never UMETA(DisplayName = "Never"),
NotPlay UMETA(DisplayName = "Editor Not Playing"),
Always UMETA(DisplayName = "Editor And PIE"),
};
/**
* Converts Speckle RenderMaterial objects into native Materials
*/
UCLASS(BlueprintType, Blueprintable)
class SPECKLEUNREAL_API UMaterialConverter : public UObject, public ISpeckleConverter
{
GENERATED_BODY()
CONVERTS_SPECKLE_TYPES()
public:
/// Material to be applied to meshes when no RenderMaterial can be converted
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
UMaterialInterface* DefaultMeshMaterial;
/// Material Parent for converted opaque materials*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
UMaterialInterface* BaseMeshOpaqueMaterial;
/// Material Parent for converted materials with an opacity less than one
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
UMaterialInterface* BaseMeshTransparentMaterial;
#if WITH_EDITORONLY_DATA
/// Specify when to create Constant materials that can only be created with Editor.
/// Otherwise will create dynamic materials
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TEnumAsByte<EConstMaterialOptions> UseConstMaterials;
#endif
/// When generating meshes, materials in this TMap will be used
/// instead of converted ones if the key matches the ID of the Object's RenderMaterial. (Takes priority over name matching)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ToNative|Overrides", DisplayName = "By Speckle ID")
TMap<FString, UMaterialInterface*> MaterialOverridesById;
/// When generating meshes, materials in this TSet will be used instead of converted ones if the material name matches the name of the Object's RenderMaterial
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "ToNative|Overrides", DisplayName = "By Name")
TSet<UMaterialInterface*> MaterialOverridesByName;
public:
UMaterialConverter();
virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld*, TScriptInterface<ISpeckleConverter>&) override;
UFUNCTION(BlueprintCallable, Category="ToNative|Overrides")
virtual bool TryGetOverride(const URenderMaterial* SpeckleMaterial, UMaterialInterface*& OutMaterial) const;
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual UMaterialInterface* GetMaterial(const URenderMaterial* SpeckleMaterial);
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual UMaterialInterface* RenderMaterialToNative(const URenderMaterial* SpeckleMaterial, UPackage* Package);
virtual void FinishConversion_Implementation() override;
protected:
/** Transient cache of materials converted from stream RenderMaterial objects */
UPROPERTY(AdvancedDisplay, BlueprintReadOnly, Transient, Category="ToNative|Cache")
TMap<FString, UMaterialInterface*> ConvertedMaterials;
UFUNCTION(BlueprintCallable, BlueprintPure, Category="ToNative")
virtual UPackage* GetPackage(const FString& ObjectID) const;
UFUNCTION(BlueprintCallable, BlueprintPure, Category="ToNative")
virtual FString RemoveInvalidFileChars(const FString& InString) const;
#if WITH_EDITOR
UFUNCTION(BlueprintCallable, BlueprintPure, Category="ToNative")
static bool ShouldCreateConstMaterial(TEnumAsByte<EConstMaterialOptions> Options);
#endif
};
@@ -0,0 +1,48 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Conversion/SpeckleConverter.h"
#include "Engine/EngineTypes.h"
#include "PointCloudConverter.generated.h"
class ULidarPointCloudComponent;
class ALidarPointCloudActor;
class ULidarPointCloud;
class UPointCloud;
/**
* Converts Speckle Point Cloud objects into LidarPointClouds
*/
UCLASS()
class SPECKLEUNREAL_API UPointCloudConverter : public UObject, public ISpeckleConverter
{
GENERATED_BODY()
CONVERTS_SPECKLE_TYPES()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TSubclassOf<ALidarPointCloudActor> PointCloudActorType;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TEnumAsByte<EComponentMobility::Type> ActorMobility;
UPointCloudConverter();
virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>&) override;
virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override;
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual ALidarPointCloudActor* PointCloudToNative(const UPointCloud* SpecklePointCloud, UWorld* World);
UFUNCTION(BlueprintCallable, Category="ToSpeckle")
virtual UPointCloud* PointCloudToSpeckle(const ULidarPointCloudComponent* Object);
protected:
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual ALidarPointCloudActor* CreateActor(UWorld* World, ULidarPointCloud* PointCloudData);
};
@@ -0,0 +1,58 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Conversion/SpeckleConverter.h"
#include "Engine/EngineTypes.h"
#include "Engine/World.h"
#include "ProceduralMeshConverter.generated.h"
class UMaterialConverter;
class UProceduralMeshComponent;
class UMesh;
class URenderMaterial;
/**
* Converts Speckle Mesh objects into native actors with a procedural mesh component.
*
* Compared with the StaticMeshConverter, this converter has some serious limitations
* - Cannot convert displayValues,
* - N-gon faces will be ignored,
* - Meshes are transient, and won't persist on level reload
*/
UCLASS()
class SPECKLEUNREAL_API UProceduralMeshConverter : public UObject, public ISpeckleConverter
{
GENERATED_BODY()
CONVERTS_SPECKLE_TYPES()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TSubclassOf<AActor> MeshActorType;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TEnumAsByte<EComponentMobility::Type> ActorMobility;
// Sets default values for this actor's properties
UProceduralMeshConverter();
virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World,
TScriptInterface<ISpeckleConverter>& AvailableConverters) override;
virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override;
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual AActor* MeshToNative(const UMesh* SpeckleMesh, UWorld* World, TScriptInterface<ISpeckleConverter>& MaterialConverter);
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual UMesh* MeshToSpeckle(const UProceduralMeshComponent* Object);
virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform,
const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters());
};
@@ -0,0 +1,115 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Conversion/SpeckleConverter.h"
#include "Engine/EngineTypes.h"
#include "Engine/World.h"
#include "Engine/StaticMesh.h"
#include "StaticMeshConverter.generated.h"
class UMaterialConverter;
class AStaticMeshActor;
class UMesh;
class URenderMaterial;
/**
* Converts Speckle Mesh objects into native Actors with a StaticMesh component
*
* Can convert multiple Speckle Mesh objects (eg with different materials) in one StaticMesh
*/
UCLASS()
class SPECKLEUNREAL_API UStaticMeshConverter : public UObject, public ISpeckleConverter
{
GENERATED_BODY()
CONVERTS_SPECKLE_TYPES()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TSubclassOf<AActor> MeshActorType;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TEnumAsByte<EComponentMobility::Type> ActorMobility;
#if WITH_EDITORONLY_DATA
// If true, will use the full Editor Only build process
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
bool UseFullBuild;
// When true, will display FSlowTask progress of editor only build process
UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative|EditorOnly")
bool DisplayBuildProgressBar;
// When true, will allow cancellation of FSlowTask progress of editor only build process
UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative|EditorOnly")
bool AllowCancelBuild;
#endif
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
bool BuildSimpleCollision;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
bool Transient;
UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative")
bool GenerateLightmapUV;
UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative")
int32 MinLightmapResolution;
UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative")
bool BuildReversedIndexBuffer;
UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative")
bool UseFullPrecisionUVs;
UPROPERTY(EditAnywhere, BlueprintReadWrite, AdvancedDisplay, Category="ToNative")
bool RemoveDegeneratesOnBuild;
public:
// Sets default values for this actor's properties
UStaticMeshConverter();
virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>& AvailableConverters) override;
virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override;
virtual void FinishConversion_Implementation() override;
// Converts a multiple Speckle Meshes to a native actor of type MeshActorType
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual AActor* MeshesToNativeActor(const UBase* Parent, const TArray<UMesh*>& SpeckleMeshes, UWorld* World, TScriptInterface<ISpeckleConverter>& RenderMaterialConverter);
// Converts a single Speckle Mesh to a native actor of type MeshActorType
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual AActor* MeshToNativeActor(const UMesh* SpeckleMesh, UWorld* World, TScriptInterface<ISpeckleConverter>& MaterialConverter);
virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform = FTransform::Identity, const FActorSpawnParameters& SpawnParameters =
FActorSpawnParameters());
UFUNCTION(BlueprintCallable, Category="ToSpeckle")
virtual UBase* MeshToSpeckle(const UStaticMeshComponent* Object);
protected:
FCriticalSection Lock_StaticMeshesToBuild;
UPROPERTY(BlueprintReadWrite, Transient, Category="ToNative")
TArray<UStaticMesh*> StaticMeshesToBuild;
virtual void GenerateMeshParams(UStaticMesh::FBuildMeshDescriptionsParams& MeshParams) const;
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual UMaterialInterface* GetMaterial(const URenderMaterial* SpeckleMaterial, UWorld* World,
TScriptInterface<ISpeckleConverter>& MaterialConverter) const;
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual UStaticMesh* MeshesToNativeMesh(UObject* Outer, const UBase* Parent, const TArray<UMesh*>& SpeckleMeshes, TScriptInterface<ISpeckleConverter>
& MaterialConverter);
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual UStaticMesh* MeshToNativeMesh(UObject* Outer, const UMesh* SpeckleMesh, TScriptInterface<ISpeckleConverter>& MaterialConverter);
};
@@ -0,0 +1,53 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "UObject/Interface.h"
#include "Templates/SubclassOf.h"
#include "SpeckleConverter.generated.h"
UINTERFACE()
class SPECKLEUNREAL_API USpeckleConverter : public UInterface
{
GENERATED_BODY()
};
/**
* Interface for conversion functions (ToSpeckle and ToNative) of a specific speckle type(s).
*
* Implementors of this interface provide conversion functions of specific types : Base
*/
class SPECKLEUNREAL_API ISpeckleConverter
{
GENERATED_BODY()
public:
/// Will return true if this converter can convert a given BaseType
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToNative")
bool CanConvertToNative(TSubclassOf<UBase> BaseType);
/// Tries to convert a given SpeckleBase into a native Actor
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToNative")
UObject* ConvertToNative(const UBase* SpeckleBase, UWorld* World, UPARAM(ref) TScriptInterface<ISpeckleConverter>& AvailableConverters);
/// Tries to convert a given Actor or Component into a Speckle Base
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToSpeckle")
UBase* ConvertToSpeckle(const UObject* Object);
/// Clean up any cached assets that now may be unused
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToNative")
void FinishConversion();
};
#define CONVERTS_SPECKLE_TYPES() \
protected: \
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Conversion") \
TSet<TSubclassOf<UBase>> SpeckleTypes; \
public: \
virtual bool CanConvertToNative_Implementation(TSubclassOf<UBase> BaseType) override { return SpeckleTypes.Contains(BaseType); } \
private:
@@ -0,0 +1,52 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "SpeckleConverterComponent.generated.h"
class ITransport;
class ISpeckleConverter;
class UBase;
class UAggregateConverter;
struct FSlowTask;
/**
* An Actor Component for encapsulating recursive conversion of Speckle Objects
*/
UCLASS(ClassGroup=(Speckle), meta=(BlueprintSpawnableComponent))
class SPECKLEUNREAL_API USpeckleConverterComponent : public UActorComponent
{
GENERATED_BODY()
public:
// Array of converters
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle|Conversion")
UAggregateConverter* SpeckleConverter;
// Sets default values for this component's properties
USpeckleConverterComponent();
// Converts the given Base and all children into native actors.
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion")
UPARAM(DisplayName = "RootActor") AActor* RecursivelyConvertToNative(AActor* AOwner, const UBase* Base,
const TScriptInterface<ITransport>& LocalTransport, bool DisplayProgressBar, TArray<AActor*>& OutActors);
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion")
virtual void FinishConversion();
protected:
virtual AActor* RecursivelyConvertToNative_Internal(AActor* AOwner, const UBase* Base, const TScriptInterface<ITransport>& LocalTransport, FSlowTask* Task, TArray<AActor*>& OutActors);
virtual void ConvertChild(const TSharedPtr<FJsonValue> Object, AActor* AOwner, const TScriptInterface<ITransport>& LocalTransport, FSlowTask* Task, TArray<AActor*>& OutActors);
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion")
virtual void AttachConvertedToOwner(AActor* AOwner, const UBase* Base, UObject* Converted);
};
+6
View File
@@ -0,0 +1,6 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
DECLARE_LOG_CATEGORY_EXTERN(LogSpeckle, Log, All);
+21
View File
@@ -0,0 +1,21 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
/// Anonymous telemetry to help us understand how to make a better Speckle.
/// This really helps us to deliver a better open source project and product!
class FAnalytics
{
protected:
static const FString MixpanelToken;
static const FString MixpanelServer;
static const FString VersionedApplicationName;
public:
static void TrackEvent(const FString& Server, const FString& EventName);
static void TrackEvent(const FString& Server, const FString& EventName, const TMap<FString, FString>& CustomProperties);
static void TrackEvent(const FString& Email, const FString& Server, const FString& EventName, const TMap<FString, FString>& CustomProperties);
static FString Hash(const FString& Input);
};
@@ -0,0 +1,93 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Dom/JsonObject.h"
#include "Base.generated.h"
class ITransport;
class ASpeckleUnrealManager;
/**
* Base type that all Object Models inherit from
*/
UCLASS(BlueprintType, meta=(DisplayName="Base (Speckle.Objects)"))
class SPECKLEUNREAL_API UBase : public UObject
{
public:
GENERATED_BODY()
protected:
explicit UBase(const TCHAR* SpeckleType): SpeckleType(FString(SpeckleType)) {}
explicit UBase(const FString& SpeckleType) : SpeckleType(SpeckleType) {}
public:
UBase() : SpeckleType("Base") {}
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects")
FString Id;
TMap<FString, TSharedPtr<FJsonValue>> DynamicProperties; //TODO this won't be serialised!
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects")
FString Units;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects")
FString SpeckleType;
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
bool IsValid = false;
DynamicProperties = Obj->Values;
if(Obj->TryGetStringField("id", Id))
{
IsValid = true;
DynamicProperties.Remove("id");
}
if(Obj->TryGetStringField("units", Units)) DynamicProperties.Remove("units");
if(Obj->TryGetStringField("speckle_type", SpeckleType)) DynamicProperties.Remove("speckle_type");
return IsValid;
}
protected:
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
int32 RemoveDynamicProperty(UPARAM(ref) const FString& Key)
{
return DynamicProperties.Remove(Key);
}
public:
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
bool TryGetDynamicString(UPARAM(ref) const FString& Key, FString& OutString) const
{
const TSharedPtr<FJsonValue> Value = DynamicProperties.FindRef(Key);
if(Value == nullptr) return false;
return Value->TryGetString(OutString);
}
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
bool TryGetDynamicNumber(UPARAM(ref) const FString& Key, float& OutNumber) const
{
const TSharedPtr<FJsonValue> Value = DynamicProperties.FindRef(Key);
if(Value == nullptr) return false;
return Value->TryGetNumber(OutNumber);
}
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
bool TryGetDynamicBool(UPARAM(ref) const FString& Key, bool& OutBool) const
{
const TSharedPtr<FJsonValue> Value = DynamicProperties.FindRef(Key);
if(Value == nullptr) return false;
return Value->TryGetBool(OutBool);
}
};
@@ -0,0 +1,32 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Base.h"
#include "DisplayValueElement.generated.h"
class UMesh;
/**
*
*/
UCLASS()
class SPECKLEUNREAL_API UDisplayValueElement : public UBase
{
GENERATED_BODY()
protected:
static TArray<FString> DisplayValueAliasStrings;
bool AddDisplayValue(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport);
public:
UDisplayValueElement() : UBase(TEXT("Objects.BuiltElements")) {}
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<UMesh*> DisplayValue;
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override;
};
@@ -0,0 +1,51 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "Mesh.generated.h"
class URenderMaterial;
/**
*
*/
UCLASS()
class SPECKLEUNREAL_API UMesh : public UBase
{
GENERATED_BODY()
public:
UMesh() : UBase(TEXT("Objects.Geometry.Mesh")) {}
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<FVector> Vertices;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<int32> Faces;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<FVector2D> TextureCoordinates;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<FColor> VertexColors;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
FMatrix Transform;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
URenderMaterial* RenderMaterial;
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override;
protected:
/// If not already so, this method will align vertices
/// such that a vertex and its corresponding texture coordinates have the same index.
/// See "https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Geometry/Mesh.cs"
virtual void AlignVerticesWithTexCoordsByIndex();
};
@@ -0,0 +1,32 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "PointCloud.generated.h"
/**
*
*/
UCLASS()
class SPECKLEUNREAL_API UPointCloud : public UBase
{
GENERATED_BODY()
public:
UPointCloud() : UBase(TEXT("Objects.Geometry.Pointcloud")) {}
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<FVector> Points;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<FColor> Colors;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<float> Sizes;
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override;
};
@@ -0,0 +1,52 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "Templates/SubclassOf.h"
#include "ObjectModelRegistry.generated.h"
class UBase;
/**
* Handles the mapping of Speckle type to Object Model
*/
UCLASS()
class SPECKLEUNREAL_API UObjectModelRegistry : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
private:
static TMap<FString, TSubclassOf<UBase>> TypeRegistry;
static void GenerateTypeRegistry();
public:
/// Attempts to find the closest registered TSubclassOf<UBase>
/// by recursively stripping away a the most specific name specifier from the given SpeckleType
/// until a UBase type is found or the FString is exhausted.
///
/// Eg. with an input of "Objects.Elements.Wall"
/// Will first look for a registered type of "Objects.Elements.Wall"
/// If one is not found, will look for "Objects.Elements" etc.
/// Returns nullptr if none found.
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
static TSubclassOf<UBase> FindClosestType(const FString& SpeckleType);
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
static bool ParentType(const FString& Type, FString& NextType);
/// Attempts to find a TSubclassOf<UBase> with a UBase::SpeckleType matching the given SpeckleType param
/// Returns nullptr if none found.
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
static TSubclassOf<UBase> GetRegisteredType(const FString& SpeckleType);
/// Attempts to find a TSubclassOf<UBase> with a UBase::SpeckleType matching the given SpeckleType param
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
static bool TryGetRegisteredType(const FString& SpeckleType, TSubclassOf<UBase>& OutType);
};
@@ -0,0 +1,33 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "BlockInstance.generated.h"
/**
*
*/
UCLASS()
class SPECKLEUNREAL_API UBlockInstance : public UBase
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
FString Name;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<UBase*> Geometry;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
FMatrix Transform;
UBlockInstance() : UBase(TEXT("Objects.Other.BlockInstance")) {}
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override;
};
@@ -0,0 +1,69 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "RenderMaterial.generated.h"
/**
*
*/
UCLASS()
class SPECKLEUNREAL_API URenderMaterial : public UBase
{
GENERATED_BODY()
public:
URenderMaterial() : UBase(TEXT("Objects.Other.RenderMaterial")) {}
UPROPERTY()
FString Name;
UPROPERTY()
double Opacity = 1;
UPROPERTY()
double Metalness = 0;
UPROPERTY()
double Roughness = 1;
UPROPERTY()
FLinearColor Diffuse = FColor{221,221,221};
UPROPERTY()
FLinearColor Emissive = FLinearColor::Black;
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override
{
if(!Super::Parse(Obj, ReadTransport)) return false;
if(Obj->TryGetStringField("name", Name)) DynamicProperties.Remove("name");
if(Obj->TryGetNumberField("opacity", Opacity)) DynamicProperties.Remove("opacity");
if(Obj->TryGetNumberField("metalness", Metalness)) DynamicProperties.Remove("metalness");
if(Obj->TryGetNumberField("roughness", Roughness)) DynamicProperties.Remove("roughness");
bool IsValid = false;
int32 ARGB;
if(Obj->TryGetNumberField("diffuse", ARGB))
{
Diffuse = FColor(ARGB);
DynamicProperties.Remove("diffuse");
IsValid = true;
}
if(Obj->TryGetNumberField("emissive", ARGB))
{
Emissive = FColor(ARGB);
DynamicProperties.Remove("emissive");
}
return IsValid;
}
};
@@ -0,0 +1,38 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "View3D.generated.h"
/**
*
*/
UCLASS()
class SPECKLEUNREAL_API UView3D : public UBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects")
FString Name;
UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects")
FVector Origin;
UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects")
FVector UpDirection;
UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects")
FVector ForwardDirection;
UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects")
bool IsOrthogonal;
UView3D() : UBase(TEXT("Objects.BuiltElements.View")) {}
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override;
};
@@ -0,0 +1,54 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "Templates/SubclassOf.h"
#include "SpeckleObjectUtils.generated.h"
class ITransport;
class UBase;
class FJsonValue;
class FJsonObject;
class UWorld;
class AActor;
/**
* Several helper functions useful for handling JSON Speckle Objects
*/
UCLASS()
class SPECKLEUNREAL_API USpeckleObjectUtils : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
static TArray<TSharedPtr<FJsonValue>> CombineChunks(const TArray<TSharedPtr<FJsonValue>>& ArrayField, const TScriptInterface<ITransport> Transport);
static bool ResolveReference(const TSharedPtr<FJsonObject> Object, const TScriptInterface<ITransport> Transport, TSharedPtr<FJsonObject>& OutObject);
static bool TryParseTransform(const TSharedPtr<FJsonObject> SpeckleObject, FMatrix& OutMatrix);
static bool ParseVector(const TSharedPtr<FJsonObject> Object, const TScriptInterface<ITransport> Transport, FVector& OutObject);
static bool ParseVectorProperty(const TSharedPtr<FJsonObject> Base, const FString& PropertyName, const TScriptInterface<ITransport> ReadTransport, FVector& OutObject);
template <typename T>
static bool ParseSpeckleObject(const TSharedPtr<FJsonObject> Object, const TScriptInterface<ITransport> Transport, T*& OutObject);
UFUNCTION(BlueprintCallable, Category="Speckle/ObjectUtils")
static float ParseScaleFactor(const FString& UnitsString);
// Given a Right Handed Z-up transformation matrix (Speckle's system), will create an equivalent Left Handed Z-up FTransform (UE's system)
UFUNCTION(BlueprintPure, Category="Speckle/ObjectUtils")
static FTransform CreateTransform(UPARAM(ref) const FMatrix& TransformMatrix);
UFUNCTION(BlueprintCallable, Category="Speckle/ObjectUtils", meta=(CallableWithoutWorldContext, WorldContext="WorldContextObject", DeterminesOutputType="Class", DynamicOutputParam="ReturnValue"))
static AActor* SpawnActorInWorld(const UObject* WorldContextObject, const TSubclassOf<AActor> Class, UPARAM(ref) const FTransform& Transform);
// Helper function to print a json obj to console
static FString DisplayAsString(const FString& msg, const TSharedPtr<FJsonObject> Obj);
};
@@ -0,0 +1,177 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "API/Models/SpeckleStream.h"
#include "ReceiveSelectionComponent.generated.h"
/**
* Actor component for selecting a Speckle Stream + Object
* Either by Stream Id + Object Id (Object selection mode)
* Or by Stream + Branch + Commit (Commit selection mode)
*/
UCLASS(ClassGroup=(Speckle), meta=(BlueprintSpawnableComponent))
class SPECKLEUNREAL_API UReceiveSelectionComponent : public UActorComponent
{
GENERATED_BODY()
public:
// URL of the speckle server
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle")
FString ServerUrl = "https://speckle.xyz";
// A Personal Access Token can be created from your Speckle Profile page (Treat tokens like passwords, do not share publicly)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", meta=(PasswordField=true))
FString AuthToken;
// Id of the stream to receive from (checkout the stream URL in the Speckle web viewer)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", meta=(EditCondition="bManualMode", EditConditionHides, DisplayAfter=bManualMode))
FString StreamId;
// Id of the Speckle Object to receive (checkout the properties panel in the Speckle web viewer)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", meta=(EditCondition="bManualMode", EditConditionHides, DisplayAfter=StreamId))
FString ObjectId;
/**
* Trys to get the currently selected Commit (Commit selection mode)
* @param OutCommit the selected Commit (if return was true)
* @returns true if a selection was made
*/
UFUNCTION(BlueprintCallable, Category="Speckle")
bool TryGetSelectedCommit(FSpeckleCommit& OutCommit) const;
/**
* Trys to get the currently selected Branch (Commit selection mode)
* @param OutBranch the selected Branch (if return was true)
* @returns true if a selection was made
*/
UFUNCTION(BlueprintCallable, Category="Speckle")
bool TryGetSelectedBranch(FSpeckleBranch& OutBranch) const;
/**
* Trys to get the currently selected Stream (Commit selection mode)
* @param OutStream the selected Stream (if return was true)
* @returns true if a selection was made
*/
UFUNCTION(BlueprintCallable, Category="Speckle")
bool TryGetSelectedStream(FSpeckleStream& OutStream) const;
/**
* @param OutStatusMessage the current status of the object selection as a human readable string
* @returns true if a complete object selection is made.
*/
UFUNCTION(BlueprintCallable, Category="Speckle", CallInEditor)
bool IsSelectionComplete(FString& OutStatusMessage) const;
// Gets the URL of the current selection/partial selection
UFUNCTION(BlueprintCallable, Category="Speckle", CallInEditor)
FString GetUrl() const;
/**
* Launches the URL of the current selection/partial selection using FPlatformProcess
* @returns true if the URL could be launched
*/
UFUNCTION(BlueprintCallable, Category="Speckle", CallInEditor)
void OpenURLInBrowser() const;
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
virtual void PropertyChangeHandler(const FName& PropertyName);
protected: //Internal logic for branch/stream/commit fetching and selection
// When true, user specifies stream id + object id, when false, user specifies stream + branch + commit
UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Category="Speckle", meta=(DisplayName="Specify by Object Id", DisplayAfter=AuthToken));
bool bManualMode = true;
// Limit of how many streams/branches/commits to fetch
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", AdvancedDisplay, meta=(DisplayName="Options Limit", ClampMin=0, ClampMax=100, UIMin = 1, UIMax=30))
int32 Limit = 15;
// Refreshes the Stream/Branch/Commit options
UFUNCTION(BlueprintCallable, Category="Speckle", CallInEditor)
void Refresh();
#pragma region Stream
UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Category="Speckle", meta=(DisplayName="Stream", GetOptions=GetStreamsOptions, EditCondition="IsAccountValid && !bManualMode", NoResetToDefault))
FString SelectedStreamText;
UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle")
TMap<FString, FSpeckleStream> Streams;
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual TArray<FString> GetStreamsOptions() const;
UFUNCTION(BlueprintCallable, Category="Speckle")
bool SelectStream(const FString& DisplayId);
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual void UpdateStreams();
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual FSpeckleStream GetSelectedStream() const;
UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle")
bool IsStreamValid = false;
UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle")
bool IsAccountValid = false;
#pragma endregion
#pragma region Branch
UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Category="Speckle", meta=(DisplayName="Branch", GetOptions=GetBranchOptions, EditCondition="IsStreamValid && !bManualMode", NoResetToDefault))
FString SelectedBranchText;
UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle")
TMap<FString, FSpeckleBranch> Branches;
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual TArray<FString> GetBranchOptions();
UFUNCTION(BlueprintCallable, Category="Speckle")
bool SelectBranch(const FString& DisplayId);
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual void UpdateBranches();
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual FSpeckleBranch GetSelectedBranch() const;
UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle")
bool IsBranchValid = false;
#pragma endregion
#pragma region Commit
UPROPERTY(EditAnywhere, BlueprintReadWrite, Transient, Category="Speckle", meta=(DisplayName="Commit", GetOptions=GetCommitOptions, EditCondition="IsCommitValid && !bManualMode", NoResetToDefault))
FString SelectedCommitText;
UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle")
TMap<FString, FSpeckleCommit> Commits;
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual TArray<FString> GetCommitOptions();
UFUNCTION(BlueprintCallable, Category="Speckle")
bool SelectCommit(const FString& DisplayId);
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual void UpdateCommits();
UFUNCTION(BlueprintCallable, Category="Speckle")
virtual FSpeckleCommit GetSelectedCommit() const;
UPROPERTY(BlueprintReadOnly, Transient, Category="Speckle")
bool IsCommitValid = false;
#pragma endregion
static void LogError(const FString& Message, const FString LogName);
};
@@ -1,4 +1,4 @@
// Copyright Epic Games, Inc. All Rights Reserved.
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -0,0 +1,75 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "GameFramework/Actor.h"
#include "SpeckleUnrealManager.generated.h"
class UServerTransport;
class ITransport;
class USpeckleConverterComponent;
class UReceiveSelectionComponent;
class FJsonObject;
/**
* An Actor to handle the receiving of Speckle objects into a level
*/
UCLASS(ClassGroup=(Speckle), AutoCollapseCategories=("Speckle|Conversion"), BlueprintType)
class SPECKLEUNREAL_API ASpeckleUnrealManager : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere, Category="Speckle", BlueprintReadWrite)
UReceiveSelectionComponent* ReceiveSelection;
// When true, will call `Receive` on BeginPlay
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", AdvancedDisplay)
bool ImportAtRuntime;
// When true, will maintain an in-memory (transient) cache of received speckle objects
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", AdvancedDisplay)
bool KeepCache;
// The Conversion component to convert received speckle objects into native Actors
UPROPERTY(VisibleAnywhere, Category="Speckle", BlueprintReadWrite)
USpeckleConverterComponent* Converter;
// When true, will display an editor progress bar while receiving objects
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Speckle", AdvancedDisplay)
bool DisplayProgressBar;
// Sets default values for this actor's properties
ASpeckleUnrealManager();
// Receives specified object from specified Speckle server
UFUNCTION(BlueprintCallable, CallInEditor, Category="Speckle", meta=(DisplayPriority=0))
virtual void Receive();
// Deletes the Actors created by the previous receive operation
UFUNCTION(BlueprintCallable, CallInEditor, Category="Speckle" , meta=(DisplayAfter="Receive"))
virtual void DeleteObjects();
virtual void BeginPlay() override;
protected:
// Cache received Speckle objects
UPROPERTY(BlueprintReadWrite, Category="Speckle")
TScriptInterface<ITransport> LocalObjectCache;
// Array of Actors created by the previous receive operation
UPROPERTY(BlueprintReadWrite, Category="Speckle")
TArray<AActor*> Actors;
// Callback when JSON has been received
virtual void HandleReceive(TSharedPtr<FJsonObject> RootObject, bool DisplayProgress = false);
// Callback when error
virtual void HandleError(FString& Message);
virtual void PrintMessage(FString& Message, bool IsError = false) const;
};
@@ -0,0 +1,39 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Transport.h"
#include "MemoryTransport.generated.h"
/**
* An in memory storage of speckle objects.
*/
UCLASS(Transient, BlueprintType)
class SPECKLEUNREAL_API UMemoryTransport : public UObject, public ITransport
{
GENERATED_BODY()
TMap<FString, TSharedPtr<FJsonObject>> SpeckleObjects;
public:
virtual TSharedPtr<FJsonObject> GetSpeckleObject(const FString& ObjectId) const override;
virtual void SaveObject(const FString& ObjectId, const TSharedPtr<FJsonObject> SerializedObject) override;
virtual bool HasObject(const FString& ObjectId) const override;
virtual void CopyObjectAndChildren(const FString& ObjectId,
TScriptInterface<ITransport> TargetTransport,
const FTransportCopyObjectCompleteDelegate& OnCompleteAction,
const FTransportErrorDelegate& OnErrorAction) override { unimplemented(); }
UFUNCTION(BlueprintPure, Category = "Speckle|Transports")
static UMemoryTransport* CreateEmptyMemoryTransport()
{
UMemoryTransport* Transport = NewObject<UMemoryTransport>();
return Transport;
}
};

Some files were not shown because too many files have changed in this diff Show More