PHP加载3D模型【WebGL】

这是另一篇关于如何使用 PHP加载 3D 模型的文章。 在这里,我使用 Laravel 作为后端及其存储。 我在前端使用 Three.Js 库来渲染和显示 3D 模型。 我将向您展示如何上传 3D 模型以及如何从 Laravel 存储加载 3D 模型。 请仔细完成以下步骤。 大家可以在评论区提出任何问题。 在这里,我展示了一条主要路径,然后你可以根据自己的喜好对其进行自定义。

在这里插入图片描述

推荐:使用 NSDT场景设计器 快速搭建 3D场景。

1、创建 Laravel 项目

创建一个新的 Laravel 项目并创建新的模型、视图和控制器。 然后使用下面的命令链接存储。

php artisan storage:link

2、上传 3D 模型

你可以使用 HTML 和 Javascript 创建一个简单的表单。 我使用 Laravel blade文件来构建前端。

<form action="{{ route('model.store') }}" method="POST" id="file-upload" enctype="multipart/form-data">
          @csrf
          <div class="form-group row">
              <label for="name" class="col-md-4 col-form-label text-md-right">Model Name</label>
              <div class="col-md-6">
              <div class="row">
                  <input id="name" type="name" class="form-control" name="name" required>
              </div>
              </div>
          </div>
        <div class="form-group row">
              <label for="file_type" class="col-md-4 col-form-label text-md-right">File Type</label>
              <div class="col-md-6">
              <div class="row">
                <select class="form-select" aria-label="Default select example" name="file_type" id="file_type">
                    <option value="gltf">GLTF</option>
                    <option value="obj">OBJ</option>
                    <option value="fbx">FBX</option>
                </select>
              </div>
              </div>
          </div>
          <div class="form-group row">
              <label for="file" class="col-md-4 col-form-label text-md-right">Upload Main File</label>
              <div class="col-md-6">
              <div class="row">
                  <input type="file" id="main"  class="form-control" name="main"  required>
              </div>
              </div>
          </div>
          <div class="form-group row">
              <label for="file" class="col-md-4 col-form-label text-md-right">Upload Other Files</label>
              <div class="col-md-6">
              <div class="row">
                  <input type="file" id="files"  class="form-control" name="files[]"  required multiple>
              </div>
              </div>
          </div>
          <div class="form-group row">
              <label for="preview" class="col-md-4 col-form-label text-md-right">Upload Preview Image</label>
              <div class="col-md-6">
              <div class="row">
                  <input type="file" id="preview"  class="form-control" name="preview"  required>
              </div>
              </div>
          </div>
          <div class="form-group row mb-0">
              <div class="col-md-6 offset-md-4">
                  <button type="button" class="btn btn-secondary" onclick="window.history.back()">Close</button>
                  <button type="submit" class="btn btn-primary" id="product_save_btn">
                      Upload Model
                  </button>
              </div>
          </div>
      </form>

使用 Ajax 调用提交表单:

$(document).ready(function() {
        $('#file-upload').submit(function(e) {
            e.preventDefault();
            let formData = new FormData(this);

            $.ajax({
                type:'POST',
                url: "{{ route('model.store') }}",
                data: formData,
                contentType: false,
                processData: false,
                success: (response) => {
                    console.log(response);
                    if (response.success) {
                        window.location.href = response.url;
                    }
                },
                error: function(response){
                    alert('Prescription has not been created successfully');
                }
          });
        });
    });

在后端,可以按如下方式实现 store() 方法:

  /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'files' => 'required',
            'file_type' => 'required',
            'main' => 'required',
            'preview' => 'required',
        ]);
        
        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()->all()]);
        }

        $date = date('Y-m-d');
        $folder = $date.time();
        $files = $request->file('files');
        foreach ($files as $file) {
            $file_name = $file->getClientOriginalName();
            $fileName = pathinfo($file_name, PATHINFO_FILENAME);
         
            try {
                $path = Storage::disk('public')->PutFileAs($folder , $file, $file->getClientOriginalName());
            } catch (\Exception $e) {
                return false;
            }
        }

        if ($request->hasFile('preview')) {
            $file = $request->file('preview');
            $file_name = $file->getClientOriginalName();
            $imageName = time().'.'.$file->extension();  
            $preview_path = Storage::disk('public')->PutFileAs($folder, $file, $file->getClientOriginalName());
        
        }

        if ($request->hasFile('main')) {
            $file = $request->file('main');
            $file_name = $file->getClientOriginalName();
            $imageName = time().'.'.$file->extension();  
            $path = Storage::disk('public')->PutFileAs($folder,$file,$file->getClientOriginalName());
        
        }

        return response()->json(['success'=> true, 'msg'=>'Record is successfully added', 'url'=> '/home']);
    
    }

