76 Commits

Author SHA1 Message Date
Jedd Morgan c91f5e12ce Merge pull request #88 from specklesystems/jrm/5.3
Added marketplace build ci for UE 5.3
2023-09-12 19:25:01 +01:00
Jedd Morgan fd71dd41ca Added 5.3 ci 2023-09-12 19:21:10 +01:00
Jedd Morgan caa56039e7 Merge pull request #87 from specklesystems/jrm/converter/collections
Support for receiving Collections and various other Bug fixes
2023-08-31 20:29:15 +01:00
Jedd Morgan c1f5476f77 Resolved warning with uninitialized struct members 2023-08-30 23:15:37 +01:00
Jedd Morgan 3c55f31a58 Removed baking mesh transforms from deserialization process 2023-08-30 22:49:43 +01:00
Jedd Morgan fce06cba20 Fixed build issue with UE5.3 Preview 1 2023-08-30 21:38:42 +01:00
Jedd Morgan 2b6ab16b22 Removed EditCondition for Branch and Commit selection 2023-08-30 20:34:20 +01:00
Jedd Morgan a60d4fef56 Added support for receiving collections 2023-08-30 18:33:36 +01:00
Jedd Morgan 6aa4afbd84 Merge pull request #86 from specklesystems/jrm/blueprint-type-fix
fix(bp): exposed SpeckleConverter as a BP type
2023-07-18 23:32:43 +01:00
Jedd Morgan b5f465e1a3 fix(bp): exposed SpeckleConverter as a BP type 2023-07-18 23:31:47 +01:00
Jedd Morgan 80b7cd886a Merge pull request #85 from specklesystems/no-bom
Removed BOM headers from files
2023-07-06 21:21:34 +01:00
Jedd Morgan f57ee4658e Merge remote-tracking branch 'origin/main' into no-bom 2023-07-06 21:20:47 +01:00
Jedd Morgan af61b08fa2 fix(ci): added line to remove BOM headers before applying copyright info 2023-07-06 21:20:28 +01:00
Jedd Morgan a6b5a09efa Merge pull request #84 from specklesystems/no-bom
fix(ci): added line to remove BOM headers before applying copyright info
2023-07-06 21:11:27 +01:00
Jedd Morgan f07eb732da fix(ci): added line to remove BOM headers before applying copyright info 2023-07-06 21:10:21 +01:00
Jedd Morgan 68cb85e029 Merge pull request #83 from specklesystems/activeUser
Updated user requests to use the new activeUser query
2023-07-06 17:32:14 +01:00
Jedd Morgan 067d66ae16 Removed marketplace publishing for UE 4.26 2023-07-06 17:22:27 +01:00
Jedd Morgan 4b4eae32a2 chore(api): user -> activeUser 2023-07-06 17:15:43 +01:00
Jedd Morgan 72738bb01b Merge pull request #81 from specklesystems/2.15
Fixes for build issues
2023-06-29 23:18:03 +01:00
Jedd Morgan 42b525107f fix(build): Added missing inlcudes to fix issue with non-unity builds 2023-06-29 23:16:56 +01:00
Jedd Morgan e5a06c8c4c fix: Additional fix for requests with empty authtokens 2023-06-29 12:52:06 +01:00
Jedd Morgan 8205c40e53 Merge pull request #80 from specklesystems/2.15
Added CI for UE5.2
2023-06-16 02:02:50 +01:00
Jedd Morgan f903742449 Added CI for UE5.2 2023-06-16 02:01:56 +01:00
Jedd Morgan 5af3717239 Merge pull request #79 from specklesystems/2.15
Bumped appolo headers
2023-06-16 01:58:14 +01:00
Jedd Morgan 761c7a28f8 Bumped appolo headers 2023-06-16 01:56:39 +01:00
Jedd Morgan 2c0564da64 Merge pull request #78 from specklesystems/2.14
Added support for new revit instances, and added support for UE5.2
2023-06-16 01:49:31 +01:00
Jedd Morgan e0eecdfb38 Update README.md 2023-06-16 01:48:47 +01:00
Jedd Morgan feae0da6c6 Added support for UE 5.2 2023-06-16 01:24:29 +01:00
Jedd Morgan ee8963535b Merge remote-tracking branch 'origin/main' into 2.14 2023-06-16 01:04:39 +01:00
Jedd Morgan b11c041a4e feat: Added support for new instances 2023-06-16 00:58:09 +01:00
Jedd Morgan f9bdd24bc9 Merge pull request #76 from specklesystems/gergo/ciContextUpdate
add circleci context to the publish job
2023-06-15 15:33:31 +01:00
Jedd Morgan 8c67c81cc1 Merge pull request #77 from moihack/main
Fixed crash when overriding material by Name
2023-06-15 14:27:08 +01:00
moihack b5d09a1f2f Fixed crash when overriding material by Name 2023-05-18 20:11:12 +03:00
Alan Rynne 25cda6e272 ci: Updated github actions to use new actions repo 2023-01-09 20:53:09 +01:00
Gergő Jedlicska 9fd8ef90c9 add circleci context to the publish job 2023-01-06 11:58:14 +01:00
Jedd Morgan 582dfe217d Merge pull request #75 from specklesystems/ue5.1
feat: Added support for UE 5.1
2022-11-30 22:38:43 +00:00
Jedd Morgan a4d452b9be feat: Added support for UE 5.1 2022-11-30 22:29:41 +00:00
Jedd Morgan 96861937e1 Merge pull request #74 from specklesystems/jrm/ue5.1-fix
Buiding on UE5.1-preview 2 now works.
2022-10-25 23:52:43 +01:00
JR-Morgan e25f56eca9 Fix(editor): Fixed issue with REINST blueprint converter classes in UE5.1 2022-10-25 23:39:19 +01:00
Jedd Morgan dcc14bf826 Merge pull request #71 from specklesystems/userid-fix
user id fix
2022-09-02 14:59:37 +01:00
JR-Morgan 5a65dd7759 fix: Fixed issue with events incorrectly tracking UserID 2022-09-02 14:53:01 +01:00
Jedd Morgan d42bfd584a Update README.md 2022-09-01 17:53:29 +01:00
Jedd Morgan 70fc6a717e Merge pull request #70 from specklesystems/apollo-headers
feat(core): Added apollo headers to graphQL requests
2022-09-01 17:44:03 +01:00
JR-Morgan 552b47b312 feat(core): Added apollo headers to graphQL requests 2022-09-01 17:40:13 +01:00
Jedd Morgan 6180e40537 Merge pull request #69 from moihack/main
Fixed triangle order in ProceduralMeshConverter
2022-09-01 17:13:47 +01:00
moihack dab56d331a Fixed triangle order in ProceduralMeshConverter 2022-08-24 11:32:13 +03:00
Jedd Morgan 2d848aa452 Merge pull request #67 from specklesystems/copyright-ci
Copyright notice to be applied through CI
2022-08-08 16:04:41 +01:00
JR-Morgan 016e31c5a4 Copyright notice to be applied through CI 2022-08-07 18:03:00 +01:00
JR-Morgan a41081a7db Added copyright notice to build files 2022-08-02 17:36:34 +01:00
JR-Morgan 13d44abe21 Ignored licence for marketplace deploy 2022-08-02 17:33:06 +01:00
JR-Morgan 753170f50e Circle CI manual deployment 2022-08-02 17:12:25 +01:00
JR-Morgan dc4638eb1a Fixed issue with .circleci being incorrectly included in git archive 2022-08-02 17:01:51 +01:00
Jedd Morgan c094f3f59d Marketplace changes (#66)
* Updated Readme and Filterplugin to include readme

* Update README.md

* Bumped version

* Update README.md
2022-08-02 15:35:27 +01:00
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
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
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
119 changed files with 2791 additions and 1290 deletions
+107
View File
@@ -0,0 +1,107 @@
version: 2.1
orbs:
aws-s3: circleci/aws-s3@2.0.0
parameters:
marketplace-deploy:
type: boolean
default: false
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
add-source-copyright:
parameters:
copyright-string:
type: string
steps:
- run: #Remove BOM header, then add copyright comment
name: "Add copyright notice to source files"
command: |
shopt -s globstar
for file in Source/**/*.{cpp,hpp,c,h,cs};
do if [ -f $file ]; then
sed -i '1s/^\xEF\xBB\xBF//' $file;
sed -i '1s/^/\/\/ <<parameters.copyright-string>>\n/' $file;
echo "added copyright notice to $file";
fi;
done;
jobs:
generate-source-zip:
docker:
- image: cimg/base:stable
parameters:
target:
type: string
steps:
- checkout
- add-source-copyright:
copyright-string: "Copyright AEC SYSTEMS 2023"
- 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:
when: <<pipeline.parameters.marketplace-deploy>>
jobs:
- generate-source-zip:
name: "Generate Source Archive UE4.27"
target: "4.27"
- generate-source-zip:
name: "Generate Source Archive UE5.0"
target: "5.0"
- generate-source-zip:
name: "Generate Source Archive UE5.1"
target: "5.1"
- generate-source-zip:
name: "Generate Source Archive UE5.2"
target: "5.2"
- generate-source-zip:
name: "Generate Source Archive UE5.3"
target: "5.3"
- marketplace-deploy:
name: "Deploy to marketplace"
context: do-spaces-speckle-releases
requires:
- "Generate Source Archive UE4.27"
- "Generate Source Archive UE5.0"
- "Generate Source Archive UE5.1"
- "Generate Source Archive UE5.2"
- "Generate Source Archive UE5.3"
+1
View File
@@ -0,0 +1 @@
.pluginconfig/* export-ignore
+4 -70
View File
@@ -6,73 +6,7 @@ on:
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 }}
uses: specklesystems/github-actions/.github/workflows/project-add-issue.yml@main
secrets: inherit
with:
issue-id: ${{ github.event.issue.node_id }}
+4 -42
View File
@@ -6,45 +6,7 @@ on:
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
uses: specklesystems/github-actions/.github/workflows/project-add-issue.yml@main
secrets: inherit
with:
issue-id: ${{ github.event.issue.node_id }}
+6
View File
@@ -0,0 +1,6 @@
.gitattributes export-ignore
.github/* export-ignore
.circleci/* export-ignore
.circleci/ export-ignore
.pluginconfig/* export-ignore
LICENSE export-ignore
+42
View File
@@ -0,0 +1,42 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "2.15.2",
"FriendlyName": "Speckle Unreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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
}
]
}
+6
View File
@@ -0,0 +1,6 @@
.gitattributes export-ignore
.github/* export-ignore
.circleci/* export-ignore
.circleci/ export-ignore
.pluginconfig/* export-ignore
LICENSE export-ignore
+42
View File
@@ -0,0 +1,42 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "2.15.2",
"FriendlyName": "Speckle Unreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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
}
]
}
+6
View File
@@ -0,0 +1,6 @@
.gitattributes export-ignore
.github/* export-ignore
.circleci/* export-ignore
.circleci/ export-ignore
.pluginconfig/* export-ignore
LICENSE export-ignore
+42
View File
@@ -0,0 +1,42 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "2.15.2",
"FriendlyName": "Speckle Unreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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.1",
"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
}
]
}
+6
View File
@@ -0,0 +1,6 @@
.gitattributes export-ignore
.github/* export-ignore
.circleci/* export-ignore
.circleci/ export-ignore
.pluginconfig/* export-ignore
LICENSE export-ignore
+42
View File
@@ -0,0 +1,42 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "2.15.2",
"FriendlyName": "Speckle Unreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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.2",
"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
}
]
}
+6
View File
@@ -0,0 +1,6 @@
.gitattributes export-ignore
.github/* export-ignore
.circleci/* export-ignore
.circleci/ export-ignore
.pluginconfig/* export-ignore
LICENSE export-ignore
+42
View File
@@ -0,0 +1,42 @@
{
"FileVersion": 3,
"Version": 1,
"VersionName": "2.15.2",
"FriendlyName": "Speckle Unreal",
"Description": "Speckle is an open source data platform for Architecture, Engineering, and Construction. It has been open sourced under the Apache License 2.0, 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.3",
"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
}
]
}
+2
View File
@@ -0,0 +1,2 @@
[CoreRedirects]
+FunctionRedirects=(OldName="/Script/SpeckleUnreal.ObjectModelRegistry.FindClosestType",NewName="/Script/SpeckleUnreal.ObjectModelRegistry.GetAtomicType")
+1 -7
View File
@@ -1,8 +1,2 @@
[FilterPlugin]
; This section lists additional files which will be packaged along with your plugin. Paths should be listed relative to the root plugin directory, and
; may include "...", "*", and "?" wildcards to match directories, files, and individual characters respectively.
;
; Examples:
; /README.txt
; /Extras/...
; /Binaries/ThirdParty/*.dll
/README.md
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.
+47 -18
View File
@@ -1,34 +1,63 @@
# Speckle Unreal
# Speckle for Unreal Engine
[![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/)
[![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/user/unreal.html)
Plugin for Unreal Engine to import objects from Speckle v2.
Speckle makes integrating Unreal Engine with your 3D workflows even easier. </br>
This plugin connects Unreal Engine to Speckle, allowing you to receive your versioned 3D data from Speckle inside Unreal Engine,
enabling interoperable collaboration between Unreal and other Speckle connectors (Revit, Rhino, Blender, Sketchup, Unity, AutoCAD, [and more!](https://speckle.systems/features/connectors/))
Screencast of an example: https://user-images.githubusercontent.com/2551138/114720093-61403e00-9d40-11eb-8045-6e8ca656554d.mp4
https://user-images.githubusercontent.com/45512892/187969471-3f548b17-3388-48ee-a07c-bd3a0ecf5149.mp4
Checkout our dedicated [Tutorials and Docs](https://speckle.systems/tag/unreal/).
If you are enjoying using Speckle, don't forget to ⭐ our [GitHub repositories](https://github.com/specklesystems),
and [join our community forum](https://speckle.community/) where you can post any questions, suggestions, and discuss exciting projects!
## Notice
We officially support Unreal Engine 4.27, 5.0, 5.1, 5.2
**Features**:
- [Receiving Speckle geometry as Actors in editor and standalone runtime](https://speckle.systems/tutorials/getting-started-with-speckle-for-unreal/).
- [Material override/substitiution](https://speckle.guide/user/unreal.html#material-converter).
- [Blueprint nodes for receiving and converting objects](https://speckle.guide/user/unreal.html#usage-blueprint).
- [Blueprint nodes for fetching stream/branch/commit/user details](https://speckle.systems/tutorials/unreal-engine-blueprint-nodes-fetch-stream-branch-commit-info-and-more/).
- [Ability to write/extend custom conversion functions in C++/BP](https://speckle.systems/tutorials/unreal-developing-custom-conversion-logic/).
**Supported Conversions**:
Speckle Type | | Native Type |
| ---: | :---: | :--- |
| [`Objects.Geometry.Mesh`](https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Geometry/Mesh.cs) | → | [Static Mesh Component](https://docs.unrealengine.com/4.27/en-US/API/Runtime/Engine/Components/UStaticMeshComponent/) /<br/> [Procedural Mesh Component](https://docs.unrealengine.com/4.27/en-US/API/Plugins/ProceduralMeshComponent/UProceduralMeshComponent/) |
| [`Objects.Geometry.PointCloud`](https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Geometry/Pointcloud.cs) | → | [LiDAR Point Cloud](https://docs.unrealengine.com/4.27/en-US/WorkingWithContent/LidarPointCloudPlugin/LidarPointCloudPluginReference/) |
| [`Objects.Other.Instance`](https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/Other/Instance.cs) | → | Actor with Transform |
| [`Objects.BuiltElements.View`](https://github.com/specklesystems/speckle-sharp/blob/main/Objects/Objects/BuiltElements/View.cs) | → | [Camera](https://docs.unrealengine.com/4.27/en-US/InteractiveExperiences/Framework/Camera/) |
**Supported platforms**: Windows, Linux, MacOS
*Other platforms may work, but currently untested*.
## NOTICE
**Limitations**:
- Currently no support for sending Unreal geometry to Speckle.
- Does not use the .NET or Python SDK, or the Speckle Kit based workflow, all code is in native C++/BP.
- Does not use our shared [Desktop UI 2](https://speckle.guide/user/ui2.html), only a simple editor UI is currently provided.
- Does not fetch [accounts from Speckle Manager](https://speckle.guide/user/manager.html#logging-in-adding-accounts), you must generate a [personal access token (auth token)](https://speckle.guide/dev/tokens.html#personal-access-tokens) to receive non-public streams.
* 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
## How To Install
**Speckle for Unreal Engine** can be installed through the [Unreal Engine Marketplace](https://www.unrealengine.com/marketplace/en-US/product/speckle-for-unreal-engine).
---
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.
Alternatively, developers may prefer to install manually.
1. Git clone [this repo](https://github.com/specklesystems/speckle-unreal) (or download and extract the [archive zip](https://github.com/specklesystems/speckle-unreal/archive/refs/heads/main.zip)) into your project's `Plugins` directory (created as needed)
2. Open/Restart your Unreal project. This will build the plugin for your environment.
See our [docs](https://speckle.guide/user/unreal.html) for usage instructions.
## 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).
https://user-images.githubusercontent.com/2551138/114720051-571e3f80-9d40-11eb-9099-d3394747a1d3.mp4
If you encounter build issues, try building your project from VS/Rider directly. Look at the `Saved\Logs\` files for error messages,
and don't hesitate to reach out on our [community forums](https://speckle.community) for help!
For contributing to any of our code repositories, please make sure you read the [contribution guidelines](https://github.com/specklesystems/speckle-sharp/blob/main/.github/CONTRIBUTING.md) for an overview of the best practices we try to follow.
@@ -0,0 +1,194 @@
#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"));
if(!AuthToken.IsEmpty())
Request->SetHeader("Authorization","Bearer " + AuthToken);
Request->SetHeader("apollographql-client-name", "Unreal Engine");
Request->SetHeader("apollographql-client-version", SPECKLE_CONNECTOR_VERSION);
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;
}
@@ -1,5 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "API/Operations/ReceiveOperation.h"
@@ -10,7 +8,10 @@
#include "Mixpanel.h"
UReceiveOperation* UReceiveOperation::ReceiveOperation(UObject* WorldContextObject, const FString& ObjectId, TScriptInterface<ITransport> RemoteTransport, TScriptInterface<ITransport> LocalTransport)
UReceiveOperation* UReceiveOperation::ReceiveOperation(UObject* WorldContextObject,
const FString& ObjectId,
TScriptInterface<ITransport> RemoteTransport,
TScriptInterface<ITransport> LocalTransport)
{
UReceiveOperation* Node = NewObject<UReceiveOperation>();
Node->ObjectId = ObjectId;
@@ -21,12 +22,10 @@ UReceiveOperation* UReceiveOperation::ReceiveOperation(UObject* WorldContextObje
return Node;
}
void UReceiveOperation::Activate()
{
FAnalytics::TrackEvent("unknown", "unknown", "NodeRun", TMap<FString, FString> { {"name", StaticClass()->GetName() }});
FAnalytics::TrackEvent("unknown", "NodeRun", TMap<FString, FString> { {"name", StaticClass()->GetName()} });
//Async(EAsyncExecution::Thread, [this]{Receive();});
Receive();
}
@@ -46,13 +45,16 @@ void UReceiveOperation::Receive()
// 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.");
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);
@@ -86,5 +88,4 @@ void UReceiveOperation::HandleError(FString& Message)
FEditorScriptExecutionGuard ScriptGuard;
OnError.Broadcast(nullptr, Message);
SetReadyToDestroy();
}
}
@@ -1,33 +0,0 @@
#include "API/Operations/SendOperation.h"
#include "Mixpanel.h"
#include "Transports/Transport.h"
USendOperation* USendOperation::SendOperation(UObject* WorldContextObject, UBase* Base, TArray<TScriptInterface<ITransport>> Transports)
{
USendOperation* Node = NewObject<USendOperation>();
Node->Base = Base;
Node->Transports = Transports;
Node->RegisterWithGameInstance(WorldContextObject);
return Node;
}
void USendOperation::Activate()
{
FAnalytics::TrackEvent("unknown", "unknown", "NodeRun", TMap<FString, FString> { {"name", StaticClass()->GetName() }});
Send();
}
void USendOperation::Send()
{
check(Transports.Num() > 0);
for (const auto t : Transports)
{
//TODO
//ITransport::
}
}
@@ -0,0 +1,68 @@
#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,57 @@
#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;
}
@@ -1,7 +1,9 @@
#include "API/SpeckleSerializer.h"
#include "API/SpeckleSerializer.h"
#include "Objects/Base.h"
#include "LogSpeckle.h"
#include "Objects/DisplayValueElement.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Objects/ObjectModelRegistry.h"
#include "Templates/SubclassOf.h"
@@ -9,31 +11,33 @@
#include "UObject/Package.h"
UBase* USpeckleSerializer::DeserializeBase(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
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))
{
// 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;
FString WorkingType{};
FString Remainder = FString(SpeckleType);
int32 Tries = 200;
while(ensure(Tries-- > 0))
{
//Try and deserialize
const bool IsLastChance = !UObjectModelRegistry::SplitSpeckleType(Remainder, Remainder, WorkingType);
if(UObjectModelRegistry::TryGetRegisteredType(WorkingType, BaseType))
{
UBase* Base = NewObject<UBase>(GetTransientPackage(), BaseType);
@@ -41,41 +45,36 @@ UBase* USpeckleSerializer::DeserializeBase(const TSharedPtr<FJsonObject> Obj, co
return Base;
}
//If we couldn't even deserialize this to a Base
if(IsLastChance)
{
//Try a fallback displayValue object
UBase* Base = NewObject<UBase>(GetTransientPackage(), UDisplayValueElement::StaticClass());
if(Base->Parse(Obj, ReadTransport))
return Base;
//If not, try a regular Base
Base = NewObject<UBase>(GetTransientPackage(), UBase::StaticClass());
if(Base->Parse(Obj, ReadTransport))
return Base;
UE_LOG(LogSpeckle, Warning, TEXT("Skipping deserilization of %s id: %s - object could not be deserilaized to Base"), *SpeckleType, *ObjectId );
return nullptr;
}
//If we couldn't even deserialize this to a Base, something is quite wrong...
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)
const TScriptInterface<ITransport> ReadTransport)
{
auto Obj = ReadTransport->GetSpeckleObject(ObjectId);
return DeserializeBase(Obj, ReadTransport);
}
UBase* TrySetProperties(const TSubclassOf<UBase> BaseType, const FString& SerialisedObject, TScriptInterface<ITransport> Transport)
{
UBase* Base = NewObject<UBase>(GetTransientPackage(), BaseType);
TSharedRef<FJsonStringReader> Reader = FJsonStringReader::Create(SerialisedObject);
for(auto foo : Reader.)
{
}
return Base;
}
+15 -10
View File
@@ -1,12 +1,13 @@
#include "Mixpanel.h"
#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 "Runtime/Launch/Resources/Version.h"
#include "Policies/CondensedJsonPrintPolicy.h"
#include "Serialization/JsonSerializerMacros.h"
#include "Serialization/JsonWriter.h"
@@ -15,23 +16,28 @@ 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& Email, const FString& Server, const FString& EventName)
void FAnalytics::TrackEvent(const FString& Server, const FString& EventName)
{
const TMap<FString, FString> CustomProperties;
TrackEvent(Email, Server, EventName, CustomProperties);
TrackEvent( Server, EventName, CustomProperties);
}
void FAnalytics::TrackEvent(const FString& Email, const FString& Server, const FString& EventName, const TMap<FString, FString>& CustomProperties)
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 UserID = FString(FPlatformProcess::ComputerName()) + FString(FPlatformProcess::UserName());
TrackEvent(UserID, Server, EventName, CustomProperties);
}
FString HashedEmail = "@" + Hash(Email); //prepending an @ so we distinguish logged and non-logged users
void FAnalytics::TrackEvent(const FString& UserID, const FString& Server, const FString& EventName, const TMap<FString, FString>& CustomProperties)
{
FString HashedUserID = "@" + Hash(UserID); //prepending an @ so we distinguish logged and non-logged users
FString HashedServer = Hash(Server);
TMap<FString, FString> Properties
{
{ "distinct_id", HashedEmail },
{ "distinct_id", HashedUserID },
{ "server_id", HashedServer },
{ "token", MixpanelToken },
{ "hostApp", "Unreal Engine" },
@@ -75,7 +81,6 @@ void FAnalytics::TrackEvent(const FString& Email, const FString& Server, const F
{
UE_LOG(LogSpeckle, Log, TEXT("Failed to send Mixpanel event to %s"), *MixpanelServer);
}
#endif
}
FString FAnalytics::Hash(const FString& Input)
@@ -1,4 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Conversion/Converters/AggregateConverter.h"
@@ -34,10 +33,11 @@ void UAggregateConverter::PostEditChangeProperty(FPropertyChangedEvent& Property
}
#endif
void UAggregateConverter::ConvertToSpeckle_Implementation(const UObject* Object, UBase* SpeckleObject)
UBase* UAggregateConverter::ConvertToSpeckle_Implementation(const UObject* Object)
{
//TODO implement ToSpeckle
unimplemented();
return nullptr;
}
@@ -79,7 +79,6 @@ bool UAggregateConverter::CanConvertToNative_Implementation(TSubclassOf<UBase> B
return GetConverter(BaseType).GetInterface() != nullptr;
}
TScriptInterface<ISpeckleConverter> UAggregateConverter::GetConverter(const TSubclassOf<UBase> BaseType)
{
// Check if this SpeckleType has a known converter.
@@ -1,12 +1,15 @@
#include "Conversion/Converters/BlockConverter.h"
#include "Conversion/Converters/BlockConverter.h"
#include "Objects/Other/BlockInstance.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Engine/World.h"
#include "Objects/Other/RevitInstance.h"
UBlockConverter::UBlockConverter()
{
SpeckleTypes.Add(UBlockInstance::StaticClass());
SpeckleTypes.Add(URevitInstance::StaticClass());
BlockInstanceActorType = AActor::StaticClass();
ActorMobility = EComponentMobility::Static;
@@ -14,13 +17,13 @@ UBlockConverter::UBlockConverter()
UObject* UBlockConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>&)
{
const UBlockInstance* Block = Cast<UBlockInstance>(SpeckleBase);
const UInstance* Block = Cast<UInstance>(SpeckleBase);
if(Block == nullptr) return nullptr;
return BlockToNative(Block, World);
}
AActor* UBlockConverter::BlockToNative(const UBlockInstance* Block, UWorld* World)
AActor* UBlockConverter::BlockToNative(const UInstance* Block, UWorld* World)
{
AActor* BlockActor = CreateEmptyActor(World, USpeckleObjectUtils::CreateTransform(Block->Transform));
//Return the block actor as is,
@@ -0,0 +1,53 @@
#include "Conversion/Converters/CollectionConverter.h"
#include "Objects/Collection.h"
UCollectionConverter::UCollectionConverter()
{
SpeckleTypes.Add(UCollection::StaticClass());
ActorType = AActor::StaticClass();
ActorMobility = EComponentMobility::Static;
}
UObject* UCollectionConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World,
TScriptInterface<ISpeckleConverter>& AvailableConverters )
{
const UCollection* p = Cast<UCollection>(SpeckleBase);
if(p == nullptr) return nullptr;
return CollectionToNative(p, World);
}
AActor* UCollectionConverter::CollectionToNative(const UCollection*, UWorld* World)
{
AActor* MeshActor = CreateEmptyActor(World);
return MeshActor;
}
AActor* UCollectionConverter::CreateEmptyActor(UWorld* World, const FActorSpawnParameters& SpawnParameters)
{
AActor* Actor = World->SpawnActor<AActor>(ActorType, SpawnParameters);
USceneComponent* Scene = NewObject<USceneComponent>(Actor, "Root");
Actor->SetRootComponent(Scene);
Scene->RegisterComponent();
Scene->SetMobility(ActorMobility);
return Actor;
}
UBase* UCollectionConverter::ConvertToSpeckle_Implementation(const UObject* Object)
{
return nullptr; //TODO implement ToSpeckle function
}
UCollection* UCollectionConverter::CollectionToSpeckle(const AActor* Object)
{
return nullptr; //TODO implement ToSpeckle function
}
@@ -1,5 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Conversion/Converters/MaterialConverter.h"
@@ -8,12 +6,15 @@
#include "Materials/MaterialInstanceDynamic.h"
#include "Objects/Other/RenderMaterial.h"
#include "UObject/ConstructorHelpers.h"
#include "Materials/MaterialInterface.h"
#include "Misc/Paths.h"
#include "UObject/Package.h"
UMaterialConverter::UMaterialConverter()
{
static ConstructorHelpers::FObjectFinder<UMaterial> SpeckleMaterial(TEXT("Material'/SpeckleUnreal/SpeckleMaterial.SpeckleMaterial'"));
static ConstructorHelpers::FObjectFinder<UMaterial> SpeckleGlassMaterial(TEXT("Material'/SpeckleUnreal/SpeckleGlassMaterial.SpeckleGlassMaterial'"));
static ConstructorHelpers::FObjectFinder<UMaterialInterface> SpeckleMaterial(TEXT("Material'/SpeckleUnreal/SpeckleMaterial.SpeckleMaterial'"));
static ConstructorHelpers::FObjectFinder<UMaterialInterface> SpeckleGlassMaterial(TEXT("Material'/SpeckleUnreal/SpeckleGlassMaterial.SpeckleGlassMaterial'"));
DefaultMeshMaterial = SpeckleMaterial.Object;
BaseMeshOpaqueMaterial = SpeckleMaterial.Object;
@@ -80,7 +81,7 @@ bool UMaterialConverter::TryGetOverride(const URenderMaterial* SpeckleMaterial,
{
if(ensureAlways(IsValid(Mat)) && Mat->GetName() == Name)
{
OutMaterial = MaterialOverridesById[MaterialID];
OutMaterial = *MaterialOverridesByName.Find(Mat);
return true;
}
}
@@ -1,12 +1,12 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Conversion/Converters/PointCloudConverter.h"
#include "LidarPointCloudActor.h"
#include "LidarPointCloudShared.h"
#include "LidarPointCloudComponent.h"
#include "Objects/Geometry/PointCloud.h"
#include "Engine/World.h"
#include "Runtime/Launch/Resources/Version.h"
UPointCloudConverter::UPointCloudConverter()
{
@@ -1,4 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Conversion/Converters/ProceduralMeshConverter.h"
@@ -19,7 +18,8 @@ UProceduralMeshConverter::UProceduralMeshConverter()
ActorMobility = EComponentMobility::Static;
}
UObject* UProceduralMeshConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>& AvailableConverters )
UObject* UProceduralMeshConverter::ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World,
TScriptInterface<ISpeckleConverter>& AvailableConverters )
{
const UMesh* m = Cast<UMesh>(SpeckleBase);
if(m != nullptr)
@@ -47,7 +47,9 @@ UObject* UProceduralMeshConverter::ConvertToNative_Implementation(const UBase* S
return nullptr;
}
AActor* UProceduralMeshConverter::MeshToNative(const UMesh* SpeckleMesh, UWorld* World, TScriptInterface<ISpeckleConverter>& MaterialConverter)
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"));
@@ -64,19 +66,19 @@ AActor* UProceduralMeshConverter::MeshToNative(const UMesh* SpeckleMesh, UWorld*
if (n == 3) //Triangles
{
Faces.Add(SpeckleMesh->Faces[i + 3]);
Faces.Add(SpeckleMesh->Faces[i + 2]);
Faces.Add(SpeckleMesh->Faces[i + 1]);
Faces.Add(SpeckleMesh->Faces[i + 2]);
Faces.Add(SpeckleMesh->Faces[i + 3]);
}
else if(n == 4) // Quads
{
Faces.Add(SpeckleMesh->Faces[i + 1]);
Faces.Add(SpeckleMesh->Faces[i + 3]);
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]);
Faces.Add(SpeckleMesh->Faces[i + 2]);
Faces.Add(SpeckleMesh->Faces[i + 3]);
}
else
{
@@ -1,4 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Conversion/Converters/StaticMeshConverter.h"
@@ -16,6 +15,10 @@
#include "Objects/DisplayValueElement.h"
#include "Objects/Other/RenderMaterial.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Components/StaticMeshComponent.h"
#include "Misc/Paths.h"
#include "UObject/Package.h"
#include "Materials/MaterialInterface.h"
#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule"
@@ -23,6 +26,8 @@ UStaticMeshConverter::UStaticMeshConverter()
{
SpeckleTypes.Add(UMesh::StaticClass());
SpeckleTypes.Add(UDisplayValueElement::StaticClass());
HiddenTypes.Add("Objects.BuiltElements.Room");
#if WITH_EDITORONLY_DATA
UseFullBuild = true;
@@ -96,10 +101,10 @@ AActor* UStaticMeshConverter::MeshesToNativeActor(const UBase* Parent, const TAr
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;
}
// if(Parent == SpeckleMeshes[0])
// {
// Transform = SpeckleMeshes[0]->Transform;
// }
AActor* Actor = CreateEmptyActor(World, USpeckleObjectUtils::CreateTransform(Transform));
TInlineComponentArray<UStaticMeshComponent*> Components;
@@ -116,6 +121,15 @@ AActor* UStaticMeshConverter::MeshesToNativeActor(const UBase* Parent, const TAr
}
MeshComponent->SetStaticMesh(Mesh);
for(const FString& t: HiddenTypes)
{
if(Parent->SpeckleType.Contains(t))
{
MeshComponent->SetVisibility(false);
break;
}
}
int i = 0;
for(const UMesh* DisplayMesh : SpeckleMeshes)
@@ -262,6 +276,13 @@ UStaticMesh* UStaticMeshConverter::MeshesToNativeMesh(UObject* Outer, const UBas
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);
@@ -366,7 +387,7 @@ void UStaticMeshConverter::GenerateMeshParams(UStaticMesh::FBuildMeshDescription
}
void UStaticMeshConverter::ConvertToSpeckle_Implementation(const UObject* Object, UBase* SpeckleObject)
UBase* UStaticMeshConverter::ConvertToSpeckle_Implementation(const UObject* Object)
{
const UStaticMeshComponent* M = Cast<UStaticMeshComponent>(Object);
@@ -378,74 +399,22 @@ void UStaticMeshConverter::ConvertToSpeckle_Implementation(const UObject* Object
M = A->FindComponentByClass<UStaticMeshComponent>();
}
}
if(M == nullptr) return;
//SpeckleObject->DynamicProperties.Add(TEXT("@displayValue"), MeshToSpeckle(M));
if(M == nullptr) return nullptr;
return MeshToSpeckle(M);
}
TArray<UMesh*> UStaticMeshConverter::MeshToSpeckle(const UStaticMeshComponent* MeshComponent)
UBase* UStaticMeshConverter::MeshToSpeckle(const UStaticMeshComponent* Object)
{
UStaticMeshDescription* StaticMeshDescription = NewObject<UStaticMeshDescription>(GetTransientPackage(), NAME_None, RF_Transient);
const FMeshDescription* MeshDescription = MeshComponent->GetStaticMesh()->GetMeshDescription(0);;
StaticMeshDescription->SetMeshDescription(*MeshDescription);
StaticMeshDescription->RegisterAttributes();
const FVertexArray& nVertices = StaticMeshDescription->Vertices();
TArray<FVector> sVertices;
sVertices.Reserve(nVertices.Num()); // * 3));
TMap<FVertexID, int32> VertexIdToIndex;
VertexIdToIndex.Reserve(nVertices.Num() * 3);
int32 i = 0;
for (const FVertexID& VertexId : nVertices.GetElementIDs())
{
const FVector Vert = StaticMeshDescription->GetVertexPosition(VertexId);
sVertices.Add(Vert);
VertexIdToIndex.Add(VertexId, i);
i++;
}
FTriangleArray& nTriangles = StaticMeshDescription->Triangles();
TArray<int32> sFaces;
sFaces.Reserve(nTriangles.Num());
for (const FTriangleID& TriangleId : nTriangles.GetElementIDs())
{
TArray<FVertexID> Tri;
StaticMeshDescription->GetTriangleVertices(TriangleId, Tri);
sFaces.Add(3);
sFaces.Add(VertexIdToIndex[Tri[0]]);
sFaces.Add(VertexIdToIndex[Tri[1]]);
sFaces.Add(VertexIdToIndex[Tri[2]]);
}
//TODO colors
//TODO tex-coords
//TODO split mesh by material
UMesh* Mesh = NewObject<UMesh>(GetTransientPackage(), NAME_None, RF_Transient);
Mesh->Vertices = sVertices;
Mesh->Faces = sFaces;
//Mesh->Colors = sColors;
//Mesh->TextureCoordinates = sTexCoords;
Mesh->Units = "cm";
return TArray<UMesh*>{Mesh};
return nullptr; //TODO implement ToSpeckle function
}
void UStaticMeshConverter::FinishConversion_Implementation()
{
if(StaticMeshesToBuild.Num() <= 0) return;
FScopeLock Lock(&Lock_StaticMeshesToBuild);
#if WITH_EDITOR
@@ -1,60 +0,0 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Conversion/SpeckleConverter.h"
#include "Conversion/SpeckleConverterComponent.h"
#include "Conversion/Converters/AggregateConverter.h"
#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule"
UBase* USpeckleConverterComponent::RecursivelyConvertToSpeckle(const TArray<AActor*>& RootActors, FActorPredicate& Predicate)
{
TArray<UBase*> ConvertedRootActors;
for(const AActor* RootActor : RootActors)
{
RecurseTreeToSpeckle(RootActor, Predicate, ConvertedRootActors);
}
UBase* Wrapper = NewObject<UBase>(GetTransientPackage(), NAME_None, RF_Transient);
//Converted->DynamicProperties["objects"] = ConvertedRootActors; //TODO set children
return Wrapper;
}
void USpeckleConverterComponent::RecurseTreeToSpeckle(const AActor* RootActor, FActorPredicate& Predicate, TArray<UBase*>& OutConverted)
{
// Convert children first
TArray<UBase*> ConvertedChildren;
ConvertedChildren.Reserve(RootActor->Children.Num());
for (const AActor* Child : RootActor->Children)
{
RecurseTreeToSpeckle(Child, Predicate, ConvertedChildren);
}
bool ShouldConvert;
Predicate.Execute(RootActor, ShouldConvert);
if(ISpeckleConverter::Execute_CanConvertToSpeckle(SpeckleConverter, RootActor) && ShouldConvert)
{
// Convert and output
UBase* Converted = NewObject<UBase>(GetTransientPackage(), NAME_None, RF_Transient);
//Converted->DynamicProperties["name"] = RootActor->GetName(),
//["transform"] = TransformToSpeckle(go.Transform), //TODO set common props
//Converted->DynamicProperties["tag"] = go.tag,
//Converted->DynamicProperties["layer"] = go.layer,
//Converted->DynamicProperties["isStatic"] = go.isStatic,
ISpeckleConverter::Execute_ConvertToSpeckle(SpeckleConverter, RootActor, Converted);
//Converted->DynamicProperties["objects"] = ConvertedChildren; //TODO set children
OutConverted.Add(Converted);
}
else
{
// Skip this object, and output any children
OutConverted.Append(ConvertedChildren);
}
}
#undef LOCTEXT_NAMESPACE
@@ -1,5 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Conversion/SpeckleConverterComponent.h"
@@ -7,15 +5,17 @@
#include "API/SpeckleSerializer.h"
#include "Conversion/Converters/AggregateConverter.h"
#include "Conversion/Converters/BlockConverter.h"
#include "Conversion/Converters/CollectionConverter.h"
#include "Conversion/Converters/PointCloudConverter.h"
#include "Conversion/Converters/StaticMeshConverter.h"
#include "Conversion/Converters/MaterialConverter.h"
#include "Misc/ScopedSlowTask.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "UObject/ConstructorHelpers.h"
#include "Dom/JsonValue.h"
#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule"
// Sets default values for this component's properties
USpeckleConverterComponent::USpeckleConverterComponent()
{
//TODO consider using an object library for default converters
@@ -23,6 +23,7 @@ USpeckleConverterComponent::USpeckleConverterComponent()
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<UCollectionConverter> CollectionConverter(TEXT("CollectionConverter'/SpeckleUnreal/Converters/DefaultCollectionConverter.DefaultCollectionConverter'"));
static ConstructorHelpers::FObjectFinder<UObject> CameraConverter(TEXT("CameraConverter'/SpeckleUnreal/Converters/DefaultCameraConverter.DefaultCameraConverter'"));
//static ConstructorHelpers::FObjectFinder<ULightConverter> LightConverter(TEXT("LightConverter'/SpeckleUnreal/Converters/DefaultLightConverter.DefaultLightConverter'"));
@@ -32,6 +33,7 @@ USpeckleConverterComponent::USpeckleConverterComponent()
SpeckleConverter->SpeckleConverters.Add(PointCloudConverter.Object);
SpeckleConverter->SpeckleConverters.Add(BlockConverter.Object);
SpeckleConverter->SpeckleConverters.Add(MaterialConverter.Object);
SpeckleConverter->SpeckleConverters.Add(CollectionConverter.Object);
SpeckleConverter->SpeckleConverters.Add(CameraConverter.Object);
//SpeckleConverter->SpeckleConverters.Add(LightConverter.Object);
@@ -42,8 +44,23 @@ AActor* USpeckleConverterComponent::RecursivelyConvertToNative(AActor* AOwner, c
const TScriptInterface<ITransport>& LocalTransport, bool DisplayProgressBar, TArray<AActor*>& OutActors)
{
float ObjectsToConvert{};
Base->TryGetDynamicNumber("totalChildrenCount", ObjectsToConvert);
FScopedSlowTask Progress(ObjectsToConvert + 2, LOCTEXT("SpeckleConvertoNative","Converting Speckle Objects to Native"), DisplayProgressBar);
if(Base->TotalChildrenCount > 0)
{
ObjectsToConvert = Base->TotalChildrenCount;
}
else
{
Base->TryGetDynamicNumber("totalChildrenCount", ObjectsToConvert);
}
if(ObjectsToConvert <= 1)
{
ObjectsToConvert = 99999; //A large number
}
// Progress bar
FScopedSlowTask Progress(ObjectsToConvert + 2,
LOCTEXT("SpeckleConvertoNative","Converting Speckle Objects to Native"), DisplayProgressBar);
#if WITH_EDITOR
Progress.MakeDialog(true, false);
#endif
@@ -85,7 +102,7 @@ AActor* USpeckleConverterComponent::RecursivelyConvertToNative_Internal(AActor*
{
if(Task->ShouldCancel()) break;
ConvertChild(Kvp.Value, AOwner, LocalTransport, Task, OutActors);
ConvertChild(Kvp.Value, NextOwner, LocalTransport, Task, OutActors);
}
return AOwner;
}
@@ -125,12 +142,14 @@ void USpeckleConverterComponent::AttachConvertedToOwner(AActor* AOwner, const UB
{
#if WITH_EDITOR
{
FString Name;
FText _Discard;
if( !(Base->TryGetDynamicString("name", Name) && FActorEditorUtils::ValidateActorName(FText::FromString(Name), _Discard)) )
FString Name = USpeckleObjectUtils::GetFriendlyObjectName(Base);
FText NameErrors;
if(!FActorEditorUtils::ValidateActorName(FText::FromString(Name), NameErrors))
{
Name = FString::Printf(TEXT("%s - %s"), *Base->SpeckleType, *Base->Id);
Name = USpeckleObjectUtils::GetBoringObjectName(Base);
}
NativeActor->SetActorLabel(Name);
}
#endif
@@ -176,4 +195,4 @@ void USpeckleConverterComponent::FinishConversion()
SpeckleConverter->FinishConversion_Internal();
}
#undef LOCTEXT_NAMESPACE
#undef LOCTEXT_NAMESPACE
+2 -1
View File
@@ -1,4 +1,5 @@
#include "LogSpeckle.h"
#include "LogSpeckle.h"
#include "Logging/LogMacros.h"
DEFINE_LOG_CATEGORY(LogSpeckle);
@@ -0,0 +1,20 @@
#include "Objects/Collection.h"
bool UCollection::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
if(!Super::Parse(Obj, ReadTransport)) return false;
// Parse Name property
if(!Obj->TryGetStringField("name", Name)) return false;
//DynamicProperties.Remove("name"); //Don't remove from dynamic, as we pick this up to name the actor
// Parse collectionType
if(!Obj->TryGetStringField("collectionType", CollectionType)) return false;
DynamicProperties.Remove("collectionType");
return true;
}
@@ -1,5 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Objects/DisplayValueElement.h"
@@ -10,8 +8,6 @@
TArray<FString> UDisplayValueElement::DisplayValueAliasStrings = {
"displayValue",
"@displayValue",
"displayMesh"
"@displayMesh"
};
@@ -1,80 +0,0 @@
// Copyright AEC Systems Ltd
#include "Objects/DynamicBase.h"
#include "Misc/Variant.h"
template <typename T>
bool UDynamicBase::TryGetDynamicProperty(const FString& Key, T& OutValue) const
{
const auto Wrapper = DynamicProperties.FindRef(Key);
if(Wrapper.IsValid()) return false;
if(Wrapper->GetType() != TVariantTraits<T>::GetType()) return false;
OutValue = Wrapper->GetValue<T>();
return true;
}
template <typename T>
void UDynamicBase::SetDynamicProperty(const FString& Key, T Value)
{
DynamicProperties.Add(Key, MakeShareable(new FVariant(Value)));
}
int32 UDynamicBase::RemoveDynamicProperty(const FString& Key)
{
return DynamicProperties.Remove(Key);
}
//-------------------
bool UDynamicBase::TryGetDynamicStringProperty(const FString& Key, FString& OutValue) const
{
return TryGetDynamicProperty(Key, OutValue);
}
bool UDynamicBase::TryGetDynamicIntProperty(const FString& Key, int32& OutValue) const
{
return TryGetDynamicProperty(Key, OutValue);
}
bool UDynamicBase::TryGetDynamicFloatProperty(const FString& Key, float& OutValue) const
{
return TryGetDynamicProperty(Key, OutValue);
}
bool UDynamicBase::TryGetDynamicBoolProperty(const FString& Key, bool& OutValue) const
{
return TryGetDynamicProperty(Key, OutValue);
}
bool UDynamicBase::TryGetDynamicBaseProperty(const FString& Key, UBase*& OutValue) const
{
return TryGetDynamicProperty(Key, OutValue);
}
void UDynamicBase::SetDynamicStringProperty(const FString& Key, FString& OutValue)
{
SetDynamicProperty(Key, OutValue);
}
void UDynamicBase::SetDynamicIntProperty(const FString& Key, int32& OutValue)
{
SetDynamicProperty(Key, OutValue);
}
void UDynamicBase::SetDynamicFloatProperty(const FString& Key, float& OutValue)
{
SetDynamicProperty(Key, OutValue);
}
void UDynamicBase::SetDynamicBoolProperty(const FString& Key, bool& OutValue)
{
SetDynamicProperty(Key, OutValue);
}
void UDynamicBase::SetDynamicBaseProperty(const FString& Key, UBase*& OutValue)
{
SetDynamicProperty(Key, OutValue);
}
@@ -1,5 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Objects/Geometry/Mesh.h"
@@ -33,12 +31,12 @@ bool UMesh::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITra
for (size_t i = 0, j = 0; i < NumberOfVertices; i++, j += 3)
{
Vertices.Add(Transform.InverseTransformPosition(FVector
Vertices.Add(FVector
(
ObjectVertices[j].Get()->AsNumber(),
-ObjectVertices[j + 1].Get()->AsNumber(),
ObjectVertices[j + 2].Get()->AsNumber()
) * ScaleFactor ));
) * ScaleFactor );
}
DynamicProperties.Remove("vertices");
}
@@ -105,70 +103,8 @@ bool UMesh::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITra
return Vertices.Num() > 0 && Faces.Num() > 0;
}
void UMesh::ToJson(TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>> Writer)
{
Super::ToJson(Writer);
// Serialize Transform
// TODO todo transform
// Serialize Vertices
{
TArray<double> FlattenedVertices;
FlattenedVertices.Reserve(Vertices.Num() * 3);
for(size_t i = 0, j = 0; i < Vertices.Num(); i++)
{
const FVector& v = Vertices[i];
FlattenedVertices[j++] = v.X;
FlattenedVertices[j++] = -v.Y;
FlattenedVertices[j++] = v.Z;
}
Writer.WriteValue(TEXT("vertices"), FlattenedVertices);
}
// Serialize Faces
Writer.WriteValue(TEXT("faces"), Faces);
//Parse TextureCoords
{
TArray<double> FlattenedTexCoords;
FlattenedTexCoords.Reserve(TextureCoordinates.Num() * 2);
for(size_t i = 0, j = 0; i < TextureCoordinates.Num(); i++)
{
const FVector2D& c = TextureCoordinates[i];
FlattenedTexCoords[j++] = c.X;
FlattenedTexCoords[j++] = -c.Y;
}
Writer.WriteValue(TEXT("textureCoordinates"), FlattenedTexCoords);
}
//Parse VertexColors
{
TArray<int32> ArgbColors;
ArgbColors.Reserve(VertexColors.Num());
for(size_t i = 0; i < VertexColors.Num(); i++)
{
ArgbColors[i] = VertexColors[i].ToPackedARGB();
}
Writer.WriteValue(TEXT("colors"), ArgbColors);
}
// Parse Optional RenderMaterial
//if (RenderMaterial != nullptr)
{
//TODO renderMaterial
}
}
/**
* 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"
*/
void UMesh::AlignVerticesWithTexCoordsByIndex()
{
if(TextureCoordinates.Num() == 0) return;
@@ -1,5 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Objects/Geometry/PointCloud.h"
@@ -1,4 +1,5 @@
#include "Objects/ObjectModelRegistry.h"
#include "Objects/ObjectModelRegistry.h"
#include "Objects/Base.h"
#include "Templates/SubclassOf.h"
@@ -20,65 +21,81 @@ void UObjectModelRegistry::GenerateTypeRegistry()
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"),
const FString& SpeckleType = Class->GetDefaultObject<UBase>()->SpeckleType;
const FString TypeName = GetTypeName(SpeckleType);
ensureAlwaysMsgf(!TypeRegistry.Contains(TypeName),
TEXT("Base class: %s conflicts with: %s for TypeName: %s"),
*Class->GetName(),
*TypeRegistry[SpeckleType]->GetName(),
*SpeckleType);
TypeRegistry.Add(SpeckleType, *It);
TypeRegistry.Add(TypeName, *It);
}
}
}
TSubclassOf<UBase> UObjectModelRegistry::FindClosestType(const FString& SpeckleType)
bool UObjectModelRegistry::SplitSpeckleType(const FString& SpeckleType, FString& OutRemainder, FString& OutTypeName, const FString& Split)
{
FString TypeString(SpeckleType);
TSubclassOf<UBase> Type = nullptr;
while(!TryGetRegisteredType(TypeString, Type))
if(SpeckleType.Split(Split, &OutRemainder, &OutTypeName, ESearchCase::CaseSensitive, ESearchDir::FromEnd))
{
if(!ParentType(TypeString, TypeString)) return nullptr;
return true;
}
else
{
OutTypeName = SpeckleType;
return false;
}
return Type;
}
bool UObjectModelRegistry::ParentType(const FString& Type, FString& NextType)
FString UObjectModelRegistry::GetTypeName(const FString& SpeckleType)
{
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;
FString Discard, Ret;
SplitSpeckleType(SpeckleType, Discard, Ret);
return Ret;
}
TSubclassOf<UBase> UObjectModelRegistry::GetRegisteredType(const FString& SpeckleType)
FString UObjectModelRegistry::GetSimplifiedTypeName(const FString& SpeckleType)
{
FString Discard, Ret;
SplitSpeckleType(SpeckleType,Discard, Ret, ".");
return Ret;
}
TSubclassOf<UBase> UObjectModelRegistry::GetAtomicType(const FString& SpeckleType)
{
FString WorkingType;
FString Remainder = FString(SpeckleType);
while(SplitSpeckleType(Remainder, Remainder, WorkingType))
{
TSubclassOf<UBase> Type;
if(TryGetRegisteredType(WorkingType, Type))
{
return Type;
}
}
return UBase::StaticClass();
}
TSubclassOf<UBase> UObjectModelRegistry::GetRegisteredType(const FString& TypeName)
{
TSubclassOf<UBase> Type = nullptr;
TryGetRegisteredType(SpeckleType, Type);
TryGetRegisteredType(TypeName, Type);
return Type;
}
bool UObjectModelRegistry::TryGetRegisteredType(const FString& SpeckleType, TSubclassOf<UBase>& OutType)
bool UObjectModelRegistry::TryGetRegisteredType(const FString& TypeName, TSubclassOf<UBase>& OutType)
{
if(TypeRegistry.Num() == 0) GenerateTypeRegistry();
const bool Contains = TypeRegistry.Contains(SpeckleType);
const bool Contains = TypeRegistry.Contains(TypeName);
if(Contains)
{
OutType = *TypeRegistry.Find(SpeckleType);
OutType = *TypeRegistry.Find(TypeName);
}
return Contains;
}
@@ -1,5 +1,3 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Objects/Other/BlockInstance.h"
#include "LogSpeckle.h"
@@ -21,15 +19,23 @@ bool UBlockInstance::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInte
//Geometries
const TSharedPtr<FJsonObject>* BlockDefinitionPtr;
if(!Obj->TryGetObjectField("blockDefinition", BlockDefinitionPtr)) return false;
//NOTE: This logic differs greatly from sharp/py implementations
const TSharedPtr<FJsonObject>* DefPtr;
if(!(Obj->TryGetObjectField("definition", DefPtr) || Obj->TryGetObjectField("blockDefinition", DefPtr) )) return false;
const FString RefID = BlockDefinitionPtr->operator->()->GetStringField("referencedId");
const TSharedPtr<FJsonObject> BlockDefinition = ReadTransport->GetSpeckleObject(RefID);
const FString RefID = DefPtr->operator->()->GetStringField("referencedId");
const TSharedPtr<FJsonObject> Definition = ReadTransport->GetSpeckleObject(RefID);
if(BlockDefinition->TryGetStringField("name", Name)) DynamicProperties.Remove("Name");
if(!Obj->TryGetStringField("name", Name))
{
if(Definition->TryGetStringField("name", Name))
{
//The instance has no name, so we'll steal it from the definition
DynamicProperties.Add("name", Definition->TryGetField("name"));
}
}
const auto Geometries = BlockDefinition->GetArrayField("geometry");
const auto Geometries = Definition->GetArrayField("geometry");
if(Geometries.Num() <= 0)
{
@@ -0,0 +1,73 @@
#include "Objects/Other/RevitInstance.h"
#include "LogSpeckle.h"
#include "API/SpeckleSerializer.h"
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "Transports/Transport.h"
bool URevitInstance::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
//NOTE: This logic differs greatly from sharp/py implementations
const TSharedPtr<FJsonObject>* DefPtr;
if(!Obj->TryGetObjectField("definition", DefPtr)) return false;
const FString RefID = DefPtr->operator->()->GetStringField("referencedId");
const TSharedPtr<FJsonObject> Definition = ReadTransport->GetSpeckleObject(RefID);
if(!Obj->TryGetStringField("name", Name))
{
if(Definition->TryGetStringField("name", Name))
{
//The instance has no name, so we'll steal it from the definition
DynamicProperties.Add("name", Definition->TryGetField("name"));
}
}
auto Geometries = TArray<TSharedPtr<FJsonValue>>();
const TArray<TSharedPtr<FJsonValue>>* ElementsPtr;
if(Definition->TryGetArrayField("elements", ElementsPtr))
Geometries.Append(*ElementsPtr);
const TArray<TSharedPtr<FJsonValue>>* DisplayValuePtr;
if(Definition->TryGetArrayField("displayValue", DisplayValuePtr))
Geometries.Append(*DisplayValuePtr);
if(Geometries.Num() <= 0)
{
UE_LOG(LogSpeckle, Warning, TEXT("Instance 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;
}
@@ -1,5 +1,3 @@
// Copyright AEC Systems Ltd
#include "Objects/Other/View3D.h"
@@ -12,7 +10,7 @@ bool UView3D::Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<IT
const float ScaleFactor = USpeckleObjectUtils::ParseScaleFactor(Units);
// Parse optional Name property
if(Obj->TryGetStringField("name", Name)) DynamicProperties.Remove("name");
if(Obj->TryGetStringField("name", Name)) { }
// Parse Origin
if(!USpeckleObjectUtils::ParseVectorProperty(Obj, "origin", ReadTransport, Origin)) return false;
@@ -1,13 +1,14 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Objects/Utils/SpeckleObjectUtils.h"
#include "LogSpeckle.h"
#include "API/SpeckleSerializer.h"
#include "Engine/World.h"
#include "Objects/ObjectModelRegistry.h"
#include "Objects/Geometry/Mesh.h"
#include "Transports/Transport.h"
#include "Serialization/JsonWriter.h"
#include "Serialization/JsonSerializer.h"
TArray<TSharedPtr<FJsonValue>> USpeckleObjectUtils::CombineChunks(const TArray<TSharedPtr<FJsonValue>>& ArrayField, const TScriptInterface<ITransport> Transport)
{
@@ -71,6 +72,9 @@ float USpeckleObjectUtils::ParseScaleFactor(const FString& UnitsString)
if (LUnits == "miles" || LUnits == "mile" || LUnits == "mi")
return 160934.4;
if (LUnits == "us_ft" || LUnits == "ussurveyfeet")
return 12000.0 / 3937.0;
return 100;
};
@@ -95,7 +99,7 @@ bool USpeckleObjectUtils::TryParseTransform(const TSharedPtr<FJsonObject> Speckl
if(SpeckleObject->TryGetArrayField("transform", TransformData)) //Handle transform as array
{ }
else if(SpeckleObject->TryGetObjectField("transform", TransformObject)
&& (*TransformObject)->TryGetArrayField("value", TransformData)) //Handle transform as object
&& (*TransformObject)->TryGetArrayField("matrix", TransformData)) //Handle transform as object
{ }
else return false;
@@ -158,7 +162,36 @@ bool USpeckleObjectUtils::ParseSpeckleObject(const TSharedPtr<FJsonObject> Objec
}
AActor* USpeckleObjectUtils::SpawnActorInWorld(const TSubclassOf<AActor> Class, UWorld* World, const FTransform& Transform)
AActor* USpeckleObjectUtils::SpawnActorInWorld(const UObject* WorldContextObject, const TSubclassOf<AActor> Class, UPARAM(ref) const FTransform& Transform)
{
return World->SpawnActor(Class, &Transform, FActorSpawnParameters());
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;
}
FString USpeckleObjectUtils::GetFriendlyObjectName(const UBase* SpeckleObject)
{
FString Prefix;
if(!(SpeckleObject->TryGetDynamicString("name", Prefix)
|| SpeckleObject->TryGetDynamicString("Name", Prefix)
|| SpeckleObject->TryGetDynamicString("Family", Prefix)))
{
Prefix = UObjectModelRegistry::GetSimplifiedTypeName(SpeckleObject->SpeckleType);
}
return FString::Printf(TEXT("%s -- %s"), *Prefix, *SpeckleObject->Id);
}
FString USpeckleObjectUtils::GetBoringObjectName(const UBase* SpeckleObject)
{
const FString Prefix = UObjectModelRegistry::GetSimplifiedTypeName(SpeckleObject->SpeckleType);
return FString::Printf(TEXT("%s -- %s"), *Prefix, *SpeckleObject->Id);
}
@@ -0,0 +1,427 @@
#include "ReceiveSelectionComponent.h"
#include "API/Models/SpeckleUser.h"
#include "API/ClientAPI.h"
#include "JsonObjectConverter.h"
#include "LogSpeckle.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{activeUser{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, "activeUser", 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,3 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "SpeckleUnreal.h"
@@ -6,13 +5,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
@@ -1,5 +1,7 @@
#include "SpeckleUnrealManager.h"
#include "ReceiveSelectionComponent.h"
#include "API/Operations/ReceiveOperation.h"
#include "Transports/MemoryTransport.h"
#include "Transports/ServerTransport.h"
@@ -9,6 +11,7 @@
#include "Misc/ScopedSlowTask.h"
#include "Objects/Base.h"
#include "Mixpanel.h"
#include "API/SpeckleAPIFunctions.h"
#include "Engine/Engine.h"
#define LOCTEXT_NAMESPACE "FSpeckleUnrealModule"
@@ -22,10 +25,9 @@ ASpeckleUnrealManager::ASpeckleUnrealManager()
RootComponent->SetMobility(EComponentMobility::Static);
Converter = CreateDefaultSubobject<USpeckleConverterComponent>(FName("Converter"));
ReceiveSelection = CreateDefaultSubobject<UReceiveSelectionComponent>(FName("ReceiveSelection"));
KeepCache = true;
DisplayProgressBar = true;
ServerUrl = "https://speckle.xyz";
}
void ASpeckleUnrealManager::BeginPlay()
@@ -37,40 +39,52 @@ void ASpeckleUnrealManager::BeginPlay()
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);
// Trim parameters
ServerUrl.TrimEndInline();
while(ServerUrl.RemoveFromEnd("/")) { }
StreamID.TrimEndInline();
ObjectID.TrimEndInline();
AuthToken.TrimEndInline();
FAnalytics::TrackEvent("unknown", "unknown", "NodeRun", TMap<FString, FString> { {"name", StaticClass()->GetName() }, {"worldType", FString::FromInt(GetWorld()->WorldType)}});
if(!KeepCache && LocalObjectCache.GetObjectRef() != nullptr)
// Setup network transports
UServerTransport* ServerTransport = UServerTransport::CreateServerTransport(ServerUrl, StreamId, AuthToken);
if(!KeepCache && LocalObjectCache)
{
LocalObjectCache.GetObjectRef()->ConditionalBeginDestroy();
LocalObjectCache = UMemoryTransport::CreateEmptyMemoryTransport();
}
if(LocalObjectCache.GetObjectRef() == nullptr)
{
LocalObjectCache = UMemoryTransport::CreateEmptyMemoryTransport();
}
UServerTransport* ServerTransport = UServerTransport::CreateServerTransport(ServerUrl,StreamID,AuthToken);
FString Message = FString::Printf(TEXT("Fetching Objects from Speckle Server: %s"), *ServerUrl);
PrintMessage(Message);
if(!LocalObjectCache) LocalObjectCache = UMemoryTransport::CreateEmptyMemoryTransport();
// Setup delegate callbacks
FTransportErrorDelegate ErrorDelegate;
ErrorDelegate.BindUObject(this, &ASpeckleUnrealManager::HandleError);
FTransportCopyObjectCompleteDelegate CompleteDelegate;
CompleteDelegate.BindUObject(this, &ASpeckleUnrealManager::HandleReceive, DisplayProgressBar);
//Receive
ServerTransport->CopyObjectAndChildren(ObjectID, LocalObjectCache, CompleteDelegate, ErrorDelegate);
// 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);
}
}
@@ -111,7 +125,7 @@ void ASpeckleUnrealManager::PrintMessage(FString& Message, bool IsError) const
{
UE_LOG(LogSpeckle, Log, TEXT("%s"), *Message);
}
FColor Color = IsError? FColor::Red : FColor::Green;
GEngine->AddOnScreenDebugMessage(0, 5.0f, Color, Message);
}
@@ -0,0 +1,77 @@
#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
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Misc/AutomationTest.h"
#include "Objects/Base.h"
@@ -1,25 +0,0 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#include "Misc/AutomationTest.h"
#include "Objects/Base.h"
#include "Transports/ServerTransport.h"
#if WITH_DEV_AUTOMATION_TESTS
IMPLEMENT_SIMPLE_AUTOMATION_TEST(FServerTransportTest, "SpeckleUnreal.Transports.ServerTransport", EAutomationTestFlags::EditorContext | EAutomationTestFlags::ProductFilter)
bool FServerTransportTest::RunTest(const FString& Parameters)
{
FString ServerUrl = TEXT("https://example.com");
FString StreamId = TEXT("1234");
FString Token = TEXT("MyAuthToken");
auto Transport = UServerTransport::CreateServerTransport(ServerUrl, StreamId, Token);
return true;
}
#endif
@@ -1,79 +0,0 @@
#include "FBatchSender.h"
FBatchSender::FBatchSender(FString& ServerUrl, FString& StreamId, FString& AuthToken, int32 MaxBatchSizeMb,
int32 MaxBufferLength, int32 ThreadCount)
: ServerUrl(ServerUrl)
, StreamId(StreamId)
, AuthToken(AuthToken)
, MaxBatchSizeMb(MaxBatchSizeMb)
, MaxBufferLength(MaxBufferLength)
, ThreadCount(ThreadCount)
{
SendingThread = FRunnableThread::Create(this, TEXT("Speckle Transport Send Thread"), 0);
ensure(SendingThread != nullptr);
}
FBatchSender::~FBatchSender()
{
if (SendingThread)
{
SendingThread->Kill();
delete SendingThread;
SendingThread = nullptr;
}
}
uint32 FBatchSender::Run()
{
while(true)
{
if(!ShouldSendThreadRun) return 0;
TArray<TTuple<FString, FString>> Buffer;
FScopeLock Lock(&Lock_SendBuffer);
if(SendBuffer.Num() > 0)
{
Buffer.Append(SendBuffer);
SendBuffer.Empty();
}
else
{
IsWriteComplete = true;
}
if(Buffer.Num() <= 0)
{
FPlatformProcess::Sleep(0.1);
continue;
}
TArray<FString> ObjectIds;
ObjectIds.Reserve(Buffer.Num());
for(const auto& Item: Buffer)
{
ObjectIds.Add(Item.Key);
}
//TODO only send objects that aren't already on the server.
//TMap<FString, bool> HasObjects = API.HasObjects(StreamId, ObjectIds);
//TODO api upload
//API.UploadObjects(StreamId, Buffer);
}
}
void FBatchSender::Stop()
{
ShouldSendThreadRun = false;
}
void FBatchSender::EnqueueSend(const FString& Id, const FString& Object)
{
FScopeLock Lock(&Lock_SendBuffer);
SendBuffer.Emplace(Id, Object);
IsWriteComplete = false;
}
@@ -1,40 +0,0 @@
#pragma once
/**
*
*/
class SPECKLEUNREAL_API FBatchSender : public FRunnable
{
protected:
FString ServerUrl;
FString StreamId;
FString AuthToken;
int32 MaxBatchSizeMb;
int32 MaxBufferLength;
int32 ThreadCount;
bool ShouldSendThreadRun = false;
bool IsWriteComplete = false;
FRunnableThread* SendingThread;
FCriticalSection Lock_SendBuffer;
TArray<TTuple<const FString, const FString>> SendBuffer;
public:
FBatchSender(FString& ServerUrl, FString& StreamId, FString& AuthToken, int32 MaxBatchSizeMb=1, int32 MaxBufferLength = 10, int32 ThreadCount = 4);
virtual ~FBatchSender() override;
virtual uint32 Run() override;
virtual void Stop() override;
virtual void EnqueueSend(const FString& Id, const FString& Object);
virtual void Flush();
protected:
virtual void SendingThreadMain();
};
@@ -1,13 +1,14 @@
// Fill out your copyright notice in the Description page of Project Settings.
#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);
@@ -16,4 +17,5 @@ TSharedPtr<FJsonObject> UMemoryTransport::GetSpeckleObject(const FString& Object
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());
}
@@ -1,218 +1,36 @@
// Fill out your copyright notice in the Description page of Project Settings.
#include "Transports/ServerTransport.h"
#include "FBatchSender.h"
#include "LogSpeckle.h"
#include "HttpModule.h"
#include "Mixpanel.h"
#include "Runtime/Launch/Resources/Version.h"
#include "JsonObjectConverter.h"
#include "HttpModule.h"
#include "Interfaces/IHttpRequest.h"
#include "Interfaces/IHttpResponse.h"
#include "Mixpanel.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> Object)
void UServerTransport::SaveObject(const FString& ObjectId, const TSharedPtr<FJsonObject> SerializedObject)
{
FString SerializedObject;
{
auto Writer = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&SerializedObject);
FJsonSerializerWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>> SerializerWriter(Writer);
FJsonSerializer::Serialize(Object.ToSharedRef(), Writer);
}
BatchSender.EnqueueSend(ObjectId, SerializedObject);
}
void UServerTransport::BeginWrite()
{
}
void UServerTransport::EndWrite()
{
BatchSender.Flush();
unimplemented(); //TODO implement
}
bool UServerTransport::HasObject(const FString& ObjectId) const
{
unimplemented();
unimplemented(); //TODO implement
return false;
}
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("unknown", 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)
{
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
{
if(!bWasSuccessful)
{
FString Message = FString::Printf(TEXT("Request for children of root object %s/%s failed: %s"), *StreamId, *ObjectId, *Response->GetContentAsString());
InvokeOnError(Message);
return;
}
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;
}
TArray<FString> Lines;
const int32 LineCount = SplitLines(Response->GetContentAsString(), Lines);
UE_LOG(LogSpeckle, Verbose, TEXT("Parsing %d downloaded objects..."), LineCount)
if(LineCount != CEnd - CStart)
{
UE_LOG(LogSpeckle, Warning, TEXT("Requested %d objects, but recieved %d"), CEnd - CStart, LineCount);
}
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::HandleRootObjectResponse(const FString& RootObjSerialized, TScriptInterface<ITransport> TargetTransport, const FString& ObjectId) const
void UServerTransport::HandleRootObjectResponse(const FString& RootObjSerialized,
TScriptInterface<ITransport> TargetTransport,
const FString& ObjectId) const
{
TSharedPtr<FJsonObject> RootObj;
if(!LoadJson(RootObjSerialized, RootObj))
@@ -236,10 +54,200 @@ void UServerTransport::HandleRootObjectResponse(const FString& RootObjSerialized
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"));
if(!AuthToken.IsEmpty())
Request->SetHeader("Authorization","Bearer " + AuthToken);
Request->SetHeader("apollographql-client-name", "Unreal Engine");
Request->SetHeader("apollographql-client-version", SPECKLE_CONNECTOR_VERSION);
// Response Callback
#if ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3
auto ResponseHandler = [=, this](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable
#else
auto ResponseHandler = [=](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable
#endif
{
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"));
if(!AuthToken.IsEmpty())
Request->SetHeader("Authorization","Bearer " + AuthToken);
Request->SetHeader("Content-Type", "application/json");
Request->SetContentAsString(Body);
}
// Response Callback
#if ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION >= 3
auto ResponseHandler = [=, this](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable
#else
auto ResponseHandler = [=](FHttpRequestPtr, FHttpResponsePtr Response, bool bWasSuccessful) mutable
#endif
{
// 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;
@@ -251,14 +259,9 @@ int32 UServerTransport::SplitLines(const FString& Content, TArray<FString>& OutL
return LineCount;
}
bool UServerTransport::LoadJson(const FString& ObjectJson, TSharedPtr<FJsonObject>& OutJsonObject)
bool UServerTransport::LoadJson(const FString& StringJson, TSharedPtr<FJsonObject>& OutJsonObject)
{
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(ObjectJson);
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(StringJson);
return FJsonSerializer::Deserialize(Reader, OutJsonObject);
}
void UServerTransport::InvokeOnError(FString& Message) const
{
ensureAlwaysMsgf(this->OnError.ExecuteIfBound(Message), TEXT("ServerTransport: Unhandled error - %s"), *Message);
}
-29
View File
@@ -1,29 +0,0 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
//#pragma once
//#include "CoreMinimal.h"
//#include "Client.generated.h"
//
// /**
// *
// */
// UCLASS()
// class SPECKLEUNREAL_API UClient : public UClass
// {
// GENERATED_BODY()
//
// public:
//
// static int DefaultBranchLimit = 10;
//
// //UFUNCTION(BlueprintCallable, Category="Speckle")
// //void GetAccounts();
//
// //UFUNCTION(BlueprintCallable, Category="Speckle")
// //Branch StreamGetBranches(FString StreamID, int BranchesLimit = DefaultBranchLimit, int CommitLimit = DefaultBranchLimit);
//
//
// };
@@ -0,0 +1,52 @@
#pragma once
#include "Interfaces/IHttpRequest.h"
#include "Dom/JsonObject.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,45 @@
#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 = 0;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Cursor;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
TArray<FSpeckleBranch> Items;
};
@@ -0,0 +1,29 @@
#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,65 @@
#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 = 0;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Cursor;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
TArray<FSpeckleCommit> Items;
};
@@ -0,0 +1,77 @@
#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 = false;
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 = 0;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Cursor;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
TArray<FSpeckleStream> Items;
};
@@ -0,0 +1,47 @@
#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")
bool Verified = false;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FString Role;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FSpeckleStreams Streams;
UPROPERTY(BlueprintReadWrite, Category="Speckle|API Models")
FSpeckleStreams FavoriteStreams;
};
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -39,7 +38,8 @@ public:
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);
static UReceiveOperation* ReceiveOperation(UObject* WorldContextObject, const FString& ObjectId,
TScriptInterface<ITransport> RemoteTransport, TScriptInterface<ITransport> LocalTransport);
virtual void Activate() override;
@@ -1,48 +0,0 @@
// 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;
void Send();
protected:
TWeakObjectPtr<UBase> Base;
TArray<TScriptInterface<ITransport>> Transports;
};
@@ -0,0 +1,62 @@
#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,30 @@
#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);
};
@@ -1,10 +1,10 @@
// 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;
@@ -21,6 +21,5 @@ public:
static UBase* DeserializeBaseById(const FString& ObjectId, const TScriptInterface<ITransport> ReadTransport);
static UBase* DeserializeBase(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport);
};
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -36,7 +35,7 @@ public:
virtual bool CanConvertToNative_Implementation(TSubclassOf<UBase> BaseType) override;
virtual void ConvertToSpeckle_Implementation(const UObject* Object, UBase* SpeckleObject) override;
virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override;
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion")
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -10,7 +9,7 @@
#include "BlockConverter.generated.h"
class UBlockInstance;
class UInstance;
/**
* Converts Speckle Block Instance objects empty native actors with transform.
@@ -37,7 +36,7 @@ public:
virtual UBase* ConvertToSpeckle_Implementation(const UObject* Object) override;
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual AActor* BlockToNative(const UBlockInstance* Block, UWorld* World);
virtual AActor* BlockToNative(const UInstance* Block, UWorld* World);
protected:
virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters());
@@ -0,0 +1,53 @@
#pragma once
#include "CoreMinimal.h"
#include "Conversion/SpeckleConverter.h"
#include "Engine/EngineTypes.h"
#include "Engine/World.h"
#include "CollectionConverter.generated.h"
class UCollection;
/**
* 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 UCollectionConverter : public UObject, public ISpeckleConverter
{
GENERATED_BODY()
CONVERTS_SPECKLE_TYPES()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TSubclassOf<AActor> ActorType;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TEnumAsByte<EComponentMobility::Type> ActorMobility;
// Sets default values for this actor's properties
UCollectionConverter();
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* CollectionToNative(const UCollection* SpeckleCollection, UWorld* World);
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual UCollection* CollectionToSpeckle(const AActor* Object);
virtual AActor* CreateEmptyActor(UWorld* World, const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters());
};
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -41,7 +40,9 @@ public:
// Sets default values for this actor's properties
UProceduralMeshConverter();
virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>& AvailableConverters) override;
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")
@@ -50,6 +51,7 @@ public:
UFUNCTION(BlueprintCallable, Category="ToNative")
virtual UMesh* MeshToSpeckle(const UProceduralMeshComponent* Object);
virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform, const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters());
virtual AActor* CreateEmptyActor(UWorld* World, const FTransform& Transform,
const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters());
};
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -30,6 +29,9 @@ class SPECKLEUNREAL_API UStaticMeshConverter : public UObject, public ISpeckleCo
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TSet<FString> HiddenTypes;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="ToNative")
TSubclassOf<AActor> MeshActorType;
@@ -76,7 +78,7 @@ public:
UStaticMeshConverter();
virtual UObject* ConvertToNative_Implementation(const UBase* SpeckleBase, UWorld* World, TScriptInterface<ISpeckleConverter>& AvailableConverters) override;
virtual void ConvertToSpeckle_Implementation(const UObject* Object, UBase* SpeckleObject) 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
@@ -91,7 +93,7 @@ public:
FActorSpawnParameters());
UFUNCTION(BlueprintCallable, Category="ToSpeckle")
virtual TArray<UMesh*> MeshToSpeckle(const UStaticMeshComponent* Object);
virtual UBase* MeshToSpeckle(const UStaticMeshComponent* Object);
protected:
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -10,7 +9,7 @@
#include "SpeckleConverter.generated.h"
UINTERFACE()
UINTERFACE(BlueprintType)
class SPECKLEUNREAL_API USpeckleConverter : public UInterface
{
GENERATED_BODY()
@@ -34,22 +33,14 @@ public:
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToNative")
UObject* ConvertToNative(const UBase* SpeckleBase, UWorld* World, UPARAM(ref) TScriptInterface<ISpeckleConverter>& AvailableConverters);
/// Clean up cached resources, and finish any pending build tasks to complete ToNative conversion.
/// Tries to convert a given Actor or Component into a Speckle Base
/// NOT IMPLEMENTED!!!
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();
/// Will return true if this converter can convert a given
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToSpeckle")
void CanConvertToSpeckle(const AActor* Actor);
/// Tries to convert a given Actor or Component into a Speckle Base
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category="ToSpeckle")
void ConvertToSpeckle(const UObject* Object, UBase* SpeckleObject);
};
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -7,18 +6,18 @@
#include "SpeckleConverterComponent.generated.h"
DECLARE_DYNAMIC_DELEGATE_TwoParams(FActorPredicate, const AActor*, Actor, bool&, OutShouldConvert);
class ITransport;
class ISpeckleConverter;
class UBase;
class UAggregateConverter;
class FJsonValue;
struct FSlowTask;
/**
* An Actor Component for encapsulating recursive conversion of Speckle Objects
*/
UCLASS(ClassGroup=(Speckle), meta=(BlueprintSpawnableComponent))
UCLASS(ClassGroup=(Speckle), meta=(BlueprintSpawnableComponent), HideCategories=(Activation, Collision, Cooking, Tags))
class SPECKLEUNREAL_API USpeckleConverterComponent : public UActorComponent
{
GENERATED_BODY()
@@ -33,25 +32,16 @@ public:
USpeckleConverterComponent();
// Converts the given Base and all children into native actors.
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion|ToNative")
UPARAM(DisplayName = "RootActor") AActor* RecursivelyConvertToNative(AActor* AOwner, const UBase* Base, const TScriptInterface<ITransport>& LocalTransport, bool DisplayProgressBar, TArray<AActor*>& OutActors);
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion|ToNative")
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();
// Converts the given Base and all children into native actors.
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion|ToSpeckle")
virtual UBase* RecursivelyConvertToSpeckle(const TArray<AActor*>& RootActors, FActorPredicate& Predicate);
UFUNCTION(BlueprintCallable, Category="Speckle|Conversion|ToSpeckle")
virtual void RecurseTreeToSpeckle(const AActor* RootActor, FActorPredicate& Predicate, TArray<UBase*>& OutConverted);
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);
-1
View File
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
+4 -4
View File
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -14,7 +13,8 @@ protected:
static const FString VersionedApplicationName;
public:
static void TrackEvent(const FString& Email, const FString& Server, const FString& EventName);
static void TrackEvent(const FString& Email, const FString& Server, const FString& EventName, const TMap<FString, FString>& CustomProperties);
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& UserID, const FString& Server, const FString& EventName, const TMap<FString, FString>& CustomProperties);
static FString Hash(const FString& Input);
};
};
+44 -21
View File
@@ -1,9 +1,7 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "DynamicBase.h"
#include "Dom/JsonObject.h"
#include "Base.generated.h"
@@ -14,8 +12,8 @@ class ASpeckleUnrealManager;
/**
* Base type that all Object Models inherit from
*/
UCLASS(BlueprintType, meta=(ScriptName="Base (Speckle.Objects)"))
class SPECKLEUNREAL_API UBase : public UDynamicBase
UCLASS(BlueprintType, meta=(DisplayName="Speckle Object (Base)"))
class SPECKLEUNREAL_API UBase : public UObject
{
public:
@@ -33,22 +31,26 @@ public:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects")
FString Id;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects")
FString Units;
int64 TotalChildrenCount = 0;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects")
FString ApplicationId;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects")
FString SpeckleType;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category="Speckle|Objects")
FString Units;
TMap<FString, TSharedPtr<FJsonValue>> DynamicProperties; //TODO this won't be serialised!
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport)
{
bool IsValid = false;
DynamicProperties.Reserve(Obj->Values.Num());
for(const auto kvp : Obj->Values)
{
SetDynamicProperty(kvp.Key, kvp.Value->Type);
}
DynamicProperties = Obj->Values;
if(Obj->TryGetStringField("id", Id))
{
IsValid = true;
@@ -57,22 +59,43 @@ public:
if(Obj->TryGetStringField("units", Units)) DynamicProperties.Remove("units");
if(Obj->TryGetStringField("speckle_type", SpeckleType)) DynamicProperties.Remove("speckle_type");
if(Obj->TryGetStringField("applicationId", ApplicationId)) DynamicProperties.Remove("applicationId");
if(Obj->TryGetNumberField("totalChildrenCount", TotalChildrenCount)) DynamicProperties.Remove("totalChildrenCount");
return IsValid;
}
protected:
virtual void ToJson(TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>> Writer)
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
int32 RemoveDynamicProperty(UPARAM(ref) const FString& Key)
{
Writer.WriteValue(TEXT("units"), Units);
Writer.WriteValue(TEXT("speckle_type"), SpeckleType);
for(const auto& p : DynamicProperties)
{
//Writer.WriteValue(p.Key, p.Value.mmmmmm));
}
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,28 @@
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "Collection.generated.h"
/**
*
*/
UCLASS()
class SPECKLEUNREAL_API UCollection : public UBase
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects")
FString Name;
UPROPERTY(BlueprintReadWrite, Category="Speckle|Objects")
FString CollectionType;
UCollection() : UBase(TEXT("Speckle.Core.Models.Collection")) {}
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override;
};
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -11,7 +10,8 @@
class UMesh;
/**
*
* This class does not exist in speckle sharp,
* This is a type to represent objects that have displayValues
*/
UCLASS()
class SPECKLEUNREAL_API UDisplayValueElement : public UBase
@@ -23,7 +23,7 @@ protected:
public:
UDisplayValueElement() : UBase(TEXT("Objects.BuiltElements")) {}
UDisplayValueElement() : UBase(TEXT("Objects.Other.DisplayValueElement")) {}
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Speckle|Objects")
TArray<UMesh*> DisplayValue;
@@ -1,66 +0,0 @@
// Copyright AEC Systems Ltd
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "DynamicBase.generated.h"
class UBase;
/**
*
*/
UCLASS(Abstract)
class SPECKLEUNREAL_API UDynamicBase : public UObject
{
GENERATED_BODY()
protected:
TMap<FString, TSharedPtr<FVariant>> DynamicProperties;
public:
template <typename T>
bool TryGetDynamicProperty(const FString& Key, T& OutValue) const;
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
bool TryGetDynamicStringProperty(UPARAM(ref) const FString& Key, FString& OutValue) const;
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
bool TryGetDynamicIntProperty(UPARAM(ref) const FString& Key, int32& OutValue) const;
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
bool TryGetDynamicFloatProperty(UPARAM(ref) const FString& Key, float& OutValue) const;
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
bool TryGetDynamicBoolProperty(UPARAM(ref) const FString& Key, bool& OutValue) const;
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
bool TryGetDynamicBaseProperty(UPARAM(ref) const FString& Key, UBase*& OutValue) const;
template <typename T>
void SetDynamicProperty(const FString& Key, T Value);
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
void SetDynamicStringProperty(UPARAM(ref) const FString& Key, FString& OutValue);
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
void SetDynamicIntProperty(UPARAM(ref) const FString& Key, int32& OutValue);
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
void SetDynamicFloatProperty(UPARAM(ref) const FString& Key, float& OutValue);
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
void SetDynamicBoolProperty(UPARAM(ref) const FString& Key, bool& OutValue);
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
void SetDynamicBaseProperty(UPARAM(ref) const FString& Key, UBase*& OutValue);
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
int32 RemoveDynamicProperty(UPARAM(ref) const FString& Key);
};
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -41,8 +40,11 @@ public:
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override;
virtual void ToJson(TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>> Writer) 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();
};
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -1,4 +1,3 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
@@ -24,29 +23,40 @@ private:
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);
/**
* @brief Searches for a closest registered speckle type
* by recursively stripping away a the most specific name specifier from the given SpeckleType
* e.g. With an input of `"Objects.BuiltElements.Wall:Objects.BuiltElements.RevitWall"` will first search for
* Will first look for a registered type of `"Objects.BuiltElements.RevitWall"`, then if not found `"Objects.BuiltElements.Wall"`, then simply will use UBase
* @param SpeckleType The full speckle type
* @return The closest registered type
*/
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
static bool ParentType(const FString& Type, FString& NextType);
static TSubclassOf<UBase> GetAtomicType(const FString& SpeckleType);
/// Attempts to find a TSubclassOf<UBase> with a UBase::SpeckleType matching the given SpeckleType param
/// Returns nullptr if none found.
// E.g. "Objects.BuiltElements.Wall:Objects.BuiltElements.RevitWall" -> "Objects.BuiltElements.RevitWall"
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Speckle|Objects")
static FString GetTypeName(const FString& SpeckleType);
// E.g. "Objects.BuiltElements.Wall:Objects.BuiltElements.RevitWall" -> "RevitWall"
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Speckle|Objects")
static FString GetSimplifiedTypeName(const FString& SpeckleType);
UFUNCTION(BlueprintCallable, BlueprintPure, Category="Speckle|Objects")
static bool SplitSpeckleType(const FString& SpeckleType, FString& OutRemainder, FString& OutTypeName, const FString& Split = ":");
/**
* @brief Attempts to find a `TSubclassOf<UBase>` with a `UBase::SpeckleType` matching the given SpeckleType param
* @param TypeName
* @return the matching type or `nullptr` if none found.
*/
UFUNCTION(BlueprintCallable, Category="Speckle|Objects")
static TSubclassOf<UBase> GetRegisteredType(const FString& SpeckleType);
static TSubclassOf<UBase> GetRegisteredType(const FString& TypeName);
/// 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);
static bool TryGetRegisteredType(const FString& TypeName, TSubclassOf<UBase>& OutType);
};
@@ -1,9 +1,8 @@
// Copyright 2022 AEC Systems, Licensed under the Apache License, Version 2.0
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "Instance.h"
#include "BlockInstance.generated.h"
@@ -11,22 +10,13 @@
*
*/
UCLASS()
class SPECKLEUNREAL_API UBlockInstance : public UBase
class SPECKLEUNREAL_API UBlockInstance : public UInstance
{
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")) {}
UBlockInstance() : UInstance(TEXT("Objects.Other.BlockInstance")) {}
virtual bool Parse(const TSharedPtr<FJsonObject> Obj, const TScriptInterface<ITransport> ReadTransport) override;
@@ -0,0 +1,32 @@
#pragma once
#include "CoreMinimal.h"
#include "Objects/Base.h"
#include "Instance.generated.h"
/**
*
*/
UCLASS(Abstract)
class SPECKLEUNREAL_API UInstance : 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;
protected:
UInstance(const FString& SpeckleType) : UBase(SpeckleType) {}
UInstance() : UBase(TEXT("Objects.Other.BlockInstance")) {}
};

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