然后就可以在存储中看到上传的文件了。 它们被组织为单独的文件夹。 要显示 3D 模型,你需要路径 URL。
在这里插入图片描述

3、加载 3D 模型

在下面的示例中,我向你展示如何从 laravel 存储加载 fbx 模型。 同样,你可以轻松加载其他文件类型。 请理解并尝试首先针对一种文件类型实施它。

 if(myData['file_type'] == 'fbx'){
          init1();
        }else if(myData['file_type'] == 'obj'){
          init2();
        }
      
      
      function init1() {
            scene = new THREE.Scene();
            scene.background = new THREE.Color(0xdddddd);

            camera = new THREE.PerspectiveCamera(5, window.innerWidth/window.innerHeight, 1, 5000);
            camera.position.z = 1000;

            light = new THREE.HemisphereLight(0xffffff, 0x444444, 1.0);
            light.position.set(0, 1, 0);
            scene.add(light);

            light = new THREE.DirectionalLight(0xffffff, 1.0);
            light.position.set(0, 1, 0);
            scene.add(light);

            renderer = new THREE.WebGLRenderer({antialias:true});
            renderer.setSize(window.innerWidth, window.innerHeight);

            container = document.getElementById( 'canvas' );
            renderer.setSize(container.offsetWidth, 400);
            
            container.appendChild( renderer.domElement );

            controls = new THREE.OrbitControls(camera,  renderer.domElement);
            controls.addEventListener('change', renderer);
            const fbxLoader = new THREE.FBXLoader();
                let text1 = "storage/";
                let result = text1.concat(myData['url']);
                console.log(result);
                fbxLoader.load('{{ asset('storage/') }}'+'/'+myData['url']+'.fbx', (object) => {
                scene.add(object);
                animate();
            });
        }
        function animate(){
            renderer.render(scene,camera);
            requestAnimationFrame(animate);
        }

这里的方法根据3D模型文件类型而改变。


原文链接:PHP加载3D模型 — BimAnt

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
服务器端利用 PHP插件 生成标签云数据,页面用 flash 3D效果展示标签,效果很爽的,放在自己博客格外吸引眼球。 查看效果: http://www.roytanck.com/about-my-themes/donations/ 下面是详细: ------------------------------------------------------------ === Plugin Name === Contributors: weefselkweekje Donate link: http://www.roytanck.com/about-my-themes/donations/ Tags: tag cloud, flash, sphere, categories, widget Requires at least: 2.3 Tested up to: 2.6.3 Stable tag: 1.17 WP-Cumulus displays your tags and/or categories in 3D by placing them on a rotating sphere. == Description == WP-Cumulus allows you to display your site's tags, categories or both using a Flash movie that rotates them in 3D. It works just like a regular tags cloud, but is more visually exciting. Clicking the tags can be a little hard (depending on your speed setting) but does take you to the appropriate page :). The sources code for the Flash movie are available from wordpress.org. == Installation == = Installation = 1. Make sure you're running WordPress version 2.3 or better. It won't work with older versions. Really. 1. Download the zip file and extract the contents. 1. Upload the 'wp-cumulus' folder to your plugins directory (wp-content/plugins/). 1. Activate the plugin through the 'plugins' page in WP. 1. See 'Options->WP Cumulus' to adjust things like display size, etc... = In order to actually display the tag cloud, you have three options. = 1. Create a page or post and type [WP-CUMULUS] anywhere in the content. This 'tag' will be replaced by the flash movie when viewing the page. 1. Add the following code anywhere in your theme to display the cloud. `<?php wp_cumulus_insert(); ?>` This can be used to add WP Cumulus to your sidebar, although it may not actually be wide enough in many cases to keep the tags readable. 1. The plugin adds a widget, so you can place it on your sidebar through 'Design'->'Widgets'. The widget uses a separate set of settings, so it's possible to have different background colors, sizes, etc. == Frequently Asked Questions == = My theme/site appears not to like this plugin. It's not displaying correctly. = There are a number of things that may prevent WP-Cumulus from displaying or cause it to display a short message about how it needs the Flash plugin. * In 99% of all cases where this happens the issue is caused by markup errors in the page where the plugin is used. Please validate your blog using [validator.w3.org](http://validator.w3.org) and fix any errors you may encounter. * Older versions had issues with PHP 5.2 (or better). This has been fixed, so please upgrade to the latest version. * The plugin requires Flash Player 9 or better and javascript. Please make sure you have both. * There have been some cases where WordPress' Automatic Plugin Upgrade feature breaks the plugin. After upgrading the plugin the Flash movie would be corrupt for some users. If this happens to you, please try disabling and reinstalling the plugin (through FTP). = Hey, but what about SEO? = I'm not sure how beneficial tag clouds are when it comes to SEO, but just in case WP Cumulus outputs the regular tag cloud (and/or categories listing) for non-flash users. This means that search engines will see the same links. = I'd like to change something in the Flash movie, will you release the .fla? = As of version 1.12 the source code is available from wordpress.org under the GP license. Click "other versions" and get the developer version. = Some of my tags occasionally hit the sides of the movie and are cropped = If this happens you should change the aspect for the movie to make it wider. This can be done by increasing the width, but also by decreasing the height. Both will make the movie 'more landscape' giving long tags more room. = Some characters are not showing up = Because of the way Flash handles text, only Latin characters are supported in the current version. This is due to a limitation where in order to be able to animate text fields smoothly the glyphs need to be embedded in the movie. The Flash movie's source code is available for download through Subversion. Doing so will allow you to create a version for your language. There's a text field in the root of the movie that you can use to embed more characters. If you change to another font, you'll need to edit the Tag class as well. More info [here](http://www.roytanck.com/2008/08/04/how-to-add-more-characters-to-wp-cumulus/). = When I click on tags, nothing happens. = This is usually caused by a Flash security feature that affects movies served from another domain as the surrounding page. If your blog is http://yourblog.com, but you have http://www.yourblog.com listed as the 'WordPress address' under Settings -> General this issue can occur. In this case you should adjust this setting to match your blog's actual URL. If you haven't already, I recommend you decide on a single URL for your blog and redirect visitors using other options. This will increase your search engine ranking and in the process help solve this issue :). = I'm not using WordPress... = * Steve Springett has ported this to Movable Type. More info over on [his site](http://www.6000rpms.com/blog/2008/04/04/flash-tag-cloud-for-mt-4.html). * Michael Robinson has ported WP-Cumulus to RapidWeaver, see his tutorial [here](http://pagesofinterest.net/mikes/blog_of_interest_files/tag_cloud.php). * Amanda Fazani managed to get Cumulus working on Blogger. More info on Blogumus [here](http://www.bloggerbuster.com/2008/08/blogumus-flash-animated-label-cloud-for.html). * Yannick Lejeune has done a [TypePad version](http://www.yannicklejeune.com/2008/09/tumulus-wp-cumu.html) based in part on Steve's work. * Christian Philipp's created a [TYPO3 version](http://typo3.org/extensions/repository/view/t3m_cumulus_tagcloud/current/). * Rob Antonishen did a [Serendipity version](http://spartacus.s9y.org/index.php?mode=bygroups_event_en) (search for serendipity\_event\_freetag). * Big Bear maintains the [Joomla version](http://joomlabear.com/Downloads/). * Pratul Kalia and Bj鰎n Jacob have ported it to [Drupal](http://drupal.org/project/cumulus). * Ryan Tomlinson has a [BlogEngine.NET version](http://www.99atoms.com/post/BlogCumulusNET-A-flash-based-tag-cloud.aspx). * I wrote [this post](http://www.roytanck.com/2008/05/19/how-to-repurpose-my-tag-cloud-flash-movie/) on how to use the flash movie in other contexts. == Screenshots == 1. The tag sphere. You can set colors that match your theme on the plugin's options page. 2. The options panel. 3. There's a separate one for the widget. == Options == The options page allows you to change the Flash movie's dimensions, change the text color as well as the background. = Width of the Flash tag cloud = The movie will scale itself to fit inside whatever dimensions you decide to give it. If you make it really small, chances are people will not be able to read less-used tags that are further away. Anything up from 300 will work fine in most cases. = Height of the Flash tag cloud = Ideally, the height should be something like 3/4 of the width. This will make the rotating cloud fit nicely, while the extra width allows for the tags to be displayed without cropping. Western text is horizontal by nature, which is why the ideal aspect is slightly landscape even though the cloud is circular. = Color of the tags = Type the hexadecimal color value you'd like to use for the tags, but not the '#' that usually precedes those in HTML. Black (000000) will obviously work well with light backgrounds, white (ffffff) is recommended for use on dark backgrounds. Optionally, you can use the second input box to specify a different color. When two colors are available, each tag's color will be from a gradient between the two. This allows you to create a multi-colored tag cloud. = Background color = The hex value for the background color you'd like to use. This options has no effect when 'Use transparent mode' is selected. = Use transparent mode = Turn on/off background transparency. Enabling this might cause issues with some (mostly older) browsers. Under Linux, transparency doesn't work in at all due to a known limitation in the Flash player. = Rotation speed = Allows you to change the speed of the sphere. Options between 25 and 500 work best. = Distribute tags evenly on sphere = When enabled, the movie will attempt to distribute the tags evenly over the surface of the sphere. = Display = Choose whether to show tags only, categories only, or both mixed together. Choosing 'both' can result in 'duplicate tags' if you have categories and tags with the same name. These words will appear twice, with one linking to the tag and the other to the category overview. = wp tag cloud parameters = This setting allows you to pass parameters to the wp\_tag\_cloud function, which is used to fetch the tag cloud. Use caution with this setting. Everything you enter will be passed to the function. Be sure to read the function's manual. Please also note that these parameters affect tags only. If you've chosen to show categories or both, the category 'tags' will not be affected. == Version history == = Version 1.16 = + Fixes an issue with categories being rendered black when all of them have the same number of posts. + Reduces the default font size (from the biggest possible to "medium") in that same situation. + Significantly reduces CPU load when the cloud isn't moving. = Version 1.15 = + Adds the possibility to create a multi-colored tag cloud by entering a second tag color. = Version 1.14 = + Fixes an issue where no tags are displayed when viewing the movie locally in MSIE. + Fixes an issue where one random tag would not be displayed. = Version 1.13 = + No longer breaks when the wp-content folder is moved to a non-standard location. = Version 1.12 = + First version hosted on WordPress.org, and released under GPL license. + Uses the Arial font to avoid font licensing issues. = Version 1.11 = + Restores an earlier fix for IE to force loading of the Flash movie. = Version 1.1 = + Complete rewrite of the Flash movie (Actionscript 3, requires Flash Player 9 or better). + Better mouse detection. + Adds option to distribute the tags evenly over the sphere. + Adds support for categories. + Adds the ability to pass parameters to the WordPress wp_tag_cloud function. + Several smaller enhancements. = Version 1.05 = * Fixes several issues with IE, including an issue where it was impossible to use the regular version and the widget on the same page. Thanks to Fadi for alerting me to these. = Version 1.04 = * Fixes the 'it kills my blog' error for people using PHP 5.2 or newer. Thanks to Mujahid for helping me debug this. * Speed improvements in the Flash code. = Version 1.03 = * Removes the wp_head hook in yet another attempt to fix issues with some other plugins and themes. * Reduces system overhead by storing less options. * Adds setting for speed. * Adds a widget with seperate options (size, colors, speeds, etc). * Attemps to detect when the mouse leaves the movie, reducing the 'spinning, but not out of control' effect. * Several minor fixes. = Version 1.02 = * Fixes issues with sites not loading after activation, reduces server load and fixes lost spaces in tags. Thanks to Dimitry for helping me debug these issues. = Version 1.01 = * Fixes an issue where the cloud would spin out of control when the browsers loses focus on OSX. = Version 1.00 = * Initial release version. ------------------------------------------------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值